1use sim_components::chain::{
56 JOINT_KEYS, JointMachine, JointSpec, MOTOR_IDS, MOTOR_KEYS, Mechanism, condition_number, solve,
57};
58use sim_components::joint::RotaryJoint;
59use sim_components::mech::ThermalFeedback;
60use sim_components::rigid::{M3, V3, add, cross, dot, exp, log, matmul, mul, transpose};
61use sim_core::{
62 AxisInfo, Config, ConfigError, Label, Machine, MachineEntry, MotorInfo, Part, RatingCheck, Scene, Shape, SignalInfo,
63};
64use std::f64::consts::{FRAC_PI_2, PI, TAU};
65
66pub static ENTRY: MachineEntry = MachineEntry {
67 id: "hexapod-rotary",
68 key: "machine-hexapod-rotary",
69 default_config: include_str!("../default.toml"),
70 i18n: &[("en", include_str!("../i18n/en.ftl")), ("de", include_str!("../i18n/de.ftl"))],
71 build,
72 suite_configs,
73};
74
75const G: f64 = 9.80665;
76
77pub const LOSSY_EFFECTS: [&str; 7] = [
79 "joint_friction",
80 "motor_friction",
81 "gearbox_drag",
82 "gearbox_lost_motion",
83 "gearbox_efficiency",
84 "torque_ripple",
85 "holding_brake",
86];
87
88const AXIS_IDS: [&str; 6] = ["x", "y", "z", "rx", "ry", "rz"];
89const AXIS_KEYS: [&str; 6] = ["axis-x", "axis-y", "axis-z", "axis-rx", "axis-ry", "axis-rz"];
90const Z: V3 = [0.0, 0.0, 1.0];
91
92pub fn lossless_config() -> Config {
94 let mut cfg = ENTRY.config();
95 for effect in LOSSY_EFFECTS {
96 cfg.set_text(&format!("effects.{effect} = false")).unwrap();
97 }
98 cfg.set_text("gearbox.damping_nm_s_rad = 0.0").unwrap();
99 cfg.set_text("joint.stop_damping_nm_s_rad = 0.0").unwrap();
100 cfg
101}
102
103fn suite_configs() -> Vec<Config> {
113 [(false, true), (false, false), (true, true), (true, false)]
114 .into_iter()
115 .map(|(elastic, payload)| {
116 let mut cfg = lossless_config();
117 cfg.set_text(&format!("effects.joint_elasticity = {elastic}")).unwrap();
118 cfg.set_text(&format!("effects.payload = {payload}")).unwrap();
119 cfg.set_text("effects.gravity = false").unwrap();
120 cfg.set_text("effects.gearbox_backlash = false").unwrap();
121 cfg
122 })
123 .collect()
124}
125
126fn sub(a: V3, b: V3) -> V3 {
127 [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
128}
129
130fn scale(a: V3, k: f64) -> V3 {
131 a.map(|v| v * k)
132}
133
134fn norm(a: V3) -> f64 {
135 dot(a, a).sqrt()
136}
137
138struct Lu {
140 a: [f64; 36],
141 pivot: [usize; 6],
142}
143
144impl Lu {
145 fn of(m: &[f64]) -> Option<Lu> {
147 let mut a: [f64; 36] = std::array::from_fn(|k| m[k]);
148 let mut pivot = [0; 6];
149 for c in 0..6 {
150 let p = (c..6).max_by(|&i, &j| a[i * 6 + c].abs().total_cmp(&a[j * 6 + c].abs()))?;
151 if !(a[p * 6 + c].abs() > 1e-300) {
152 return None;
153 }
154 pivot[c] = p;
155 if p != c {
156 for k in 0..6 {
157 a.swap(p * 6 + k, c * 6 + k);
158 }
159 }
160 for r in c + 1..6 {
161 let f = a[r * 6 + c] / a[c * 6 + c];
162 a[r * 6 + c] = f;
163 for k in c + 1..6 {
164 a[r * 6 + k] -= f * a[c * 6 + k];
165 }
166 }
167 }
168 Some(Lu { a, pivot })
169 }
170
171 fn solve(&self, mut b: [f64; 6]) -> [f64; 6] {
173 for c in 0..6 {
175 b.swap(c, self.pivot[c]);
176 }
177 for c in 0..6 {
178 for r in c + 1..6 {
179 b[r] -= self.a[r * 6 + c] * b[c];
180 }
181 }
182 for c in (0..6).rev() {
183 let s: f64 = (c + 1..6).map(|k| self.a[c * 6 + k] * b[k]).sum();
184 b[c] = (b[c] - s) / self.a[c * 6 + c];
185 }
186 b
187 }
188}
189
190pub fn segment_distance(p0: V3, p1: V3, q0: V3, q1: V3) -> f64 {
192 let (d1, d2, r) = (sub(p1, p0), sub(q1, q0), sub(p0, q0));
193 let (a, e, f) = (dot(d1, d1), dot(d2, d2), dot(d2, r));
194 let (c, b) = (dot(d1, r), dot(d1, d2));
195 let denom = a * e - b * b;
196 let mut s = if denom > 1e-18 { ((b * f - c * e) / denom).clamp(0.0, 1.0) } else { 0.0 };
197 let mut t = (b * s + f) / e;
198 if t < 0.0 {
199 t = 0.0;
200 s = (-c / a).clamp(0.0, 1.0);
201 } else if t > 1.0 {
202 t = 1.0;
203 s = ((b - c) / a).clamp(0.0, 1.0);
204 }
205 norm(sub(add(p0, scale(d1, s)), add(q0, scale(d2, t))))
206}
207
208#[derive(Debug, Clone, Copy, Default)]
212pub struct Leg {
213 pub tip: V3,
214 pub t: V3,
215 pub t2: V3,
216 pub joint: V3,
217 pub b: V3,
218 pub u: V3,
219 pub length: f64,
220 pub arm: f64,
221 pub cos: f64,
222}
223
224#[derive(Debug, Clone, Copy)]
227pub struct Crank {
228 pub tip: V3,
229 pub t: V3,
230 pub t2: V3,
231 pub cos: f64,
232}
233
234#[derive(Debug, Clone)]
236pub struct Geometry {
237 pub base: [V3; 6],
240 pub dir: [V3; 6],
241 pub axis: [V3; 6],
242 pub anchors: [V3; 6],
243 pub platform_radius: f64,
244 pub crank: f64,
245 pub rod: f64,
246 pub branch: f64,
248 pub min_margin: f64,
252 pub max_crank_joint: f64,
253 pub max_platform_joint: f64,
254 pub min_clearance: f64,
255 pub min_body_clearance: f64,
257 pub max_condition: f64,
258 pub home: [f64; 6],
260 home_q: [f64; 6],
263 home_k: [f64; 36],
264}
265
266impl Geometry {
267 pub fn new(
270 base_radius: f64,
271 base_half: f64,
272 platform_radius: f64,
273 platform_half: f64,
274 axis_turn: f64,
275 crank: f64,
276 rod: f64,
277 out: bool,
278 ) -> Self {
279 let at = |radius: f64, deg: f64| [radius * deg.to_radians().cos(), radius * deg.to_radians().sin(), 0.0];
280 let side = |i: usize| if i.is_multiple_of(2) { -1.0 } else { 1.0 };
281 let base = std::array::from_fn(|i| at(base_radius, 120.0 * (i / 2) as f64 + side(i) * base_half));
282 let anchors =
283 std::array::from_fn(|i| at(platform_radius, 120.0 * (i / 2) as f64 + side(i) * (60.0 - platform_half)));
284 let dir: [V3; 6] = std::array::from_fn(|i| {
285 let n = at(1.0, 120.0 * (i / 2) as f64 + side(i) * (base_half + axis_turn));
286 scale([-n[1], n[0], 0.0], side(i))
288 });
289 let axis = std::array::from_fn(|i| cross(dir[i], Z));
290 Self {
291 base,
292 dir,
293 axis,
294 anchors,
295 platform_radius,
296 crank,
297 rod,
298 branch: if out { -1.0 } else { 1.0 },
299 min_margin: 0.0,
300 max_crank_joint: FRAC_PI_2,
301 max_platform_joint: PI,
302 min_clearance: 0.0,
303 min_body_clearance: 0.0,
304 max_condition: f64::INFINITY,
305 home: [0.0; 6],
306 home_q: [0.0; 6],
307 home_k: [0.0; 36],
308 }
309 }
310
311 pub fn set_home(&mut self, home: [f64; 6]) {
314 (self.home, self.home_q, self.home_k) = (home, [0.0; 6], [0.0; 36]);
315 let mut q = [0.0; 6];
316 if !self.inverse(&home, &mut q) {
317 return;
318 }
319 let legs = self.legs_at(&q, [home[0], home[1], home[2]], &Self::rotation(&home));
320 let Some(lu) = Lu::of(&Self::constraint(&legs)) else { return };
321 for c in 0..6 {
322 let col = lu.solve(std::array::from_fn(|i| if i == c { legs[c].arm } else { 0.0 }));
323 (0..6).for_each(|r| self.home_k[r * 6 + c] = col[r]);
324 }
325 self.home_q = q;
326 }
327
328 pub fn rotation(tool: &[f64]) -> M3 {
329 exp([tool[3], tool[4], tool[5]])
330 }
331
332 pub fn tip(&self, i: usize, theta: f64) -> Crank {
334 let (s, c) = theta.sin_cos();
335 let (r, d) = (self.crank, self.dir[i]);
336 Crank {
337 tip: add(self.base[i], scale(add(scale(d, c), scale(Z, s)), r)),
338 t: scale(add(scale(d, -s), scale(Z, c)), r),
339 t2: scale(add(scale(d, c), scale(Z, s)), -r),
340 cos: c,
341 }
342 }
343
344 pub fn cranks(&self, q: &[f64]) -> [Crank; 6] {
347 std::array::from_fn(|i| self.tip(i, q[i]))
348 }
349
350 pub fn crank_angle(&self, i: usize, joint: V3) -> Option<f64> {
352 let e = sub(joint, self.base[i]);
353 let (a, b) = (dot(e, self.dir[i]), e[2]);
354 let c = (dot(e, e) + self.crank * self.crank - self.rod * self.rod) / (2.0 * self.crank);
355 let rho = a.hypot(b);
356 if !(c.abs() <= rho) {
357 return None;
358 }
359 Some(b.atan2(a) + self.branch * (c / rho).acos())
360 }
361
362 pub fn legs_at(&self, q: &[f64], p: V3, r: &M3) -> [Leg; 6] {
364 self.legs_on(&self.cranks(q), p, r)
365 }
366
367 fn legs_on(&self, cranks: &[Crank; 6], p: V3, r: &M3) -> [Leg; 6] {
369 std::array::from_fn(|i| {
370 let Crank { tip, t, t2, cos } = cranks[i];
371 let b = mul(r, self.anchors[i]);
372 let joint = add(p, b);
373 let d = sub(joint, tip);
374 let length = norm(d);
375 let u = scale(d, 1.0 / length);
376 Leg { tip, t, t2, joint, b, u, length, arm: dot(u, t), cos }
377 })
378 }
379
380 pub fn inverse(&self, tool: &[f64], q: &mut [f64]) -> bool {
382 let (p, r) = ([tool[0], tool[1], tool[2]], Self::rotation(tool));
383 for i in 0..6 {
384 match self.crank_angle(i, add(p, mul(&r, self.anchors[i]))) {
385 Some(theta) => q[i] = theta,
386 None => return false,
387 }
388 }
389 true
390 }
391
392 pub fn legs(&self, tool: &[f64]) -> Option<[Leg; 6]> {
394 let mut q = [0.0; 6];
395 self.inverse(tool, &mut q).then(|| self.legs_at(&q, [tool[0], tool[1], tool[2]], &Self::rotation(tool)))
396 }
397
398 pub fn constraint(legs: &[Leg; 6]) -> [f64; 36] {
400 let mut a = [0.0; 36];
401 for (i, leg) in legs.iter().enumerate() {
402 let m = cross(leg.b, leg.u);
403 a[i * 6..i * 6 + 6].copy_from_slice(&[leg.u[0], leg.u[1], leg.u[2], m[0], m[1], m[2]]);
404 }
405 a
406 }
407
408 pub fn inverse_jacobian(legs: &[Leg; 6]) -> Vec<f64> {
410 let mut j = Self::constraint(legs);
411 for (i, leg) in legs.iter().enumerate() {
412 j[i * 6..i * 6 + 6].iter_mut().for_each(|v| *v /= leg.arm);
413 }
414 j.to_vec()
415 }
416
417 pub fn pose(&self, q: &[f64]) -> Option<(V3, M3)> {
420 self.pose_on(&self.cranks(q), q)
421 }
422
423 fn pose_on(&self, cranks: &[Crank; 6], q: &[f64]) -> Option<(V3, M3)> {
425 let dq: [f64; 6] = std::array::from_fn(|c| q[c] - self.home_q[c]);
426 let guess: [f64; 6] = std::array::from_fn(|r| (0..6).map(|c| self.home_k[r * 6 + c] * dq[c]).sum());
427 let ok = guess.iter().all(|v| v.is_finite() && v.abs() < 0.5);
429 let guess = if ok { guess } else { [0.0; 6] };
430 let p = add([self.home[0], self.home[1], self.home[2]], [guess[0], guess[1], guess[2]]);
431 let r = matmul(&exp([guess[3], guess[4], guess[5]]), &Self::rotation(&self.home));
432 self.pose_from(cranks, p, r)
433 }
434
435 fn pose_from(&self, cranks: &[Crank; 6], mut p: V3, mut r: M3) -> Option<(V3, M3)> {
437 for _ in 0..40 {
438 let legs = self.legs_on(cranks, p, &r);
439 let miss: [f64; 6] = std::array::from_fn(|i| self.rod - legs[i].length);
440 let worst = miss.iter().fold(0.0f64, |m, v| m.max(v.abs()));
441 if !worst.is_finite() {
442 return None;
443 }
444 let step = Lu::of(&Self::constraint(&legs))?.solve(miss);
445 p = add(p, [step[0], step[1], step[2]]);
446 r = matmul(&exp([step[3], step[4], step[5]]), &r);
447 if worst < 1e-12 {
451 return Some((p, r));
452 }
453 }
454 None
455 }
456
457 pub fn forward(&self, q: &[f64], tool: &mut [f64]) {
459 match self.pose(q) {
460 Some((p, r)) => {
461 let rv = log(&r);
462 tool[..6].copy_from_slice(&[p[0], p[1], p[2], rv[0], rv[1], rv[2]]);
463 }
464 None => tool.iter_mut().for_each(|v| *v = f64::NAN),
465 }
466 }
467
468 pub fn condition(&self, tool: &[f64]) -> f64 {
472 let Some(legs) = self.legs(tool) else { return f64::INFINITY };
473 let mut j = Self::inverse_jacobian(&legs);
474 for i in 0..6 {
475 for c in 3..6 {
476 j[i * 6 + c] /= self.platform_radius;
477 }
478 }
479 if !j.iter().all(|v| v.is_finite()) {
480 return f64::INFINITY;
481 }
482 condition_number(&j, 6, 6)
483 }
484
485 pub fn angles(&self, legs: &[Leg; 6], r: &M3) -> [[f64; 3]; 6] {
488 let normal = mul(r, Z);
489 std::array::from_fn(|i| {
490 let leg = &legs[i];
491 [
492 (leg.arm.abs() / self.crank).clamp(0.0, 1.0).acos(),
493 dot(leg.u, self.axis[i]).abs().clamp(0.0, 1.0).asin(),
494 dot(leg.u, normal).clamp(-1.0, 1.0).acos(),
495 ]
496 })
497 }
498
499 pub fn clearance(legs: &[Leg; 6]) -> f64 {
501 let mut least = f64::INFINITY;
502 for i in 0..6 {
503 for j in i + 1..6 {
504 least = least.min(segment_distance(legs[i].tip, legs[i].joint, legs[j].tip, legs[j].joint));
505 }
506 }
507 least
508 }
509
510 pub fn body_clearance(&self, legs: &[Leg; 6]) -> f64 {
513 let mut least = f64::INFINITY;
514 for i in 0..6 {
515 for j in 0..6 {
516 let k = (j + 1) % 6;
517 if i != j && i != k {
518 least = least.min(segment_distance(legs[i].tip, legs[i].joint, legs[j].joint, legs[k].joint));
519 least = least.min(segment_distance(legs[i].tip, legs[i].joint, self.base[j], self.base[k]));
520 }
521 }
522 }
523 least
524 }
525}
526
527#[derive(Debug, Clone, Copy)]
530struct Body {
531 mass: f64,
532 moment: V3,
533 inertia: M3,
534}
535
536fn shifted(diag: V3, m: f64, c: V3) -> M3 {
538 std::array::from_fn(|i| {
539 std::array::from_fn(|j| if i == j { diag[i] + m * dot(c, c) } else { 0.0 } - m * c[i] * c[j])
540 })
541}
542
543impl Body {
544 fn plus(&self, other: &Body) -> Body {
545 Body {
546 mass: self.mass + other.mass,
547 moment: add(self.moment, other.moment),
548 inertia: std::array::from_fn(|i| std::array::from_fn(|j| self.inertia[i][j] + other.inertia[i][j])),
549 }
550 }
551}
552
553#[derive(Clone)]
555pub struct RotaryPlatform {
556 pub geo: Geometry,
557 platform: Body,
558 payload: Body,
559 attached: bool,
560 rods_inertia: Body,
563 rods_weight: Body,
564 pub crank_mass: f64,
565 pub crank_cg: f64,
566 pub crank_inertia: f64,
567 pub rod_mass: f64,
568 g: f64,
569 dead_centre_limit: f64,
572 buckling_limit: f64,
573 last: LastFound,
575}
576
577struct Motion {
580 tool: [f64; 6],
581 r: M3,
582 legs: [Leg; 6],
583 k: [f64; 36],
584 xi: [f64; 6],
585 xi0: [f64; 6],
586}
587
588#[derive(Debug, Clone, Copy)]
591struct Found {
592 key: [i64; 6],
593 q: [f64; 6],
594 p: V3,
595 r: M3,
596 k: [f64; 36],
597}
598
599const ANCHOR_STEP: f64 = 1e-3;
602
603#[derive(Debug, Default)]
605struct LastFound(std::sync::Mutex<Option<Found>>);
606
607impl LastFound {
608 fn get(&self) -> Option<Found> {
609 self.0.lock().ok().and_then(|f| *f)
610 }
611 fn set(&self, found: Option<Found>) {
612 if let Ok(mut f) = self.0.lock() {
613 *f = found;
614 }
615 }
616}
617
618impl Clone for LastFound {
619 fn clone(&self) -> Self {
620 Self(std::sync::Mutex::new(self.get()))
621 }
622}
623
624fn build(cfg: &Config) -> Result<Box<dyn Machine>, ConfigError> {
625 let (machine, _) = RotaryPlatform::from_config(cfg)?;
626 sim_components::base::mount(cfg, machine)
627}
628
629fn vec3(cfg: &Config, key: &str, positive: bool) -> Result<V3, ConfigError> {
630 let v = cfg.f64s(key)?;
631 if v.len() != 3 || v.iter().any(|x| !x.is_finite() || (positive && !(*x > 0.0))) {
632 return Err(ConfigError::Invalid(key.into()));
633 }
634 Ok([v[0], v[1], v[2]])
635}
636
637impl RotaryPlatform {
638 pub fn from_config(cfg: &Config) -> Result<(Box<dyn Machine>, RotaryPlatform), ConfigError> {
640 let out = match cfg.get("crank.branch")?.as_str() {
641 Some("out") => true,
642 Some("in") => false,
643 _ => return Err(ConfigError::Invalid("crank.branch".into())),
644 };
645 let (crank, rod) = (cfg.positive("crank.length_m")?, cfg.positive("rod.length_m")?);
646 let mut geo = Geometry::new(
647 cfg.positive("platform.base_radius_m")?,
648 cfg.non_negative("platform.base_half_angle_deg")?,
649 cfg.positive("platform.platform_radius_m")?,
650 cfg.non_negative("platform.platform_half_angle_deg")?,
651 cfg.f64("crank.axis_turn_deg")?,
652 crank,
653 rod,
654 out,
655 );
656 geo.min_margin = cfg.non_negative("workspace.min_dead_centre_margin_deg")?.to_radians();
657 geo.max_crank_joint = cfg.positive("workspace.crank_joint_max_angle_deg")?.to_radians();
658 geo.max_platform_joint = cfg.positive("workspace.platform_joint_max_angle_deg")?.to_radians();
659 geo.min_clearance = cfg.non_negative("workspace.min_rod_clearance_m")?;
660 geo.min_body_clearance = cfg.non_negative("workspace.min_body_clearance_m")?;
661 geo.max_condition = cfg.positive("workspace.max_condition_number")?;
662 let (min, max) = (cfg.f64s("workspace.tool_min")?, cfg.f64s("workspace.tool_max")?);
663 if min.len() != 6 || max.len() != 6 {
664 return Err(ConfigError::Invalid("workspace.tool_min".into()));
665 }
666 if (0..6).any(|k| !(min[k] < max[k])) {
667 return Err(ConfigError::Invalid("workspace.tool_max".into()));
668 }
669 geo.set_home(std::array::from_fn(|k| 0.5 * (min[k] + max[k])));
670 let body =
671 |mass: f64, cg: V3, diag: V3| Body { mass, moment: scale(cg, mass), inertia: shifted(diag, mass, cg) };
672 let platform = body(
673 cfg.positive("mass.platform_kg")?,
674 vec3(cfg, "mass.platform_cg_m", false)?,
675 vec3(cfg, "mass.platform_inertia_kgm2", true)?,
676 );
677 let payload = if cfg.bool("effects.payload")? {
678 body(
679 cfg.non_negative("mass.payload_kg")?,
680 vec3(cfg, "mass.payload_cg_m", false)?,
681 vec3(cfg, "mass.payload_inertia_kgm2", false)?,
682 )
683 } else {
684 body(0.0, [0.0; 3], [0.0; 3])
685 };
686 let (d_out, wall) = (cfg.positive("rod.outer_diameter_m")?, cfg.positive("rod.wall_m")?);
688 if 2.0 * wall > d_out {
689 return Err(ConfigError::Invalid("rod.wall_m".into()));
690 }
691 let second_moment = PI / 64.0 * (d_out.powi(4) - (d_out - 2.0 * wall).powi(4));
692 let euler = PI * PI * cfg.positive("rod.youngs_modulus_pa")? * second_moment / (rod * rod);
693 let rod_mass = cfg.non_negative("rod.mass_kg")?;
694 let at_joints =
695 |m: f64| geo.anchors.iter().fold(body(0.0, [0.0; 3], [0.0; 3]), |sum, a| sum.plus(&body(m, *a, [0.0; 3])));
696 let (rods_inertia, rods_weight) = (at_joints(rod_mass / 3.0), at_joints(rod_mass / 2.0));
697 let mech = RotaryPlatform {
698 geo,
699 platform,
700 payload,
701 attached: true,
702 rods_inertia,
703 rods_weight,
704 crank_mass: cfg.non_negative("crank.mass_kg")?,
705 crank_cg: cfg.non_negative("crank.cg_m")?,
706 crank_inertia: cfg.positive("crank.inertia_kgm2")?,
707 rod_mass,
708 g: if cfg.bool("effects.gravity")? { G } else { 0.0 },
709 dead_centre_limit: FRAC_PI_2 - cfg.non_negative("ratings.crank_dead_centre_margin_deg")?.to_radians(),
710 buckling_limit: euler / cfg.positive("ratings.rod_buckling_safety_factor")?,
711 last: LastFound::default(),
712 };
713 let joint = RotaryJoint::from_config(cfg)?;
714 let axes = (0..6)
715 .map(|k| {
716 let unit = if k < 3 { "m" } else { "rad" };
717 let get =
718 |what: &str, rate: &str| cfg.positive(&format!("axis.{}.max_{what}_{unit}_{rate}", AXIS_IDS[k]));
719 Ok(AxisInfo {
720 id: AXIS_IDS[k],
721 key: AXIS_KEYS[k],
722 unit,
723 min: min[k],
724 max: max[k],
725 max_vel: get("velocity", "s")?,
726 max_acc: get("acceleration", "s2")?,
727 max_jerk: get("jerk", "s3")?,
728 })
729 })
730 .collect::<Result<Vec<_>, ConfigError>>()?;
731 let specs = (0..6)
732 .map(|k| JointSpec {
733 drive: joint.clone(),
734 id: MOTOR_IDS[k],
735 key: JOINT_KEYS[k],
736 gear_lever: None,
737 unit: "rad",
738 })
739 .collect();
740 let motors = (0..6).map(|k| MotorInfo { id: MOTOR_IDS[k], key: MOTOR_KEYS[k] }).collect();
741 let machine = JointMachine::new(
742 mech.clone(),
743 specs,
744 cfg.bool("effects.joint_elasticity")?,
745 ThermalFeedback::from_config(cfg)?,
746 axes,
747 motors,
748 );
749 Ok((Box::new(machine), mech))
750 }
751
752 fn body(&self) -> Body {
754 if self.attached { self.platform.plus(&self.payload) } else { self.platform }
755 }
756
757 pub fn buckling_limit(&self) -> f64 {
759 self.buckling_limit
760 }
761
762 fn motion(&self, q: &[f64], qd: &[f64]) -> Option<Motion> {
765 let cranks = self.geo.cranks(q);
766 self.motion_at(&cranks, qd, self.geo.pose_on(&cranks, q)?)
767 }
768
769 fn warm_motion(&self, q: &[f64], qd: &[f64]) -> Option<Motion> {
774 let key: [i64; 6] = std::array::from_fn(|i| (q[i] / ANCHOR_STEP).round() as i64);
775 let cranks = self.geo.cranks(q);
776 let anchor = self.last.get().filter(|f| f.key == key).or_else(|| {
777 let g: [f64; 6] = std::array::from_fn(|i| key[i] as f64 * ANCHOR_STEP);
778 let at_grid = self.geo.cranks(&g);
779 let (p, r) = self.geo.pose_on(&at_grid, &g)?;
780 let found = Found { key, q: g, p, r, k: self.motion_at(&at_grid, &[0.0; 6], (p, r))?.k };
781 self.last.set(Some(found));
782 Some(found)
783 });
784 let warm = anchor.and_then(|f| {
785 let xi: [f64; 6] = std::array::from_fn(|r| (0..6).map(|c| f.k[r * 6 + c] * (q[c] - f.q[c])).sum());
786 self.geo.pose_from(&cranks, add(f.p, [xi[0], xi[1], xi[2]]), matmul(&exp([xi[3], xi[4], xi[5]]), &f.r))
787 });
788 let pose = match warm {
789 Some(pose) => pose,
790 None => self.geo.pose_on(&cranks, q)?,
791 };
792 self.motion_at(&cranks, qd, pose)
793 }
794
795 fn motion_at(&self, cranks: &[Crank; 6], qd: &[f64], (p, r): (V3, M3)) -> Option<Motion> {
797 let rv = log(&r);
798 let tool = [p[0], p[1], p[2], rv[0], rv[1], rv[2]];
799 let legs = self.geo.legs_on(cranks, p, &r);
800 let lu = Lu::of(&Geometry::constraint(&legs))?;
801 let mut k = [0.0; 36];
802 for c in 0..6 {
803 let col = lu.solve(std::array::from_fn(|i| if i == c { legs[c].arm } else { 0.0 }));
804 (0..6).for_each(|r| k[r * 6 + c] = col[r]);
805 }
806 let xi = lu.solve(std::array::from_fn(|i| legs[i].arm * qd[i]));
807 let (v, w) = ([xi[0], xi[1], xi[2]], [xi[3], xi[4], xi[5]]);
808 let s: [f64; 6] = std::array::from_fn(|i| {
809 let leg = &legs[i];
810 let slip = sub(add(v, cross(w, leg.b)), scale(leg.t, qd[i]));
811 dot(leg.u, leg.t2) * qd[i] * qd[i] - dot(slip, slip) / self.geo.rod - dot(leg.u, cross(w, cross(w, leg.b)))
812 });
813 let xi0 = lu.solve(s);
814 Some(Motion { tool, r, legs, k, xi, xi0 })
815 }
816
817 fn joint_jacobian(m: &Motion, b: V3) -> [[f64; 6]; 3] {
819 let mut out = [[0.0; 6]; 3];
820 for c in 0..6 {
821 let v = [m.k[c], m.k[6 + c], m.k[12 + c]];
822 let w = [m.k[18 + c], m.k[24 + c], m.k[30 + c]];
823 let col = add(v, cross(w, b));
824 (0..3).for_each(|r| out[r][c] = col[r]);
825 }
826 out
827 }
828
829 fn twist_terms(&self, m: &Motion, body: &Body, weight: &Body) -> ([f64; 36], [f64; 6], [f64; 6]) {
832 let s = mul(&m.r, body.moment);
833 let inertia = matmul(&matmul(&m.r, &body.inertia), &transpose(&m.r));
834 let mut mx = [0.0; 36];
835 for i in 0..3 {
836 mx[i * 6 + i] = body.mass;
837 for j in 0..3 {
838 mx[(3 + i) * 6 + 3 + j] = inertia[i][j];
839 }
840 }
841 let sx = [[0.0, -s[2], s[1]], [s[2], 0.0, -s[0]], [-s[1], s[0], 0.0]];
843 for i in 0..3 {
844 for j in 0..3 {
845 mx[(3 + i) * 6 + j] = sx[i][j];
846 mx[i * 6 + 3 + j] = -sx[i][j];
847 }
848 }
849 let w = [m.xi[3], m.xi[4], m.xi[5]];
850 let (f, t) = (cross(w, cross(w, s)), cross(w, mul(&inertia, w)));
851 let gw = cross(mul(&m.r, weight.moment), [0.0, 0.0, -self.g]);
852 (mx, [f[0], f[1], f[2], t[0], t[1], t[2]], [0.0, 0.0, -weight.mass * self.g, gw[0], gw[1], gw[2]])
853 }
854
855 pub fn rod_forces(&self, q: &[f64], qd: &[f64], qdd: &[f64]) -> Option<[f64; 6]> {
858 let m = self.motion(q, qd)?;
859 let xi_acc: [f64; 6] = std::array::from_fn(|r| m.xi0[r] + (0..6).map(|c| m.k[r * 6 + c] * qdd[c]).sum::<f64>());
860 let body = self.body();
861 let (mx, c, g) = self.twist_terms(&m, &body, &body);
862 let mut wrench: [f64; 6] =
863 std::array::from_fn(|r| (0..6).map(|k| mx[r * 6 + k] * xi_acc[k]).sum::<f64>() + c[r] - g[r]);
864 let (v_acc, w_acc, w) =
865 ([xi_acc[0], xi_acc[1], xi_acc[2]], [xi_acc[3], xi_acc[4], xi_acc[5]], [m.xi[3], m.xi[4], m.xi[5]]);
866 for (i, leg) in m.legs.iter().enumerate() {
867 let a_high = add(add(v_acc, cross(w_acc, leg.b)), cross(w, cross(w, leg.b)));
868 let a_low = add(scale(leg.t, qdd[i]), scale(leg.t2, qd[i] * qd[i]));
869 let a_mid = scale(add(a_low, a_high), 0.5);
870 let need = |a: V3| [a[0], a[1], a[2] + self.g];
871 let f = add(scale(need(a_high), self.rod_mass / 6.0), scale(need(a_mid), self.rod_mass / 3.0));
872 let t = cross(leg.b, f);
873 for k in 0..3 {
874 wrench[k] += f[k];
875 wrench[3 + k] += t[k];
876 }
877 }
878 let a = Geometry::constraint(&m.legs);
879 let at: Vec<f64> = (0..36).map(|k| a[(k % 6) * 6 + k / 6]).collect();
880 let f = solve(&at, &wrench)?;
881 Some(std::array::from_fn(|i| f[i]))
882 }
883}
884
885impl Mechanism for RotaryPlatform {
886 fn dynamics(&self, q: &[f64], qd: &[f64], mass: &mut [f64], bias: &mut [f64]) {
887 let Some(m) = self.warm_motion(q, qd) else {
888 mass.fill(f64::NAN);
889 bias.fill(f64::NAN);
890 return;
891 };
892 let (inertial, weighing) = (self.body().plus(&self.rods_inertia), self.body().plus(&self.rods_weight));
897 let (mx, c, g) = self.twist_terms(&m, &inertial, &weighing);
898 let need: [f64; 6] =
899 std::array::from_fn(|r| (0..6).map(|k| mx[r * 6 + k] * m.xi0[k]).sum::<f64>() + c[r] - g[r]);
900 let mk: [f64; 36] = std::array::from_fn(|rc| (0..6).map(|k| mx[rc / 6 * 6 + k] * m.k[k * 6 + rc % 6]).sum());
902 for i in 0..6 {
903 bias[i] = (0..6).map(|r| m.k[r * 6 + i] * need[r]).sum();
904 for j in 0..6 {
905 mass[i * 6 + j] = (0..6).map(|r| m.k[r * 6 + i] * mk[r * 6 + j]).sum();
906 }
907 }
908 let (rod, w) = (self.rod_mass, [m.xi[3], m.xi[4], m.xi[5]]);
909 for (i, leg) in m.legs.iter().enumerate() {
910 let high = Self::joint_jacobian(&m, leg.b);
911 let a_high = add(add([m.xi0[0], m.xi0[1], m.xi0[2]], cross([m.xi0[3], m.xi0[4], m.xi0[5]], leg.b)), {
912 cross(w, cross(w, leg.b))
913 });
914 let a_low = scale(leg.t2, qd[i] * qd[i]);
915 for c in 0..6 {
916 let col = [high[0][c], high[1][c], high[2][c]];
917 let cross_term = rod / 6.0 * dot(leg.t, col);
918 mass[i * 6 + c] += cross_term;
919 mass[c * 6 + i] += cross_term;
920 bias[c] += rod / 6.0 * dot(col, a_low);
921 }
922 mass[i * 6 + i] += self.crank_inertia + rod / 3.0 * dot(leg.t, leg.t);
923 bias[i] += rod / 6.0 * dot(leg.t, a_high)
924 + self.g * (self.crank_mass * self.crank_cg + 0.5 * rod * self.geo.crank) * leg.cos;
925 }
926 }
927
928 fn frame_momentum(&self, q: &[f64], qd: &[f64], rotor_spin: &[f64]) -> Option<sim_core::FrameMomentum> {
931 use sim_components::base::{add_point, add_spin, add_turning};
932 let m = self.motion(q, qd)?;
933 let mut f = sim_core::FrameMomentum { gravity: [0.0, 0.0, -self.g], ..Default::default() };
934 let body = self.body();
935 let (p, v, w) = ([m.tool[0], m.tool[1], m.tool[2]], [m.xi[0], m.xi[1], m.xi[2]], [m.xi[3], m.xi[4], m.xi[5]]);
936 if body.mass > 0.0 {
937 let rc = scale(mul(&m.r, body.moment), 1.0 / body.mass);
938 add_point(&mut f, body.mass, add(p, rc), add(v, cross(w, rc)));
939 let about_p = matmul(&matmul(&m.r, &body.inertia), &transpose(&m.r));
940 let own: M3 = std::array::from_fn(|i| {
941 std::array::from_fn(|j| {
942 about_p[i][j] - body.mass * (if i == j { dot(rc, rc) } else { 0.0 } - rc[i] * rc[j])
943 })
944 });
945 let spin = mul(&own, w);
946 (0..3).for_each(|k| f.angular[k] += spin[k]);
947 }
948 for (i, leg) in m.legs.iter().enumerate() {
949 let (v_low, v_high) = (scale(leg.t, qd[i]), add(v, cross(w, leg.b)));
950 add_point(&mut f, self.rod_mass / 6.0, leg.tip, v_low);
951 add_point(&mut f, self.rod_mass / 6.0, leg.joint, v_high);
952 add_point(
953 &mut f,
954 2.0 * self.rod_mass / 3.0,
955 scale(add(leg.tip, leg.joint), 0.5),
956 scale(add(v_low, v_high), 0.5),
957 );
958 let r = self.geo.crank;
959 let dir = scale(sub(leg.tip, self.geo.base[i]), 1.0 / r);
960 add_turning(
961 &mut f,
962 self.geo.base[i],
963 dir,
964 scale(leg.t, 1.0 / r),
965 qd[i],
966 self.crank_inertia,
967 self.crank_mass * self.crank_cg,
968 );
969 add_spin(&mut f, self.geo.axis[i], 1.0, rotor_spin[i]);
970 }
971 Some(f)
972 }
973
974 fn potential(&self, q: &[f64]) -> f64 {
975 let mut tool = [0.0; 6];
976 self.geo.forward(q, &mut tool);
977 let r = Geometry::rotation(&tool);
978 let legs = self.geo.legs_at(q, [tool[0], tool[1], tool[2]], &r);
979 let body = self.body();
980 let rods: f64 = legs.iter().map(|l| 0.5 * self.rod_mass * (l.tip[2] + l.joint[2])).sum();
981 let cranks: f64 = q[..6].iter().map(|t| self.crank_mass * self.crank_cg * t.sin()).sum();
982 self.g * (body.mass * tool[2] + mul(&r, body.moment)[2] + rods + cranks)
983 }
984 fn set_payload_attached(&mut self, attached: bool) {
985 self.attached = attached;
986 }
987
988 fn forward(&self, q: &[f64], tool: &mut [f64]) {
989 self.geo.forward(q, tool);
990 }
991 fn inverse(&self, tool: &[f64], q: &mut [f64]) -> bool {
992 self.geo.inverse(tool, q)
993 }
994 fn unreachable(&self, tool: &[f64], _slack: f64) -> Option<&'static str> {
998 let legs = self.geo.legs(tool)?;
999 let angles = self.geo.angles(&legs, &Geometry::rotation(tool));
1000 if angles.iter().any(|a| !(FRAC_PI_2 - a[0] >= self.geo.min_margin)) {
1001 return Some("error-rss-dead-centre");
1002 }
1003 if angles.iter().any(|a| !(a[1] <= self.geo.max_crank_joint && a[2] <= self.geo.max_platform_joint)) {
1004 return Some("error-rss-ball-joint");
1005 }
1006 if !(Geometry::clearance(&legs) >= self.geo.min_clearance) {
1007 return Some("error-rss-rods-cross");
1008 }
1009 if !(self.geo.body_clearance(&legs) >= self.geo.min_body_clearance) {
1010 return Some("error-rss-rods-cross-body");
1011 }
1012 if !(self.geo.condition(tool) <= self.geo.max_condition) {
1013 return Some("error-rss-singularity");
1014 }
1015 None
1016 }
1017 fn condition(&self, tool: &[f64]) -> Option<f64> {
1018 Some(self.geo.condition(tool))
1019 }
1020 fn tool_is_joints(&self) -> bool {
1021 false
1022 }
1023
1024 fn signal_infos(&self) -> Vec<SignalInfo> {
1027 let mut out = Vec::new();
1028 for i in 0..6 {
1029 let id = MOTOR_IDS[i];
1030 out.push(SignalInfo::new(
1031 format!("crank.{id}.dead_centre_angle"),
1032 JOINT_KEYS[i],
1033 "quantity-dead-centre-angle",
1034 "rad",
1035 ));
1036 out.push(SignalInfo::new(format!("rod.{id}.force"), JOINT_KEYS[i], "quantity-rod-force", "N"));
1037 out.push(SignalInfo::new(format!("rod.{id}.compression"), JOINT_KEYS[i], "quantity-rod-compression", "N"));
1038 out.push(SignalInfo::new(
1039 format!("crank.{id}.ball_joint_angle"),
1040 JOINT_KEYS[i],
1041 "quantity-crank-ball-joint-angle",
1042 "rad",
1043 ));
1044 out.push(SignalInfo::new(
1045 format!("platform.{id}.ball_joint_angle"),
1046 JOINT_KEYS[i],
1047 "quantity-platform-ball-joint-angle",
1048 "rad",
1049 ));
1050 }
1051 out.push(SignalInfo::new("kinematics.condition", "group-platform", "quantity-condition-number", ""));
1052 out
1053 }
1054 fn signals(&self, q: &[f64], qd: &[f64], qdd: &[f64], _force: &[f64], out: &mut Vec<f64>) {
1055 let Some(m) = self.motion(q, qd) else {
1056 out.extend(std::iter::repeat_n(f64::NAN, 31));
1057 return;
1058 };
1059 let angles = self.geo.angles(&m.legs, &m.r);
1060 let forces = self.rod_forces(q, qd, qdd).unwrap_or([f64::NAN; 6]);
1061 for i in 0..6 {
1062 out.extend([angles[i][0], forces[i], forces[i].max(0.0), angles[i][1], angles[i][2]]);
1063 }
1064 out.push(self.geo.condition(&m.tool));
1065 }
1066 fn rating_checks(&self) -> Vec<RatingCheck> {
1068 (0..6)
1069 .flat_map(|i| {
1070 let id = MOTOR_IDS[i];
1071 [
1072 ("crank-dead-centre", format!("crank.{id}.dead_centre_angle"), self.dead_centre_limit),
1073 ("rod-buckling", format!("rod.{id}.compression"), self.buckling_limit),
1074 ("crank-ball-joint", format!("crank.{id}.ball_joint_angle"), self.geo.max_crank_joint),
1075 ("platform-ball-joint", format!("platform.{id}.ball_joint_angle"), self.geo.max_platform_joint),
1076 ]
1077 .map(|(check, signal, limit)| RatingCheck {
1078 check,
1079 signal,
1080 motor: Some(i),
1081 limit,
1082 life: false,
1083 })
1084 })
1085 .collect()
1086 }
1087
1088 fn collision_parts(&self) -> &'static [&'static str] {
1089 &["tool", "payload"]
1090 }
1091
1092 fn scene(&self, q: &[f64], rotors: &[f64], rotor_speeds: &[f64], out: &mut Scene) {
1095 let mut tool = [0.0; 6];
1096 self.geo.forward(q, &mut tool);
1097 if !tool.iter().all(|v| v.is_finite()) {
1098 return;
1099 }
1100 let r = Geometry::rotation(&tool);
1101 let p = [tool[0], tool[1], tool[2]];
1102 let legs = self.geo.legs_at(q, p, &r);
1103 for i in 0..6 {
1104 let next = (i + 1) % 6;
1105 out.parts.push(Part::new(
1106 "base",
1107 Shape::Segment { to: self.geo.base[next], width: 0.04 },
1108 self.geo.base[i],
1109 [0.55, 0.57, 0.6],
1110 ));
1111 out.parts.push(Part::new(
1112 "platform",
1113 Shape::Segment { to: legs[next].joint, width: 0.04 },
1114 legs[i].joint,
1115 [0.3, 0.45, 0.7],
1116 ));
1117 }
1118 for (i, leg) in legs.iter().enumerate() {
1119 let (b, k) = (self.geo.base[i], self.geo.axis[i]);
1120 out.parts.push(Part::new("crank", Shape::Segment { to: leg.tip, width: 0.04 }, b, [0.45, 0.47, 0.5]));
1121 out.parts.push(Part::new("rod", Shape::Segment { to: leg.joint, width: 0.02 }, leg.tip, [0.85, 0.86, 0.9]));
1122 out.parts.push(Part::new(
1123 "gearbox",
1124 Shape::Segment { to: add(b, scale(k, -0.12)), width: 0.08 },
1125 add(b, scale(k, -0.03)),
1126 [0.25, 0.25, 0.28],
1127 ));
1128 out.parts.push(Part::new(
1129 sim_core::scene::MOTOR_PART,
1130 Shape::Segment { to: add(b, scale(k, -0.25)), width: 0.09 },
1131 add(b, scale(k, -0.12)),
1132 [0.9, 0.45, 0.1],
1133 ));
1134 out.parts.push(
1135 Part::new("rotor-bar", Shape::Box { size: [0.07, 0.004, 0.012] }, add(b, scale(k, -0.27)), [0.1; 3])
1136 .turned(rotors[i]),
1137 );
1138 out.labels.push(Label {
1139 pos: add(b, add(scale(k, -0.3), [0.0, 0.0, -0.05])),
1140 owner_key: MOTOR_KEYS[i],
1141 value: rotor_speeds[i] * 60.0 / TAU,
1142 unit_key: "unit-rpm",
1143 decimals: 0,
1144 });
1145 out.labels.push(Label {
1146 pos: add(leg.tip, [0.0, 0.0, 0.05]),
1147 owner_key: JOINT_KEYS[i],
1148 value: q[i].to_degrees(),
1149 unit_key: "unit-deg",
1150 decimals: 1,
1151 });
1152 }
1153 out.parts.push(Part::new(
1154 "tool",
1155 Shape::Box { size: [0.1, 0.1, 0.03] },
1156 add(p, mul(&r, [0.0, 0.0, 0.015])),
1157 [0.2, 0.22, 0.26],
1158 ));
1159 if self.attached && self.payload.mass > 0.0 {
1160 let at = scale(self.payload.moment, 1.0 / self.payload.mass);
1161 out.parts.push(Part::new(
1162 "payload",
1163 Shape::Box { size: [0.3, 0.3, 0.3] },
1164 add(p, mul(&r, at)),
1165 [0.2, 0.7, 0.3],
1166 ));
1167 }
1168 out.labels.push(Label {
1169 pos: add(p, [0.0, 0.0, 0.5]),
1170 owner_key: "axis-z",
1171 value: p[2],
1172 unit_key: "unit-m",
1173 decimals: 3,
1174 });
1175 }
1176 fn scene_point(&self, tool: &[f64]) -> Option<[f64; 3]> {
1177 Some([tool[0], tool[1], tool[2]])
1178 }
1179}
1180
1181#[cfg(test)]
1182mod tests;