1use sim_components::chain::{
60 JOINT_KEYS, JointMachine, JointSpec, MOTOR_IDS, MOTOR_KEYS, Mechanism, condition_number, invert,
61};
62use sim_components::joint::RotaryJoint;
63use sim_components::mech::{HardStop, ShaftFriction, ThermalFeedback};
64use sim_components::rigid::{M3, V3, add, cross, dot, matmul, mul, transpose};
65use sim_components::transmission::BallScrew;
66use sim_core::{
67 AxisInfo, Config, ConfigError, Label, Machine, MachineEntry, MotorInfo, Part, RatingCheck, Scene, Shape, SignalInfo,
68};
69use std::f64::consts::TAU;
70
71pub static ENTRY: MachineEntry = MachineEntry {
72 id: "tripod",
73 key: "machine-tripod",
74 default_config: include_str!("../default.toml"),
75 i18n: &[("en", include_str!("../i18n/en.ftl")), ("de", include_str!("../i18n/de.ftl"))],
76 build,
77 suite_configs,
78};
79
80const G: f64 = 9.80665;
81
82pub const LOSSY_EFFECTS: [&str; 7] = [
84 "joint_friction",
85 "motor_friction",
86 "gearbox_drag",
87 "gearbox_lost_motion",
88 "gearbox_efficiency",
89 "torque_ripple",
90 "holding_brake",
91];
92
93const AXIS_IDS: [&str; 3] = ["z", "rx", "ry"];
94const AXIS_KEYS: [&str; 3] = ["axis-z", "axis-rx", "axis-ry"];
95
96pub fn lossless_config() -> Config {
98 let mut cfg = ENTRY.config();
99 for effect in LOSSY_EFFECTS {
100 cfg.set_text(&format!("effects.{effect} = false")).unwrap();
101 }
102 cfg.set_text("gearbox.damping_nm_s_rad = 0.0").unwrap();
103 cfg.set_text("leg.stop_damping_n_s_m = 0.0").unwrap();
104 cfg
105}
106
107fn suite_configs() -> Vec<Config> {
112 [(false, true), (false, false), (true, true), (true, false)]
113 .into_iter()
114 .map(|(elastic, payload)| {
115 let mut cfg = lossless_config();
116 cfg.set_text(&format!("effects.joint_elasticity = {elastic}")).unwrap();
117 cfg.set_text(&format!("effects.payload = {payload}")).unwrap();
118 cfg.set_text("effects.gravity = false").unwrap();
119 cfg
120 })
121 .collect()
122}
123
124fn sub(a: V3, b: V3) -> V3 {
125 [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
126}
127
128fn norm(a: V3) -> f64 {
129 dot(a, a).sqrt()
130}
131
132fn scale(a: V3, k: f64) -> V3 {
133 a.map(|v| v * k)
134}
135
136fn rot_x(a: f64) -> M3 {
138 let (s, c) = a.sin_cos();
139 [[1.0, 0.0, 0.0], [0.0, c, -s], [0.0, s, c]]
140}
141fn rot_y(a: f64) -> M3 {
142 let (s, c) = a.sin_cos();
143 [[c, 0.0, s], [0.0, 1.0, 0.0], [-s, 0.0, c]]
144}
145fn rot_z(a: f64) -> M3 {
146 let (s, c) = a.sin_cos();
147 [[c, -s, 0.0], [s, c, 0.0], [0.0, 0.0, 1.0]]
148}
149
150fn apply(m: &[f64], v: &[f64]) -> Vec<f64> {
152 let cols = v.len();
153 (0..m.len() / cols).map(|r| (0..cols).map(|c| m[r * cols + c] * v[c]).sum()).collect()
154}
155
156pub struct Lu {
158 a: [f64; 36],
159 perm: [usize; 6],
160}
161
162impl Lu {
163 pub fn new(m: &[f64]) -> Option<Self> {
165 let mut a = [0.0; 36];
166 a.copy_from_slice(&m[..36]);
167 let mut perm = [0, 1, 2, 3, 4, 5];
168 for c in 0..6 {
169 let p = (c..6).max_by(|&i, &j| a[i * 6 + c].abs().total_cmp(&a[j * 6 + c].abs()))?;
170 if !(a[p * 6 + c].abs() > 1e-300) {
171 return None;
172 }
173 if p != c {
174 for k in 0..6 {
175 a.swap(p * 6 + k, c * 6 + k);
176 }
177 perm.swap(p, c);
178 }
179 for r in c + 1..6 {
180 let f = a[r * 6 + c] / a[c * 6 + c];
181 a[r * 6 + c] = f;
182 for k in c + 1..6 {
183 a[r * 6 + k] -= f * a[c * 6 + k];
184 }
185 }
186 }
187 Some(Self { a, perm })
188 }
189
190 pub fn solve(&self, b: &[f64; 6]) -> [f64; 6] {
191 let mut x: [f64; 6] = std::array::from_fn(|i| b[self.perm[i]]);
192 for r in 1..6 {
193 for k in 0..r {
194 x[r] -= self.a[r * 6 + k] * x[k];
195 }
196 }
197 for r in (0..6).rev() {
198 for k in r + 1..6 {
199 x[r] -= self.a[r * 6 + k] * x[k];
200 }
201 x[r] /= self.a[r * 6 + r];
202 }
203 x
204 }
205
206 pub fn columns(&self) -> [[f64; 6]; 3] {
208 std::array::from_fn(|c| self.solve(&std::array::from_fn(|r| if r == c { 1.0 } else { 0.0 })))
209 }
210}
211
212#[derive(Debug, Clone, Copy)]
215pub struct Place {
216 pub p: V3,
217 pub r: M3,
218 pub turn: f64,
219}
220
221#[derive(Debug, Clone, Copy)]
224pub struct Legs {
225 pub u: [V3; 3],
226 pub length: [f64; 3],
227 pub b: [V3; 3],
228}
229
230#[derive(Debug, Clone)]
232pub struct Geometry {
233 pub base: [V3; 3],
236 pub anchors: [V3; 3],
237 pub tangents: [V3; 3],
238 pub radial: [V3; 3],
239 pub platform_radius: f64,
240 pub closed: f64,
241 pub stroke: f64,
242 pub max_revolute: f64,
245 pub max_cone: f64,
246 pub max_condition: f64,
247 pub home: [f64; 3],
249 pub chord: Vec<f64>,
250}
251
252impl Geometry {
253 pub fn new(base_radius: f64, platform_radius: f64) -> Self {
254 let azimuth = [0.0f64, 120.0, 240.0].map(|deg| deg.to_radians().sin_cos());
255 let radial = azimuth.map(|(s, c)| [c, s, 0.0]);
256 Self {
257 base: radial.map(|r| scale(r, base_radius)),
258 anchors: radial.map(|r| scale(r, platform_radius)),
259 tangents: azimuth.map(|(s, c)| [-s, c, 0.0]),
260 radial,
261 platform_radius,
262 closed: 0.0,
263 stroke: 1.0,
264 max_revolute: std::f64::consts::FRAC_PI_2,
265 max_cone: std::f64::consts::FRAC_PI_2,
266 max_condition: f64::INFINITY,
267 home: [0.0; 3],
268 chord: Vec::new(),
269 }
270 }
271
272 pub fn set_home(&mut self, home: [f64; 3]) -> bool {
274 self.home = home;
275 let legs = self.legs(&home);
276 match self.rates(&home, &legs) {
277 Some(k) => {
278 self.chord = k;
279 true
280 }
281 None => false,
282 }
283 }
284
285 pub fn place(&self, tool: &[f64]) -> Place {
287 let (z, a, b) = (tool[0], tool[1], tool[2]);
288 let (sa, ca) = a.sin_cos();
289 let (sb, cb) = b.sin_cos();
290 let turn = (-sa * sb).atan2(ca + cb);
291 let (sg, cg) = turn.sin_cos();
292 let rp = self.platform_radius;
293 let p = [rp * (cb * cg + sa * sb * sg - ca * cg) / 2.0, rp * cb * sg, z];
294 Place { p, r: matmul(&matmul(&rot_x(a), &rot_y(b)), &rot_z(turn)), turn }
295 }
296
297 pub fn legs_at(&self, place: &Place) -> Legs {
298 let mut legs = Legs { u: [[0.0; 3]; 3], length: [0.0; 3], b: [[0.0; 3]; 3] };
299 for i in 0..3 {
300 let b = mul(&place.r, self.anchors[i]);
301 let d = sub(add(place.p, b), self.base[i]);
302 let l = norm(d);
303 legs.u[i] = scale(d, 1.0 / l);
304 legs.length[i] = l;
305 legs.b[i] = b;
306 }
307 legs
308 }
309
310 pub fn legs(&self, tool: &[f64]) -> Legs {
311 self.legs_at(&self.place(tool))
312 }
313
314 pub fn constraint_matrix(&self, legs: &Legs) -> Vec<f64> {
316 let mut g = vec![0.0; 36];
317 for i in 0..3 {
318 let (m, n) = (cross(legs.b[i], legs.u[i]), cross(legs.b[i], self.tangents[i]));
319 let e = self.tangents[i];
320 g[i * 6..i * 6 + 6].copy_from_slice(&[legs.u[i][0], legs.u[i][1], legs.u[i][2], m[0], m[1], m[2]]);
321 g[(3 + i) * 6..(3 + i) * 6 + 6].copy_from_slice(&[e[0], e[1], e[2], n[0], n[1], n[2]]);
322 }
323 g
324 }
325
326 fn selection(tool: &[f64]) -> [f64; 18] {
328 let (sa, ca) = tool[1].sin_cos();
329 let tb = tool[2].tan();
330 let mut s = [0.0; 18];
331 s[2] = 1.0;
332 s[6 + 3] = 1.0;
333 s[6 + 4] = tb * sa;
334 s[6 + 5] = -tb * ca;
335 s[12 + 4] = ca;
336 s[12 + 5] = sa;
337 s
338 }
339
340 pub fn rates(&self, tool: &[f64], legs: &Legs) -> Option<Vec<f64>> {
343 let a = Lu::new(&self.constraint_matrix(legs))?.columns();
344 let s = Self::selection(tool);
345 Some((0..9).map(|rc| (0..6).map(|k| s[rc / 3 * 6 + k] * a[rc % 3][k]).sum()).collect())
346 }
347
348 pub fn jacobian(&self, tool: &[f64]) -> Option<Vec<f64>> {
350 invert(&self.rates(tool, &self.legs(tool))?, 3)
351 }
352
353 pub fn inverse(&self, tool: &[f64], q: &mut [f64]) -> bool {
355 let legs = self.legs(tool);
356 for i in 0..3 {
357 q[i] = legs.length[i] - self.closed;
358 }
359 q[..3].iter().all(|v| v.is_finite()) && legs.length.iter().all(|l| *l > 0.0)
360 }
361
362 fn miss(&self, q: &[f64], x: &[f64; 3]) -> (Vec<f64>, f64) {
364 let legs = self.legs(x);
365 let miss: Vec<f64> = (0..3).map(|i| q[i] + self.closed - legs.length[i]).collect();
366 let worst = miss.iter().fold(0.0f64, |m, v| m.max(v.abs()));
367 (miss, worst)
368 }
369
370 pub fn forward(&self, q: &[f64], tool: &mut [f64]) {
376 let mut x = self.home;
377 let (mut miss, mut worst) = self.miss(q, &x);
378 let (mut fast, mut fell_back, mut converged) = (None::<Vec<f64>>, false, false);
379 for _ in 0..100 {
380 if !worst.is_finite() || x[1].abs() > 1.5 || x[2].abs() > 1.5 {
381 break;
382 }
383 if worst < 1e-13 {
384 converged = true;
385 break;
386 }
387 let step = apply(fast.as_deref().unwrap_or(&self.chord), &miss);
388 let next = [x[0] + step[0], x[1] + step[1], x[2] + step[2]];
389 let (next_miss, next_worst) = self.miss(q, &next);
390 if fast.is_some() && !(next_worst < 0.5 * worst) {
391 (fast, fell_back) = (None, true);
392 continue;
393 }
394 (x, miss, worst) = (next, next_miss, next_worst);
395 if fast.is_none() && !fell_back {
396 fast = self.rates(&x, &self.legs(&x));
397 fell_back = fast.is_none();
398 }
399 }
400 if converged {
401 tool[..3].copy_from_slice(&x);
402 } else {
403 tool.iter_mut().for_each(|v| *v = f64::NAN);
404 }
405 }
406
407 pub fn joint_angles(&self, tool: &[f64]) -> ([f64; 3], [f64; 3]) {
410 let place = self.place(tool);
411 let legs = self.legs_at(&place);
412 let normal = [place.r[0][2], place.r[1][2], place.r[2][2]];
413 (
414 std::array::from_fn(|i| dot(legs.u[i], self.radial[i]).atan2(legs.u[i][2])),
415 std::array::from_fn(|i| dot(legs.u[i], normal).clamp(-1.0, 1.0).acos()),
416 )
417 }
418
419 pub fn condition(&self, tool: &[f64]) -> f64 {
422 let Some(mut k) = self.rates(tool, &self.legs(tool)) else { return f64::INFINITY };
423 for v in &mut k[3..] {
424 *v *= self.platform_radius;
425 }
426 condition_number(&k, 3, 3)
427 }
428
429 pub fn parasitic(&self, tool: &[f64]) -> [f64; 4] {
433 let place = self.place(tool);
434 let d = [place.p[0], place.p[1], 0.0];
435 let pure = matmul(&rot_x(tool[1]), &rot_y(tool[2]));
436 let local = mul(&transpose(&pure), d);
437 let c = 2.0 * self.platform_radius * (0.5 * place.turn).sin().abs();
438 let error = (dot(d, d) + c * c + 2.0 * c * local[0].hypot(local[1])).sqrt();
439 [place.p[0], place.p[1], place.turn, error]
440 }
441
442 pub fn chord_contraction(&self, tool: &[f64]) -> f64 {
445 let Some(k) = self.jacobian(tool) else { return f64::INFINITY };
446 let w = [1.0, self.platform_radius, self.platform_radius];
447 (0..3)
448 .map(|r| {
449 (0..3)
450 .map(|c| {
451 let prod: f64 = (0..3).map(|m| self.chord[r * 3 + m] * k[m * 3 + c]).sum();
452 (w[r] * (if r == c { 1.0 } else { 0.0 } - prod) / w[c]).abs()
453 })
454 .sum::<f64>()
455 })
456 .fold(0.0, f64::max)
457 }
458}
459
460#[derive(Debug, Clone, Copy)]
463struct Body {
464 mass: f64,
465 moment: V3,
466 inertia: M3,
467}
468
469impl Body {
470 fn at(m: f64, c: V3, own: M3) -> Self {
472 let inertia = std::array::from_fn(|i| {
473 std::array::from_fn(|j| own[i][j] + m * (if i == j { dot(c, c) } else { 0.0 } - c[i] * c[j]))
474 });
475 Self { mass: m, moment: scale(c, m), inertia }
476 }
477 fn plus(self, o: Self) -> Self {
478 Self {
479 mass: self.mass + o.mass,
480 moment: add(self.moment, o.moment),
481 inertia: std::array::from_fn(|i| std::array::from_fn(|j| self.inertia[i][j] + o.inertia[i][j])),
482 }
483 }
484}
485
486fn diagonal(cfg: &Config, key: &str) -> Result<M3, ConfigError> {
487 let d = cfg.f64s(key)?;
488 if d.len() != 3 || d.iter().any(|v| !(*v >= 0.0)) {
489 return Err(ConfigError::Invalid(key.into()));
490 }
491 Ok(std::array::from_fn(|i| std::array::from_fn(|j| if i == j { d[i] } else { 0.0 })))
492}
493
494#[derive(Debug, Clone, Copy)]
497struct LegPart {
498 mass: f64,
499 centre: f64,
500 inertia: f64,
501 on_platform: bool,
502}
503
504struct PartMotion {
508 a: [V3; 6],
509 a0: V3,
510 au: [V3; 6],
511 u2: V3,
512}
513
514#[derive(Clone)]
515pub struct Tripod {
516 pub geo: Geometry,
517 screw: BallScrew,
518 empty: Body,
520 loaded: Body,
521 parts: [LegPart; 2],
523 attached: bool,
524 g: f64,
525 required_life: Option<f64>,
526 max_force: f64,
527 parasitic_tolerance: Option<f64>,
528}
529
530fn build(cfg: &Config) -> Result<Box<dyn Machine>, ConfigError> {
531 let (machine, _) = Tripod::from_config(cfg)?;
532 sim_components::base::mount(cfg, machine)
533}
534
535impl Tripod {
536 pub fn from_config(cfg: &Config) -> Result<(Box<dyn Machine>, Tripod), ConfigError> {
538 let mut geo = Geometry::new(cfg.positive("tripod.base_radius_m")?, cfg.positive("tripod.platform_radius_m")?);
539 geo.closed = cfg.positive("leg.closed_length_m")?;
540 geo.stroke = cfg.positive("leg.stroke_m")?;
541 geo.max_revolute = cfg.positive("workspace.max_revolute_angle_deg")?.to_radians();
542 geo.max_cone = cfg.positive("workspace.max_cone_angle_deg")?.to_radians();
543 geo.max_condition = cfg.positive("workspace.max_condition_number")?;
544 let (min, max) = (cfg.f64s("workspace.tool_min")?, cfg.f64s("workspace.tool_max")?);
545 if min.len() != 3 || max.len() != 3 {
546 return Err(ConfigError::Invalid("workspace.tool_min".into()));
547 }
548 if (0..3).any(|k| !(min[k] < max[k])) || (1..3).any(|k| !(min[k] > -1.0 && max[k] < 1.0)) {
549 return Err(ConfigError::Invalid("workspace.tool_max".into()));
550 }
551 if !geo.set_home(std::array::from_fn(|k| 0.5 * (min[k] + max[k]))) {
552 return Err(ConfigError::Invalid("workspace.tool_min".into()));
553 }
554 let share = cfg.non_negative("leg.platform_share")?;
555 if share > 1.0 {
556 return Err(ConfigError::Invalid("leg.platform_share".into()));
557 }
558 let leg_mass = cfg.non_negative("leg.mass_kg")?;
559 let part = |key: &str, on_platform: bool, mass: f64| -> Result<LegPart, ConfigError> {
560 let get = |what: &str| cfg.non_negative(&format!("leg.{key}_{what}"));
561 Ok(LegPart { mass, centre: get("centre_m")?, inertia: get("inertia_kgm2")?, on_platform })
562 };
563 let parts =
564 [part("base_part", false, (1.0 - share) * leg_mass)?, part("platform_part", true, share * leg_mass)?];
565 let platform_inertia = diagonal(cfg, "mass.platform_inertia_kgm2")?;
566 let empty = Body::at(cfg.positive("mass.platform_kg")?, [0.0; 3], platform_inertia);
567 let offset = cfg.f64s("mass.payload_offset_m")?;
568 if offset.len() != 3 || offset.iter().any(|v| !v.is_finite()) {
569 return Err(ConfigError::Invalid("mass.payload_offset_m".into()));
570 }
571 let payload = if cfg.bool("effects.payload")? { cfg.non_negative("mass.payload_kg")? } else { 0.0 };
572 let own = if payload > 0.0 { diagonal(cfg, "mass.payload_inertia_kgm2")? } else { [[0.0; 3]; 3] };
573 let loaded = empty.plus(Body::at(payload, [offset[0], offset[1], offset[2]], own));
574 let screw = BallScrew::from_config(cfg)?;
575 if screw.length < geo.stroke {
576 return Err(ConfigError::Invalid("screw.length_m".into()));
577 }
578 let on = cfg.bool("effects.joint_friction")?;
579 let friction = ShaftFriction {
580 coulomb: if on { cfg.non_negative("leg.friction_coulomb_n")? } else { 0.0 },
581 viscous: if on { cfg.non_negative("leg.friction_viscous_n_s_m")? } else { 0.0 },
582 smoothing: cfg.positive("leg.friction_smoothing_m_s")?,
583 ..ShaftFriction::NONE
584 };
585 let stops = if cfg.bool("effects.hard_stops")? {
586 HardStop {
587 stiffness: cfg.positive("leg.stop_stiffness_n_m")?,
588 damping: cfg.non_negative("leg.stop_damping_n_s_m")?,
589 }
590 } else {
591 HardStop { stiffness: 0.0, damping: 0.0 }
592 };
593 let mut joint = RotaryJoint::with(cfg, friction, stops, (0.0, geo.stroke))?;
594 let r2 = geo.anchors.iter().map(|a| dot(*a, *a)).fold(0.0, f64::max);
597 let i_min = (0..3).map(|k| platform_inertia[k][k]).fold(f64::INFINITY, f64::min);
598 let leg_output = 1.0 / (1.0 / cfg.positive("mass.platform_kg")? + r2 / i_min);
599 screw.converter(screw.softest_position()).apply_to(cfg, &mut joint, leg_output)?;
600 if on {
602 joint.friction.coulomb += screw.preload_torque() * screw.ratio();
603 }
604 let lever = 1.0 / screw.ratio();
605 let mech = Tripod {
606 geo,
607 screw,
608 empty,
609 loaded,
610 parts,
611 attached: true,
612 g: if cfg.bool("effects.gravity")? { G } else { 0.0 },
613 required_life: cfg.f64("ratings.required_life_h").ok(),
614 max_force: cfg.positive("leg.max_force_n")?,
615 parasitic_tolerance: cfg.f64("ratings.parasitic_tolerance_m").ok(),
616 };
617 let axes = (0..3)
618 .map(|k| {
619 let unit = if k < 1 { "m" } else { "rad" };
620 let get =
621 |what: &str, rate: &str| cfg.positive(&format!("axis.{}.max_{what}_{unit}_{rate}", AXIS_IDS[k]));
622 Ok(AxisInfo {
623 id: AXIS_IDS[k],
624 key: AXIS_KEYS[k],
625 unit,
626 min: min[k],
627 max: max[k],
628 max_vel: get("velocity", "s")?,
629 max_acc: get("acceleration", "s2")?,
630 max_jerk: get("jerk", "s3")?,
631 })
632 })
633 .collect::<Result<Vec<_>, ConfigError>>()?;
634 let specs = (0..3)
635 .map(|k| JointSpec {
636 drive: joint.clone(),
637 id: MOTOR_IDS[k],
638 key: JOINT_KEYS[k],
639 gear_lever: Some(lever),
640 unit: "m",
641 })
642 .collect();
643 let motors = (0..3).map(|k| MotorInfo { id: MOTOR_IDS[k], key: MOTOR_KEYS[k] }).collect();
644 let machine = JointMachine::new(
645 mech.clone(),
646 specs,
647 cfg.bool("effects.joint_elasticity")?,
648 ThermalFeedback::from_config(cfg)?,
649 axes,
650 motors,
651 );
652 Ok((Box::new(machine), mech))
653 }
654
655 fn body(&self) -> Body {
656 if self.attached { self.loaded } else { self.empty }
657 }
658
659 fn pose(&self, q: &[f64]) -> Option<([f64; 3], Place, Legs)> {
661 let mut tool = [0.0; 3];
662 self.geo.forward(q, &mut tool);
663 if !tool.iter().all(|v| v.is_finite()) {
664 return None;
665 }
666 let place = self.geo.place(&tool);
667 Some((tool, place, self.geo.legs_at(&place)))
668 }
669
670 fn turned(&self, r: &M3) -> (f64, V3, M3) {
672 let b = self.body();
673 (b.mass, mul(r, b.moment), matmul(&matmul(r, &b.inertia), &transpose(r)))
674 }
675
676 fn part_motion(&self, i: usize, legs: &Legs, xi: &[f64; 6], part: &LegPart) -> PartMotion {
678 let (u, l, b) = (legs.u[i], legs.length[i], legs.b[i]);
679 let (v, w) = ([xi[0], xi[1], xi[2]], [xi[3], xi[4], xi[5]]);
680 let (d1, d2) = (add(v, cross(w, b)), cross(w, cross(w, b)));
681 let rate = dot(u, d1);
682 let up = scale(sub(d1, scale(u, rate)), 1.0 / l);
683 let rate2 = dot(up, d1) + dot(u, d2);
684 let u2: V3 = std::array::from_fn(|k| (d2[k] - 2.0 * up[k] * rate - u[k] * rate2) / l);
685 let unit = |k: usize| -> V3 {
687 let e: V3 = std::array::from_fn(|r| if r == k % 3 { 1.0 } else { 0.0 });
688 if k < 3 { e } else { cross(e, b) }
689 };
690 let au: [V3; 6] = std::array::from_fn(|k| {
691 let d = unit(k);
692 scale(sub(d, scale(u, dot(u, d))), 1.0 / l)
693 });
694 let c = part.centre;
695 if part.on_platform {
696 PartMotion { a: std::array::from_fn(|k| sub(unit(k), scale(au[k], c))), a0: sub(d2, scale(u2, c)), au, u2 }
697 } else {
698 PartMotion { a: au.map(|col| scale(col, c)), a0: scale(u2, c), au, u2 }
699 }
700 }
701
702 fn parts_terms(&self, legs: &Legs, xi: &[f64; 6]) -> (Vec<f64>, [f64; 6]) {
705 let (mut m, mut held) = (vec![0.0; 36], [0.0; 6]);
706 for i in 0..3 {
707 for part in self.parts.iter().filter(|p| p.mass > 0.0 || p.inertia > 0.0) {
708 let pm = self.part_motion(i, legs, xi, part);
709 let accel = [pm.a0[0], pm.a0[1], pm.a0[2] + self.g];
710 for r in 0..6 {
711 held[r] += part.mass * dot(pm.a[r], accel) + part.inertia * dot(pm.au[r], pm.u2);
712 for c in 0..6 {
713 m[r * 6 + c] += part.mass * dot(pm.a[r], pm.a[c]) + part.inertia * dot(pm.au[r], pm.au[c]);
714 }
715 }
716 }
717 }
718 (m, held)
719 }
720
721 fn part_position(&self, i: usize, legs: &Legs, p: V3, part: &LegPart) -> V3 {
723 let u = scale(legs.u[i], part.centre);
724 if part.on_platform { sub(add(p, legs.b[i]), u) } else { add(self.geo.base[i], u) }
725 }
726
727 fn twist_mass(m: f64, s: V3, ip: &M3) -> Vec<f64> {
729 let sx = [[0.0, -s[2], s[1]], [s[2], 0.0, -s[0]], [-s[1], s[0], 0.0]];
730 let mut out = vec![0.0; 36];
731 for r in 0..3 {
732 out[r * 6 + r] = m;
733 for c in 0..3 {
734 out[r * 6 + 3 + c] = -sx[r][c];
735 out[(3 + r) * 6 + c] = sx[r][c];
736 out[(3 + r) * 6 + 3 + c] = ip[r][c];
737 }
738 }
739 out
740 }
741
742 fn weight(&self, m: f64, s: V3) -> [f64; 6] {
744 [0.0, 0.0, m * self.g, self.g * s[1], -self.g * s[0], 0.0]
745 }
746
747 pub fn static_leg_forces(&self, tool: &[f64]) -> Option<[f64; 3]> {
749 let place = self.geo.place(tool);
750 let legs = self.geo.legs_at(&place);
751 let a = Lu::new(&self.geo.constraint_matrix(&legs))?.columns();
752 let (m, s, _) = self.turned(&place.r);
753 let mut g = self.weight(m, s);
754 let (_, parts) = self.parts_terms(&legs, &[0.0; 6]);
756 g.iter_mut().zip(parts).for_each(|(w, p)| *w += p);
757 Some(std::array::from_fn(|i| (0..6).map(|k| a[i][k] * g[k]).sum()))
758 }
759}
760
761impl Mechanism for Tripod {
762 fn dynamics(&self, q: &[f64], qd: &[f64], mass: &mut [f64], bias: &mut [f64]) {
763 let fail = |mass: &mut [f64], bias: &mut [f64]| {
764 mass.fill(f64::NAN);
765 bias.fill(f64::NAN);
766 };
767 let Some((_, place, legs)) = self.pose(q) else { return fail(mass, bias) };
768 let Some(lu) = Lu::new(&self.geo.constraint_matrix(&legs)) else { return fail(mass, bias) };
769 let columns = lu.columns();
771 let a = |r: usize, c: usize| columns[c][r];
772 let xi: Vec<f64> = (0..6).map(|r| (0..3).map(|c| a(r, c) * qd[c]).sum()).collect();
773 let (v, w) = ([xi[0], xi[1], xi[2]], [xi[3], xi[4], xi[5]]);
774 let mut rest = [0.0; 6];
775 for i in 0..3 {
776 let spin = cross(w, cross(w, legs.b[i]));
777 let wi = add(v, cross(w, legs.b[i]));
778 let along = dot(legs.u[i], wi);
779 rest[i] = -((dot(wi, wi) - along * along) / legs.length[i] + dot(legs.u[i], spin));
780 rest[3 + i] = -dot(self.geo.tangents[i], spin);
781 }
782 let beta = lu.solve(&rest);
783 let (m, s, ip) = self.turned(&place.r);
784 let mut mx = Self::twist_mass(m, s, &ip);
785 let xi6: [f64; 6] = std::array::from_fn(|r| xi[r]);
786 let (parts_mass, parts_held) = self.parts_terms(&legs, &xi6);
787 mx.iter_mut().zip(&parts_mass).for_each(|(a, b)| *a += b);
788 let (lin, gyro) = (cross(w, cross(w, s)), cross(w, mul(&ip, w)));
789 let weight = self.weight(m, s);
790 let held: [f64; 6] =
791 std::array::from_fn(|k| [lin[0], lin[1], lin[2], gyro[0], gyro[1], gyro[2]][k] + parts_held[k]);
792 let mbeta = apply(&mx, &beta);
793 let wrench: Vec<f64> = (0..6).map(|k| mbeta[k] + held[k] + weight[k]).collect();
794 for i in 0..3 {
795 bias[i] = (0..6).map(|k| a(k, i) * wrench[k]).sum();
796 for j in 0..3 {
797 mass[i * 3 + j] = (0..6).map(|k| a(k, i) * (0..6).map(|l| mx[k * 6 + l] * a(l, j)).sum::<f64>()).sum();
798 }
799 }
800 }
801
802 fn frame_momentum(&self, q: &[f64], qd: &[f64], rotor_spin: &[f64]) -> Option<sim_core::FrameMomentum> {
806 let (_, place, legs) = self.pose(q)?;
807 let a = Lu::new(&self.geo.constraint_matrix(&legs))?.columns();
808 let xi: Vec<f64> = (0..6).map(|r| (0..3).map(|c| a[c][r] * qd[c]).sum()).collect();
809 let (v, w) = ([xi[0], xi[1], xi[2]], [xi[3], xi[4], xi[5]]);
810 let (m, s, ip) = self.turned(&place.r);
811 let p = place.p;
812 let linear = add(scale(v, m), cross(w, s));
813 let angular = add(add(cross(s, v), mul(&ip, w)), cross(p, linear));
814 let mut f = sim_core::FrameMomentum { gravity: [0.0, 0.0, -self.g], ..Default::default() };
815 f.linear = linear;
816 f.angular = angular;
817 f.mass = m;
818 f.first_moment = add(scale(p, m), s);
819 let xi6: [f64; 6] = std::array::from_fn(|r| xi[r]);
820 for i in 0..3 {
821 for part in self.parts.iter().filter(|p| p.mass > 0.0 || p.inertia > 0.0) {
822 let pm = self.part_motion(i, &legs, &xi6, part);
823 let speed: V3 = std::array::from_fn(|k| (0..6).map(|c| pm.a[c][k] * xi6[c]).sum());
824 let at = self.part_position(i, &legs, p, part);
825 sim_components::base::add_point(&mut f, part.mass, at, speed);
826 if !part.on_platform {
827 f.mass -= part.mass;
829 (0..3).for_each(|k| f.first_moment[k] -= part.mass * self.geo.base[i][k]);
830 }
831 let rate: V3 = std::array::from_fn(|k| (0..6).map(|c| pm.au[c][k] * xi6[c]).sum());
833 let spin = cross(legs.u[i], rate);
834 (0..3).for_each(|k| f.angular[k] += part.inertia * spin[k]);
835 }
836 }
837 for (u, spin) in legs.u.iter().zip(rotor_spin) {
838 sim_components::base::add_spin(&mut f, *u, 1.0, *spin);
839 }
840 Some(f)
841 }
842 fn potential(&self, q: &[f64]) -> f64 {
843 self.pose(q).map_or(f64::NAN, |(_, place, legs)| {
844 let (m, s, _) = self.turned(&place.r);
845 let parts: f64 = (0..3)
846 .flat_map(|i| self.parts.iter().map(move |part| (i, part)))
847 .map(|(i, part)| part.mass * self.part_position(i, &legs, place.p, part)[2])
848 .sum();
849 self.g * (m * place.p[2] + s[2] + parts)
850 })
851 }
852 fn set_payload_attached(&mut self, attached: bool) {
853 self.attached = attached;
854 }
855
856 fn forward(&self, q: &[f64], tool: &mut [f64]) {
857 self.geo.forward(q, tool);
858 }
859 fn inverse(&self, tool: &[f64], q: &mut [f64]) -> bool {
860 self.geo.inverse(tool, q)
861 }
862 fn unreachable(&self, tool: &[f64], _slack: f64) -> Option<&'static str> {
863 let (swing, cone) = self.geo.joint_angles(tool);
864 if !swing.iter().all(|a| a.abs() <= self.geo.max_revolute) {
865 return Some("error-tripod-revolute-angle");
866 }
867 if !cone.iter().all(|a| *a <= self.geo.max_cone) {
868 return Some("error-tripod-cone-angle");
869 }
870 if !(self.geo.condition(tool) <= self.geo.max_condition) {
871 return Some("error-tripod-singularity");
872 }
873 None
874 }
875 fn condition(&self, tool: &[f64]) -> Option<f64> {
876 Some(self.geo.condition(tool))
877 }
878 fn tool_is_joints(&self) -> bool {
879 false
880 }
881
882 fn signal_infos(&self) -> Vec<SignalInfo> {
885 let mut out = Vec::new();
886 for i in 0..3 {
887 out.extend(self.screw.signal_infos(MOTOR_IDS[i], JOINT_KEYS[i]));
888 }
889 for i in 0..3 {
890 let id = MOTOR_IDS[i];
891 out.push(SignalInfo::new(format!("leg.{id}.from_middle"), JOINT_KEYS[i], "quantity-leg-from-middle", "m"));
892 out.push(SignalInfo::new(format!("leg.{id}.swing"), JOINT_KEYS[i], "quantity-revolute-swing", "rad"));
893 out.push(SignalInfo::new(format!("leg.{id}.cone"), JOINT_KEYS[i], "quantity-cone-angle", "rad"));
894 }
895 out.push(SignalInfo::new("platform.condition", "group-tripod", "quantity-condition-number", ""));
896 out.push(SignalInfo::new("platform.x", "group-tripod", "quantity-parasitic-x", "m"));
897 out.push(SignalInfo::new("platform.y", "group-tripod", "quantity-parasitic-y", "m"));
898 out.push(SignalInfo::new("platform.turn", "group-tripod", "quantity-parasitic-turn", "rad"));
899 out.push(SignalInfo::new("platform.pose_error", "group-tripod", "quantity-pose-error", "m"));
900 out
901 }
902 fn signals(&self, q: &[f64], qd: &[f64], _qdd: &[f64], force: &[f64], out: &mut Vec<f64>) {
903 for i in 0..3 {
904 self.screw.signals(qd[i], force[i], out);
905 }
906 let tool = self.pose(q).map(|(tool, ..)| tool);
907 let (swing, cone) = tool.map_or(([f64::NAN; 3], [f64::NAN; 3]), |t| self.geo.joint_angles(&t));
908 for i in 0..3 {
909 out.extend([q[i] - 0.5 * self.geo.stroke, swing[i], cone[i]]);
910 }
911 out.push(tool.map_or(f64::INFINITY, |t| self.geo.condition(&t)));
912 out.extend(tool.map_or([f64::NAN; 4], |t| self.geo.parasitic(&t)));
913 }
914 fn rating_checks(&self) -> Vec<RatingCheck> {
917 let mut out: Vec<RatingCheck> =
918 (0..3).flat_map(|i| self.screw.rating_checks(MOTOR_IDS[i], i, self.required_life)).collect();
919 for i in 0..3 {
920 let id = MOTOR_IDS[i];
921 let check = |check: &'static str, signal: String, limit: f64| RatingCheck {
922 check,
923 signal,
924 motor: Some(i),
925 limit,
926 life: false,
927 };
928 out.push(check("tripod-leg-force", format!("joint.{id}.force"), self.max_force));
929 out.push(check("tripod-leg-stroke", format!("leg.{id}.from_middle"), 0.5 * self.geo.stroke));
930 out.push(check("tripod-revolute-angle", format!("leg.{id}.swing"), self.geo.max_revolute));
931 out.push(check("tripod-cone-angle", format!("leg.{id}.cone"), self.geo.max_cone));
932 }
933 if let Some(limit) = self.parasitic_tolerance {
934 out.push(RatingCheck {
935 check: "tripod-parasitic",
936 signal: "platform.pose_error".into(),
937 motor: None,
938 limit,
939 life: false,
940 });
941 }
942 out
943 }
944
945 fn collision_parts(&self) -> &'static [&'static str] {
946 &["tool", "payload"]
947 }
948
949 fn scene(&self, q: &[f64], rotors: &[f64], rotor_speeds: &[f64], out: &mut Scene) {
952 let Some((_, place, legs)) = self.pose(q) else { return };
953 let p = place.p;
954 let top: Vec<V3> = (0..3).map(|i| add(p, legs.b[i])).collect();
955 for i in 0..3 {
956 let next = (i + 1) % 3;
957 out.parts.push(Part::new(
958 "base",
959 Shape::Segment { to: self.geo.base[next], width: 0.04 },
960 self.geo.base[i],
961 [0.55, 0.57, 0.6],
962 ));
963 out.parts.push(Part::new(
964 "platform",
965 Shape::Segment { to: top[next], width: 0.04 },
966 top[i],
967 [0.3, 0.45, 0.7],
968 ));
969 }
970 let body = 0.6 * self.geo.closed;
971 for i in 0..3 {
972 let (b, u) = (self.geo.base[i], legs.u[i]);
973 let end = add(b, scale(u, body));
974 out.parts.push(Part::new("cylinder", Shape::Segment { to: end, width: 0.06 }, b, [0.75, 0.75, 0.78]));
975 out.parts.push(Part::new(
976 "rod",
977 Shape::Segment { to: add(b, scale(u, 0.9 * body)), width: 0.03 },
978 top[i],
979 [0.85, 0.86, 0.9],
980 ));
981 out.parts.push(Part::new(
982 sim_core::scene::MOTOR_PART,
983 Shape::Box { size: [0.08, 0.08, 0.1] },
984 add(b, [0.0, 0.0, -0.07]),
985 [0.9, 0.45, 0.1],
986 ));
987 out.parts.push(
989 Part::new("rotor-bar", Shape::Box { size: [0.08, 0.004, 0.012] }, add(b, [0.0, 0.0, -0.13]), [0.1; 3])
990 .turned(rotors[i]),
991 );
992 out.labels.push(Label {
993 pos: add(b, [0.0, 0.0, -0.16]),
994 owner_key: MOTOR_KEYS[i],
995 value: rotor_speeds[i] * 60.0 / TAU,
996 unit_key: "unit-rpm",
997 decimals: 0,
998 });
999 out.labels.push(Label {
1000 pos: add(b, scale(u, 0.5 * legs.length[i])),
1001 owner_key: JOINT_KEYS[i],
1002 value: legs.length[i],
1003 unit_key: "unit-m",
1004 decimals: 3,
1005 });
1006 }
1007 let normal = [place.r[0][2], place.r[1][2], place.r[2][2]];
1008 out.parts.push(Part::new(
1009 "tool",
1010 Shape::Box { size: [0.08, 0.08, 0.03] },
1011 add(p, scale(normal, 0.015)),
1012 [0.2, 0.22, 0.26],
1013 ));
1014 let b = self.body();
1015 if self.attached && (b.mass - self.empty.mass) > 0.0 {
1016 let own = sub(b.moment, self.empty.moment);
1017 let centre = add(p, mul(&place.r, scale(own, 1.0 / (b.mass - self.empty.mass))));
1018 out.parts.push(Part::new("payload", Shape::Box { size: [0.2, 0.2, 0.12] }, centre, [0.2, 0.7, 0.3]));
1019 }
1020 out.labels.push(Label {
1021 pos: add(p, [0.0, 0.0, 0.25]),
1022 owner_key: "axis-z",
1023 value: p[2],
1024 unit_key: "unit-m",
1025 decimals: 3,
1026 });
1027 }
1028 fn scene_point(&self, tool: &[f64]) -> Option<[f64; 3]> {
1029 Some(self.geo.place(tool).p)
1030 }
1031}
1032
1033#[cfg(test)]
1034mod tests;