Skip to main content

metaverse_mesh/animation/
generate.rs

1use crate::animation::retarget::{
2    apply_joint_scale, filter_animation_keyframes, filter_bind_skeleton,
3};
4use crate::errors::MetaverseMeshError;
5use crate::{animation::gltf::export_animation, errors::MetaverseMeshAnimationError};
6use benthic_default_asset_converter::generated::DEFAULT_SKELETON;
7use benthic_protocol::default_animations::AnimationClip;
8use benthic_protocol::skeleton::{JointName, Skeleton};
9use std::collections::BTreeSet;
10use std::path::Path;
11use std::{
12    ffi::{CStr, c_char},
13    fs,
14    path::PathBuf,
15};
16
17pub fn generate_gltf_animation(
18    animation_json_path: &PathBuf,
19    out_path: &PathBuf,
20) -> Result<(), MetaverseMeshError> {
21    let file = fs::File::open(animation_json_path)
22        .unwrap_or_else(|e| panic!("Failed to read {:?}, {:?}", animation_json_path, e));
23    let animations: AnimationClip = serde_json::from_reader(&file)
24        .unwrap_or_else(|e| panic!("Failed to deserialize joint animation {:?}", e));
25    export_animation(&animations, out_path)
26}
27
28fn load_animation(path: &Path) -> Result<AnimationClip, MetaverseMeshAnimationError> {
29    let file = fs::File::open(path).map_err(|source| MetaverseMeshAnimationError::ReadFile {
30        path: path.to_path_buf(),
31        source,
32    })?;
33
34    serde_json::from_reader(file).map_err(|source| MetaverseMeshAnimationError::Deserialize {
35        path: path.to_path_buf(),
36        source,
37    })
38}
39
40pub fn retarget_gltf_animation<S>(
41    animation_json_path: &Path,
42    target_skeleton: S,
43    filtered_animation_out_path: &Path,
44    out_path: &Path,
45) -> Result<(), MetaverseMeshAnimationError>
46where
47    S: IntoSkeleton,
48{
49    let target_skeleton = target_skeleton.into_skeleton()?;
50    let used_joints = used_joints(&target_skeleton);
51
52    let animation = load_animation(animation_json_path)?;
53    let skeleton = &DEFAULT_SKELETON.clone();
54
55    let animation_clip = AnimationClip {
56        bind_skeleton: filter_bind_skeleton(skeleton, &used_joints)?,
57        joints: filter_animation_keyframes(&animation.joints, skeleton, &used_joints)?,
58    };
59    let file = fs::File::create(filtered_animation_out_path).map_err(|source| {
60        MetaverseMeshAnimationError::CreateOutput {
61            path: filtered_animation_out_path.to_path_buf(),
62            source,
63        }
64    })?;
65
66    serde_json::to_writer_pretty(file, &animation_clip).map_err(|source| {
67        MetaverseMeshAnimationError::Serialize {
68            path: filtered_animation_out_path.to_path_buf(),
69            source,
70        }
71    })?;
72    apply_joint_scale(animation_clip, out_path, &target_skeleton, &used_joints)
73}
74
75pub fn retarget_filtered_gltf_animation<S>(
76    filtered_animation_json_path: &Path,
77    target_skeleton: S,
78    out_path: &Path,
79) -> Result<(), MetaverseMeshAnimationError>
80where
81    S: IntoSkeleton,
82{
83    let target_skeleton = target_skeleton.into_skeleton()?;
84    let animation = load_animation(filtered_animation_json_path)?;
85    let used_joints = used_joints(&target_skeleton);
86
87    apply_joint_scale(animation, out_path, &target_skeleton, &used_joints)
88}
89
90#[unsafe(no_mangle)]
91/// Allow external projects to generate animation from json. This will return the string of where the file
92/// was generated on disk!
93pub unsafe extern "C" fn generate_gltf_animation_legacy(
94    animation_json_path: *const c_char,
95    out_path: *const c_char,
96) -> *mut c_char {
97    // Parse animation json path
98    let animation_json = {
99        let s = unsafe {
100            CStr::from_ptr(animation_json_path)
101                .to_string_lossy()
102                .into_owned()
103        };
104
105        PathBuf::from(s)
106    };
107
108    // Parse output path
109    let out = {
110        let s = unsafe { CStr::from_ptr(out_path).to_string_lossy().into_owned() };
111
112        PathBuf::from(s)
113    };
114
115    // Generate animation
116    match generate_gltf_animation(&animation_json, &out) {
117        Ok(_) => std::ffi::CString::new("Success").unwrap().into_raw(),
118
119        Err(e) => {
120            eprintln!("Failed to generate joint animation: {:?}", e);
121            std::ptr::null_mut()
122        }
123    }
124}
125
126#[unsafe(no_mangle)]
127/// Retarget a GLTF animation using a target skeleton loaded from JSON.
128///
129/// Returns "Success" on success or null on failure.
130pub unsafe extern "C" fn retarget_gltf_animation_legacy(
131    animation_json_path: *const c_char,
132    target_skeleton_path: *const c_char,
133    filtered_animation_out_path: *const c_char,
134    out_path: *const c_char,
135) -> *mut c_char {
136    let animation_json = {
137        let s = unsafe {
138            CStr::from_ptr(animation_json_path)
139                .to_string_lossy()
140                .into_owned()
141        };
142
143        PathBuf::from(s)
144    };
145
146    let target_skeleton = {
147        let s = unsafe {
148            CStr::from_ptr(target_skeleton_path)
149                .to_string_lossy()
150                .into_owned()
151        };
152
153        PathBuf::from(s)
154    };
155
156    let filtered_animation_out = {
157        let s = unsafe {
158            CStr::from_ptr(filtered_animation_out_path)
159                .to_string_lossy()
160                .into_owned()
161        };
162
163        PathBuf::from(s)
164    };
165
166    let out = {
167        let s = unsafe { CStr::from_ptr(out_path).to_string_lossy().into_owned() };
168
169        PathBuf::from(s)
170    };
171
172    match retarget_gltf_animation(
173        &animation_json,
174        target_skeleton.as_path(),
175        &filtered_animation_out,
176        &out,
177    ) {
178        Ok(_) => std::ffi::CString::new("Success").unwrap().into_raw(),
179
180        Err(e) => {
181            eprintln!("Failed to retarget GLTF animation: {:?}", e);
182            std::ptr::null_mut()
183        }
184    }
185}
186
187#[unsafe(no_mangle)]
188/// Retarget a previously filtered GLTF animation using a target skeleton
189/// loaded from JSON.
190///
191/// Returns "Success" on success or null on failure.
192pub unsafe extern "C" fn retarget_filtered_gltf_animation_legacy(
193    filtered_animation_json_path: *const c_char,
194    target_skeleton_path: *const c_char,
195    out_path: *const c_char,
196) -> *mut c_char {
197    let filtered_animation_json = {
198        let s = unsafe {
199            CStr::from_ptr(filtered_animation_json_path)
200                .to_string_lossy()
201                .into_owned()
202        };
203
204        PathBuf::from(s)
205    };
206
207    let target_skeleton = {
208        let s = unsafe {
209            CStr::from_ptr(target_skeleton_path)
210                .to_string_lossy()
211                .into_owned()
212        };
213
214        PathBuf::from(s)
215    };
216
217    let out = {
218        let s = unsafe { CStr::from_ptr(out_path).to_string_lossy().into_owned() };
219
220        PathBuf::from(s)
221    };
222
223    match retarget_filtered_gltf_animation(
224        &filtered_animation_json,
225        target_skeleton.as_path(),
226        &out,
227    ) {
228        Ok(_) => std::ffi::CString::new("Success").unwrap().into_raw(),
229
230        Err(e) => {
231            eprintln!("Failed to retarget filtered GLTF animation: {:?}", e);
232            std::ptr::null_mut()
233        }
234    }
235}
236
237pub trait IntoSkeleton {
238    fn into_skeleton(self) -> Result<Skeleton, MetaverseMeshAnimationError>;
239}
240
241impl IntoSkeleton for &Skeleton {
242    fn into_skeleton(self) -> Result<Skeleton, MetaverseMeshAnimationError> {
243        Ok(self.clone())
244    }
245}
246
247impl IntoSkeleton for &Path {
248    fn into_skeleton(self) -> Result<Skeleton, MetaverseMeshAnimationError> {
249        load_skeleton(self)
250    }
251}
252
253fn load_skeleton(path: &Path) -> Result<Skeleton, MetaverseMeshAnimationError> {
254    let file = fs::File::open(path).map_err(|source| MetaverseMeshAnimationError::ReadFile {
255        path: path.to_path_buf(),
256        source,
257    })?;
258
259    serde_json::from_reader(file).map_err(|source| MetaverseMeshAnimationError::Deserialize {
260        path: path.to_path_buf(),
261        source,
262    })
263}
264
265fn used_joints(skeleton: &Skeleton) -> BTreeSet<JointName> {
266    skeleton
267        .joints
268        .values()
269        .filter(|joint| {
270            joint
271                .global_transforms
272                .last()
273                .is_some_and(|transform| transform.rank != 0)
274        })
275        .map(|joint| joint.name)
276        .collect()
277}