vrm-runtime 0.1.0

Renderer-agnostic VRM 1.0 loader, validator, animation system, and runtime
Documentation
use glam::{Quat, Vec3};
use vrm_spec::vrmc_vrm_1_0 as vrm_schema;

/// How the eyes are driven once the gaze direction is known.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LookAtType {
    /// Rotate the eye bones directly.
    Bone,
    /// Drive the lookUp/lookDown/lookLeft/lookRight expression weights.
    Expression,
}

/// Maps an input angle (degrees) to an output weight/rotation via a linear
/// range: `clamp(|deg|, 0, input_max) / input_max * output_scale`.
#[derive(Debug, Clone)]
pub struct LookAtRangeMap {
    /// Input yaw or pitch angle at which the output reaches its maximum.
    pub input_max_value: f32,
    /// Maximum bone angle in degrees or expression weight, depending on the mode.
    pub output_scale: f32,
}

impl LookAtRangeMap {
    /// Creates a range map from its input angle and output maximum.
    pub const fn new(input_max_value: f32, output_scale: f32) -> Self {
        Self {
            input_max_value,
            output_scale,
        }
    }

    /// Maps an input angle to the configured output range.
    pub fn map_value(&self, deg: f32) -> f32 {
        let max_in = self.input_max_value.max(0.001);
        let clamped = deg.abs().min(max_in);
        (clamped / max_in) * self.output_scale
    }

    fn validate(&self, label: &str) -> Result<(), String> {
        if !self.input_max_value.is_finite() || !(0.0..=180.0).contains(&self.input_max_value) {
            return Err(format!(
                "{label}.inputMaxValue must be finite and within 0..=180"
            ));
        }
        if !self.output_scale.is_finite() {
            return Err(format!("{label}.outputScale must be finite"));
        }
        Ok(())
    }
}

impl Default for LookAtRangeMap {
    fn default() -> Self {
        Self {
            input_max_value: 90.0,
            output_scale: 10.0,
        }
    }
}

/// The eye-gaze configuration of an avatar: pivot offset from the head bone,
/// range maps per direction, and the mode (bone vs expression).
#[derive(Debug, Clone)]
pub struct LookAt {
    /// Whether gaze drives eye bones or expression presets.
    pub look_at_type: LookAtType,
    /// Gaze origin relative to the head bone.
    pub offset_from_head_bone: Vec3,
    /// Range used when either eye turns toward the nose.
    pub range_map_horizontal_inner: LookAtRangeMap,
    /// Range used when either eye turns away from the nose.
    pub range_map_horizontal_outer: LookAtRangeMap,
    /// Range used for downward gaze.
    pub range_map_vertical_down: LookAtRangeMap,
    /// Range used for upward gaze.
    pub range_map_vertical_up: LookAtRangeMap,
}

impl LookAt {
    /// Creates a LookAt configuration with the VRM fallback offset and ranges.
    pub fn new(look_at_type: LookAtType) -> Self {
        Self {
            look_at_type,
            offset_from_head_bone: Vec3::new(0.0, 0.06, 0.0),
            range_map_horizontal_inner: LookAtRangeMap::default(),
            range_map_horizontal_outer: LookAtRangeMap::default(),
            range_map_vertical_down: LookAtRangeMap::default(),
            range_map_vertical_up: LookAtRangeMap::default(),
        }
    }

    pub(crate) fn load_look_at(schema: &vrm_schema::LookAt) -> Self {
        let look_at_type = match schema.look_at_type {
            Some(vrm_schema::LookAtType::Expression) => LookAtType::Expression,
            _ => LookAtType::Bone,
        };

        let offset_from_head_bone = schema
            .offset_from_head_bone
            .as_ref()
            .and_then(|v| {
                if v.len() >= 3 {
                    Some(Vec3::new(v[0] as f32, v[1] as f32, v[2] as f32))
                } else {
                    None
                }
            })
            .unwrap_or(Vec3::new(0.0, 0.06, 0.0));

        let map_range = |range: Option<&vrm_schema::LookAtRangeMap>| {
            range
                .map(|r| LookAtRangeMap {
                    input_max_value: r.input_max_value.map(|v| v as f32).unwrap_or(90.0),
                    output_scale: r.output_scale.map(|v| v as f32).unwrap_or(10.0),
                })
                .unwrap_or_default()
        };

        Self {
            look_at_type,
            offset_from_head_bone,
            range_map_horizontal_inner: map_range(schema.range_map_horizontal_inner.as_ref()),
            range_map_horizontal_outer: map_range(schema.range_map_horizontal_outer.as_ref()),
            range_map_vertical_down: map_range(schema.range_map_vertical_down.as_ref()),
            range_map_vertical_up: map_range(schema.range_map_vertical_up.as_ref()),
        }
    }

