use crate::{
simplify_generic, simplify_scale, simplify_with_attributes_generic, Attributes, Error, Limits,
Positions, SimplifyOptions, SimplifySettings, Usage, VertexFlags, Workspace,
};
use alloc::vec::Vec;
use core::fmt;
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub enum LodTargets<'a> {
Counts(&'a [usize]),
Ratios(&'a [f32]),
}
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub enum LodErrors<'a> {
Uniform(f32),
PerLevel(&'a [f32]),
}
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct LodChainAttributes<'a> {
pub attributes: Attributes<'a>,
pub weights: &'a [f32],
}
impl<'a> LodChainAttributes<'a> {
pub fn new(attributes: Attributes<'a>, weights: &'a [f32]) -> Self {
Self {
attributes,
weights,
}
}
}
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub struct LodChainOptions<'a> {
pub targets: LodTargets<'a>,
pub errors: LodErrors<'a>,
pub simplify_options: SimplifyOptions,
pub attributes: Option<LodChainAttributes<'a>>,
pub vertex_flags: Option<&'a [VertexFlags]>,
pub independent: bool,
}
impl<'a> LodChainOptions<'a> {
pub fn new(targets: LodTargets<'a>, errors: LodErrors<'a>) -> Self {
Self {
targets,
errors,
simplify_options: SimplifyOptions::EMPTY,
attributes: None,
vertex_flags: None,
independent: false,
}
}
#[must_use]
pub fn with_simplify_options(mut self, options: SimplifyOptions) -> Self {
self.simplify_options = options;
self
}
#[must_use]
pub fn with_attributes(mut self, attributes: LodChainAttributes<'a>) -> Self {
self.attributes = Some(attributes);
self
}
#[must_use]
pub fn with_vertex_flags(mut self, flags: &'a [VertexFlags]) -> Self {
self.vertex_flags = Some(flags);
self
}
#[must_use]
pub fn with_independent(mut self, independent: bool) -> Self {
self.independent = independent;
self
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct LodLevelGeneric<I: crate::Index = u32> {
pub indices: Vec<I>,
pub error: f32,
pub scale: f32,
pub triangle_count: usize,
pub target_reached: bool,
pub stopped_at_error_limit: bool,
}
#[derive(Debug)]
#[non_exhaustive]
pub struct LodChainGeneric<I: crate::Index = u32> {
pub levels: Vec<LodLevelGeneric<I>>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct LodChainError {
pub level: Option<usize>,
pub error: Error,
}
impl fmt::Display for LodChainError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.level {
Some(level) => write!(f, "LOD level {level}: {}", self.error),
None => write!(f, "LOD chain: {}", self.error),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for LodChainError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
Some(&self.error)
}
}
struct Meter {
limit: u64,
spent: u64,
peak: usize,
}
impl Meter {
fn charge(&mut self, visits: usize) -> Result<(), Error> {
let visits = u64::try_from(visits).map_err(|_| Error::SizeOverflow)?;
self.spent = self.spent.saturating_add(visits);
if self.spent > self.limit {
return Err(Error::LimitExceeded);
}
Ok(())
}
}
pub fn build_lod_chain_generic<I: crate::Index>(
indices: &[I],
positions: Positions<'_>,
options: &LodChainOptions<'_>,
workspace: &mut Workspace,
) -> Result<LodChainGeneric<I>, LodChainError> {
build_lod_chain_internal(indices, positions, options, workspace, false)
}
pub(crate) fn build_lod_chain_internal<I: crate::Index>(
indices: &[I],
positions: Positions<'_>,
options: &LodChainOptions<'_>,
workspace: &mut Workspace,
allow_equal: bool,
) -> Result<LodChainGeneric<I>, LodChainError> {
let limits = workspace.limits();
let mut meter = Meter {
limit: limits.max_work,
spent: 0,
peak: 0,
};
let result = build(
indices,
positions,
options,
workspace,
limits,
&mut meter,
allow_equal,
);
workspace.set_lod_limits(limits);
workspace.set_lod_usage(Usage {
bytes: meter.peak,
work: meter.spent,
});
result
}
#[allow(clippy::too_many_arguments)]
fn build<I: crate::Index>(
indices: &[I],
positions: Positions<'_>,
options: &LodChainOptions<'_>,
workspace: &mut Workspace,
limits: Limits,
meter: &mut Meter,
allow_equal: bool,
) -> Result<LodChainGeneric<I>, LodChainError> {
let whole = |error: Error| LodChainError { level: None, error };
let at = |level: usize| {
move |error: Error| LodChainError {
level: Some(level),
error,
}
};
let len = match options.targets {
LodTargets::Counts(v) => v.len(),
LodTargets::Ratios(v) => v.len(),
};
if len == 0 {
return Err(whole(Error::InvalidParameter));
}
if let LodErrors::PerLevel(v) = options.errors {
if v.len() != len {
return Err(whole(Error::InvalidParameter));
}
}
meter.charge(len).map_err(whole)?;
let target = |i: usize| match options.targets {
LodTargets::Counts(v) => v[i],
LodTargets::Ratios(v) => {
((v[i] as f64 * (indices.len() / 3) as f64) as usize).saturating_mul(3)
}
};
let cap = |i: usize| match options.errors {
LodErrors::Uniform(v) => v,
LodErrors::PerLevel(v) => v[i],
};
let mut prev = indices.len();
let mut prev_ratio = 1.0f32;
for i in 0..len {
let t = target(i);
let e = cap(i);
let order_ok = match options.targets {
LodTargets::Counts(_) => t < prev || (allow_equal && len == 1 && t == prev),
LodTargets::Ratios(v) => {
let r = v[i];
let ok = r.is_finite() && r >= 0.0 && r < prev_ratio && t <= prev;
prev_ratio = r;
ok
}
};
if !order_ok || !e.is_finite() || e < 0.0 {
return Err(at(i)(Error::InvalidParameter));
}
prev = t;
}
let mut levels: Vec<LodLevelGeneric<I>> = Vec::new();
let metadata = len
.checked_mul(core::mem::size_of::<LodLevelGeneric<I>>())
.ok_or(Error::SizeOverflow)
.map_err(whole)?;
if metadata > limits.max_bytes {
meter.peak = metadata;
return Err(whole(Error::LimitExceeded));
}
levels
.try_reserve_exact(len)
.map_err(|_| whole(Error::AllocationFailed))?;
let mut used = levels
.capacity()
.checked_mul(core::mem::size_of::<LodLevelGeneric<I>>())
.ok_or(Error::SizeOverflow)
.map_err(whole)?;
meter.peak = used;
let sparse = options.simplify_options.contains(SimplifyOptions::SPARSE);
let mut dense_scale: Option<f32> = None;
for i in 0..len {
let input = if options.independent || i == 0 {
indices
} else {
&levels[i - 1].indices
};
let settings = SimplifySettings {
target_index_count: target(i).min(input.len()),
target_error: cap(i),
options: options.simplify_options,
};
workspace.set_lod_limits(Limits {
max_bytes: limits
.max_bytes
.checked_sub(used)
.ok_or(Error::LimitExceeded)
.map_err(at(i))?,
max_work: limits
.max_work
.checked_sub(meter.spent)
.ok_or(Error::LimitExceeded)
.map_err(at(i))?,
});
let result = match (options.attributes, options.vertex_flags) {
(Some(a), flags) => simplify_with_attributes_generic(
input,
positions,
a.attributes,
a.weights,
flags,
settings,
workspace,
),
(None, Some(flags)) => I::with_input(input, workspace, |input, workspace| {
crate::simplify::simplify_flagged(input, positions, flags, settings, workspace)
.and_then(|value| crate::index::Convert::<I>::convert(value, workspace))
}),
(None, None) => simplify_generic(input, positions, settings, workspace),
};
let error_limited = workspace.lod_error_limited;
let usage = workspace.usage();
meter.spent = meter.spent.saturating_add(usage.work);
meter.peak = meter.peak.max(used.saturating_add(usage.bytes));
let result = result.map_err(at(i))?;
let scale = if sparse {
meter.charge(input.len()).map_err(at(i))?;
sparse_scale(input, positions).map_err(at(i))?
} else if let Some(scale) = dense_scale {
scale
} else {
meter.charge(positions.len()).map_err(at(i))?;
let scale = simplify_scale(positions).map_err(at(i))?;
dense_scale = Some(scale);
scale
};
used = used
.checked_add(
result
.indices
.capacity()
.checked_mul(core::mem::size_of::<I>())
.ok_or(Error::SizeOverflow)
.map_err(at(i))?,
)
.ok_or(Error::SizeOverflow)
.map_err(at(i))?;
levels.push(LodLevelGeneric {
triangle_count: result.indices.len() / 3,
target_reached: result.indices.len() <= target(i),
stopped_at_error_limit: result.indices.len() > target(i) && error_limited,
indices: result.indices,
error: result.error,
scale,
});
}
Ok(LodChainGeneric { levels })
}
fn sparse_scale<I: crate::Index>(input: &[I], positions: Positions<'_>) -> Result<f32, Error> {
if input.is_empty() {
return Ok(0.0);
}
let mut lo = [f32::INFINITY; 3];
let mut hi = [f32::NEG_INFINITY; 3];
for &index in input {
let p = positions
.get(index.to_u32() as usize)
.ok_or(Error::IndexOutOfBounds)?;
for k in 0..3 {
lo[k] = lo[k].min(p[k]);
hi[k] = hi[k].max(p[k]);
}
}
Ok((hi[0] - lo[0]).max(hi[1] - lo[1]).max(hi[2] - lo[2]))
}
#[inline]
pub fn build_lod_chain(
indices: &[u32],
positions: Positions<'_>,
options: &LodChainOptions<'_>,
workspace: &mut Workspace,
) -> Result<LodChain, LodChainError> {
build_lod_chain_generic::<u32>(indices, positions, options, workspace).map(Into::into)
}
#[derive(Debug)]
#[non_exhaustive]
pub struct LodLevel {
pub indices: Vec<u32>,
pub error: f32,
pub scale: f32,
pub triangle_count: usize,
pub target_reached: bool,
pub stopped_at_error_limit: bool,
}
impl From<LodLevelGeneric<u32>> for LodLevel {
#[inline]
fn from(value: LodLevelGeneric<u32>) -> Self {
Self {
indices: value.indices,
error: value.error,
scale: value.scale,
triangle_count: value.triangle_count,
target_reached: value.target_reached,
stopped_at_error_limit: value.stopped_at_error_limit,
}
}
}
impl From<LodLevel> for LodLevelGeneric<u32> {
#[inline]
fn from(value: LodLevel) -> Self {
Self {
indices: value.indices,
error: value.error,
scale: value.scale,
triangle_count: value.triangle_count,
target_reached: value.target_reached,
stopped_at_error_limit: value.stopped_at_error_limit,
}
}
}
#[derive(Debug)]
#[non_exhaustive]
pub struct LodChain {
pub levels: Vec<LodLevel>,
}
impl From<LodChainGeneric<u32>> for LodChain {
#[inline]
fn from(value: LodChainGeneric<u32>) -> Self {
Self {
levels: value.levels.into_iter().map(Into::into).collect(),
}
}
}
impl From<LodChain> for LodChainGeneric<u32> {
#[inline]
fn from(value: LodChain) -> Self {
Self {
levels: value.levels.into_iter().map(Into::into).collect(),
}
}
}