use std::error::Error;
use std::fmt;
#[cfg(not(target_arch = "wasm32"))]
use rayon::prelude::*;
use super::render::{apply_explicit_window, encode_rendered_frame, RenderedFramePixels};
pub use super::render::{RenderFrameOutput, RenderOutputFormat};
use super::types::RenderError;
use super::volume::{canonical_view_basis, rotate_basis, Interpolation, Volume};
type Vec3 = [f64; 3];
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VolumeRenderMode {
MaximumIntensity,
MinimumIntensity,
Average,
Composite,
}
impl VolumeRenderMode {
pub fn parse(value: &str) -> Result<Self, VolumeRenderError> {
match value.trim().to_ascii_lowercase().as_str() {
"mip" => Ok(Self::MaximumIntensity),
"minip" => Ok(Self::MinimumIntensity),
"average" | "avg" => Ok(Self::Average),
"composite" | "dvr" => Ok(Self::Composite),
other => Err(VolumeRenderError::InvalidOptions(format!(
"unknown volume render mode '{other}'; expected 'mip', 'minip', 'average' or 'composite'"
))),
}
}
pub fn name(self) -> &'static str {
match self {
Self::MaximumIntensity => "mip",
Self::MinimumIntensity => "minip",
Self::Average => "average",
Self::Composite => "composite",
}
}
}
#[derive(Debug)]
pub enum VolumeRenderError {
InvalidOptions(String),
InvalidOutputDimensions,
Render(RenderError),
}
impl fmt::Display for VolumeRenderError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::InvalidOptions(message) => write!(formatter, "{message}"),
Self::InvalidOutputDimensions => write!(
formatter,
"volume render output width/height must be between 1 and 65535"
),
Self::Render(error) => {
write!(formatter, "failed to encode the volume rendering: {error}")
}
}
}
}
impl Error for VolumeRenderError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
Self::Render(error) => Some(error),
_ => None,
}
}
}
impl From<RenderError> for VolumeRenderError {
fn from(value: RenderError) -> Self {
Self::Render(value)
}
}
fn invalid(message: impl Into<String>) -> VolumeRenderError {
VolumeRenderError::InvalidOptions(message.into())
}
#[derive(Clone, Debug, PartialEq)]
pub struct TransferFunctionPoint {
pub value: f64,
pub relative: bool,
pub color: [u8; 3],
pub opacity: f64,
}
#[derive(Clone, Debug, PartialEq)]
pub struct TransferFunction {
pub points: Vec<TransferFunctionPoint>,
}
pub const VOLUME_RENDER_PRESETS: &[(&str, &str, &str)] = &[
(
"ct-bone",
"CT bone: soft tissue transparent, bone ivory to white",
"-1000:0,0,0,0;150:0,0,0,0;220:190,120,80,0.08;400:230,200,160,0.55;800:245,235,215,0.85;3000:255,255,255,0.95",
),
(
"ct-soft-tissue",
"CT soft tissue: faint skin and fat, muscle and organs red-brown, bone white",
"-1000:0,0,0,0;-500:0,0,0,0;-200:200,150,120,0;-60:210,160,120,0.01;20:190,80,60,0.06;80:210,90,70,0.18;200:230,180,150,0.35;600:245,235,220,0.75;3000:255,255,255,0.9",
),
(
"ct-lung",
"CT lung: air and soft tissue transparent, lung parenchyma pale pink, bone faint",
"-1000:0,0,0,0;-950:0,0,0,0;-900:200,140,140,0.02;-700:225,170,160,0.08;-500:230,190,170,0.12;-350:200,120,110,0;250:240,230,220,0;500:245,240,230,0.08;3000:255,255,255,0.1",
),
(
"ct-angio",
"CT angiography: contrast-filled vessels red, bone white",
"-1000:0,0,0,0;120:0,0,0,0;180:170,20,20,0.15;300:220,60,50,0.6;500:245,210,190,0.8;1000:250,245,240,0.9;3000:255,255,255,0.95",
),
(
"mr-default",
"MR default: relative to the volume's value range, dark background transparent",
"0%:0,0,0,0;10%:0,0,0,0;20%:150,90,70,0.02;40%:210,160,130,0.15;70%:240,220,200,0.5;100%:255,255,255,0.8",
),
];
pub fn volume_render_preset_names() -> Vec<&'static str> {
VOLUME_RENDER_PRESETS
.iter()
.map(|(name, _, _)| *name)
.collect()
}
impl TransferFunction {
pub fn parse(spec: &str) -> Result<Self, VolumeRenderError> {
let mut points = Vec::new();
for segment in spec.split(';') {
let segment = segment.trim();
if segment.is_empty() {
continue;
}
let bad = |why: &str| {
invalid(format!(
"invalid transfer function point '{segment}': {why} (expected VALUE:R,G,B,A, e.g. 300:255,240,220,0.8)"
))
};
let (value_text, color_text) =
segment.split_once(':').ok_or_else(|| bad("missing ':'"))?;
let value_text = value_text.trim();
let (number_text, relative) = match value_text.strip_suffix('%') {
Some(stripped) => (stripped.trim(), true),
None => (value_text, false),
};
let value: f64 = number_text
.parse()
.ok()
.filter(|value: &f64| value.is_finite())
.ok_or_else(|| bad("VALUE is not a number"))?;
let parts: Vec<&str> = color_text.split(',').map(str::trim).collect();
if parts.len() != 4 {
return Err(bad("expected four comma-separated numbers after ':'"));
}
let mut color = [0u8; 3];
for (slot, part) in color.iter_mut().zip(&parts[..3]) {
let component: f64 = part
.parse()
.ok()
.filter(|value: &f64| (0.0..=255.0).contains(value))
.ok_or_else(|| bad("R, G and B must be numbers from 0 to 255"))?;
*slot = component.round() as u8;
}
let opacity: f64 = parts[3]
.parse()
.ok()
.filter(|value: &f64| (0.0..=1.0).contains(value))
.ok_or_else(|| bad("A (opacity) must be a number from 0 to 1"))?;
points.push(TransferFunctionPoint {
value,
relative,
color,
opacity,
});
}
if points.is_empty() {
return Err(invalid(
"transfer function has no points (expected VALUE:R,G,B,A;VALUE:R,G,B,A;...)",
));
}
Ok(Self { points })
}
pub fn preset(name: &str) -> Result<Self, VolumeRenderError> {
let wanted = name.trim().to_ascii_lowercase();
VOLUME_RENDER_PRESETS
.iter()
.find(|(preset, _, _)| *preset == wanted)
.map(|(_, _, spec)| Self::parse(spec).expect("built-in presets parse"))
.ok_or_else(|| {
invalid(format!(
"unknown volume render preset '{name}'; expected one of: {}",
volume_render_preset_names().join(", ")
))
})
}
pub fn default_for_modality(modality: Option<&str>) -> Self {
let name = match modality.map(str::trim) {
Some(value) if value.eq_ignore_ascii_case("CT") => "ct-bone",
_ => "mr-default",
};
Self::preset(name).expect("built-in presets exist")
}
pub fn to_spec_string(&self) -> String {
self.points
.iter()
.map(|point| {
format!(
"{}{}:{},{},{},{}",
point.value,
if point.relative { "%" } else { "" },
point.color[0],
point.color[1],
point.color[2],
point.opacity
)
})
.collect::<Vec<_>>()
.join(";")
}
fn resolve(&self, data_min: f64, data_max: f64) -> Vec<(f64, [f32; 3], f32)> {
let mut resolved: Vec<(f64, [f32; 3], f32)> = self
.points
.iter()
.map(|point| {
let value = if point.relative {
data_min + (data_max - data_min) * point.value / 100.0
} else {
point.value
};
(
value,
point.color.map(|c| f32::from(c) / 255.0),
point.opacity as f32,
)
})
.collect();
resolved.sort_by(|a, b| a.0.partial_cmp(&b.0).unwrap_or(std::cmp::Ordering::Equal));
resolved
}
}
const LUT_SIZE: usize = 4096;
struct TransferLut {
low: f32,
scale: f32,
rgba: Vec<[f32; 4]>,
nonzero_prefix: Vec<u32>,
}
impl TransferLut {
fn new(function: &TransferFunction, data_min: f64, data_max: f64, step_mm: f64) -> Self {
let points = function.resolve(data_min, data_max);
let low = points[0].0;
let high = points[points.len() - 1].0;
let span = (high - low).max(1e-6);
let mut rgba = Vec::with_capacity(LUT_SIZE);
let mut segment = 0usize;
for index in 0..LUT_SIZE {
let value = low + span * index as f64 / (LUT_SIZE - 1) as f64;
while segment + 1 < points.len() && points[segment + 1].0 < value {
segment += 1;
}
let (color, opacity) = if points.len() == 1 || value <= points[0].0 {
(points[0].1, points[0].2)
} else if segment + 1 >= points.len() {
let last = points[points.len() - 1];
(last.1, last.2)
} else {
let (v0, c0, a0) = points[segment];
let (v1, c1, a1) = points[segment + 1];
let t = if v1 > v0 {
((value - v0) / (v1 - v0)).clamp(0.0, 1.0) as f32
} else {
1.0
};
(
[0, 1, 2].map(|k| c0[k] + (c1[k] - c0[k]) * t),
a0 + (a1 - a0) * t,
)
};
let corrected = if opacity <= 0.0 {
0.0
} else if opacity >= 1.0 {
1.0
} else {
1.0 - (1.0 - opacity).powf(step_mm as f32)
};
rgba.push([color[0], color[1], color[2], corrected]);
}
let mut nonzero_prefix = Vec::with_capacity(LUT_SIZE + 1);
let mut count = 0u32;
nonzero_prefix.push(0);
for entry in &rgba {
if entry[3] > 0.0 {
count += 1;
}
nonzero_prefix.push(count);
}
Self {
low: low as f32,
scale: ((LUT_SIZE - 1) as f64 / span) as f32,
rgba,
nonzero_prefix,
}
}
#[inline(always)]
fn index(&self, value: f32) -> usize {
let position = (value - self.low) * self.scale + 0.5;
if position <= 0.0 {
0
} else {
(position as usize).min(LUT_SIZE - 1)
}
}
#[inline(always)]
fn lookup(&self, value: f32) -> [f32; 4] {
self.rgba[self.index(value)]
}
fn transparent_between(&self, min: f32, max: f32) -> bool {
let low = self.index(min);
let high = self.index(max);
self.nonzero_prefix[high + 1] == self.nonzero_prefix[low]
}
}
pub fn volume_render_view_basis(
view: &str,
volume: &Volume,
) -> Result<(Vec3, Vec3), VolumeRenderError> {
match view.trim().to_ascii_lowercase().as_str() {
"anterior" | "front" => Ok(([1.0, 0.0, 0.0], [0.0, 0.0, -1.0])),
"posterior" | "back" => Ok(([-1.0, 0.0, 0.0], [0.0, 0.0, -1.0])),
"left" => Ok(([0.0, 1.0, 0.0], [0.0, 0.0, -1.0])),
"right" => Ok(([0.0, -1.0, 0.0], [0.0, 0.0, -1.0])),
"superior" | "top" => Ok(([-1.0, 0.0, 0.0], [0.0, 1.0, 0.0])),
"inferior" | "bottom" => Ok(([1.0, 0.0, 0.0], [0.0, 1.0, 0.0])),
"coronal" => canonical_view_basis("coronal", volume).map_err(|e| invalid(e.to_string())),
"sagittal" => canonical_view_basis("sagittal", volume).map_err(|e| invalid(e.to_string())),
"axial" => canonical_view_basis("axial", volume).map_err(|e| invalid(e.to_string())),
other => Err(invalid(format!(
"unknown volume render view '{other}'; expected anterior, posterior, left, right, superior, inferior (or coronal, sagittal, axial)"
))),
}
}
pub fn orbit_basis(row_dir: Vec3, col_dir: Vec3, degrees: f64) -> (Vec3, Vec3) {
if degrees.abs() < 1e-12 {
return (row_dir, col_dir);
}
let axis = normalize3(col_dir);
let (sin, cos) = degrees.to_radians().sin_cos();
let v = row_dir;
let rotated = add3(
add3(scale3(v, cos), scale3(cross3(axis, v), sin)),
scale3(axis, dot3(axis, v) * (1.0 - cos)),
);
(normalize3(rotated), col_dir)
}
#[derive(Clone, Debug)]
pub struct VolumeRenderParams {
pub mode: VolumeRenderMode,
pub center: Vec3,
pub row_dir: Vec3,
pub col_dir: Vec3,
pub output_width: u32,
pub output_height: u32,
pub spacing_mm: f64,
pub step_mm: f64,
pub perspective_fov_deg: Option<f64>,
pub transfer_function: Option<TransferFunction>,
pub shading: bool,
pub window_center: Option<f64>,
pub window_width: Option<f64>,
pub crop_voxels: Option<[f64; 6]>,
pub crop_mm: Option<[f64; 6]>,
pub background: [u8; 3],
pub interpolation: Interpolation,
}
#[derive(Clone, Debug, Default)]
pub struct VolumeRenderOptions {
pub mode: Option<String>,
pub view: Option<String>,
pub rotation_deg: Option<[f64; 3]>,
pub orbit_deg: Option<f64>,
pub center: Option<Vec3>,
pub spacing_mm: Option<f64>,
pub zoom: Option<f64>,
pub output_width: Option<u32>,
pub output_height: Option<u32>,
pub max_dim: Option<u32>,
pub step_mm: Option<f64>,
pub preset: Option<String>,
pub transfer_function: Option<String>,
pub shading: Option<bool>,
pub perspective_fov_deg: Option<f64>,
pub crop_voxels: Option<[f64; 6]>,
pub crop_mm: Option<[f64; 6]>,
pub window_center: Option<f64>,
pub window_width: Option<f64>,
pub background: Option<[u8; 3]>,
pub interpolation: Option<String>,
}
pub fn parse_on_off(value: &str) -> Option<bool> {
match value.trim().to_ascii_lowercase().as_str() {
"on" | "true" | "yes" | "1" => Some(true),
"off" | "false" | "no" | "0" => Some(false),
_ => None,
}
}
fn validate_box(values: &[f64; 6], what: &str) -> Result<(), VolumeRenderError> {
for axis in 0..3 {
let (low, high) = (values[axis * 2], values[axis * 2 + 1]);
if !low.is_finite() || !high.is_finite() || low > high {
return Err(invalid(format!(
"{what} must give MIN <= MAX on each axis (got {low}..{high})"
)));
}
}
Ok(())
}
pub fn resolve_volume_render_params(
volume: &Volume,
options: &VolumeRenderOptions,
) -> Result<VolumeRenderParams, VolumeRenderError> {
resolve_params(volume, options, false)
}
pub fn resolve_turntable_volume_render_params(
volume: &Volume,
options: &VolumeRenderOptions,
) -> Result<VolumeRenderParams, VolumeRenderError> {
resolve_params(volume, options, true)
}
struct FramingPoint {
u: f64,
v: f64,
depth: f64,
radius: f64,
}
struct Framing {
points: Vec<FramingPoint>,
perspective_tan: Option<f64>,
orbit: bool,
}
impl Framing {
fn near_depth(&self, point: &FramingPoint) -> f64 {
if self.orbit {
-point.radius
} else {
point.depth
}
}
fn orthographic_half_u(&self) -> f64 {
self.points
.iter()
.map(|point| {
if self.orbit {
point.radius
} else {
point.u.abs()
}
})
.fold(0.0, f64::max)
}
fn half_v(&self) -> f64 {
let orthographic = self.points.iter().map(|p| p.v.abs()).fold(0.0, f64::max);
let Some(tan) = self.perspective_tan else {
return orthographic;
};
let mut distance: f64 = 0.0;
let mut nearest: f64 = 0.0;
let mut extent: f64 = 0.0;
for point in &self.points {
let near = self.near_depth(point);
distance = distance.max(point.v.abs() / tan - near);
nearest = nearest.max(-near);
extent = extent.max(point.radius).max(point.v.abs());
}
distance = distance.max(nearest + extent * 0.01 + 1e-3);
distance * tan
}
fn half_u(&self, half_height: f64) -> Option<f64> {
let Some(tan) = self.perspective_tan else {
return Some(self.orthographic_half_u());
};
let distance = half_height / tan;
let mut half: f64 = 0.0;
for point in &self.points {
if distance + self.near_depth(point) <= 1e-6 * distance.max(1.0) {
return None;
}
let projected = if self.orbit {
point.radius * distance / (distance * distance - point.radius * point.radius).sqrt()
} else {
point.u.abs() * distance / (distance + point.depth)
};
half = half.max(projected);
}
Some(half)
}
}
fn resolve_params(
volume: &Volume,
options: &VolumeRenderOptions,
orbit_framing: bool,
) -> Result<VolumeRenderParams, VolumeRenderError> {
let mode = VolumeRenderMode::parse(options.mode.as_deref().unwrap_or("composite"))?;
let composite = mode == VolumeRenderMode::Composite;
if !composite {
if options.preset.is_some() || options.transfer_function.is_some() {
return Err(invalid(
"a transfer function / preset only applies to composite volume rendering",
));
}
if options.shading.is_some() {
return Err(invalid(
"shading only applies to composite volume rendering",
));
}
if options.background.is_some() {
return Err(invalid(
"a background color only applies to composite volume rendering",
));
}
} else if options.window_center.is_some() || options.window_width.is_some() {
return Err(invalid(
"window center/width only apply to the mip, minip and average volume render modes",
));
}
if options.window_center.is_some() != options.window_width.is_some() {
return Err(invalid(
"window center and window width must be given together",
));
}
if options.preset.is_some() && options.transfer_function.is_some() {
return Err(invalid(
"give either a transfer function preset or a custom transfer function, not both",
));
}
let transfer_function = if composite {
Some(match (&options.preset, &options.transfer_function) {
(Some(name), None) => TransferFunction::preset(name)?,
(None, Some(spec)) => TransferFunction::parse(spec)?,
_ => TransferFunction::default_for_modality(volume.modality.as_deref()),
})
} else {
None
};
let interpolation = match options.interpolation.as_deref().map(str::trim) {
None | Some("trilinear") => Interpolation::Trilinear,
Some("nearest") => Interpolation::Nearest,
Some(other) => {
return Err(invalid(format!(
"invalid interpolation '{other}'; expected 'trilinear' or 'nearest'"
)))
}
};
if let Some(crop) = &options.crop_voxels {
validate_box(crop, "the voxel crop box")?;
}
if let Some(crop) = &options.crop_mm {
validate_box(crop, "the millimeter crop box")?;
}
let (mut row_dir, mut col_dir) =
volume_render_view_basis(options.view.as_deref().unwrap_or("anterior"), volume)?;
if let Some([yaw, pitch, roll]) = options.rotation_deg {
if !(yaw.is_finite() && pitch.is_finite() && roll.is_finite()) {
return Err(invalid("rotation angles must be finite numbers"));
}
(row_dir, col_dir) = rotate_basis(row_dir, col_dir, yaw, pitch, roll);
}
if let Some(orbit) = options.orbit_deg {
if !orbit.is_finite() {
return Err(invalid("the orbit angle must be a finite number"));
}
(row_dir, col_dir) = orbit_basis(row_dir, col_dir, orbit);
}
let geometry = Geometry::new(volume);
let (box_low, box_high) = geometry.clip_box(options.crop_voxels.as_ref())?;
let corners = geometry.box_corners_world(box_low, box_high, options.crop_mm.as_ref());
let center = match options.center {
Some(center) => {
if !center.iter().all(|value| value.is_finite()) {
return Err(invalid("the render center must be finite numbers"));
}
center
}
None if options.crop_voxels.is_some() || options.crop_mm.is_some() => {
let mut sum = [0.0; 3];
for corner in &corners {
sum = add3(sum, *corner);
}
scale3(sum, 1.0 / corners.len().max(1) as f64)
}
None => volume.center(),
};
if let Some(fov) = options.perspective_fov_deg {
if !(fov > 0.0 && fov < 180.0) {
return Err(invalid(
"the perspective field of view must be between 0 and 180 degrees (exclusive)",
));
}
}
let view_dir = normalize3(cross3(row_dir, col_dir));
let framing = Framing {
points: corners
.iter()
.map(|corner| {
let rel = sub3(*corner, center);
let (u, depth) = (dot3(rel, row_dir), dot3(rel, view_dir));
FramingPoint {
u,
v: dot3(rel, col_dir),
depth,
radius: u.hypot(depth),
}
})
.collect(),
perspective_tan: options
.perspective_fov_deg
.map(|fov| (fov.to_radians() / 2.0).tan()),
orbit: orbit_framing,
};
let half_v = framing.half_v();
let base_spacing = volume.min_spacing_mm().max(1e-4);
if let Some(spacing) = options.spacing_mm {
if !(spacing > 0.0) || !spacing.is_finite() {
return Err(invalid("the output spacing must be greater than zero"));
}
}
let zoom = options.zoom.unwrap_or(1.0);
if !(zoom > 0.0) || !zoom.is_finite() {
return Err(invalid("zoom must be greater than zero"));
}
let mut spacing_mm = options.spacing_mm.unwrap_or(base_spacing);
let fit = |spacing: f64, half: f64| ((2.0 * half / spacing).ceil() as u32).saturating_add(1);
let half_u = |height: u32, spacing: f64| {
let height = options.output_height.unwrap_or(height);
framing
.half_u(f64::from(height) * spacing / 2.0)
.unwrap_or_else(|| framing.orthographic_half_u())
};
let mut height = fit(spacing_mm, half_v);
let mut width = fit(spacing_mm, half_u(height, spacing_mm));
if options.spacing_mm.is_none() {
if let Some(cap) = options.max_dim.filter(|&cap| cap > 0) {
let longest = width.max(height);
if longest > cap {
spacing_mm *= f64::from(longest) / f64::from(cap);
height = fit(spacing_mm, half_v).min(cap);
width = fit(spacing_mm, half_u(height, spacing_mm)).min(cap);
}
}
}
let output_width = options.output_width.unwrap_or(width);
let output_height = options.output_height.unwrap_or(height);
validate_output_dimensions(output_width, output_height)?;
spacing_mm /= zoom;
let step_mm = options.step_mm.unwrap_or(base_spacing * 0.5);
if !(step_mm > 0.0) || !step_mm.is_finite() {
return Err(invalid("the sample step must be greater than zero"));
}
validate_sample_budget(&geometry, box_low, box_high, step_mm)?;
Ok(VolumeRenderParams {
mode,
center,
row_dir,
col_dir,
output_width,
output_height,
spacing_mm,
step_mm,
perspective_fov_deg: options.perspective_fov_deg,
transfer_function,
shading: composite && options.shading.unwrap_or(true),
window_center: options.window_center,
window_width: options.window_width,
crop_voxels: options.crop_voxels,
crop_mm: options.crop_mm,
background: options.background.unwrap_or([0, 0, 0]),
interpolation,
})
}
pub const MAX_VOLUME_RENDER_OUTPUT_PIXELS: u64 = 100_000_000;
pub const MAX_VOLUME_RENDER_SAMPLES_PER_RAY: u64 = 1 << 18;
fn validate_output_dimensions(width: u32, height: u32) -> Result<(), VolumeRenderError> {
if width == 0 || height == 0 || width > u16::MAX as u32 || height > u16::MAX as u32 {
return Err(VolumeRenderError::InvalidOutputDimensions);
}
let pixels = u64::from(width) * u64::from(height);
if pixels > MAX_VOLUME_RENDER_OUTPUT_PIXELS {
return Err(invalid(format!(
"a {width}x{height} volume rendering ({pixels} pixels) exceeds the {MAX_VOLUME_RENDER_OUTPUT_PIXELS}-pixel output limit"
)));
}
Ok(())
}
fn validate_sample_budget(
geometry: &Geometry<'_>,
low: Vec3,
high: Vec3,
step_mm: f64,
) -> Result<(), VolumeRenderError> {
let spacings = [
geometry.col_spacing,
geometry.row_spacing,
geometry.slice_spacing,
];
let longest_path_mm: f64 = (0..3)
.map(|axis| (high[axis] - low[axis]).max(0.0) * spacings[axis])
.sum();
let samples = longest_path_mm / step_mm + 1.0;
if !(samples <= MAX_VOLUME_RENDER_SAMPLES_PER_RAY as f64) {
return Err(invalid(format!(
"the sample step {step_mm} mm is too small for this volume: rays up to {longest_path_mm:.1} mm long would take more than {MAX_VOLUME_RENDER_SAMPLES_PER_RAY} samples (use a step of at least {:.4} mm)",
longest_path_mm / (MAX_VOLUME_RENDER_SAMPLES_PER_RAY - 1) as f64
)));
}
Ok(())
}
struct Geometry<'a> {
samples: &'a [f32],
cols: usize,
rows: usize,
slices: usize,
origin: Vec3,
row_vector: Vec3,
col_vector: Vec3,
slice_normal: Vec3,
col_spacing: f64,
row_spacing: f64,
slice_spacing: f64,
irregular: Option<SlicePositions>,
}
struct SlicePositions {
zs: Vec<f32>,
interval_at: Vec<u32>,
}
const SLICE_CELLS_PER_UNIT: usize = 8;
impl SlicePositions {
fn new(slice_zs: &[f64], nominal_spacing: f64) -> Self {
let first = slice_zs[0];
let zs: Vec<f32> = slice_zs
.iter()
.map(|&z| ((z - first) / nominal_spacing) as f32)
.collect();
let last_interval = zs.len().saturating_sub(2);
let cells = (f64::from(zs[zs.len() - 1]).max(0.0) * SLICE_CELLS_PER_UNIT as f64).ceil()
as usize
+ 1;
let mut interval_at = Vec::with_capacity(cells);
let mut k = 0usize;
for cell in 0..cells {
let u = cell as f32 / SLICE_CELLS_PER_UNIT as f32;
while k < last_interval && zs[k + 1] <= u {
k += 1;
}
interval_at.push(k as u32);
}
Self { zs, interval_at }
}
#[inline(always)]
fn real_index(&self, u: f32) -> f32 {
let zs = &self.zs;
let last_interval = zs.len() - 2;
let cell =
((u.max(0.0) * SLICE_CELLS_PER_UNIT as f32) as usize).min(self.interval_at.len() - 1);
let mut k = self.interval_at[cell] as usize;
while k < last_interval && zs[k + 1] <= u {
k += 1;
}
let gap = (zs[k + 1] - zs[k]).max(1e-6);
k as f32 + (u - zs[k]) / gap
}
fn uniform_coordinate(&self, r: f64) -> f64 {
let zs = &self.zs;
let last = zs.len() - 1;
if r <= 0.0 {
return f64::from(zs[0]) + r;
}
if r >= last as f64 {
return f64::from(zs[last]) + (r - last as f64);
}
let k = (r.floor() as usize).min(last - 1);
let t = r - k as f64;
f64::from(zs[k]) + (f64::from(zs[k + 1]) - f64::from(zs[k])) * t
}
}
const BLOCK_SHIFT: usize = 3;
const BLOCK: usize = 1 << BLOCK_SHIFT;
impl<'a> Geometry<'a> {
fn new(volume: &'a Volume) -> Self {
let slices = volume.num_slices.max(1) as usize;
let nominal = volume.nominal_slice_spacing_mm();
let slice_spacing = if nominal > 0.0 { nominal } else { 1.0 };
let irregular = (volume.has_irregular_spacing() && slices >= 3)
.then(|| SlicePositions::new(&volume.slice_zs, slice_spacing));
Self {
samples: &volume.samples,
cols: volume.cols.max(1) as usize,
rows: volume.rows.max(1) as usize,
slices,
origin: volume.origin,
row_vector: volume.row_vector,
col_vector: volume.col_vector,
slice_normal: volume.slice_normal,
col_spacing: volume.col_spacing_mm,
row_spacing: volume.row_spacing_mm,
slice_spacing,
irregular,
}
}
fn world_to_index(&self, world: Vec3) -> Vec3 {
let delta = sub3(world, self.origin);
[
dot3(delta, self.row_vector) / self.col_spacing,
dot3(delta, self.col_vector) / self.row_spacing,
dot3(delta, self.slice_normal) / self.slice_spacing,
]
}
fn direction_to_index(&self, direction: Vec3) -> Vec3 {
[
dot3(direction, self.row_vector) / self.col_spacing,
dot3(direction, self.col_vector) / self.row_spacing,
dot3(direction, self.slice_normal) / self.slice_spacing,
]
}
fn index_to_world(&self, index: Vec3) -> Vec3 {
add3(
add3(
add3(
self.origin,
scale3(self.row_vector, index[0] * self.col_spacing),
),
scale3(self.col_vector, index[1] * self.row_spacing),
),
scale3(self.slice_normal, index[2] * self.slice_spacing),
)
}
fn clip_box(&self, crop: Option<&[f64; 6]>) -> Result<(Vec3, Vec3), VolumeRenderError> {
let mut low: Vec3 = [-0.5; 3];
let mut high = [
self.cols as f64 - 0.5,
self.rows as f64 - 0.5,
self.slices as f64 - 0.5,
];
if let Some(crop) = crop {
for axis in 0..3 {
let (mut crop_low, mut crop_high) =
(crop[axis * 2] - 0.5, crop[axis * 2 + 1] + 0.5);
if axis == 2 {
if let Some(positions) = &self.irregular {
crop_low = positions.uniform_coordinate(crop_low);
crop_high = positions.uniform_coordinate(crop_high);
}
}
low[axis] = low[axis].max(crop_low);
high[axis] = high[axis].min(crop_high);
if !(low[axis] < high[axis]) {
let (name, size) = match axis {
0 => ("column", self.cols),
1 => ("row", self.rows),
_ => ("slice", self.slices),
};
return Err(invalid(format!(
"the voxel crop box's {name} range {}..{} does not overlap the volume's {size} {name}s (0..{})",
crop[axis * 2],
crop[axis * 2 + 1],
size.saturating_sub(1)
)));
}
}
}
Ok((low, high))
}
fn box_corners_world(&self, low: Vec3, high: Vec3, crop_mm: Option<&[f64; 6]>) -> Vec<Vec3> {
let mut corners = Vec::with_capacity(8);
for &x in &[low[0], high[0]] {
for &y in &[low[1], high[1]] {
for &z in &[low[2], high[2]] {
let mut world = self.index_to_world([x, y, z]);
if let Some(crop) = crop_mm {
for axis in 0..3 {
world[axis] = world[axis].clamp(crop[axis * 2], crop[axis * 2 + 1]);
}
}
corners.push(world);
}
}
}
corners
}
#[inline(always)]
fn voxel(&self, col: usize, row: usize, slice: usize) -> f32 {
self.samples[(slice * self.rows + row) * self.cols + col]
}
#[inline(always)]
fn real_slice(&self, z: f32) -> f32 {
match &self.irregular {
None => z,
Some(positions) => positions.real_index(z),
}
}
#[inline(always)]
fn cell(&self, x: f32, y: f32, z: f32) -> ([usize; 3], [f32; 3]) {
let z = self.real_slice(z);
let clamp = |value: f32, size: usize| -> (usize, f32) {
let max = (size - 1) as f32;
let value = value.clamp(0.0, max);
let base = (value as usize).min(size.saturating_sub(2));
(base, value - base as f32)
};
let (x0, fx) = clamp(x, self.cols);
let (y0, fy) = clamp(y, self.rows);
let (z0, fz) = clamp(z, self.slices);
([x0, y0, z0], [fx, fy, fz])
}
#[inline(always)]
fn sample_cell(&self, base: [usize; 3], frac: [f32; 3], nearest: bool) -> f32 {
let [x0, y0, z0] = base;
let x1 = (x0 + 1).min(self.cols - 1);
let y1 = (y0 + 1).min(self.rows - 1);
let z1 = (z0 + 1).min(self.slices - 1);
let [fx, fy, fz] = frac;
if nearest {
return self.voxel(
if fx >= 0.5 { x1 } else { x0 },
if fy >= 0.5 { y1 } else { y0 },
if fz >= 0.5 { z1 } else { z0 },
);
}
let plane = self.rows * self.cols;
let s = self.samples;
let i000 = (z0 * self.rows + y0) * self.cols;
let i010 = (z0 * self.rows + y1) * self.cols;
let i001 = i000 + (z1 - z0) * plane;
let i011 = i010 + (z1 - z0) * plane;
let lerp = |a: f32, b: f32, t: f32| a + (b - a) * t;
let c00 = lerp(s[i000 + x0], s[i000 + x1], fx);
let c10 = lerp(s[i010 + x0], s[i010 + x1], fx);
let c01 = lerp(s[i001 + x0], s[i001 + x1], fx);
let c11 = lerp(s[i011 + x0], s[i011 + x1], fx);
lerp(lerp(c00, c10, fy), lerp(c01, c11, fy), fz)
}
#[inline(always)]
fn sample(&self, x: f32, y: f32, z: f32, nearest: bool) -> f32 {
let (base, frac) = self.cell(x, y, z);
self.sample_cell(base, frac, nearest)
}
fn gradient_world(&self, x: f32, y: f32, z: f32) -> Vec3 {
let gx = (self.sample(x + 1.0, y, z, false) - self.sample(x - 1.0, y, z, false)) as f64
/ (2.0 * self.col_spacing);
let gy = (self.sample(x, y + 1.0, z, false) - self.sample(x, y - 1.0, z, false)) as f64
/ (2.0 * self.row_spacing);
let gz = (self.sample(x, y, z + 1.0, false) - self.sample(x, y, z - 1.0, false)) as f64
/ (2.0 * self.slice_spacing);
add3(
add3(scale3(self.row_vector, gx), scale3(self.col_vector, gy)),
scale3(self.slice_normal, gz),
)
}
}
struct BlockGrid {
nx: usize,
ny: usize,
min: Vec<f32>,
max: Vec<f32>,
}
impl BlockGrid {
fn new(geometry: &Geometry<'_>) -> Self {
let nx = geometry.cols.div_ceil(BLOCK);
let ny = geometry.rows.div_ceil(BLOCK);
let nz = geometry.slices.div_ceil(BLOCK);
let per_layer = nx * ny;
let mut min = vec![f32::INFINITY; per_layer * nz];
let mut max = vec![f32::NEG_INFINITY; per_layer * nz];
let fill_layer = |(bz, (min_layer, max_layer)): (usize, (&mut [f32], &mut [f32]))| {
let z_start = bz * BLOCK;
let z_end = ((bz + 1) * BLOCK).min(geometry.slices - 1);
for z in z_start..=z_end {
for y in 0..geometry.rows {
let by = y >> BLOCK_SHIFT;
let also_above = y > 0 && y % BLOCK == 0;
let row_offset = (z * geometry.rows + y) * geometry.cols;
let row = &geometry.samples[row_offset..row_offset + geometry.cols];
for bx in 0..nx {
let x_start = bx * BLOCK;
let x_end = ((bx + 1) * BLOCK).min(geometry.cols - 1);
let mut low = f32::INFINITY;
let mut high = f32::NEG_INFINITY;
for &value in &row[x_start..=x_end] {
low = low.min(value);
high = high.max(value);
}
let mut update = |index: usize| {
min_layer[index] = min_layer[index].min(low);
max_layer[index] = max_layer[index].max(high);
};
update(by * nx + bx);
if also_above {
update((by - 1) * nx + bx);
}
}
}
}
};
#[cfg(not(target_arch = "wasm32"))]
min.par_chunks_mut(per_layer)
.zip(max.par_chunks_mut(per_layer))
.enumerate()
.for_each(fill_layer);
#[cfg(target_arch = "wasm32")]
min.chunks_mut(per_layer)
.zip(max.chunks_mut(per_layer))
.enumerate()
.for_each(fill_layer);
Self { nx, ny, min, max }
}
#[inline(always)]
fn index(&self, base: [usize; 3]) -> usize {
((base[2] >> BLOCK_SHIFT) * self.ny + (base[1] >> BLOCK_SHIFT)) * self.nx
+ (base[0] >> BLOCK_SHIFT)
}
fn value_range(&self) -> (f32, f32) {
let low = self.min.iter().copied().fold(f32::INFINITY, f32::min);
let high = self.max.iter().copied().fold(f32::NEG_INFINITY, f32::max);
(low, high)
}
}
struct Ray {
start: [f32; 3],
step: [f32; 3],
count: usize,
direction: Vec3,
}
struct Caster<'a> {
geometry: Geometry<'a>,
params: &'a VolumeRenderParams,
box_low: Vec3,
box_high: Vec3,
view_dir: Vec3,
row_dir: Vec3,
col_dir: Vec3,
eye: Option<Vec3>,
}
impl<'a> Caster<'a> {
fn new(volume: &'a Volume, params: &'a VolumeRenderParams) -> Result<Self, VolumeRenderError> {
let geometry = Geometry::new(volume);
let (box_low, box_high) = geometry.clip_box(params.crop_voxels.as_ref())?;
validate_sample_budget(&geometry, box_low, box_high, params.step_mm)?;
let row_dir = normalize3(params.row_dir);
let col_dir = normalize3(sub3(
params.col_dir,
scale3(row_dir, dot3(params.col_dir, row_dir)),
));
let view_dir = normalize3(cross3(row_dir, col_dir));
let eye = params.perspective_fov_deg.map(|fov| {
let half_height = params.output_height as f64 * params.spacing_mm / 2.0;
let distance = half_height / (fov.to_radians() / 2.0).tan();
sub3(params.center, scale3(view_dir, distance))
});
Ok(Self {
geometry,
params,
box_low,
box_high,
view_dir,
row_dir,
col_dir,
eye,
})
}
fn ray(&self, px: usize, py: usize) -> Option<Ray> {
let params = self.params;
let half_width = params.output_width as f64 / 2.0;
let half_height = params.output_height as f64 / 2.0;
let pixel = add3(
params.center,
add3(
scale3(self.row_dir, (px as f64 - half_width) * params.spacing_mm),
scale3(self.col_dir, (py as f64 - half_height) * params.spacing_mm),
),
);
let (origin, direction, mut t_enter, mut t_exit) = match self.eye {
Some(eye) => (eye, normalize3(sub3(pixel, eye)), 0.0, f64::INFINITY),
None => (pixel, self.view_dir, f64::NEG_INFINITY, f64::INFINITY),
};
let index_origin = self.geometry.world_to_index(origin);
let index_direction = self.geometry.direction_to_index(direction);
for axis in 0..3 {
clip_slab(
index_origin[axis],
index_direction[axis],
self.box_low[axis],
self.box_high[axis],
&mut t_enter,
&mut t_exit,
)?;
}
if let Some(crop) = ¶ms.crop_mm {
for axis in 0..3 {
clip_slab(
origin[axis],
direction[axis],
crop[axis * 2],
crop[axis * 2 + 1],
&mut t_enter,
&mut t_exit,
)?;
}
}
if !(t_exit >= t_enter) || !t_enter.is_finite() || !t_exit.is_finite() {
return None;
}
let step_mm = params.step_mm;
let first = (t_enter / step_mm).ceil() * step_mm;
if first > t_exit {
return None;
}
let count = ((t_exit - first) / step_mm)
.floor()
.min(MAX_VOLUME_RENDER_SAMPLES_PER_RAY as f64) as usize
+ 1;
let start = add3(index_origin, scale3(index_direction, first));
let step = scale3(index_direction, step_mm);
Some(Ray {
start: start.map(|v| v as f32),
step: step.map(|v| v as f32),
count,
direction,
})
}
}
fn clip_slab(
origin: f64,
direction: f64,
low: f64,
high: f64,
t_enter: &mut f64,
t_exit: &mut f64,
) -> Option<()> {
if direction.abs() < 1e-12 {
if origin < low || origin > high {
return None;
}
return Some(());
}
let mut t0 = (low - origin) / direction;
let mut t1 = (high - origin) / direction;
if t0 > t1 {
std::mem::swap(&mut t0, &mut t1);
}
*t_enter = t_enter.max(t0);
*t_exit = t_exit.min(t1);
if *t_enter > *t_exit {
return None;
}
Some(())
}
#[inline(always)]
fn steps_to_leave_block(base: [usize; 3], position: [f32; 3], step: [f32; 3]) -> usize {
let mut steps = f32::INFINITY;
for axis in 0..3 {
let d = step[axis];
let block_start = ((base[axis] >> BLOCK_SHIFT) << BLOCK_SHIFT) as f32;
let to_exit = if d > 1e-9 {
(block_start + BLOCK as f32 - position[axis]) / d
} else if d < -1e-9 {
(position[axis] - block_start) / -d + 1e-4
} else {
continue;
};
steps = steps.min(to_exit);
}
if steps.is_finite() && steps > 1.0 {
steps.ceil() as usize
} else {
1
}
}
fn cast_projection(caster: &Caster<'_>, blocks: &BlockGrid, ray: &Ray) -> Option<f32> {
let geometry = &caster.geometry;
let nearest = caster.params.interpolation == Interpolation::Nearest;
let can_jump = geometry.irregular.is_none();
let [x0, y0, z0] = ray.start;
let [dx, dy, dz] = ray.step;
let mode = caster.params.mode;
let mut best = match mode {
VolumeRenderMode::MinimumIntensity => f32::INFINITY,
_ => f32::NEG_INFINITY,
};
if ray.count == 0 {
return None;
}
if mode == VolumeRenderMode::Average {
let mut sum = 0.0f64;
for i in 0..ray.count {
let t = i as f32;
let (base, frac) = geometry.cell(x0 + dx * t, y0 + dy * t, z0 + dz * t);
sum += f64::from(geometry.sample_cell(base, frac, nearest));
}
return Some((sum / ray.count as f64) as f32);
}
let maximum = mode == VolumeRenderMode::MaximumIntensity;
let mut i = 0usize;
while i < ray.count {
let t = i as f32;
let position = [x0 + dx * t, y0 + dy * t, z0 + dz * t];
let (base, frac) = geometry.cell(position[0], position[1], position[2]);
let block = blocks.index(base);
let skip = if maximum {
blocks.max[block] <= best
} else {
blocks.min[block] >= best
};
if skip {
i += if can_jump {
steps_to_leave_block(base, position, ray.step)
} else {
1
};
continue;
}
let value = geometry.sample_cell(base, frac, nearest);
best = if maximum {
best.max(value)
} else {
best.min(value)
};
i += 1;
}
Some(best)
}
const AMBIENT: f32 = 0.25;
const DIFFUSE: f32 = 0.75;
const SPECULAR: f32 = 0.3;
const SHININESS: i32 = 24;
const OPAQUE: f32 = 0.99;
fn cast_composite(
caster: &Caster<'_>,
blocks: &BlockGrid,
lut: &TransferLut,
transparent_blocks: &[bool],
ray: &Ray,
) -> [f32; 4] {
let geometry = &caster.geometry;
let nearest = caster.params.interpolation == Interpolation::Nearest;
let shading = caster.params.shading;
let light = scale3(ray.direction, -1.0);
let can_jump = geometry.irregular.is_none();
let [x0, y0, z0] = ray.start;
let [dx, dy, dz] = ray.step;
let mut color = [0.0f32; 3];
let mut alpha = 0.0f32;
let mut i = 0usize;
while i < ray.count {
let t = i as f32;
let (sx, sy, sz) = (x0 + dx * t, y0 + dy * t, z0 + dz * t);
let (base, frac) = geometry.cell(sx, sy, sz);
if transparent_blocks[blocks.index(base)] {
i += if can_jump {
steps_to_leave_block(base, [sx, sy, sz], ray.step)
} else {
1
};
continue;
}
i += 1;
let value = geometry.sample_cell(base, frac, nearest);
let [r, g, b, a] = lut.lookup(value);
if a <= 0.0 {
continue;
}
let mut sample_color = [r, g, b];
if shading {
let gradient = geometry.gradient_world(sx, sy, sz);
let magnitude = norm3(gradient);
if magnitude > 1e-6 {
let n_dot_l = (dot3(gradient, light) / magnitude).abs() as f32;
let diffuse = AMBIENT + DIFFUSE * n_dot_l;
let specular = SPECULAR * n_dot_l.powi(SHININESS);
sample_color = sample_color.map(|c| (c * diffuse + specular).min(1.0));
}
}
let weight = (1.0 - alpha) * a;
for k in 0..3 {
color[k] += weight * sample_color[k];
}
alpha += weight;
if alpha >= OPAQUE {
break;
}
}
[color[0], color[1], color[2], alpha]
}
fn for_each_pixel<T: Copy + Send + Sync + Default>(
width: usize,
height: usize,
channels: usize,
per_pixel: impl Fn(usize, usize, &mut [T]) + Send + Sync,
) -> Vec<T> {
let mut out = vec![T::default(); width * height * channels];
let row_len = width * channels;
let fill_row = |(py, row): (usize, &mut [T])| {
for px in 0..width {
per_pixel(px, py, &mut row[px * channels..(px + 1) * channels]);
}
};
#[cfg(not(target_arch = "wasm32"))]
out.par_chunks_mut(row_len).enumerate().for_each(fill_row);
#[cfg(target_arch = "wasm32")]
out.chunks_mut(row_len).enumerate().for_each(fill_row);
out
}
fn validate_params(params: &VolumeRenderParams) -> Result<(), VolumeRenderError> {
validate_output_dimensions(params.output_width, params.output_height)?;
if !(params.spacing_mm > 0.0) || !params.spacing_mm.is_finite() {
return Err(invalid("the output spacing must be greater than zero"));
}
if !(params.step_mm > 0.0) || !params.step_mm.is_finite() {
return Err(invalid("the sample step must be greater than zero"));
}
if norm3(cross3(params.row_dir, params.col_dir)) < 1e-6 {
return Err(invalid(
"the camera row and column directions must not be parallel",
));
}
if let Some(fov) = params.perspective_fov_deg {
if !(fov > 0.0 && fov < 180.0) {
return Err(invalid(
"the perspective field of view must be between 0 and 180 degrees (exclusive)",
));
}
}
Ok(())
}
pub fn render_volume_values(
volume: &Volume,
params: &VolumeRenderParams,
) -> Result<Vec<f32>, VolumeRenderError> {
validate_params(params)?;
if params.mode == VolumeRenderMode::Composite {
return Err(invalid(
"composite volume rendering produces colors, not values; use render_volume_pixels",
));
}
let caster = Caster::new(volume, params)?;
let blocks = BlockGrid::new(&caster.geometry);
let values: Vec<f32> = for_each_pixel(
params.output_width as usize,
params.output_height as usize,
1,
|px, py, out: &mut [f32]| {
out[0] = caster
.ray(px, py)
.and_then(|ray| cast_projection(&caster, &blocks, &ray))
.unwrap_or(f32::NAN);
},
);
let background = values
.iter()
.copied()
.filter(|value| !value.is_nan())
.fold(f32::INFINITY, f32::min);
let background = if background.is_finite() {
background
} else {
0.0
};
Ok(values
.into_iter()
.map(|value| if value.is_nan() { background } else { value })
.collect())
}
#[derive(Clone, Debug)]
pub struct VolumeRenderPixels {
pub width: u32,
pub height: u32,
pub samples_per_pixel: u16,
pub pixels: Vec<u8>,
}
impl VolumeRenderPixels {
pub fn to_rgba(&self) -> Vec<u8> {
match self.samples_per_pixel {
4 => self.pixels.clone(),
_ => self
.pixels
.iter()
.flat_map(|&value| [value, value, value, 255])
.collect(),
}
}
pub fn flatten(&self, background: [u8; 3]) -> (u16, Vec<u8>) {
match self.samples_per_pixel {
4 => (
3,
self.pixels
.chunks_exact(4)
.flat_map(|pixel| {
let alpha = f32::from(pixel[3]) / 255.0;
[0, 1, 2].map(|k| {
(f32::from(pixel[k]) * alpha + f32::from(background[k]) * (1.0 - alpha))
.round()
.clamp(0.0, 255.0) as u8
})
})
.collect(),
),
spp => (spp, self.pixels.clone()),
}
}
}
pub fn render_volume_pixels(
volume: &Volume,
params: &VolumeRenderParams,
) -> Result<VolumeRenderPixels, VolumeRenderError> {
validate_params(params)?;
let width = params.output_width as usize;
let height = params.output_height as usize;
if params.mode != VolumeRenderMode::Composite {
let values = render_volume_values(volume, params)?;
let filled: Vec<f64> = values.into_iter().map(f64::from).collect();
return Ok(VolumeRenderPixels {
width: params.output_width,
height: params.output_height,
samples_per_pixel: 1,
pixels: apply_explicit_window(&filled, params.window_center, params.window_width),
});
}
let function = params
.transfer_function
.clone()
.unwrap_or_else(|| TransferFunction::default_for_modality(volume.modality.as_deref()));
let caster = Caster::new(volume, params)?;
let blocks = BlockGrid::new(&caster.geometry);
let (data_min, data_max) = blocks.value_range();
let lut = TransferLut::new(
&function,
f64::from(data_min),
f64::from(data_max),
params.step_mm,
);
let transparent_blocks: Vec<bool> = blocks
.min
.iter()
.zip(&blocks.max)
.map(|(&low, &high)| low > high || lut.transparent_between(low, high))
.collect();
let pixels: Vec<u8> = for_each_pixel(width, height, 4, |px, py, out: &mut [u8]| {
let Some(ray) = caster.ray(px, py) else {
return;
};
let [r, g, b, a] = cast_composite(&caster, &blocks, &lut, &transparent_blocks, &ray);
if a <= 0.0 {
return;
}
let to_byte = |value: f32| (value * 255.0).round().clamp(0.0, 255.0) as u8;
out[0] = to_byte(r / a);
out[1] = to_byte(g / a);
out[2] = to_byte(b / a);
out[3] = to_byte(a);
});
Ok(VolumeRenderPixels {
width: params.output_width,
height: params.output_height,
samples_per_pixel: 4,
pixels,
})
}
pub fn render_volume(
volume: &Volume,
params: &VolumeRenderParams,
output_format: RenderOutputFormat,
jpeg_quality: u8,
) -> Result<RenderFrameOutput, VolumeRenderError> {
let rendered = render_volume_pixels(volume, params)?;
let (samples_per_pixel, bytes) = rendered.flatten(params.background);
let frame = RenderedFramePixels {
width: rendered.width as u16,
height: rendered.height as u16,
samples_per_pixel,
bytes,
};
Ok(encode_rendered_frame(&frame, output_format, jpeg_quality)?)
}
fn dot3(a: Vec3, b: Vec3) -> f64 {
a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
}
fn cross3(a: Vec3, b: Vec3) -> Vec3 {
[
a[1] * b[2] - a[2] * b[1],
a[2] * b[0] - a[0] * b[2],
a[0] * b[1] - a[1] * b[0],
]
}
fn sub3(a: Vec3, b: Vec3) -> Vec3 {
[a[0] - b[0], a[1] - b[1], a[2] - b[2]]
}
fn add3(a: Vec3, b: Vec3) -> Vec3 {
[a[0] + b[0], a[1] + b[1], a[2] + b[2]]
}
fn scale3(a: Vec3, s: f64) -> Vec3 {
[a[0] * s, a[1] * s, a[2] * s]
}
fn norm3(a: Vec3) -> f64 {
dot3(a, a).sqrt()
}
fn normalize3(a: Vec3) -> Vec3 {
let length = norm3(a).max(1e-12);
scale3(a, 1.0 / length)
}