    pub(crate) fn validate_programmatic(&self) -> Result<(), String> {
        if !self.offset_from_head_bone.is_finite() {
            return Err("LookAt offsetFromHeadBone must be finite".to_string());
        }
        for (label, range) in [
            (
                "LookAt.rangeMapHorizontalInner",
                &self.range_map_horizontal_inner,
            ),
            (
                "LookAt.rangeMapHorizontalOuter",
                &self.range_map_horizontal_outer,
            ),
            ("LookAt.rangeMapVerticalDown", &self.range_map_vertical_down),
            ("LookAt.rangeMapVerticalUp", &self.range_map_vertical_up),
        ] {
            range.validate(label)?;
        }
        Ok(())
    }

    /// Converts yaw and pitch into left- and right-eye local rotations.
    ///
    /// The return order is `(left_eye, right_eye)`.
    pub fn apply_bone(&self, yaw_deg: f32, pitch_deg: f32) -> (Quat, Quat) {
        let left_yaw = if yaw_deg > 0.0 {
            self.range_map_horizontal_outer.map_value(yaw_deg)
        } else {
            -self.range_map_horizontal_inner.map_value(yaw_deg)
        };

        let right_yaw = if yaw_deg > 0.0 {
            self.range_map_horizontal_inner.map_value(yaw_deg)
        } else {
            -self.range_map_horizontal_outer.map_value(yaw_deg)
        };

        let pitch = if pitch_deg > 0.0 {
            self.range_map_vertical_down.map_value(pitch_deg)
        } else {
            -self.range_map_vertical_up.map_value(pitch_deg)
        };

        let left_rot = Quat::from_euler(
            glam::EulerRot::YXZ,
            left_yaw.to_radians(),
            pitch.to_radians(),
            0.0,
        );
        let right_rot = Quat::from_euler(
            glam::EulerRot::YXZ,
            right_yaw.to_radians(),
            pitch.to_radians(),
            0.0,
        );

        (left_rot, right_rot)
    }

    /// Converts yaw and pitch into directional expression weights.
    ///
    /// The return order is `(look_left, look_right, look_down, look_up)`.
    pub fn apply_expression(&self, yaw_deg: f32, pitch_deg: f32) -> (f32, f32, f32, f32) {
        let (look_left, look_right) = if yaw_deg > 0.0 {
            (
                self.range_map_horizontal_outer.map_value(yaw_deg).min(1.0),
                0.0,
            )
        } else {
            (
                0.0,
                self.range_map_horizontal_outer.map_value(yaw_deg).min(1.0),
            )
        };

        let (look_down, look_up) = if pitch_deg > 0.0 {
            (
                self.range_map_vertical_down.map_value(pitch_deg).min(1.0),
                0.0,
            )
        } else {
            (
                0.0,
                self.range_map_vertical_up.map_value(pitch_deg).min(1.0),
            )
        };

        (look_left, look_right, look_down, look_up)
    }
}

impl Default for LookAt {
    fn default() -> Self {
        Self::new(LookAtType::Bone)
    }
}

pub(crate) fn validate_schema(schema: &vrm_schema::LookAt) -> Result<(), String> {
    if let Some(offset) = &schema.offset_from_head_bone {
        if offset.len() != 3 {
            return Err("LookAt.offsetFromHeadBone must contain exactly three values".to_string());
        }
        if offset.iter().any(|&value| !representable_f32(value)) {
            return Err(
                "LookAt.offsetFromHeadBone values must be finite and representable as f32"
                    .to_string(),
            );
        }
    }

    for (label, range) in [
        (
            "LookAt.rangeMapHorizontalInner",
            schema.range_map_horizontal_inner.as_ref(),
        ),
        (
            "LookAt.rangeMapHorizontalOuter",
            schema.range_map_horizontal_outer.as_ref(),
        ),
        (
            "LookAt.rangeMapVerticalDown",
            schema.range_map_vertical_down.as_ref(),
        ),
        (
            "LookAt.rangeMapVerticalUp",
            schema.range_map_vertical_up.as_ref(),
        ),
    ] {
        let Some(range) = range else {
            continue;
        };
        if range
            .input_max_value
            .is_some_and(|value| !representable_f32(value) || !(0.0..=180.0).contains(&value))
        {
            return Err(format!(
                "{label}.inputMaxValue must be finite, representable as f32, and within 0..=180"
            ));
        }
        if range
            .output_scale
            .is_some_and(|value| !representable_f32(value))
        {
            return Err(format!(
                "{label}.outputScale must be finite and representable as f32"
            ));
        }
    }
    Ok(())
}

fn representable_f32(value: f64) -> bool {
    value.is_finite() && (value as f32).is_finite()
}

/// Converts a direction vector (from the look-at pivot toward the target)
/// into horizontal (yaw) and vertical (pitch) angles in degrees.
pub fn calc_yaw_pitch(local_target: Vec3) -> (f32, f32) {
    let x = local_target.x;
    let y = local_target.y;
    let z = local_target.z;

    let yaw = x.atan2(z).to_degrees();
    let xz = (x * x + z * z).sqrt();
    let pitch = (-y).atan2(xz).to_degrees();

    (yaw, pitch)
}