euv-core 0.53.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
use super::*;

/// Wraps or clamps `time_secs` into `[0.0, duration_secs]` according to `repeat_mode`.
///
/// # Arguments
///
/// - `f32` - Unbounded layer playback clock in seconds.
/// - `f32` - Total animation clip duration in seconds.
/// - `NlaRepeatMode` - Playback wrap policy.
///
/// # Returns
///
/// - `f32` - Normalized evaluation timestamp in `[0.0, duration_secs]`.
#[must_use]
pub fn wrap_animation_time(time_secs: f32, duration_secs: f32, repeat_mode: NlaRepeatMode) -> f32 {
    if duration_secs <= ANIM_MIN_SPAN_SECS {
        return 0.0;
    }
    match repeat_mode {
        NlaRepeatMode::Loop => time_secs - (time_secs / duration_secs).floor() * duration_secs,
        NlaRepeatMode::Clamp => time_secs.clamp(0.0, duration_secs),
        NlaRepeatMode::PingPong => {
            let period: f32 = duration_secs * 2.0;
            let cycle_pos: f32 = time_secs - (time_secs / period).floor() * period;
            if cycle_pos <= duration_secs {
                cycle_pos
            } else {
                period - cycle_pos
            }
        }
    }
}

/// Applies sparse active Blender shape keys (`MorphTarget3D`) onto `base_vertices` into `out_vertices` with zero steady-state allocations.
///
/// # Arguments
///
/// - `&[Vertex3D]` - Undeformed base mesh vertices.
/// - `&[MorphTarget3D]` - Shape-key displacement targets aligned with `weights`.
/// - `&[f32]` - Active per-target morph blend weights.
/// - `&mut Vec<Vertex3D>` - Reusable destination vertex buffer populated in place.
///
/// # Returns
///
/// - `bool` - `true` when at least one non-zero shape key modified the output buffer.
pub fn apply_morph_targets_into(
    base_vertices: &[Vertex3D],
    morph_targets: &[MorphTarget3D],
    weights: &[f32],
    out_vertices: &mut Vec<Vertex3D>,
) -> bool {
    let target_count: usize = morph_targets.len().min(weights.len());
    let mut has_active_target: bool = false;
    for weight_val in weights.iter().take(target_count) {
        if weight_val.abs() > MORPH_WEIGHT_EPSILON {
            has_active_target = true;
            break;
        }
    }
    if !has_active_target || base_vertices.is_empty() {
        return false;
    }
    out_vertices.clear();
    if out_vertices.capacity() < base_vertices.len() {
        out_vertices.reserve(base_vertices.len() - out_vertices.len());
    }
    out_vertices.extend_from_slice(base_vertices);
    let vert_count: usize = out_vertices.len();
    let mut normals_modified: bool = false;
    let mut tangents_modified: bool = false;
    for target_idx in 0..target_count {
        let weight_val: f32 = weights[target_idx];
        if weight_val.abs() <= MORPH_WEIGHT_EPSILON {
            continue;
        }
        let target: &MorphTarget3D = &morph_targets[target_idx];
        let delta_positions: &[[f32; 3]] = target.get_delta_positions().as_slice();
        if delta_positions.len() >= vert_count {
            for vert_idx in 0..vert_count {
                let pos_cur: Vec3 = out_vertices[vert_idx].get_position();
                let delta_pos: [f32; 3] = delta_positions[vert_idx];
                out_vertices[vert_idx].set_position(Vec3::new(
                    pos_cur.get_x() + delta_pos[0] * weight_val,
                    pos_cur.get_y() + delta_pos[1] * weight_val,
                    pos_cur.get_z() + delta_pos[2] * weight_val,
                ));
            }
        }
        let delta_normals: &[[f32; 3]] = target.get_delta_normals().as_slice();
        if delta_normals.len() >= vert_count {
            normals_modified = true;
            for vert_idx in 0..vert_count {
                let norm_cur: Vec3 = out_vertices[vert_idx].get_normal();
                let delta_norm: [f32; 3] = delta_normals[vert_idx];
                out_vertices[vert_idx].set_normal(Vec3::new(
                    norm_cur.get_x() + delta_norm[0] * weight_val,
                    norm_cur.get_y() + delta_norm[1] * weight_val,
                    norm_cur.get_z() + delta_norm[2] * weight_val,
                ));
            }
        }
        let delta_tangents: &[[f32; 3]] = target.get_delta_tangents().as_slice();
        if delta_tangents.len() >= vert_count {
            tangents_modified = true;
            for vert_idx in 0..vert_count {
                let tan_cur: [f32; 4] = out_vertices[vert_idx].get_tangent();
                let delta_tan: [f32; 3] = delta_tangents[vert_idx];
                out_vertices[vert_idx].set_tangent([
                    tan_cur[0] + delta_tan[0] * weight_val,
                    tan_cur[1] + delta_tan[1] * weight_val,
                    tan_cur[2] + delta_tan[2] * weight_val,
                    tan_cur[3],
                ]);
            }
        }
    }
    if normals_modified {
        for vertex_item in out_vertices.iter_mut() {
            let norm_vec: Vec3 = vertex_item.get_normal();
            if norm_vec.length_sq() > 1.0e-10 {
                vertex_item.set_normal(norm_vec.normalize());
            }
        }
    }
    if tangents_modified {
        for vertex_item in out_vertices.iter_mut() {
            let tan_val: [f32; 4] = vertex_item.get_tangent();
            let tan_vec: Vec3 = Vec3::new(tan_val[0], tan_val[1], tan_val[2]);
            if tan_vec.length_sq() > 1.0e-10 {
                let norm_tan: Vec3 = tan_vec.normalize();
                vertex_item.set_tangent([
                    norm_tan.get_x(),
                    norm_tan.get_y(),
                    norm_tan.get_z(),
                    tan_val[3],
                ]);
            }
        }
    }
    true
}

