* claim: #3713 * Exploded views export as an animation (#3713) motion.export_animation takes an exploded view (view: id|name) as well as a study or a joint: the parts come apart at a steady pace from the assembled placement to where the view shows them, and back together with back: true (exploded at the middle frame). 41 frames by default, 81 with back. The home view frames the parts both assembled and exploded. As with explode.show, the design keeps its placements, its history and its saved state. explode.show and the export share the moves; moves a design file gives with no finite translation are left out. * Mechanisms skill: an exploded view's default frame count --------- Co-authored-by: MateuszSychXpl <151755914+MateuszSychXpl@users.noreply.github.com>
This commit is contained in:
@@ -69,7 +69,16 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
.noundo()
|
||||
.params("study; samples? (default steps + 1); path? (.json or .csv) → occurrence positions per step (the design is not changed)"),
|
||||
CommandSpec::new("motion.export_animation", "Export Motion Animation", animation::export).icon("export").noundo().params(
|
||||
"study: id|name, or joint: id|name with from and to (degrees for angles, mm for distances, or expressions) and index?; path: a .gif file, or a folder for PNG frames (frame-0001.png, frame-0002.png, …); samples? (frames, 2…1000; default the study's steps + 1, or 100); width?, height? (16…4096 pixels, default 800 × 500); camera?: {target, yaw, pitch, roll?, distance, fov?, up?} (ui.camera's reply; fields left out keep the default view: view.apply's camera, or the home view framing the model); fps? (1…50, default 20); grid?, axes? (default true: the ground grid and the origin's axes) - draws the study as it plays, or the joint as it is driven, with the headless renderer → path, format, frames, width, height, fps (GIF), bytes, renderer, stopped_at, stopped_by_loop, stopped_by_contact (the design is not changed)",
|
||||
"study: id|name, or joint: id|name with from and to (degrees for angles, mm for distances, or expressions) and index?, or \
|
||||
view: id|name (an exploded view, coming apart from the assembled placement) with back? (default false; true: back together \
|
||||
too, exploded at the middle frame of an odd count); path: a .gif file, or a folder for PNG frames (frame-0001.png, \
|
||||
frame-0002.png, …); samples? (frames, 2…1000; default the study's steps + 1, 100 for a joint, 41 for a view or 81 with \
|
||||
back); width?, height? (16…4096 pixels, default 800 × 500); camera?: {target, yaw, pitch, roll?, distance, fov?, up?} \
|
||||
(ui.camera's reply; fields left out keep the default view: view.apply's camera, or the home view framing the model, for a \
|
||||
view both assembled and exploded); fps? (1…50, default 20); grid?, axes? (default true: the ground grid and the origin's \
|
||||
axes) - draws the study as it plays, the joint as it is driven or the view as it explodes, with the headless renderer → \
|
||||
path, format, frames, width, height, fps (GIF), bytes, renderer, stopped_at, stopped_by_loop, stopped_by_contact (the \
|
||||
design is not changed, nor its placements)",
|
||||
),
|
||||
CommandSpec::new("motion.trace", "Motion Trace", trace).at("SOLID", "ASSEMBLE").icon("trace").noundo().params(concat!(
|
||||
trace_doc!(),
|
||||
@@ -87,7 +96,10 @@ pub static COMMANDS: &[CommandSpec] = &[
|
||||
Edits a saved associative trace's driving conditions in one undo step",
|
||||
),
|
||||
CommandSpec::new("motion.plot", "Plot Motion Study", analysis::plot).icon("graph").noundo().params(analysis::PLOT_DOC),
|
||||
CommandSpec::new("motion.interference", "Motion Interference", analysis::interference).icon("interference").noundo().params(analysis::INTERFERENCE_DOC),
|
||||
CommandSpec::new("motion.interference", "Motion Interference", analysis::interference)
|
||||
.icon("interference")
|
||||
.noundo()
|
||||
.params(analysis::INTERFERENCE_DOC),
|
||||
CommandSpec::new("joint.sweep", "Sweep Joint", sweep::sweep).icon("interference").params(sweep::SWEEP_DOC),
|
||||
CommandSpec::new("motion.list", "List Motion Studies", list_studies).icon("list").noundo(),
|
||||
CommandSpec::new("motion.delete", "Delete Motion Study", delete_study).icon("delete").params("study"),
|
||||
@@ -1051,21 +1063,34 @@ fn explode_show(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
}
|
||||
let i = view_index(s, p, cmd)?;
|
||||
let v = s.doc.assembly.exploded.get(i).cloned().ok_or_else(|| bad(cmd, "view"))?;
|
||||
s.pending_moves.clear();
|
||||
for (o, t) in &v.moves {
|
||||
let Some(occ) = s.doc.occurrences.iter().find(|x| x.id == *o) else { continue };
|
||||
let mut m = occ.transform;
|
||||
if let Some(r) = m.get_mut(3) {
|
||||
r[0] += t.x;
|
||||
r[1] += t.y;
|
||||
r[2] += t.z;
|
||||
}
|
||||
s.pending_moves.insert(*o, m);
|
||||
}
|
||||
s.pending_moves = exploded_at(&explode_moves(s, &v), 1.0);
|
||||
s.revision += 1;
|
||||
Ok(json!({"view": v.id, "name": v.name}))
|
||||
}
|
||||
|
||||
/// What exploded view `v` moves: (occurrence, its placement, the translation the view adds). Moves
|
||||
/// of occurrences no longer in the design, or not finite (a hostile design file), are left out;
|
||||
/// a later move of one occurrence replaces an earlier one.
|
||||
fn explode_moves(s: &Session, v: &ExplodedView) -> Vec<(u64, Mat, Vec3)> {
|
||||
let placed: std::collections::BTreeMap<u64, Mat> = s.doc.occurrences.iter().map(|o| (o.id, o.transform)).collect();
|
||||
v.moves.iter().filter(|(_, t)| t.len() < 1e7).filter_map(|(o, t)| Some((*o, *placed.get(o)?, *t))).collect()
|
||||
}
|
||||
|
||||
/// The pending moves that show `moves` `amount` of the way out: 0 assembled, 1 exploded.
|
||||
fn exploded_at(moves: &[(u64, Mat, Vec3)], amount: f64) -> std::collections::BTreeMap<u64, Mat> {
|
||||
let mut out = std::collections::BTreeMap::new();
|
||||
for (o, m, t) in moves {
|
||||
let mut m = *m;
|
||||
if let Some(r) = m.get_mut(3) {
|
||||
r[0] += t.x * amount;
|
||||
r[1] += t.y * amount;
|
||||
r[2] += t.z * amount;
|
||||
}
|
||||
out.insert(*o, m);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn explode_list(s: &mut Session, _p: &Value) -> Result<Value> {
|
||||
Ok(json!({"views": s.doc.assembly.exploded}))
|
||||
}
|
||||
|
||||
@@ -1,16 +1,28 @@
|
||||
//! Motion animations (`motion.export_animation`): a study played, or one joint driven, drawn
|
||||
//! frame by frame by the headless renderer the host installed ([`crate::capture`]) and written as
|
||||
//! an animated GIF or a folder of PNG frames. Sampled on a copy, as a trace is: the design is not
|
||||
//! changed.
|
||||
//! Motion animations (`motion.export_animation`): a study played, one joint driven, or an exploded
|
||||
//! view coming apart (and back together), drawn frame by frame by the headless renderer the host
|
||||
//! installed ([`crate::capture`]) and written as an animated GIF or a folder of PNG frames. Sampled
|
||||
//! on a copy, as a trace is: the design is not changed, nor its placements.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use solidcraft_doc::Mat;
|
||||
use solidcraft_geom::Vec3;
|
||||
|
||||
use super::{drive_with_contact, motion_plan, sample_count};
|
||||
use super::{Plan, drive_with_contact, explode_moves, exploded_at, motion_plan, sample_count, view_index};
|
||||
use crate::capture::{self, Renderer};
|
||||
use crate::params::{bad, str_};
|
||||
use crate::render::Camera;
|
||||
use crate::{Result, Session};
|
||||
|
||||
/// What the frames show.
|
||||
enum Motion {
|
||||
/// A study played or a joint driven: the values driven, and what they are at each frame.
|
||||
Drive(BTreeSet<(u64, usize)>, Plan),
|
||||
/// An exploded view's moves coming apart, and back together when true.
|
||||
Explode(Vec<(u64, Mat, Vec3)>, bool),
|
||||
}
|
||||
|
||||
/// Most frames of one animation.
|
||||
const MAX_FRAMES: usize = 1000;
|
||||
/// Largest frame side, in pixels.
|
||||
@@ -57,14 +69,44 @@ pub(super) fn export_with(s: &Session, p: &Value, renderer: Option<&Renderer>) -
|
||||
None => 20.0,
|
||||
Some(v) => v.as_f64().filter(|n| n.is_finite() && (1.0..=50.0).contains(n)).ok_or_else(|| bad(cmd, "`fps` must be 1…50"))?,
|
||||
};
|
||||
let cam = camera(s, p.get("camera"), cmd)?;
|
||||
let shown = |key: &str| match p.get(key) {
|
||||
None => Ok(true),
|
||||
let flag = |key: &str, default: bool| match p.get(key) {
|
||||
None => Ok(default),
|
||||
Some(Value::Bool(b)) => Ok(*b),
|
||||
Some(_) => Err(bad(cmd, format!("`{key}` must be true or false"))),
|
||||
};
|
||||
let guides = crate::view::Guides { grid: shown("grid")?, axes: shown("axes")? };
|
||||
let (default, given, plan) = motion_plan(s, p, cmd)?;
|
||||
let guides = crate::view::Guides { grid: flag("grid", true)?, axes: flag("axes", true)? };
|
||||
let (default, motion) = match (p.get("view"), p.get("study").or(p.get("joint"))) {
|
||||
(Some(_), Some(_)) => return Err(bad(cmd, "give an exploded `view`, a `study` or a `joint`: one of them")),
|
||||
(Some(_), None) => {
|
||||
let back = flag("back", false)?;
|
||||
let v = s.doc.assembly.exploded.get(view_index(s, p, cmd)?).ok_or_else(|| bad(cmd, "view"))?;
|
||||
(if back { 81 } else { 41 }, Motion::Explode(explode_moves(s, v), back))
|
||||
}
|
||||
(None, driven) => {
|
||||
if driven.is_none() {
|
||||
return Err(bad(cmd, "give a `study`, a `joint` with `from` and `to`, or an exploded `view`"));
|
||||
}
|
||||
if p.get("back").is_some() {
|
||||
return Err(bad(cmd, "`back` goes with an exploded `view`"));
|
||||
}
|
||||
let (default, given, plan) = motion_plan(s, p, cmd)?;
|
||||
(default, Motion::Drive(given, plan))
|
||||
}
|
||||
};
|
||||
let home = || match &motion {
|
||||
// Framing both ends: every frame lies between the parts assembled and exploded.
|
||||
Motion::Explode(moves, _) => {
|
||||
let mut t = s.scratch();
|
||||
t.pending_moves.clear();
|
||||
let assembled = crate::view::bounds(&t);
|
||||
t.pending_moves = exploded_at(moves, 1.0);
|
||||
let mut c = crate::view::home_camera(&t);
|
||||
c.fit(&assembled.union(&crate::view::bounds(&t)));
|
||||
c
|
||||
}
|
||||
Motion::Drive(..) => crate::view::home_camera(s),
|
||||
};
|
||||
let cam = camera(s, home, p.get("camera"), cmd)?;
|
||||
// At least 4 frames fit even at the largest size.
|
||||
let max = MAX_FRAMES.min(if gif { MAX_GIF_PIXELS } else { MAX_PNG_PIXELS } / (width as usize * height as usize));
|
||||
let n = sample_count(p, default.min(max), max, cmd).map_err(|_| bad(cmd, format!("`samples` must be 2…{max} for {width} × {height} frames")))?;
|
||||
@@ -83,15 +125,24 @@ pub(super) fn export_with(s: &Session, p: &Value, renderer: Option<&Renderer>) -
|
||||
}
|
||||
let mut t = s.scratch();
|
||||
// From where the parts are placed: moves only shown (an exploded view, the pose an open
|
||||
// Motion Study dialog shows) are not where the joints are solved.
|
||||
// Motion Study dialog shows) are not where the joints are solved, nor the assembled placement.
|
||||
t.pending_moves.clear();
|
||||
let (mut frames, mut bytes, mut drawn_by) = (Vec::new(), 0, "");
|
||||
let mut stop = (Value::Null, Value::Null, Value::Null);
|
||||
for k in 0..n {
|
||||
let want = plan(&t, k, n);
|
||||
let (r, _) = drive_with_contact(&mut t, &want, &given)?;
|
||||
if stop.0.is_null() && (r["stopped_by_loop"].is_object() || r["stopped_by_contact"].is_object()) {
|
||||
stop = (json!(k), r["stopped_by_loop"].clone(), r["stopped_by_contact"].clone());
|
||||
match &motion {
|
||||
Motion::Drive(given, plan) => {
|
||||
let want = plan(&t, k, n);
|
||||
let (r, _) = drive_with_contact(&mut t, &want, given)?;
|
||||
if stop.0.is_null() && (r["stopped_by_loop"].is_object() || r["stopped_by_contact"].is_object()) {
|
||||
stop = (json!(k), r["stopped_by_loop"].clone(), r["stopped_by_contact"].clone());
|
||||
}
|
||||
}
|
||||
// Shown as explode.show shows it, the way out at a steady pace (and back).
|
||||
Motion::Explode(moves, back) => {
|
||||
let u = k as f64 / (n - 1) as f64;
|
||||
t.pending_moves = exploded_at(moves, if *back { 1.0 - (2.0 * u - 1.0).abs() } else { u });
|
||||
}
|
||||
}
|
||||
let scene = crate::view::scene_with_guides(&t, &cam, s.section, guides);
|
||||
let picture = capture::rgba_with(Some(renderer), &scene, &cam, width, height).map_err(|e| bad(cmd, e))?;
|
||||
@@ -125,10 +176,10 @@ pub(super) fn export_with(s: &Session, p: &Value, renderer: Option<&Renderer>) -
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The camera the frames are drawn from: the session's (`view.apply`), or the home view framing
|
||||
/// the model, with the fields `given` sets (`ui.camera`'s reply sets them all).
|
||||
fn camera(s: &Session, given: Option<&Value>, cmd: &str) -> Result<Camera> {
|
||||
let base = s.camera.unwrap_or_else(|| crate::view::home_camera(s));
|
||||
/// The camera the frames are drawn from: the session's (`view.apply`), or `home` framing the
|
||||
/// model, with the fields `given` sets (`ui.camera`'s reply sets them all).
|
||||
fn camera(s: &Session, home: impl FnOnce() -> Camera, given: Option<&Value>, cmd: &str) -> Result<Camera> {
|
||||
let base = s.camera.unwrap_or_else(home);
|
||||
let Some(given) = given else { return Ok(base) };
|
||||
let fields = given.as_object().ok_or_else(|| bad(cmd, "`camera` must be an object, such as ui.camera's reply"))?;
|
||||
let mut v = serde_json::to_value(base).map_err(|e| bad(cmd, e.to_string()))?;
|
||||
|
||||
@@ -824,10 +824,78 @@ fn an_animation_is_drawn_from_the_camera_given() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_exploded_view_animates_apart_and_back_without_moving_the_design() {
|
||||
let mut s = rail();
|
||||
run(&mut s, "explode.create", json!({"name": "Apart", "scale": 1}));
|
||||
// Another view shown: the animation starts from the assembled placement all the same.
|
||||
run(&mut s, "explode.create", json!({"name": "Up", "moves": [{"occurrence": "B", "translate": [0, 0, 50]}]}));
|
||||
run(&mut s, "explode.show", json!({"view": "Up"}));
|
||||
s.mark_saved();
|
||||
let (doc, pending, undo) = (s.doc.clone(), s.pending_moves.clone(), s.undo.len());
|
||||
// Each frame: the lowest x and z of each body drawn, rounded to a micrometre.
|
||||
let seen = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));
|
||||
let record = {
|
||||
let seen = seen.clone();
|
||||
move |scene: &crate::render::Scene, cam: &crate::render::Camera, w: u32, h: u32| {
|
||||
let mut lows: Vec<[i64; 2]> =
|
||||
scene.meshes.iter().map(|m| m.mesh.bounds().min).map(|v| [(v.x * 1e3).round() as i64, (v.z * 1e3).round() as i64]).collect();
|
||||
lows.sort();
|
||||
seen.lock().unwrap().push((lows, *cam));
|
||||
cpu(scene, cam, w, h)
|
||||
}
|
||||
};
|
||||
let dir = out_dir("explode");
|
||||
let gif = dir.join("apart.gif");
|
||||
let frames = |p: Value| {
|
||||
let mut p = p;
|
||||
p["path"] = json!(gif.to_string_lossy());
|
||||
p["width"] = json!(24);
|
||||
p["height"] = json!(16);
|
||||
let r = super::animation::export_with(&s, &p, Some(&record)).unwrap();
|
||||
let seen = std::mem::take(&mut *seen.lock().unwrap());
|
||||
assert_eq!(r["frames"].as_u64(), Some(seen.len() as u64), "{r}");
|
||||
assert_eq!(gif_frames(&std::fs::read(&gif).unwrap()), (24, 16, seen.len()));
|
||||
seen
|
||||
};
|
||||
let lows = |seen: &[(Vec<[i64; 2]>, crate::render::Camera)]| seen.iter().map(|(l, _)| l.clone()).collect::<Vec<_>>();
|
||||
// A at x 0, B at x 20: each moves 10 mm out, at a steady pace.
|
||||
let at = |x: i64| vec![[x * 1000, 0], [(20 - x) * 1000, 0]];
|
||||
let apart = frames(json!({"view": "Apart", "samples": 3}));
|
||||
assert_eq!(lows(&apart), [at(0), at(-5), at(-10)]);
|
||||
// Back together too: exploded at the middle frame, assembled at both ends.
|
||||
let round = frames(json!({"view": "Apart", "back": true, "samples": 5}));
|
||||
assert_eq!(lows(&round), [at(0), at(-5), at(-10), at(-5), at(0)]);
|
||||
// One camera for the whole clip, framing the parts assembled and exploded alike.
|
||||
assert!(round.iter().all(|(_, c)| *c == round[0].1));
|
||||
let mut framed = crate::render::Camera::default();
|
||||
framed.fit(&solidcraft_geom::Aabb3 { min: Vec3::new(-10.0, 0.0, 0.0), max: Vec3::new(40.0, 10.0, 10.0) });
|
||||
assert!(round[0].1.target.dist(framed.target) < 1e-9 && (round[0].1.distance - framed.distance).abs() < 1e-9, "{:?}", round[0].1);
|
||||
// Without samples: 41 frames, or 81 with back (the middle one exploded).
|
||||
assert_eq!(frames(json!({"view": "Apart"})).len(), 41);
|
||||
let long = frames(json!({"view": "Up", "back": true}));
|
||||
assert_eq!(long.len(), 81);
|
||||
assert_eq!(long[40].0, [[0, 0], [20_000, 50_000]], "B up at the middle");
|
||||
assert_eq!((long[0].0.clone(), long[80].0.clone()), (vec![[0, 0], [20_000, 0]], vec![[0, 0], [20_000, 0]]));
|
||||
// The design keeps its placements, the view shown, its history and its saved state.
|
||||
assert_eq!((&*s.doc, &s.pending_moves, s.undo.len()), (&*doc, &pending, undo));
|
||||
// Through the registry too.
|
||||
crate::capture::install_test_renderer();
|
||||
let r = run(
|
||||
&mut s,
|
||||
"motion.export_animation",
|
||||
json!({"view": "Apart", "back": true, "path": gif.to_string_lossy(), "samples": 3, "width": 16, "height": 16}),
|
||||
);
|
||||
assert_eq!(r["frames"], 3, "{r}");
|
||||
assert_eq!((&*s.doc, &s.pending_moves, s.undo.len(), s.is_dirty()), (&*doc, &pending, undo, false));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hostile_animation_params_are_refused() {
|
||||
let mut s = rail();
|
||||
run(&mut s, "motion.study", json!({"name": "Push", "steps": 10, "keys": [{"joint": "Rail", "points": [[0, 10], [10, 0]]}]}));
|
||||
run(&mut s, "explode.create", json!({"name": "Apart", "scale": 1}));
|
||||
let dir = out_dir("hostile");
|
||||
let gif = dir.join("x.gif").to_string_lossy().to_string();
|
||||
let base = json!({"study": "Push", "path": gif, "samples": 2, "width": 16, "height": 16});
|
||||
@@ -873,6 +941,12 @@ fn hostile_animation_params_are_refused() {
|
||||
json!({"study": null}),
|
||||
json!({"study": "Nope"}),
|
||||
json!({"study": null, "joint": "Rail"}),
|
||||
json!({"back": true}),
|
||||
json!({"view": "Apart"}),
|
||||
json!({"study": null, "view": "Nope"}),
|
||||
json!({"study": null, "view": [1]}),
|
||||
json!({"study": null, "view": "Apart", "back": "yes"}),
|
||||
json!({"study": null, "view": "Apart", "joint": "Rail", "from": 0, "to": 1}),
|
||||
// 4096 × 4096 frames: a GIF holds four of them.
|
||||
json!({"width": 4096, "height": 4096, "samples": 5}),
|
||||
] {
|
||||
@@ -891,6 +965,20 @@ fn hostile_animation_params_are_refused() {
|
||||
assert!(refused(json!({"path": root.join("in.gif").to_string_lossy()})).is_none());
|
||||
});
|
||||
assert!(root.join("in.gif").exists() && !dir.join("out").exists());
|
||||
// A design file's exploded view moving parts by no number, too far, or parts gone: those
|
||||
// moves are left out, here and in explode.show.
|
||||
let b = occ(&s, "B");
|
||||
let moves = vec![
|
||||
(b, Vec3::new(f64::NAN, 0.0, 0.0)),
|
||||
(b, Vec3::new(0.0, f64::INFINITY, 0.0)),
|
||||
(b, Vec3::new(1e300, 0.0, 0.0)),
|
||||
(999, Vec3::new(1.0, 0.0, 0.0)),
|
||||
];
|
||||
s.doc_mut().assembly.exploded.push(solidcraft_doc::motion::ExplodedView { id: 900, name: "Bad".into(), moves });
|
||||
let p = json!({"view": "Bad", "path": gif, "samples": 2, "width": 16, "height": 16});
|
||||
super::animation::export_with(&s, &p, Some(&cpu)).unwrap();
|
||||
run(&mut s, "explode.show", json!({"view": "Bad"}));
|
||||
assert!(s.pending_moves.is_empty(), "{:?}", s.pending_moves);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user