use serde_json::{json, Map, Value};
use super::animation_utils;
use super::keyframe_track::KeyframeTrack;
use crate::error::Error;
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum AnimationBlendMode {
#[default]
Normal,
Additive,
}
impl AnimationBlendMode {
pub fn as_number(self) -> u32 {
match self {
Self::Normal => 2500,
Self::Additive => 2501,
}
}
pub fn from_number(n: u32) -> Option<Self> {
match n {
2500 => Some(Self::Normal),
2501 => Some(Self::Additive),
_ => None,
}
}
}
fn generate_uuid() -> String {
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(0);
let nanos = (crate::utils::time::real_date_now_ms() * 1e6) as u64;
let counter = COUNTER.fetch_add(1, Ordering::Relaxed);
let mut state = nanos ^ (counter.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1);
let mut next = move || {
state ^= state >> 12;
state ^= state << 25;
state ^= state >> 27;
state.wrapping_mul(0x2545_F491_4F6C_DD1D)
};
let mut bytes = [0u8; 16];
for chunk in bytes.chunks_mut(8) {
let r = next().to_le_bytes();
chunk.copy_from_slice(&r[..chunk.len()]);
}
bytes[6] = (bytes[6] & 0x0f) | 0x40; bytes[8] = (bytes[8] & 0x3f) | 0x80;
let hex: String = bytes.iter().map(|b| format!("{b:02x}")).collect();
format!(
"{}-{}-{}-{}-{}",
&hex[0..8],
&hex[8..12],
&hex[12..16],
&hex[16..20],
&hex[20..32]
)
}
#[derive(Clone, Debug, PartialEq)]
pub struct AnimationClip {
pub name: String,
pub tracks: Vec<KeyframeTrack>,
pub duration: f64,
pub blend_mode: AnimationBlendMode,
pub uuid: String,
pub user_data: Map<String, Value>,
}
impl AnimationClip {
pub fn new(
name: &str,
duration: f64,
tracks: Vec<KeyframeTrack>,
blend_mode: AnimationBlendMode,
) -> Self {
let mut clip = Self {
name: name.to_string(),
tracks,
duration,
blend_mode,
uuid: generate_uuid(),
user_data: Map::new(),
};
if clip.duration < 0.0 {
clip.reset_duration();
}
clip
}
pub fn from_tracks(name: &str, tracks: Vec<KeyframeTrack>) -> Self {
Self::new(name, -1.0, tracks, AnimationBlendMode::Normal)
}
pub fn parse(json: &Value) -> Result<Self, Error> {
let mut tracks = Vec::new();
let json_tracks = json
.get("tracks")
.and_then(Value::as_array)
.map(|a| a.as_slice())
.unwrap_or(&[]);
let fps = match json.get("fps").and_then(Value::as_f64) {
Some(fps) if fps != 0.0 && !fps.is_nan() => fps,
_ => 1.0,
};
let frame_time = 1.0 / fps;
for json_track in json_tracks {
let mut track = KeyframeTrack::parse(json_track)?;
track.scale(frame_time);
tracks.push(track);
}
let duration = json.get("duration").and_then(Value::as_f64).unwrap_or(-1.0);
let name = json.get("name").and_then(Value::as_str).unwrap_or("");
let blend_mode = json
.get("blendMode")
.and_then(Value::as_u64)
.and_then(|n| AnimationBlendMode::from_number(n as u32))
.unwrap_or_default();
let mut clip = Self::new(name, duration, tracks, blend_mode);
if let Some(uuid) = json.get("uuid").and_then(Value::as_str) {
clip.uuid = uuid.to_string();
}
clip.user_data = json
.get("userData")
.and_then(Value::as_str)
.and_then(|s| serde_json::from_str::<Value>(s).ok())
.and_then(|v| match v {
Value::Object(map) => Some(map),
_ => None,
})
.unwrap_or_default();
Ok(clip)
}
pub fn to_json(&self) -> Value {
let tracks: Vec<Value> = self.tracks.iter().map(KeyframeTrack::to_json).collect();
json!({
"name": self.name,
"duration": self.duration,
"tracks": tracks,
"uuid": self.uuid,
"blendMode": self.blend_mode.as_number(),
"userData": Value::Object(self.user_data.clone()).to_string(),
})
}
pub fn create_from_morph_target_sequence(
name: &str,
morph_target_sequence: &[&str],
fps: f64,
no_loop: bool,
) -> Result<Self, Error> {
let num_morph_targets = morph_target_sequence.len();
let mut tracks = Vec::new();
for (i, morph_target_name) in morph_target_sequence.iter().enumerate() {
let mut times: Vec<f64> = Vec::new();
let mut values: Vec<f64> = Vec::new();
let n = num_morph_targets as f64;
let i_f = i as f64;
times.push((i_f + n - 1.0) % n);
times.push(i_f);
times.push((i_f + 1.0) % n);
values.push(0.0);
values.push(1.0);
values.push(0.0);
let order = animation_utils::get_keyframe_order(×);
times = animation_utils::sorted_array(×, 1, &order);
values = animation_utils::sorted_array(&values, 1, &order);
if !no_loop && times[0] == 0.0 {
times.push(n);
values.push(values[0]);
}
let mut track = KeyframeTrack::number(
&format!(".morphTargetInfluences[{}]", morph_target_name),
times,
values,
None,
)?;
track.scale(1.0 / fps);
tracks.push(track);
}
Ok(Self::new(name, -1.0, tracks, AnimationBlendMode::Normal))
}
pub fn find_by_name<'a>(
clip_array: &'a [AnimationClip],
name: &str,
) -> Option<&'a AnimationClip> {
clip_array.iter().find(|clip| clip.name == name)
}
pub fn create_clips_from_morph_target_sequences(
morph_targets: &[&str],
fps: f64,
no_loop: bool,
) -> Result<Vec<Self>, Error> {
let mut animation_to_morph_targets: Vec<(String, Vec<&str>)> = Vec::new();
for morph_target in morph_targets {
let Some(name) = morph_target_group(morph_target) else {
continue;
};
match animation_to_morph_targets
.iter_mut()
.find(|(key, _)| key == name)
{
Some((_, group)) => group.push(morph_target),
None => animation_to_morph_targets.push((name.to_string(), vec![morph_target])),
}
}
let mut clips = Vec::new();
for (name, group) in &animation_to_morph_targets {
clips.push(Self::create_from_morph_target_sequence(
name, group, fps, no_loop,
)?);
}
Ok(clips)
}
pub fn reset_duration(&mut self) -> &mut Self {
let mut duration: f64 = 0.0;
for track in &self.tracks {
if let Some(&last) = track.times.last() {
duration = duration.max(last);
}
}
self.duration = duration;
self
}
pub fn trim(&mut self) -> &mut Self {
let duration = self.duration;
for track in &mut self.tracks {
track.trim(0.0, duration);
}
self
}
pub fn validate(&self) -> bool {
let mut valid = true;
for track in &self.tracks {
valid = valid && track.validate();
}
valid
}
pub fn optimize(&mut self) -> &mut Self {
for track in &mut self.tracks {
track.optimize();
}
self
}
pub fn clone_clip(&self) -> Self {
let tracks: Vec<KeyframeTrack> =
self.tracks.iter().map(KeyframeTrack::clone_track).collect();
let mut clip = Self::new(&self.name, self.duration, tracks, self.blend_mode);
clip.user_data = self.user_data.clone();
clip
}
}
fn morph_target_group(name: &str) -> Option<&str> {
let digits_start = name
.char_indices()
.rev()
.take_while(|(_, c)| c.is_ascii_digit())
.last()
.map(|(i, _)| i)?;
let prefix = &name[..digits_start];
if prefix
.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
{
Some(prefix)
} else {
None
}
}