/// Evaluates a glTF 2.0 animation sampler (`STEP`, `LINEAR`, or Hermite `CUBICSPLINE`) at `time_secs` into `out_values` with zero steady-state allocations.
///
/// # Arguments
///
/// - `&ImportedAnimationSampler3D` - Source glTF keyframe sampler.
/// - `f32` - Normalized playback timestamp in seconds.
/// - `bool` - Whether values represent unit quaternions `[x, y, z, w]` requiring shortest-arc SLERP and renormalization.
/// - `&mut Vec<f32>` - Reusable destination scalar slice overwritten with `value_stride` components.
pub fn sample_gltf_sampler_into(
    sampler: &ImportedAnimationSampler3D,
    time_secs: f32,
    is_rotation: bool,
    out_values: &mut Vec<f32>,
) {
    out_values.clear();
    let timestamps: &[f32] = sampler.get_timestamps().as_slice();
    let values: &[f32] = sampler.get_values().as_slice();
    let stride: usize = sampler.get_value_stride();
    if timestamps.is_empty() || stride == 0 {
        return;
    }
    let interp_mode: GltfInterpolationMode = sampler.get_interpolation();
    let is_cubic: bool = interp_mode == GltfInterpolationMode::CubicSpline;
    let frame_floats: usize = if is_cubic { stride * 3 } else { stride };
    let value_offset: usize = if is_cubic { stride } else { 0 };
    if values.len() < frame_floats {
        return;
    }
    let max_keys: usize = timestamps.len().min(values.len() / frame_floats);
    if max_keys == 0 {
        return;
    }
    let key_times: &[f32] = &timestamps[..max_keys];
    if out_values.capacity() < stride {
        out_values.reserve(stride - out_values.len());
    }
    if max_keys == 1 || time_secs <= key_times[0] {
        let start_idx: usize = value_offset;
        out_values.extend_from_slice(&values[start_idx..(start_idx + stride)]);
        normalize_quaternion_slice(out_values, is_rotation);
        return;
    }
    let last_idx: usize = max_keys - 1;
    if time_secs >= key_times[last_idx] {
        let start_idx: usize = last_idx * frame_floats + value_offset;
        out_values.extend_from_slice(&values[start_idx..(start_idx + stride)]);
        normalize_quaternion_slice(out_values, is_rotation);
        return;
    }
    let upper_pos: usize = key_times.partition_point(|stamp_val: &f32| *stamp_val <= time_secs);
    let next_idx: usize = upper_pos.clamp(1, last_idx);
    let prev_idx: usize = next_idx - 1;
    let time_prev: f32 = key_times[prev_idx];
    let time_next: f32 = key_times[next_idx];
    let delta_time: f32 = (time_next - time_prev).max(ANIM_MIN_SPAN_SECS);
    let interp_t: f32 = ((time_secs - time_prev) / delta_time).clamp(0.0, 1.0);
    match interp_mode {
        GltfInterpolationMode::Step => {
            let start_idx: usize = prev_idx * frame_floats;
            out_values.extend_from_slice(&values[start_idx..(start_idx + stride)]);
            normalize_quaternion_slice(out_values, is_rotation);
        }
        GltfInterpolationMode::Linear => {
            let prev_off: usize = prev_idx * stride;
            let next_off: usize = next_idx * stride;
            if is_rotation && stride == 4 {
                let quat_prev: Quat = Quat::from_xyzw(
                    values[prev_off],
                    values[prev_off + 1],
                    values[prev_off + 2],
                    values[prev_off + 3],
                )
                .normalize();
                let quat_next: Quat = Quat::from_xyzw(
                    values[next_off],
                    values[next_off + 1],
                    values[next_off + 2],
                    values[next_off + 3],
                )
                .normalize();
                let blended: Quat = quat_prev.slerp(quat_next, interp_t);
                out_values.extend_from_slice(&blended.to_array());
            } else {
                for comp_idx in 0..stride {
                    let val_prev: f32 = values[prev_off + comp_idx];
                    let val_next: f32 = values[next_off + comp_idx];
                    out_values.push(val_prev + (val_next - val_prev) * interp_t);
                }
            }
        }
        GltfInterpolationMode::CubicSpline => {
            let prev_base: usize = prev_idx * frame_floats;
            let next_base: usize = next_idx * frame_floats;
            let prev_val_off: usize = prev_base + stride;
            let prev_out_off: usize = prev_base + stride * 2;
            let next_in_off: usize = next_base;
            let next_val_off: usize = next_base + stride;
            let t_sq: f32 = interp_t * interp_t;
            let t_cu: f32 = t_sq * interp_t;
            let h00: f32 = 2.0 * t_cu - 3.0 * t_sq + 1.0;
            let h10: f32 = (t_cu - 2.0 * t_sq + interp_t) * delta_time;
            let h01: f32 = -2.0 * t_cu + 3.0 * t_sq;
            let h11: f32 = (t_cu - t_sq) * delta_time;
            for comp_idx in 0..stride {
                let val_prev: f32 = values[prev_val_off + comp_idx];
                let out_tan_prev: f32 = values[prev_out_off + comp_idx];
                let val_next: f32 = values[next_val_off + comp_idx];
                let in_tan_next: f32 = values[next_in_off + comp_idx];
                let hermite_val: f32 =
                    h00 * val_prev + h10 * out_tan_prev + h01 * val_next + h11 * in_tan_next;
                out_values.push(hermite_val);
            }
            normalize_quaternion_slice(out_values, is_rotation);
        }
    }
}

/// Normalizes a 4-component `[x, y, z, w]` slice in place when `is_rotation` is enabled.
///
/// # Arguments
///
/// - `&mut [f32]` - Output scalar slice.
/// - `bool` - Whether the slice stores a rotation quaternion.
fn normalize_quaternion_slice(out_values: &mut [f32], is_rotation: bool) {
    if !is_rotation || out_values.len() < 4 {
        return;
    }
    let unit_quat: Quat =
        Quat::from_xyzw(out_values[0], out_values[1], out_values[2], out_values[3]).normalize();
    let packed: [f32; 4] = unit_quat.to_array();
    out_values[0] = packed[0];
    out_values[1] = packed[1];
    out_values[2] = packed[2];
    out_values[3] = packed[3];
}