1use sim_components::joint::RotaryJoint;
81use sim_components::mech::ThermalFeedback;
82use sim_core::{
83 AxisInfo, Config, ConfigError, ENERGY_PARTS, LOSS_PREFIX, Label, Machine, MachineEntry, Mode, MotorInfo, Part,
84 Scene, Shape, SignalInfo, TORQUE_PARTS, ThermalPart,
85};
86
87pub static ENTRY: MachineEntry = MachineEntry {
88 id: "delta-h4",
89 key: "machine-delta-h4",
90 default_config: include_str!("../default.toml"),
91 i18n: &[("en", include_str!("../i18n/en.ftl")), ("de", include_str!("../i18n/de.ftl"))],
92 build,
93 suite_configs,
94};
95
96const G: f64 = 9.80665;
97
98pub const LOSSY_EFFECTS: [&str; 7] = [
100 "joint_friction",
101 "motor_friction",
102 "gearbox_drag",
103 "gearbox_lost_motion",
104 "gearbox_efficiency",
105 "torque_ripple",
106 "holding_brake",
107];
108
109fn build(cfg: &Config) -> Result<Box<dyn Machine>, ConfigError> {
110 sim_components::base::mount(cfg, Box::new(H4::new(cfg)?))
111}
112
113fn lowered(cfg: &mut Config, dz: f64) {
115 let s = cfg.f64s("start.pose").unwrap();
116 cfg.set_text(&format!("start.pose = [{:?}, {:?}, {:?}, {:?}]", s[0], s[1], s[2] + dz, s[3])).unwrap();
117 let segments: Vec<String> = cfg
118 .array("cycle.segment")
119 .unwrap()
120 .iter()
121 .map(|s| {
122 let t: Vec<f64> = s["target"].as_array().unwrap().iter().map(|v| v.as_float().unwrap()).collect();
123 format!(
124 "{{ target = [{:?}, {:?}, {:?}, {:?}], dwell_s = {:?}, payload = {} }}",
125 t[0],
126 t[1],
127 t[2] + dz,
128 t[3],
129 s["dwell_s"].as_float().unwrap(),
130 s["payload"].as_bool().unwrap()
131 )
132 })
133 .collect();
134 cfg.set_text(&format!("cycle.segment = [{}]", segments.join(", "))).unwrap();
135}
136
137pub fn lossless_config() -> Config {
139 let mut cfg = ENTRY.config();
140 for effect in LOSSY_EFFECTS {
141 cfg.set_text(&format!("effects.{effect} = false")).unwrap();
142 }
143 for damping in ["gearbox.damping_nm_s_rad", "joint.stop_damping_nm_s_rad", "plate.amplifier_damping_nm_s_rad"] {
144 cfg.set_text(&format!("{damping} = 0.0")).unwrap();
145 }
146 cfg
147}
148
149fn suite_configs() -> Vec<Config> {
160 let mut out = Vec::new();
161 for (elastic, payload) in [(false, true), (false, false), (true, true), (true, false)] {
162 let mut cfg = lossless_config();
163 cfg.set_text("workspace.top_z_m = -0.95").unwrap();
164 lowered(&mut cfg, -0.2);
165 cfg.set_text(&format!("effects.joint_elasticity = {elastic}")).unwrap();
166 cfg.set_text(&format!("effects.amplifier_compliance = {elastic}")).unwrap();
167 cfg.set_text(&format!("effects.payload = {payload}")).unwrap();
168 cfg.set_text(&format!("effects.part_heating = {}", elastic && payload)).unwrap();
169 cfg.set_text(&format!("effects.thermal_feedback = {}", elastic && payload)).unwrap();
170 out.push(cfg);
171 }
172 out
173}
174
175type V3 = [f64; 3];
176type V4 = [f64; 4];
177type M4 = [[f64; 4]; 4];
178type LoadN<const N: usize> = ([[f64; N]; N], [f64; N], [f64; N]);
181type Load = LoadN<4>;
183type Pose = (V4, M4, M4);
185
186fn dot(a: V3, b: V3) -> f64 {
187 a[0] * b[0] + a[1] * b[1] + a[2] * b[2]
188}
189
190fn sub(a: V3, b: V3) -> V3 {
191 [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
192}
193
194fn cross(a: V3, b: V3) -> V3 {
195 [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]]
196}
197
198fn norm(a: V3) -> f64 {
199 dot(a, a).sqrt()
200}
201
202fn dot4(a: V4, b: V4) -> f64 {
203 a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]
204}
205
206fn mul4(m: &M4, v: V4) -> V4 {
207 std::array::from_fn(|r| dot4(m[r], v))
208}
209
210fn solve4(m: &M4, b: V4) -> Option<V4> {
212 let (mut a, mut x) = (*m, b);
213 for c in 0..4 {
214 let p = (c..4).max_by(|&i, &j| a[i][c].abs().total_cmp(&a[j][c].abs()))?;
215 if !(a[p][c].abs() > 1e-300) {
216 return None;
217 }
218 a.swap(p, c);
219 x.swap(p, c);
220 for r in c + 1..4 {
221 let f = a[r][c] / a[c][c];
222 for k in c..4 {
223 a[r][k] -= f * a[c][k];
224 }
225 x[r] -= f * x[c];
226 }
227 }
228 for c in (0..4).rev() {
229 let s: f64 = (c + 1..4).map(|k| a[c][k] * x[k]).sum();
230 x[c] = (x[c] - s) / a[c][c];
231 }
232 x.iter().all(|v| v.is_finite()).then_some(x)
233}
234
235fn inverse4(m: &M4) -> Option<M4> {
237 sim_components::chain::Lu::new(m)?.inverse()
238}
239
240fn add_point<const N: usize>(load: &mut LoadN<N>, m: f64, jm: &[[f64; N]; 3], am: V3, g: f64) {
243 for r in 0..N {
244 for c in 0..N {
245 load.0[r][c] += m * (0..3).map(|k| jm[k][r] * jm[k][c]).sum::<f64>();
246 }
247 load.1[r] += m * (0..3).map(|k| jm[k][r] * am[k]).sum::<f64>();
248 load.2[r] -= m * g * jm[2][r];
249 }
250}
251
252fn add_turn<const N: usize>(load: &mut LoadN<N>, inertia: f64, row: [f64; N], a0: f64) {
255 for r in 0..N {
256 for c in 0..N {
257 load.0[r][c] += inertia * row[r] * row[c];
258 }
259 load.1[r] += inertia * row[r] * a0;
260 }
261}
262
263fn arm_modes(
274 (root, coupling): (f64, f64),
275 distal: &[Vec<f64>],
276 k_gear: Option<V4>,
277 k_bend: f64,
278 k_lateral: f64,
279) -> Vec<(f64, Vec<f64>)> {
280 let (fb, fl) = (1.0 / k_bend, 1.0 / k_lateral);
281 let n = 4 + distal.len();
282 let (mut m, mut f) = (vec![vec![0.0; n]; n], vec![vec![0.0; n]; n]);
283 for i in 0..4 {
284 m[i][i] = root;
285 (m[i][4 + i], m[4 + i][i]) = (coupling, coupling);
286 let fg = k_gear.map_or(0.0, |k| 1.0 / k[i]);
287 (f[i][i], f[i][4 + i], f[4 + i][i], f[4 + i][4 + i]) = (fg, fg, fg, fg + fb);
288 f[8 + i][8 + i] = fl;
289 }
290 for (r, row) in distal.iter().enumerate() {
291 m[4 + r][4..].copy_from_slice(row);
292 }
293 let mut l = vec![vec![0.0; n]; n];
294 for i in 0..n {
295 for j in 0..=i {
296 let s = m[i][j] - (0..j).map(|k| l[i][k] * l[j][k]).sum::<f64>();
297 l[i][j] = if i == j { s.max(0.0).sqrt() } else { s / l[j][j] };
298 }
299 }
300 let times = |a: &[Vec<f64>], b: &[Vec<f64>]| -> Vec<Vec<f64>> {
301 (0..n).map(|r| (0..n).map(|c| (0..n).map(|k| a[r][k] * b[k][c]).sum()).collect()).collect()
302 };
303 let lt: Vec<Vec<f64>> = (0..n).map(|r| (0..n).map(|c| l[c][r]).collect()).collect();
304 let fl_ = times(&f, &l);
305 let (mu, z) = symmetric_eigen(times(<, &fl_));
306 let largest = mu.iter().fold(0f64, |a, b| a.max(*b));
307 let mut out: Vec<(f64, Vec<f64>)> = (0..n)
308 .filter(|&k| mu[k] > 1e-9 * largest)
309 .map(|k| (1.0 / mu[k], (0..n).map(|r| (0..n).map(|c| fl_[r][c] * z[c][k]).sum::<f64>() / mu[k]).collect()))
310 .collect();
311 out.sort_by(|a, b| a.0.total_cmp(&b.0));
312 out
313}
314
315fn symmetric_eigen(mut a: Vec<Vec<f64>>) -> (Vec<f64>, Vec<Vec<f64>>) {
317 let n = a.len();
318 let mut v: Vec<Vec<f64>> = (0..n).map(|i| (0..n).map(|j| if i == j { 1.0 } else { 0.0 }).collect()).collect();
319 for _ in 0..50 {
320 let off: f64 = (0..n).flat_map(|p| (p + 1..n).map(move |q| (p, q))).map(|(p, q)| a[p][q] * a[p][q]).sum();
321 let diagonal: f64 = (0..n).map(|i| a[i][i] * a[i][i]).sum();
322 if !(off > 1e-30 * diagonal) {
323 break;
324 }
325 for p in 0..n {
326 for q in p + 1..n {
327 if a[p][q] == 0.0 {
328 continue;
329 }
330 let theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q]);
331 let t = theta.signum() / (theta.abs() + (theta * theta + 1.0).sqrt());
332 let c = 1.0 / (t * t + 1.0).sqrt();
333 let s = t * c;
334 for k in 0..n {
335 (a[k][p], a[k][q]) = (c * a[k][p] - s * a[k][q], s * a[k][p] + c * a[k][q]);
336 }
337 for k in 0..n {
338 (a[p][k], a[q][k]) = (c * a[p][k] - s * a[q][k], s * a[p][k] + c * a[q][k]);
339 (v[k][p], v[k][q]) = (c * v[k][p] - s * v[k][q], s * v[k][p] + c * v[k][q]);
340 }
341 }
342 }
343 }
344 ((0..n).map(|i| a[i][i]).collect(), v)
345}
346
347pub fn condition_number(j: &M4) -> f64 {
351 let jtj: Vec<Vec<f64>> =
352 (0..4).map(|r| (0..4).map(|c| (0..4).map(|k| j[k][r] * j[k][c]).sum()).collect()).collect();
353 let (eigen, _) = symmetric_eigen(jtj);
354 let (smallest, largest) = eigen.iter().fold((f64::INFINITY, 0f64), |(lo, hi), e| (lo.min(*e), hi.max(*e)));
355 if smallest <= 0.0 || !smallest.is_finite() { f64::INFINITY } else { (largest / smallest).sqrt() }
356}
357
358pub const SIDE: [f64; 4] = [-1.0, -1.0, 1.0, 1.0];
360
361#[derive(Debug, Clone)]
363pub struct Legs {
364 pub e: f64,
366 pub la: f64,
367 pub lb: f64,
368 pub azimuth: [(f64, f64); 4],
370 pub slide: V3,
372}
373
374impl Legs {
375 pub fn new(e: f64, la: f64, lb: f64) -> Self {
376 let azimuth = [0.0f64, 90.0, 180.0, 270.0].map(|deg| (deg.to_radians().cos(), deg.to_radians().sin()));
377 let s = std::f64::consts::FRAC_1_SQRT_2;
378 Self { e, la, lb, azimuth, slide: [s, -s, 0.0] }
379 }
380
381 fn to_base(&self, i: usize, v: V3) -> V3 {
383 let (c, s) = self.azimuth[i];
384 [c * v[0] - s * v[1], s * v[0] + c * v[1], v[2]]
385 }
386 fn to_leg(&self, i: usize, v: V3) -> V3 {
387 let (c, s) = self.azimuth[i];
388 [c * v[0] + s * v[1], -s * v[0] + c * v[1], v[2]]
389 }
390
391 pub fn elbow(&self, i: usize, t: f64) -> [V3; 3] {
393 let (s, c) = t.sin_cos();
394 let la = self.la;
395 [
396 self.to_base(i, [self.e + la * c, 0.0, -la * s]),
397 self.to_base(i, [-la * s, 0.0, -la * c]),
398 self.to_base(i, [-la * c, 0.0, la * s]),
399 ]
400 }
401
402 pub fn tangent(&self, i: usize) -> V3 {
404 self.to_base(i, [0.0, 1.0, 0.0])
405 }
406
407 pub fn end(&self, i: usize, x: V4) -> V3 {
409 std::array::from_fn(|k| x[k] + SIDE[i] * x[3] * self.slide[k])
410 }
411
412 pub fn elbows_moved(&self, t: V4, y: V4) -> [V3; 4] {
414 std::array::from_fn(|i| {
415 let (c, tg) = (self.elbow(i, t[i])[0], self.tangent(i));
416 std::array::from_fn(|k| c[k] + y[i] * tg[k])
417 })
418 }
419
420 pub fn inverse(&self, x: V4) -> Option<V4> {
422 self.inverse_moved(x, [0.0; 4])
423 }
424
425 pub fn inverse_moved(&self, x: V4, moved: V4) -> Option<V4> {
427 let mut out = [0.0; 4];
428 for (i, t) in out.iter_mut().enumerate() {
429 let [lx, ly, lz] = self.to_leg(i, self.end(i, x));
430 let ly = ly - moved[i];
431 let (a, b, c) = (
432 -2.0 * self.la * (lx - self.e),
433 2.0 * self.la * lz,
434 (lx - self.e).powi(2) + ly * ly + lz * lz + self.la * self.la - self.lb * self.lb,
435 );
436 let d = a * a + b * b - c * c;
437 if !(d >= 0.0) {
438 return None;
439 }
440 *t = 2.0 * if b < 0.0 { (a + c) / (d.sqrt() - b) } else { (-b - d.sqrt()) / (c - a) }.atan();
443 }
444 Some(out)
445 }
446
447 pub fn forward(&self, t: V4) -> Option<V4> {
450 self.forward_moved(t, [0.0; 4])
451 }
452
453 pub fn forward_moved(&self, t: V4, moves: V4) -> Option<V4> {
455 let moved = self.elbows_moved(t, moves);
456 let c: [V3; 3] = std::array::from_fn(|i| moved[i]);
457 let ex = sub(c[1], c[0]);
458 let d = norm(ex);
459 let ex = ex.map(|v| v / d);
460 let to3 = sub(c[2], c[0]);
461 let i = dot(ex, to3);
462 let ey = sub(to3, ex.map(|v| v * i));
463 let ey_len = norm(ey);
464 if !(d > 1e-12 && ey_len > 1e-12) {
465 return None;
466 }
467 let ey = ey.map(|v| v / ey_len);
468 let ez = cross(ex, ey);
469 let j = dot(ey, to3);
470 let x = d / 2.0;
471 let y = (i * i + j * j - 2.0 * i * x) / (2.0 * j);
472 let z = (self.lb * self.lb - x * x - y * y).max(0.0).sqrt();
474 let base: V3 = std::array::from_fn(|k| c[0][k] + x * ex[k] + y * ey[k]);
475 let (up, down): (V3, V3) =
476 (std::array::from_fn(|k| base[k] + z * ez[k]), std::array::from_fn(|k| base[k] - z * ez[k]));
477 let start = if up[2] < down[2] { up } else { down };
478 self.forward_from_moved(t, moves, [start[0], start[1], start[2], 0.0])
479 }
480
481 pub fn forward_from(&self, t: V4, x: V4) -> Option<V4> {
483 self.forward_from_moved(t, [0.0; 4], x)
484 }
485
486 pub fn forward_from_moved(&self, t: V4, y: V4, mut x: V4) -> Option<V4> {
488 let lb2 = self.lb * self.lb;
489 for _ in 0..50 {
490 let (jx, ..) = self.constraint_moved(t, y, x);
491 let r: V4 = std::array::from_fn(|k| {
492 let u = [jx[k][0], jx[k][1], jx[k][2]];
493 -0.5 * (dot(u, u) - lb2)
494 });
495 let dx = solve4(&jx, r)?;
496 for k in 0..4 {
497 x[k] += dx[k];
498 }
499 if dx.iter().all(|v| v.abs() < 1e-14) {
500 break;
501 }
502 }
503 let (jx, ..) = self.constraint_moved(t, y, x);
504 (0..4)
505 .all(|k| {
506 let u = [jx[k][0], jx[k][1], jx[k][2]];
507 (dot(u, u) - lb2).abs() < 1e-9 * lb2 && u[2] < 0.0
508 })
509 .then_some(x)
510 }
511
512 fn constraint_moved(&self, t: V4, y: V4, x: V4) -> (M4, V4, V4) {
515 let (mut jx, mut jq, mut jy) = ([[0.0; 4]; 4], [0.0; 4], [0.0; 4]);
516 for k in 0..4 {
517 let ([c, d1, _], a) = (self.elbow(k, t[k]), self.tangent(k));
518 let moved: V3 = std::array::from_fn(|i| c[i] + y[k] * a[i]);
519 let u = sub(self.end(k, x), moved);
520 jx[k] = [u[0], u[1], u[2], SIDE[k] * dot(u, self.slide)];
521 jq[k] = dot(u, d1);
522 jy[k] = dot(u, a);
523 }
524 (jx, jq, jy)
525 }
526
527 pub fn jacobian(&self, t: V4, x: V4) -> Option<M4> {
529 self.jacobians(t, [0.0; 4], x).map(|(j, _)| j)
530 }
531
532 pub fn jacobians(&self, t: V4, y: V4, x: V4) -> Option<(M4, M4)> {
535 let (jx, jq, jy) = self.constraint_moved(t, y, x);
536 let inv = inverse4(&jx)?;
537 let scaled = |d: V4| -> M4 { std::array::from_fn(|i| std::array::from_fn(|j| inv[i][j] * d[j])) };
538 Some((scaled(jq), scaled(jy)))
539 }
540
541 pub fn velocity_term(&self, t: V4, x: V4, wt: V4, xv: V4) -> Option<V4> {
543 self.velocity_term_moved(t, [0.0; 4], x, wt, [0.0; 4], xv)
544 }
545
546 pub fn velocity_term_moved(&self, t: V4, y: V4, x: V4, wt: V4, yv: V4, xv: V4) -> Option<V4> {
549 let (jx, ..) = self.constraint_moved(t, y, x);
550 let w: V4 = std::array::from_fn(|k| {
551 let ([_, d1, d2], a) = (self.elbow(k, t[k]), self.tangent(k));
552 let rel: V3 =
553 std::array::from_fn(|i| xv[i] + SIDE[k] * xv[3] * self.slide[i] - d1[i] * wt[k] - a[i] * yv[k]);
554 wt[k] * wt[k] * dot([jx[k][0], jx[k][1], jx[k][2]], d2) - dot(rel, rel)
555 });
556 solve4(&jx, w)
557 }
558
559 pub fn rods(&self, i: usize, t: f64, x: V4, r: f64, spacing: f64) -> [(V3, V3); 2] {
563 self.rods_moved(i, t, 0.0, x, r, spacing)
564 }
565
566 pub fn rods_moved(&self, i: usize, t: f64, y: f64, x: V4, r: f64, spacing: f64) -> [(V3, V3); 2] {
568 let (c, sn) = self.azimuth[i];
569 let (at, tg) = (self.elbow(i, t)[0], self.tangent(i));
570 let elbow: V3 = std::array::from_fn(|k| at[k] + y * tg[k]);
571 let end = self.end(i, x);
572 let half = [-0.5 * spacing * sn, 0.5 * spacing * c, 0.0];
573 let (arm_end, plate_end) =
574 ([elbow[0] + r * c, elbow[1] + r * sn, elbow[2]], [end[0] + r * c, end[1] + r * sn, end[2]]);
575 [-1.0, 1.0].map(|side| {
576 (
577 std::array::from_fn(|k| arm_end[k] + side * half[k]),
578 std::array::from_fn(|k| plate_end[k] + side * half[k]),
579 )
580 })
581 }
582}
583
584#[derive(Debug, Clone, Copy)]
587pub struct Amplifier {
588 pub stiffness: f64,
589 pub damping: f64,
590 pub half_backlash: f64,
591}
592
593impl Amplifier {
594 fn beyond(&self, twist: f64) -> f64 {
596 (twist.abs() - self.half_backlash).max(0.0) * twist.signum()
597 }
598 fn contact(&self, twist: f64) -> bool {
599 self.half_backlash == 0.0 || twist.abs() > self.half_backlash
600 }
601 pub fn torque(&self, twist: f64, rate: f64) -> f64 {
603 if self.contact(twist) { self.stiffness * self.beyond(twist) + self.damping * rate } else { 0.0 }
604 }
605 pub fn energy(&self, twist: f64) -> f64 {
606 0.5 * self.stiffness * self.beyond(twist).powi(2)
607 }
608 pub fn loss_power(&self, twist: f64, rate: f64) -> f64 {
609 if self.contact(twist) { self.damping * rate * rate } else { 0.0 }
610 }
611}
612
613#[derive(Debug, Clone, Copy)]
616struct Bending {
617 k: f64,
618 c: f64,
619 k_lateral: f64,
620 c_lateral: f64,
621}
622
623pub struct H4 {
624 legs: Legs,
625 base_radius: f64,
627 plate_radius: f64,
628 rod_spacing: f64,
629 elastic: bool,
630 g: f64,
631 arm_inertia: f64,
633 arm_moment: f64,
634 root_inertia: f64,
638 root_moment: f64,
639 tip_inertia: f64,
640 tip_moment: f64,
641 m_lateral: f64,
642 m_elbow: f64,
645 tube_mass: f64,
646 twist_inertia: f64,
647 tube_coupling: f64,
649 bending: Option<Bending>,
651 m_rod_middle: f64,
653 m_forearms: f64,
656 forearm_share: f64,
657 weight_shift: f64,
660 rod_spin: f64,
661 m_part: f64,
663 m_carriage: f64,
664 m_payload: f64,
665 kappa: f64,
667 j_tool: f64,
669 j_payload: f64,
670 amplifier: Option<Amplifier>,
672 payload_attached: bool,
673 brake_engaged: bool,
674 push: V4,
676 joints: [RotaryJoint; 4],
677 thermal: Option<ThermalFeedback>,
678 radius: f64,
680 top: f64,
681 sphere: (f64, f64),
682 max_condition: f64,
683 axes: [AxisInfo; 4],
684 motors: [MotorInfo; 4],
685 rest_slack: f64,
687}
688
689const N_ELASTIC: usize = 20;
694const N_RIGID: usize = 12;
695
696struct Losses {
700 powers: [f64; 16],
701 gear_at_rotor: V4,
702}
703
704impl H4 {
705 pub fn new(cfg: &Config) -> Result<Self, ConfigError> {
706 let base_radius = cfg.positive("geometry.base_radius_m")?;
707 let plate_radius = cfg.non_negative("geometry.plate_radius_m")?;
708 let (la, lb) = (cfg.positive("geometry.upper_arm_m")?, cfg.positive("geometry.forearm_m")?);
709 if lb <= la {
710 return Err(ConfigError::Invalid("geometry.forearm_m".into()));
711 }
712 let share = cfg.non_negative("mass.forearm_elbow_share")?;
713 if share > 1.0 {
714 return Err(ConfigError::Invalid("mass.forearm_elbow_share".into()));
715 }
716 let (m_arm, cg, i_arm) = (
717 cfg.positive("mass.upper_arm_kg")?,
718 cfg.non_negative("mass.upper_arm_cg_m")?,
719 cfg.positive("mass.upper_arm_inertia_kgm2")?,
720 );
721 let (m_elbow, m_fb) = (cfg.non_negative("mass.elbow_kg")?, cfg.non_negative("mass.forearm_pair_kg")?);
722 let rods = cfg.bool("effects.forearm_inertia")?;
724 let (share, middle) = if rods { (1.0 / 6.0, 2.0 / 3.0) } else { (share, 0.0) };
725 let elbow = m_elbow + share * m_fb;
726 let spin = cfg.non_negative("mass.forearm_rod_spin_inertia_kgm2")?;
727 let kappa = cfg.positive("plate.gear_ratio")? / cfg.positive("plate.pinion_radius_m")?;
728 let amplifier = Amplifier {
729 stiffness: cfg.positive("plate.amplifier_stiffness_nm_rad")?,
730 damping: cfg.non_negative("plate.amplifier_damping_nm_s_rad")?,
731 half_backlash: 0.5 * cfg.non_negative("plate.amplifier_backlash_rad")?,
732 };
733 let amplifier = Amplifier {
734 half_backlash: if cfg.bool("effects.amplifier_backlash")? { amplifier.half_backlash } else { 0.0 },
735 ..amplifier
736 };
737 let (radius, top) = (cfg.positive("workspace.radius_m")?, cfg.f64("workspace.top_z_m")?);
738 let (edge, centre) = (cfg.positive("workspace.height_edge_m")?, cfg.positive("workspace.height_centre_m")?);
739 if centre < edge {
740 return Err(ConfigError::Invalid("workspace.height_centre_m".into()));
741 }
742 let sag = centre - edge;
744 let sphere = if sag > 0.0 {
745 let r = (radius * radius + sag * sag) / (2.0 * sag);
746 (top - centre + r, r)
747 } else {
748 (f64::INFINITY, f64::INFINITY)
749 };
750 let joint = RotaryJoint::from_config(cfg)?;
751 let axis = |id: &'static str, key: &'static str, min: f64, max: f64| -> Result<AxisInfo, ConfigError> {
752 Ok(AxisInfo {
753 id,
754 key,
755 unit: "m",
756 min,
757 max,
758 max_vel: cfg.positive(&format!("axis.{id}.max_velocity_m_s"))?,
759 max_acc: cfg.positive(&format!("axis.{id}.max_acceleration_m_s2"))?,
760 max_jerk: cfg.positive(&format!("axis.{id}.max_jerk_m_s3"))?,
761 })
762 };
763 let (c_min, c_max) =
764 (cfg.f64("axis.c.min_angle_deg")?.to_radians(), cfg.f64("axis.c.max_angle_deg")?.to_radians());
765 if c_min >= c_max {
766 return Err(ConfigError::Invalid("axis.c.max_angle_deg".into()));
767 }
768 let bending = if cfg.get("effects.arm_bending").is_ok() && cfg.bool("effects.arm_bending")? {
771 let (d, wall) = (cfg.positive("upper_arm.tube_outer_diameter_m")?, cfg.positive("upper_arm.tube_wall_m")?);
774 if 2.0 * wall > d {
775 return Err(ConfigError::Invalid("upper_arm.tube_wall_m".into()));
776 }
777 let ei = cfg.positive("upper_arm.youngs_modulus_pa")? * std::f64::consts::PI / 64.0
778 * (d.powi(4) - (d - 2.0 * wall).powi(4));
779 Some(Bending {
780 k: 3.0 * ei / la,
781 c: cfg.non_negative("upper_arm.bending_damping_nm_s_rad")?,
782 k_lateral: 3.0 * ei / la.powi(3),
783 c_lateral: cfg.non_negative("upper_arm.lateral_damping_n_s_m")?,
784 })
785 } else {
786 None
787 };
788 let rod_spacing = cfg.non_negative("geometry.forearm_spacing_m")?;
791 let (mut root_inertia, mut root_moment, mut tip_inertia, mut tip_moment, mut m_lateral) =
792 (i_arm, m_arm * cg, la * la * elbow, la * elbow, elbow);
793 let (mut tube_mass, mut twist_inertia, mut tube_coupling) = (0.0, 0.0, 0.0);
794 if bending.is_some() && cfg.get("effects.arm_tube_inertia").is_ok() && cfg.bool("effects.arm_tube_inertia")? {
795 use sim_components::beam::{STATIC_SHAPE_MASS, STATIC_SHAPE_PARTICIPATION, STATIC_SHAPE_TIP_SLOPE};
796 let m_tube = m_arm.min(3.0 * i_arm / (la * la));
799 let (inertia, moment) = (STATIC_SHAPE_MASS * m_tube * la * la, STATIC_SHAPE_PARTICIPATION * m_tube * la);
800 tube_coupling = (TUBE_MOMENT - STATIC_SHAPE_MASS) * m_tube * la * la;
801 if moment > root_moment {
802 return Err(ConfigError::Invalid("mass.upper_arm_inertia_kgm2".into()));
803 }
804 (root_inertia, root_moment, tip_inertia, tip_moment) = (
805 root_inertia - inertia - 2.0 * tube_coupling,
806 root_moment - moment,
807 tip_inertia + inertia,
808 tip_moment + moment,
809 );
810 twist_inertia =
811 cfg.non_negative("mass.elbow_twist_inertia_kgm2")? + share * m_fb * rod_spacing * rod_spacing / 4.0;
812 m_lateral += STATIC_SHAPE_MASS * m_tube + twist_inertia * (STATIC_SHAPE_TIP_SLOPE / la).powi(2);
813 tube_mass = m_tube;
814 }
815 let mut h4 = Self {
816 legs: Legs::new(base_radius - plate_radius, la, lb),
817 root_inertia,
818 root_moment,
819 tip_inertia,
820 tip_moment,
821 m_lateral,
822 m_elbow: elbow,
823 tube_mass,
824 twist_inertia,
825 tube_coupling,
826 bending,
827 base_radius,
828 plate_radius,
829 rod_spacing,
830 elastic: cfg.bool("effects.joint_elasticity")?,
831 g: if cfg.bool("effects.gravity")? { G } else { 0.0 },
832 arm_inertia: i_arm + la * la * elbow,
833 arm_moment: m_arm * cg + la * elbow,
834 m_rod_middle: middle * m_fb,
835 m_forearms: m_fb,
836 forearm_share: share,
837 weight_shift: if rods { 0.0 } else { (share - 0.5) * m_fb },
838 rod_spin: if rods { 2.0 * spin } else { 0.0 },
839 m_part: cfg.non_negative("mass.plate_part_kg")? + 2.0 * (1.0 - share - middle) * m_fb,
840 m_carriage: cfg.positive("mass.carriage_kg")?,
841 m_payload: if cfg.bool("effects.payload")? { cfg.non_negative("mass.payload_kg")? } else { 0.0 },
842 kappa,
843 j_tool: cfg.positive("tool.inertia_kgm2")?,
844 j_payload: if cfg.bool("effects.payload")? { cfg.non_negative("tool.payload_inertia_kgm2")? } else { 0.0 },
845 amplifier: cfg.bool("effects.amplifier_compliance")?.then_some(amplifier),
846 payload_attached: true,
847 brake_engaged: false,
848 push: [0.0; 4],
849 joints: [joint.clone(), joint.clone(), joint.clone(), joint],
850 thermal: ThermalFeedback::from_config(cfg)?,
851 radius,
852 top,
853 sphere,
854 max_condition: cfg.positive("workspace.max_condition_number")?,
855 axes: [
856 axis("x", "axis-x", -radius, radius)?,
857 axis("y", "axis-y", -radius, radius)?,
858 axis("z", "axis-z", top - centre, top)?,
859 AxisInfo {
860 id: "c",
861 key: "axis-c",
862 unit: "rad",
863 min: c_min,
864 max: c_max,
865 max_vel: cfg.positive("axis.c.max_velocity_rad_s")?,
866 max_acc: cfg.positive("axis.c.max_acceleration_rad_s2")?,
867 max_jerk: cfg.positive("axis.c.max_jerk_rad_s3")?,
868 },
869 ],
870 motors: [
871 MotorInfo { id: "1", key: "motor-arm-1" },
872 MotorInfo { id: "2", key: "motor-arm-2" },
873 MotorInfo { id: "3", key: "motor-arm-3" },
874 MotorInfo { id: "4", key: "motor-arm-4" },
875 ],
876 rest_slack: 0.0,
877 };
878 h4.rest_slack = h4.rest_sag();
879 Ok(h4)
880 }
881
882 pub fn legs(&self) -> &Legs {
883 &self.legs
884 }
885
886 pub fn kappa(&self) -> f64 {
888 self.kappa
889 }
890
891 fn ratio(&self) -> f64 {
892 self.joints[0].ratio()
893 }
894
895 pub fn carried(&self) -> f64 {
897 self.m_carriage + if self.payload_attached { self.m_payload } else { 0.0 }
898 }
899
900 pub fn part_mass(&self) -> f64 {
902 self.m_part
903 }
904
905 pub fn tool_inertia(&self) -> f64 {
907 self.j_tool + if self.payload_attached { self.j_payload } else { 0.0 }
908 }
909
910 pub fn arm_inertia(&self) -> f64 {
912 self.arm_inertia
913 }
914 pub fn arm_moment(&self) -> f64 {
915 self.arm_moment
916 }
917
918 fn coordinates(&self, tool: &[f64]) -> V4 {
920 [tool[0], tool[1], tool[2], tool[3] / self.kappa]
921 }
922
923 fn arms(&self, s: &[f64]) -> (V4, V4) {
925 ([s[0], s[1], s[2], s[3]], [s[4], s[5], s[6], s[7]])
926 }
927
928 fn rotors(&self, s: &[f64]) -> (V4, V4) {
930 if self.elastic {
931 ([s[8], s[9], s[10], s[11]], [s[12], s[13], s[14], s[15]])
932 } else {
933 let i = self.ratio();
934 ([s[0] * i, s[1] * i, s[2] * i, s[3] * i], [s[4] * i, s[5] * i, s[6] * i, s[7] * i])
935 }
936 }
937
938 fn brakes(&self, s: &[f64]) -> V4 {
939 let at = if self.elastic { 16 } else { 8 };
940 [s[at], s[at + 1], s[at + 2], s[at + 3]]
941 }
942
943 fn turn_at(&self) -> usize {
945 if self.elastic { N_ELASTIC } else { N_RIGID }
946 }
947
948 fn bend_at(&self) -> usize {
950 self.turn_at() + if self.amplifier.is_some() { 2 } else { 0 }
951 }
952
953 fn bend(&self, s: &[f64]) -> (V4, V4) {
955 if self.bending.is_none() {
956 return ([0.0; 4], [0.0; 4]);
957 }
958 let at = self.bend_at();
959 ([s[at], s[at + 1], s[at + 2], s[at + 3]], [s[at + 4], s[at + 5], s[at + 6], s[at + 7]])
960 }
961
962 fn lateral(&self, s: &[f64]) -> (V4, V4) {
964 if self.bending.is_none() {
965 return ([0.0; 4], [0.0; 4]);
966 }
967 let at = self.bend_at() + 8;
968 ([s[at], s[at + 1], s[at + 2], s[at + 3]], [s[at + 4], s[at + 5], s[at + 6], s[at + 7]])
969 }
970
971 fn pushed<const N: usize>(&self, s: &[f64], at: usize) -> [f64; N] {
974 sim_core::tool_force_on_rates(self, s, &self.push, at..at + N)
975 .map_or([0.0; N], |q| std::array::from_fn(|i| q[i]))
976 }
977
978 fn pushed_on_arms(&self, s: &[f64]) -> V4 {
980 if self.bending.is_some() { [0.0; 4] } else { self.pushed(s, 4) }
981 }
982
983 fn elbows(&self, s: &[f64]) -> (V4, V4) {
985 let ((t, w), (b, r)) = (self.arms(s), self.bend(s));
986 (std::array::from_fn(|k| t[k] + b[k]), std::array::from_fn(|k| w[k] + r[k]))
987 }
988
989 fn pose(&self, t: V4) -> (V4, M4) {
991 let (x, j, _) = self.pose_moved(t, [0.0; 4]);
992 (x, j)
993 }
994
995 fn pose_moved(&self, t: V4, y: V4) -> Pose {
997 self.legs
998 .forward_moved(t, y)
999 .and_then(|x| {
1000 let (j, jy) = self.legs.jacobians(t, y, x)?;
1001 Some((x, j, jy))
1002 })
1003 .unwrap_or(([f64::NAN; 4], [[f64::NAN; 4]; 4], [[f64::NAN; 4]; 4]))
1004 }
1005
1006 fn pose_at(&self, s: &[f64]) -> Pose {
1008 self.pose_moved(self.elbows(s).0, self.lateral(s).0)
1009 }
1010
1011 fn slide_of(&self, s: &[f64], (x, j, jy): &Pose) -> (f64, f64) {
1013 let ((_, w), (_, yv)) = (self.elbows(s), self.lateral(s));
1014 (self.kappa * x[3], self.kappa * (dot4(j[3], w) + dot4(jy[3], yv)))
1015 }
1016
1017 fn twist(&self, s: &[f64]) -> (f64, f64) {
1019 if self.amplifier.is_none() {
1020 return (0.0, 0.0);
1021 }
1022 self.twist_at(s, &self.pose_at(s))
1023 }
1024
1025 fn twist_at(&self, s: &[f64], pose: &Pose) -> (f64, f64) {
1027 let at = self.turn_at();
1028 let (slide, rate) = self.slide_of(s, pose);
1029 (slide - s[at], rate - s[at + 1])
1030 }
1031
1032 fn amplifier_torque_at(&self, s: &[f64], pose: &Pose) -> f64 {
1034 self.amplifier.map_or(0.0, |a| {
1035 let (twist, rate) = self.twist_at(s, pose);
1036 a.torque(twist, rate)
1037 })
1038 }
1039
1040 pub fn load_at(&self, t: V4, w: V4, carried: f64, spin: f64) -> Load {
1044 let (x, j) = self.pose(t);
1045 self.load_with(t, x, j, w, carried, spin)
1046 }
1047
1048 fn load_with(&self, t: V4, x: V4, j: M4, w: V4, carried: f64, spin: f64) -> Load {
1050 self.load_n::<4>(t, [0.0; 4], (x, j, [[0.0; 4]; 4]), w, [0.0; 4], carried, spin, true)
1051 }
1052
1053 fn load_n<const N: usize>(
1061 &self,
1062 t: V4,
1063 y: V4,
1064 (x, j, jy): Pose,
1065 w: V4,
1066 yv: V4,
1067 carried: f64,
1068 spin: f64,
1069 root: bool,
1070 ) -> LoadN<N> {
1071 let jx: [[f64; N]; 4] =
1073 std::array::from_fn(|r| std::array::from_fn(|c| if c < 4 { j[r][c] } else { jy[r][c - 4] }));
1074 let qv: [f64; N] = std::array::from_fn(|c| if c < 4 { w[c] } else { yv[c - 4] });
1075 let xv: V4 = std::array::from_fn(|r| (0..N).map(|c| jx[r][c] * qv[c]).sum());
1076 let a0 = self.legs.velocity_term_moved(t, y, x, w, yv, xv).unwrap_or([f64::NAN; 4]);
1077 let d = self.legs.slide;
1078 let point = |side: f64| -> ([[f64; N]; 3], V3) {
1080 (
1081 std::array::from_fn(|r| std::array::from_fn(|c| jx[r][c] + side * d[r] * jx[3][c])),
1082 std::array::from_fn(|r| a0[r] + side * d[r] * a0[3]),
1083 )
1084 };
1085 let mut load = ([[0.0; N]; N], [0.0; N], [0.0; N]);
1086 for side in [-1.0, 1.0] {
1087 let (jp, ap) = point(side);
1088 add_point(&mut load, self.m_part, &jp, ap, self.g);
1089 }
1090 let (jp, ap) = point(0.0);
1091 add_point(&mut load, carried, &jp, ap, self.g);
1092 add_turn(&mut load, spin * self.kappa * self.kappa, jx[3], a0[3]);
1093 let (inertia, moment) =
1094 if root { (self.arm_inertia, self.arm_moment) } else { (self.tip_inertia, self.tip_moment) };
1095 for i in 0..4 {
1096 load.0[i][i] += inertia;
1097 load.2[i] += self.g * moment * t[i].cos();
1098 if N == 8 {
1099 load.0[4 + i][4 + i] += self.m_lateral;
1101 }
1102 if self.weight_shift != 0.0 {
1103 load.2[i] -= self.g * self.weight_shift * self.legs.la * t[i].cos();
1105 let (jq, _) = point(SIDE[i]);
1106 (0..N).for_each(|c| load.2[c] -= self.weight_shift * self.g * jq[2][c]);
1107 }
1108 if self.m_rod_middle == 0.0 && self.rod_spin == 0.0 {
1109 continue;
1110 }
1111 let ([elbow, d1, d2], axis) = (self.legs.elbow(i, t[i]), self.legs.tangent(i));
1113 let (jq, aq) = point(SIDE[i]);
1114 let je: [[f64; N]; 3] = std::array::from_fn(|r| {
1115 std::array::from_fn(|c| {
1116 if c == i {
1117 d1[r]
1118 } else if c == 4 + i {
1119 axis[r]
1120 } else {
1121 0.0
1122 }
1123 })
1124 });
1125 let ae = d2.map(|v| v * w[i] * w[i]);
1126 if self.m_rod_middle > 0.0 {
1127 let jm = std::array::from_fn(|r| std::array::from_fn(|c| 0.5 * (jq[r][c] + je[r][c])));
1128 add_point(&mut load, self.m_rod_middle, &jm, std::array::from_fn(|k| 0.5 * (aq[k] + ae[k])), self.g);
1129 }
1130 if self.rod_spin > 0.0 {
1131 let ju = std::array::from_fn(|r| std::array::from_fn(|c| jq[r][c] - je[r][c]));
1132 let accel = std::array::from_fn(|k| aq[k] - ae[k]);
1133 let moved: V3 = std::array::from_fn(|k| elbow[k] + y[i] * axis[k]);
1134 self.add_spin(&mut load, axis, sub(self.legs.end(i, x), moved), &ju, &qv, accel);
1135 }
1136 }
1137 load
1138 }
1139
1140 fn add_spin<const N: usize>(&self, load: &mut LoadN<N>, a: V3, u: V3, ju: &[[f64; N]; 3], w: &[f64; N], accel: V3) {
1147 let l = self.legs.lb;
1148 let du: V3 = std::array::from_fn(|r| (0..N).map(|c| ju[r][c] * w[c]).sum());
1149 let (sigma, n) = (dot(a, u), dot(a, cross(du, u)));
1150 let d = l * l - sigma * sigma;
1151 let s = -sigma * n / (l * d);
1152 let axis = cross(u, a);
1153 let g: [f64; N] = std::array::from_fn(|c| -sigma / (l * d) * (0..3).map(|k| ju[k][c] * axis[k]).sum::<f64>());
1154 let (dsigma, dn) = (dot(a, du), dot(a, cross(accel, u)));
1155 let ds = -(dsigma * n + sigma * dn) / (l * d) - 2.0 * sigma * sigma * dsigma * n / (l * d * d);
1156 let turn = cross(du, u).map(|v| v / l.powi(3));
1157 for r in 0..N {
1158 for c in 0..N {
1159 load.0[r][c] += self.rod_spin * g[r] * g[c];
1160 }
1161 load.1[r] += self.rod_spin * (ds * g[r] + s * (0..3).map(|k| ju[k][r] * turn[k]).sum::<f64>());
1162 }
1163 }
1164
1165 fn rigid_load(&self, t: V4, w: V4) -> Load {
1167 self.load_at(t, w, self.carried(), self.tool_inertia())
1168 }
1169
1170 fn joint_load(&self, s: &[f64]) -> Load {
1175 let (t, w) = self.arms(s);
1176 if self.amplifier.is_none() && self.bending.is_none() {
1177 return self.rigid_load(t, w);
1178 }
1179 self.joint_load_at(s, &self.pose_at(s))
1180 }
1181
1182 fn joint_load_at(&self, s: &[f64], pose: &Pose) -> Load {
1184 let (t, w) = self.arms(s);
1185 if let Some(b) = self.bending {
1186 let ((e, _), (bend, rate), (y, _)) = (self.elbows(s), self.bend(s), self.lateral(s));
1187 let (.., tip) = self.load_n::<8>(e, y, *pose, [0.0; 4], [0.0; 4], self.carried(), 0.0, false);
1188 let mut mass: M4 =
1189 std::array::from_fn(|r| std::array::from_fn(|c| if r == c { self.root_inertia } else { 0.0 }));
1190 let gravity = std::array::from_fn(|i| self.g * self.root_moment * t[i].cos() + tip[i]);
1191 let mut velocity: V4 = std::array::from_fn(|i| tip[i] - b.k * bend[i] - b.c * rate[i]);
1192 if self.tube_coupling > 0.0 {
1193 let (m, f) = self.distal(s, pose, b);
1195 let inv = sim_components::chain::Lu::new(&m).and_then(|lu| lu.inverse()).unwrap_or([[f64::NAN; 8]; 8]);
1196 let bb = self.tube_coupling;
1197 for r in 0..4 {
1198 for c in 0..4 {
1199 mass[r][c] -= bb * bb * inv[r][c];
1200 }
1201 velocity[r] += bb * (0..8).map(|c| inv[r][c] * f[c]).sum::<f64>();
1202 }
1203 }
1204 return (mass, velocity, gravity);
1205 }
1206 let (x, j, _) = *pose;
1207 let mut load = self.load_with(t, x, j, w, self.carried(), 0.0);
1208 let torque = self.amplifier_torque_at(s, pose);
1209 for r in 0..4 {
1210 load.1[r] += self.kappa * j[3][r] * torque;
1211 }
1212 load
1213 }
1214
1215 fn bend_rates(&self, s: &[f64], pose: &Pose, acc: V4, out: &mut [f64]) {
1220 let Some(b) = self.bending else { return };
1221 let ((_, rate), (_, yv)) = (self.bend(s), self.lateral(s));
1222 let (mass, mut rhs) = self.distal(s, pose, b);
1223 for i in 0..4 {
1225 rhs[i] -= self.tube_coupling * acc[i];
1226 }
1227 let q = sim_components::chain::solve(mass.as_flattened(), &rhs).unwrap_or_else(|| vec![f64::NAN; 8]);
1228 let at = self.bend_at();
1229 out[at..at + 4].copy_from_slice(&rate);
1230 for i in 0..4 {
1231 out[at + 4 + i] = q[i] - acc[i];
1232 }
1233 out[at + 8..at + 12].copy_from_slice(&yv);
1234 out[at + 12..at + 16].copy_from_slice(&q[4..]);
1235 }
1236
1237 fn distal(&self, s: &[f64], pose: &Pose, b: Bending) -> ([[f64; 8]; 8], [f64; 8]) {
1240 let ((e, speeds), (bend, rate), (y, yv)) = (self.elbows(s), self.bend(s), self.lateral(s));
1241 let spin = if self.amplifier.is_some() { 0.0 } else { self.tool_inertia() };
1242 let (mass, velocity, gravity) = self.load_n::<8>(e, y, *pose, speeds, yv, self.carried(), spin, false);
1243 let torque = self.amplifier_torque_at(s, pose);
1244 let (_, j, jy) = *pose;
1245 let at = self.bend_at();
1247 let (on_elbows, on_moves): (V4, V4) = (self.pushed(s, at + 4), self.pushed(s, at + 12));
1248 let rhs = std::array::from_fn(|i| {
1249 let slide = if i < 4 { j[3][i] } else { jy[3][i - 4] };
1250 let spring =
1251 if i < 4 { b.k * bend[i] + b.c * rate[i] } else { b.k_lateral * y[i - 4] + b.c_lateral * yv[i - 4] };
1252 let push = if i < 4 { on_elbows[i] } else { on_moves[i - 4] };
1253 gravity[i] - velocity[i] - self.kappa * slide * torque - spring + push
1254 });
1255 (mass, rhs)
1256 }
1257
1258 fn rest_at(&self, b: Bending, x: V4, carried: f64) -> (V4, V4, V4, V4) {
1263 let tip_at = |y: V4| {
1264 let e = self.legs.inverse_moved(x, y).unwrap_or([f64::NAN; 4]);
1265 let pose = match self.legs.jacobians(e, y, x) {
1266 Some((j, jy)) => (x, j, jy),
1267 None => ([f64::NAN; 4], [[f64::NAN; 4]; 4], [[f64::NAN; 4]; 4]),
1268 };
1269 (e, self.load_n::<8>(e, y, pose, [0.0; 4], [0.0; 4], carried, 0.0, false).2)
1270 };
1271 let mut y = [0.0; 4];
1273 for _ in 0..20 {
1274 let (_, tip) = tip_at(y);
1275 let next: V4 = std::array::from_fn(|i| tip[4 + i] / b.k_lateral);
1276 let settled = (0..4).all(|i| (next[i] - y[i]).abs() <= 1e-15);
1277 y = next;
1278 if settled {
1279 break;
1280 }
1281 }
1282 let (e, tip) = tip_at(y);
1283 let bend: V4 = std::array::from_fn(|i| tip[i] / b.k);
1284 let t: V4 = std::array::from_fn(|i| e[i] - bend[i]);
1285 (t, std::array::from_fn(|i| self.g * self.root_moment * t[i].cos() + tip[i]), bend, y)
1286 }
1287
1288 fn rigid_solve(&self, s: &[f64], torque: &[f64]) -> (V4, V4, V4) {
1291 let (t, w) = self.arms(s);
1292 let (rotor, rotor_speed) = self.rotors(s);
1293 let brakes = self.brakes(s);
1294 let (mass, velocity, gravity) = self.joint_load(s);
1295 let drive: V4 = std::array::from_fn(|k| {
1296 self.joints[k].rigid_drive(torque[k], rotor[k], rotor_speed[k], brakes[k], self.brake_engaged).0
1297 });
1298 let push = self.pushed_on_arms(s);
1299 let rest: V4 =
1300 std::array::from_fn(|k| gravity[k] - velocity[k] + self.joints[k].output_torque(t[k], w[k]) + push[k]);
1301 let solve = |loss: V4| -> V4 {
1302 let m: M4 = std::array::from_fn(|r| {
1303 std::array::from_fn(|c| {
1304 mass[r][c] + if r == c { loss[r] * self.joints[r].reflected_inertia() } else { 0.0 }
1305 })
1306 });
1307 solve4(&m, std::array::from_fn(|k| loss[k] * drive[k] + rest[k])).unwrap_or([f64::NAN; 4])
1308 };
1309 let loss = sim_components::mech::settled_loss([1.0; 4], |loss| {
1311 let acc = solve(*loss);
1312 std::array::from_fn(|k| {
1313 self.joints[k].gearbox.loss_factor(drive[k] - self.joints[k].reflected_inertia() * acc[k], w[k])
1314 })
1315 });
1316 let acc = solve(loss);
1317 let into: V4 = std::array::from_fn(|k| drive[k] - self.joints[k].reflected_inertia() * acc[k]);
1318 (acc, into, std::array::from_fn(|k| loss[k] * into[k]))
1319 }
1320
1321 fn arm_acceleration(&self, s: &[f64], torque: &[f64]) -> V4 {
1323 if self.elastic {
1324 let mut d = vec![0.0; self.state_len()];
1325 self.derivatives(s, torque, &mut d);
1326 [d[4], d[5], d[6], d[7]]
1327 } else {
1328 self.rigid_solve(s, torque).0
1329 }
1330 }
1331
1332 fn gear_output(&self, s: &[f64], torque: &[f64]) -> V4 {
1334 if self.elastic {
1335 std::array::from_fn(|k| self.joints[k].gearbox.torque(s[8 + k], s[12 + k], s[k], s[4 + k]).output)
1336 } else {
1337 self.rigid_solve(s, torque).2
1338 }
1339 }
1340
1341 fn energy_parts(&self, s: &[f64]) -> [f64; 3] {
1342 let (t, w) = self.arms(s);
1343 let ((e, ew), (y, yv)) = (self.elbows(s), self.lateral(s));
1344 let pose = self.pose_at(s);
1345 let x = pose.0;
1346 let spin = if self.amplifier.is_some() { 0.0 } else { self.tool_inertia() };
1347 let mut kinetic = if self.bending.is_some() {
1350 let (mass, ..) = self.load_n::<8>(e, y, pose, ew, yv, self.carried(), spin, false);
1351 let q: [f64; 8] = std::array::from_fn(|i| if i < 4 { ew[i] } else { yv[i - 4] });
1352 let moving: f64 = (0..8).map(|r| q[r] * (0..8).map(|c| mass[r][c] * q[c]).sum::<f64>()).sum();
1353 0.5 * moving + 0.5 * self.root_inertia * dot4(w, w) + self.tube_coupling * dot4(w, ew)
1354 } else {
1355 let (mass, ..) = self.load_with(t, x, pose.1, w, self.carried(), spin);
1356 0.5 * dot4(w, mul4(&mass, w))
1357 };
1358 let middles: f64 = (0..4).map(|i| 0.5 * (self.legs.elbow(i, e[i])[0][2] + x[2])).sum();
1359 let sines = |a: V4| a.iter().map(|v| v.sin()).sum::<f64>();
1360 let shifted = self.g * self.weight_shift * (4.0 * x[2] + self.legs.la * sines(e));
1362 let potential = shifted
1363 + if self.bending.is_some() {
1364 self.g
1365 * ((2.0 * self.m_part + self.carried()) * x[2] + self.m_rod_middle * middles
1366 - self.root_moment * sines(t)
1367 - self.tip_moment * sines(e))
1368 } else {
1369 self.g
1370 * ((2.0 * self.m_part + self.carried()) * x[2] + self.m_rod_middle * middles
1371 - self.arm_moment * sines(t))
1372 };
1373 let mut elastic: f64 = (0..4).map(|k| self.joints[k].stop_energy(t[k])).sum();
1374 if let Some(b) = self.bending {
1375 let (bend, _) = self.bend(s);
1376 elastic += 0.5 * b.k * dot4(bend, bend) + 0.5 * b.k_lateral * dot4(y, y);
1377 }
1378 if self.elastic {
1379 for k in 0..4 {
1380 kinetic += 0.5 * self.joints[k].rotor_inertia * s[12 + k] * s[12 + k];
1381 elastic += self.joints[k].gearbox.energy(s[8 + k], s[k]);
1382 }
1383 } else {
1384 kinetic += 0.5 * (0..4).map(|k| self.joints[k].reflected_inertia() * w[k] * w[k]).sum::<f64>();
1385 }
1386 if let Some(a) = self.amplifier {
1387 let at = self.turn_at();
1388 kinetic += 0.5 * self.tool_inertia() * s[at + 1] * s[at + 1];
1389 elastic += a.energy(self.kappa * x[3] - s[at]);
1390 }
1391 [kinetic, potential, elastic]
1392 }
1393
1394 fn loss_signals(&self, losses: &Losses, out: &mut Vec<f64>) {
1397 out.extend(&losses.powers[..14]);
1398 if self.amplifier.is_some() {
1399 out.push(losses.powers[14]);
1400 }
1401 if self.bending.is_some() {
1402 out.push(losses.powers[15]);
1403 }
1404 }
1405
1406 fn losses(&self, s: &[f64], torque: &[f64]) -> Losses {
1407 let (t, w) = self.arms(s);
1408 let (rotor, rotor_speed) = self.rotors(s);
1409 let brakes = self.brakes(s);
1410 let mut powers = [0.0; 16];
1411 let mut gear_at_rotor = [0.0; 4];
1412 let rigid = (!self.elastic).then(|| self.rigid_solve(s, torque));
1413 let (mut stops, mut other) = (0.0, 0.0);
1414 for k in 0..4 {
1415 let joint = &self.joints[k];
1416 let [friction, stop, shaft, drag] = joint.losses(t[k], w[k], rotor_speed[k], brakes[k], self.brake_engaged);
1417 let gear = match &rigid {
1418 Some((_, into, out)) => {
1419 gear_at_rotor[k] = (into[k] - out[k]) / joint.ratio();
1420 (into[k] - out[k]) * w[k]
1421 }
1422 None => {
1423 let g = joint.gearbox.torque(s[8 + k], s[12 + k], s[k], s[4 + k]);
1424 gear_at_rotor[k] = g.rotor - g.output / joint.ratio();
1425 joint.gearbox.loss_power(s[8 + k], s[12 + k], s[k], s[4 + k])
1426 }
1427 };
1428 powers[3 * k..3 * k + 3].copy_from_slice(&[friction, shaft, gear + drag]);
1429 stops += stop;
1430 other += (torque[k] - joint.ripple.apply(torque[k], rotor[k])) * rotor_speed[k];
1431 }
1432 powers[12] = stops;
1433 powers[13] = other;
1434 if let Some(a) = self.amplifier {
1435 let (twist, rate) = self.twist(s);
1436 powers[14] = a.loss_power(twist, rate);
1437 }
1438 if let Some(b) = self.bending {
1439 let ((_, rate), (_, moving)) = (self.bend(s), self.lateral(s));
1440 powers[15] = b.c * dot4(rate, rate) + b.c_lateral * dot4(moving, moving);
1441 }
1442 Losses { powers, gear_at_rotor }
1443 }
1444
1445 fn in_envelope(&self, p: &[f64], slack: f64) -> bool {
1447 let (centre, r) = self.sphere;
1448 let below = if centre.is_finite() {
1449 (p[0] * p[0] + p[1] * p[1] + (p[2] - centre).powi(2)).sqrt() <= r + slack
1450 } else {
1451 p[2] >= self.axes[2].min - slack
1452 };
1453 p[0].hypot(p[1]) <= self.radius + slack && p[2] <= self.top + slack && below
1454 }
1455
1456 fn rest_sag(&self) -> f64 {
1463 if !self.elastic && self.bending.is_none() {
1464 return 1e-4;
1465 }
1466 let mut most = 0f64;
1467 let (bottom, top) = (self.axes[2].min, self.top);
1468 let turns = [self.axes[3].min, 0.5 * (self.axes[3].min + self.axes[3].max), self.axes[3].max];
1469 for ring in 0..=4 {
1470 let rho = self.radius * ring as f64 / 4.0;
1471 for turn in 0..12 {
1472 let (sin, cos) = (turn as f64 * std::f64::consts::TAU / 12.0).sin_cos();
1473 let (centre, r) = self.sphere;
1474 let lowest = if centre.is_finite() { centre - (r * r - rho * rho).max(0.0).sqrt() } else { bottom };
1475 for z in (0..=8).map(|k| lowest + (top - lowest) * k as f64 / 8.0) {
1476 let p = [rho * cos, rho * sin, z];
1477 if !self.in_envelope(&p, 1e-9) {
1478 continue;
1479 }
1480 for c in turns {
1481 let x = self.coordinates(&[p[0], p[1], p[2], c]);
1482 let Some(t) = self.legs.inverse(x) else { continue };
1483 let Some(j) = self.legs.jacobian(t, x) else { continue };
1484 for m in [self.m_carriage, self.m_carriage + self.m_payload] {
1485 let (t, gravity) = match self.bending {
1487 Some(b) => {
1488 let (t, gravity, ..) = self.rest_at(b, x, m);
1489 (t, gravity)
1490 }
1491 None => (t, self.load_with(t, x, j, [0.0; 4], m, 0.0).2),
1492 };
1493 let twist: V4 = std::array::from_fn(|k| {
1495 if !self.elastic {
1496 return 0.0;
1497 }
1498 (-gravity[k] - self.joints[k].output_torque(t[k], 0.0))
1499 / self.joints[k].gearbox.stiffness
1500 });
1501 for signs in 0..16 {
1502 let half = |k: usize| {
1503 let sign = if signs >> k & 1 == 1 { 1.0 } else { -1.0 };
1504 if self.elastic { sign * self.joints[k].gearbox.half_backlash } else { 0.0 }
1505 };
1506 let moved = std::array::from_fn(|k| t[k] + twist[k] + half(k));
1507 if let Some(q) = self.legs.forward_from(moved, x) {
1508 let off: V4 =
1509 std::array::from_fn(|k| (q[k] - x[k]) * if k == 3 { self.kappa } else { 1.0 });
1510 most = most.max(dot4(off, off).sqrt());
1511 }
1512 }
1513 }
1514 }
1515 }
1516 }
1517 }
1518 (1.1 * most).max(1e-4)
1519 }
1520
1521 fn modes_at(&self, tool: &[f64], small: bool) -> Vec<(f64, f64, Vec<f64>)> {
1533 if (!self.elastic && self.bending.is_none()) || tool.len() != 4 {
1534 return Vec::new();
1535 }
1536 let x = self.coordinates(tool);
1537 let Some(t) = self.legs.inverse(x) else { return Vec::new() };
1538 let spin = if self.amplifier.is_some() { 0.0 } else { self.tool_inertia() };
1539 let Some(b) = self.bending else {
1540 let (mass, ..) = self.load_at(t, [0.0; 4], self.carried(), spin);
1541 let (mu, v) = symmetric_eigen(mass.iter().map(|row| row.to_vec()).collect());
1542 let g = &self.joints[0].gearbox;
1543 let (k, c) = (g.stiffness + if small && g.hysteresis > 0.0 { g.dahl_stiffness } else { 0.0 }, g.damping);
1544 let mut out: Vec<(f64, f64, Vec<f64>)> = (0..4)
1545 .filter(|&i| mu[i] > 0.0)
1546 .map(|i| {
1547 let w = (k / mu[i]).sqrt();
1548 (w / std::f64::consts::TAU, c / (2.0 * w * mu[i]), (0..4).map(|r| v[r][i]).collect())
1549 })
1550 .collect();
1551 out.sort_by(|a, b| a.0.total_cmp(&b.0));
1552 return out;
1553 };
1554 let Some((j, jy)) = self.legs.jacobians(t, [0.0; 4], x) else { return Vec::new() };
1555 let distal: Vec<Vec<f64>> = self
1556 .load_n::<8>(t, [0.0; 4], (x, j, jy), [0.0; 4], [0.0; 4], self.carried(), spin, false)
1557 .0
1558 .map(Vec::from)
1559 .into();
1560 let k_gear = self.elastic.then(|| {
1562 std::array::from_fn(|i| {
1563 let g = &self.joints[i].gearbox;
1564 g.stiffness + if small && g.hysteresis > 0.0 { g.dahl_stiffness } else { 0.0 }
1565 })
1566 });
1567 let c_gear: V4 = std::array::from_fn(|i| if self.elastic { self.joints[i].gearbox.damping } else { 0.0 });
1568 arm_modes((self.root_inertia, self.tube_coupling), &distal, k_gear, b.k, b.k_lateral)
1569 .into_iter()
1570 .map(|(w2, v)| {
1571 let distal_kinetic: f64 =
1572 (0..8).map(|r| v[4 + r] * (0..8).map(|c| distal[r][c] * v[4 + c]).sum::<f64>()).sum();
1573 let kinetic = (0..4)
1574 .map(|i| self.root_inertia * v[i] * v[i] + 2.0 * self.tube_coupling * v[i] * v[4 + i])
1575 .sum::<f64>()
1576 + distal_kinetic;
1577 let damped: f64 = (0..4)
1578 .map(|i| {
1579 c_gear[i] * v[i] * v[i] + b.c * (v[4 + i] - v[i]).powi(2) + b.c_lateral * v[8 + i] * v[8 + i]
1580 })
1581 .sum();
1582 let w = w2.sqrt();
1583 (w / std::f64::consts::TAU, damped / (2.0 * w * kinetic), v)
1584 })
1585 .collect()
1586 }
1587
1588 fn modes_with(&self, tool_pose: &[f64], small: bool) -> Vec<Mode> {
1590 let mut out: Vec<Mode> =
1591 self.modes_at(tool_pose, small).into_iter().map(|(hz, damping, _)| Mode { hz, damping }).collect();
1592 out.extend(self.amplifier_mode());
1593 out.sort_by(|a, b| a.hz.total_cmp(&b.hz));
1594 out
1595 }
1596
1597 pub fn amplifier_mode(&self) -> Option<Mode> {
1600 let a = self.amplifier?;
1601 let j = self.tool_inertia();
1602 Some(Mode {
1603 hz: (a.stiffness / j).sqrt() / std::f64::consts::TAU,
1604 damping: a.damping / (2.0 * (a.stiffness * j).sqrt()),
1605 })
1606 }
1607
1608 fn tool_bar(&self, p: V3, c: f64) -> (V3, V3) {
1610 let half = [0.06 * c.cos(), 0.06 * c.sin(), 0.0];
1611 let under = [p[0], p[1], p[2] - 0.04];
1612 (std::array::from_fn(|k| under[k] - half[k]), std::array::from_fn(|k| under[k] + half[k]))
1613 }
1614
1615 fn plate_bars(&self, x: V4) -> [(V3, V3); 2] {
1618 let r = self.plate_radius.max(0.03);
1619 let end = |i: usize| {
1620 let (q, (c, s)) = (self.legs.end(i, x), self.legs.azimuth[i]);
1621 [q[0] + r * c, q[1] + r * s, q[2]]
1622 };
1623 [(end(0), end(1)), (end(2), end(3))]
1624 }
1625
1626 fn on_carriage(&self, p: V3) -> Vec<Part> {
1628 let mut parts = vec![Part::new("carriage", Shape::Box { size: [0.08, 0.08, 0.05] }, p, [0.55, 0.55, 0.6])];
1629 if self.payload_attached && self.m_payload > 0.0 {
1630 parts.push(Part::new(
1631 "payload",
1632 Shape::Box { size: [0.12, 0.12, 0.08] },
1633 [p[0], p[1], p[2] - 0.1],
1634 [0.2, 0.7, 0.3],
1635 ));
1636 }
1637 parts
1638 }
1639
1640 fn arm(&self, k: usize, t: V4, y: V4) -> (V3, V3) {
1643 let (c, sn) = self.legs.azimuth[k];
1644 let elbow = self.legs.elbows_moved(t, y)[k];
1645 (
1646 [self.base_radius * c, self.base_radius * sn, 0.0],
1647 [elbow[0] + self.plate_radius * c, elbow[1] + self.plate_radius * sn, elbow[2]],
1648 )
1649 }
1650
1651 fn turn(&self, s: &[f64]) -> (f64, f64) {
1653 if self.amplifier.is_some() {
1654 let at = self.turn_at();
1655 return (s[at], s[at + 1]);
1656 }
1657 self.slide_of(s, &self.pose_at(s))
1658 }
1659
1660 fn view_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
1662 let (_, w) = self.arms(s);
1663 let (_, rotor_speed) = self.rotors(s);
1664 let brakes = self.brakes(s);
1665 let (mass, velocity, gravity) = self.joint_load(s);
1666 let acc = self.arm_acceleration(s, torque);
1667 let moving = mul4(&mass, acc);
1668 let losses = self.losses(s, torque);
1669 for k in 0..4 {
1670 let joint = &self.joints[k];
1671 let i = joint.ratio();
1672 let held = joint.brake.torque(self.brake_engaged, rotor_speed[k], brakes[k]).0;
1673 let parts = [
1674 (moving[k] + velocity[k] + joint.reflected_inertia() * acc[k]) / i,
1675 -gravity[k] / i,
1676 joint.shaft.torque(rotor_speed[k]) + held + losses.gear_at_rotor[k] + joint.friction.torque(w[k]) / i,
1677 ];
1678 out.extend(parts);
1679 out.push(torque[k] - parts.iter().sum::<f64>());
1680 }
1681 self.loss_signals(&losses, out);
1682 out.extend(self.energy_parts(s));
1683 for k in 0..4 {
1684 out.extend(self.joints[k].friction_signals(w[k]));
1685 }
1686 }
1687
1688 fn effect_infos(&self, out: &mut Vec<SignalInfo>) {
1689 for motor in &self.motors {
1690 out.extend(TORQUE_PARTS.map(|part| {
1691 SignalInfo::new(
1692 format!("motor.{}.torque_{part}", motor.id),
1693 motor.key,
1694 &format!("quantity-torque-{part}"),
1695 "N m",
1696 )
1697 }));
1698 }
1699 for (k, motor) in self.motors.iter().enumerate() {
1700 let gear = if self.joints[k].gearbox.is_coupling() {
1701 "quantity-coupling-loss-power"
1702 } else {
1703 "quantity-gearbox-loss-power"
1704 };
1705 out.push(SignalInfo::new(
1706 format!("{LOSS_PREFIX}joint_{}", motor.id),
1707 ARMS[k],
1708 "quantity-friction-power",
1709 "W",
1710 ));
1711 out.push(SignalInfo::new(
1712 format!("{LOSS_PREFIX}shaft_{}", motor.id),
1713 motor.key,
1714 "quantity-shaft-friction-power",
1715 "W",
1716 ));
1717 out.push(SignalInfo::new(format!("{LOSS_PREFIX}gearbox_{}", motor.id), motor.key, gear, "W"));
1718 }
1719 out.push(SignalInfo::new(format!("{LOSS_PREFIX}hard_stops"), "group-joint", "quantity-damping-power", "W"));
1720 out.push(SignalInfo::new(format!("{LOSS_PREFIX}other"), "loss-other", "quantity-power-given-off", "W"));
1721 if self.amplifier.is_some() {
1722 out.push(SignalInfo::new(format!("{LOSS_PREFIX}amplifier"), "group-plate", "quantity-damping-power", "W"));
1723 }
1724 if self.bending.is_some() {
1725 out.push(SignalInfo::new(
1726 format!("{LOSS_PREFIX}arm_bending"),
1727 "group-upper-arms",
1728 "quantity-damping-power",
1729 "W",
1730 ));
1731 }
1732 out.extend(ENERGY_PARTS.map(|part| {
1733 SignalInfo::new(format!("energy.{part}"), "group-energy", &format!("quantity-energy-{part}"), "J")
1734 }));
1735 for k in 0..4 {
1736 out.extend(sim_components::joint::RotaryJoint::friction_infos(JOINT_CONTACTS[k], ARMS[k]));
1737 }
1738 }
1739}
1740
1741const ARMS: [&str; 4] = ["arm-1", "arm-2", "arm-3", "arm-4"];
1743const JOINT_CONTACTS: [&str; 4] = ["joint.1", "joint.2", "joint.3", "joint.4"];
1745
1746impl Machine for H4 {
1747 fn frame_momentum(&self, s: &[f64]) -> Option<sim_core::FrameMomentum> {
1755 use sim_components::base::{add_point, add_spin, add_turning};
1756 let mut f = sim_core::FrameMomentum { gravity: [0.0, 0.0, -self.g], ..Default::default() };
1757 let (t, w) = self.arms(s);
1758 let ((e, ew), (y, yv)) = (self.elbows(s), self.lateral(s));
1759 let (x, j, jy) = self.pose_at(s);
1760 let xv: V4 = std::array::from_fn(|r| dot4(j[r], ew) + dot4(jy[r], yv));
1761 let d = self.legs.slide;
1762 let point = |side: f64| -> (V3, V3) {
1764 (std::array::from_fn(|k| x[k] + side * d[k] * x[3]), std::array::from_fn(|k| xv[k] + side * d[k] * xv[3]))
1765 };
1766 for side in [-1.0, 1.0] {
1767 let (r, v) = point(side);
1768 add_point(&mut f, self.m_part, r, v);
1769 }
1770 let (r, v) = point(0.0);
1771 add_point(&mut f, self.carried(), r, v);
1772 let rotor_speed = self.rotors(s).1;
1773 for i in 0..4 {
1774 let (sin, cos) = t[i].sin_cos();
1775 let (dir, ddir) = (self.legs.to_base(i, [cos, 0.0, -sin]), self.legs.to_base(i, [-sin, 0.0, -cos]));
1776 let joint = self.legs.to_base(i, [self.base_radius, 0.0, 0.0]);
1777 let tangent = self.legs.tangent(i);
1778 if self.bending.is_some() {
1779 let la = self.legs.la;
1785 add_turning(&mut f, joint, dir, ddir, w[i], self.root_inertia, self.root_moment);
1786 let (sin, cos) = e[i].sin_cos();
1787 let (tip, dtip) = (self.legs.to_base(i, [cos, 0.0, -sin]), self.legs.to_base(i, [-sin, 0.0, -cos]));
1788 let point = la * la * self.m_elbow;
1789 add_turning(
1790 &mut f,
1791 joint,
1792 tip,
1793 dtip,
1794 ew[i],
1795 self.tip_inertia - point,
1796 self.tip_moment - la * self.m_elbow,
1797 );
1798 add_spin(&mut f, cross(dir, ddir), self.tube_coupling, w[i] + ew[i]);
1800 let elbow: V3 = std::array::from_fn(|k| joint[k] + la * tip[k] + y[i] * tangent[k]);
1801 let elbow_v: V3 = std::array::from_fn(|k| la * ew[i] * dtip[k] + yv[i] * tangent[k]);
1802 add_point(&mut f, self.m_elbow, elbow, elbow_v);
1803 if self.tube_mass > 0.0 {
1804 use sim_components::beam::{STATIC_SHAPE_MASS, STATIC_SHAPE_PARTICIPATION, STATIC_SHAPE_TIP_SLOPE};
1805 let m = STATIC_SHAPE_PARTICIPATION * self.tube_mass;
1806 let at: V3 = std::array::from_fn(|k| joint[k] + TUBE_CENTROID * la * tip[k]);
1807 add_point(
1808 &mut f,
1809 m,
1810 std::array::from_fn(|k| at[k] + y[i] * tangent[k]),
1811 tangent.map(|v| v * yv[i]),
1812 );
1813 add_point(&mut f, -m, at, [0.0; 3]);
1814 let along = self.tube_mass * la * (TUBE_MOMENT * w[i] + STATIC_SHAPE_MASS * (ew[i] - w[i]));
1815 let off = cross(tangent.map(|v| v * y[i]), dtip.map(|v| v * along));
1816 (0..3).for_each(|k| f.angular[k] += off[k]);
1817 add_spin(&mut f, cross(tip, tangent), self.twist_inertia, STATIC_SHAPE_TIP_SLOPE * yv[i] / la);
1818 }
1819 } else {
1820 add_turning(&mut f, joint, dir, ddir, w[i], self.arm_inertia, self.arm_moment);
1821 }
1822 add_spin(&mut f, tangent, self.joints[i].rotor_inertia, rotor_speed[i]);
1823 if self.m_forearms > 0.0 || self.rod_spin > 0.0 {
1824 let (elbow, d1) = (self.legs.elbows_moved(e, y)[i], self.legs.elbow(i, e[i])[1]);
1825 let (end, end_v) = point(SIDE[i]);
1826 let elbow_v: V3 = std::array::from_fn(|k| d1[k] * ew[i] + tangent[k] * yv[i]);
1827 let (c, sn) = self.legs.azimuth[i];
1830 let out = [self.plate_radius * c, self.plate_radius * sn, 0.0];
1831 let middle = std::array::from_fn(|k| 0.5 * (elbow[k] + end[k]) + out[k]);
1832 let m_fb = self.m_forearms;
1836 let at_elbow = (self.forearm_share - 1.0 / 6.0) * m_fb;
1837 let at_plate = (5.0 / 6.0 - self.forearm_share) * m_fb - self.m_rod_middle;
1838 add_point(&mut f, -at_elbow, std::array::from_fn(|k| elbow[k] + out[k]), elbow_v);
1839 add_point(&mut f, -at_plate, end, end_v);
1840 add_point(&mut f, 2.0 / 3.0 * m_fb, middle, std::array::from_fn(|k| 0.5 * (elbow_v[k] + end_v[k])));
1841 if self.rod_spin > 0.0 {
1842 let (u, du) = (sub(end, elbow), std::array::from_fn(|k| end_v[k] - elbow_v[k]));
1843 let (l, a) = (self.legs.lb, self.legs.tangent(i));
1844 let sigma = dot(a, u);
1845 let spin = -sigma * dot(a, cross(du, u)) / (l * (l * l - sigma * sigma));
1846 add_spin(&mut f, u.map(|v| v / l), self.rod_spin, spin);
1847 }
1848 }
1849 }
1850 let turn = match self.amplifier {
1851 Some(_) => s[self.turn_at() + 1],
1852 None => self.kappa * xv[3],
1853 };
1854 add_spin(&mut f, [0.0, 0.0, 1.0], self.tool_inertia(), turn);
1855 Some(f)
1856 }
1857 fn axes(&self) -> &[AxisInfo] {
1858 &self.axes
1859 }
1860 fn motors(&self) -> &[MotorInfo] {
1861 &self.motors
1862 }
1863
1864 fn inverse(&self, tool: &[f64], motors: &mut [f64]) {
1866 let t = self.legs.inverse(self.coordinates(tool)).unwrap_or([f64::NAN; 4]);
1867 for k in 0..4 {
1868 motors[k] = self.ratio() * t[k];
1869 }
1870 }
1871 fn forward(&self, motors: &[f64], tool: &mut [f64]) {
1872 let i = self.ratio();
1873 let x = self.legs.forward(std::array::from_fn(|k| motors[k] / i)).unwrap_or([f64::NAN; 4]);
1874 tool[..3].copy_from_slice(&x[..3]);
1875 tool[3] = self.kappa * x[3];
1876 }
1877
1878 fn state_len(&self) -> usize {
1879 self.bend_at() + if self.bending.is_some() { 16 } else { 0 }
1880 }
1881
1882 fn equilibrium(&self, tool: &[f64], state: &mut Vec<f64>, torque: &mut [f64]) {
1883 let (t, gravity, bend, lateral) = match self.bending {
1885 Some(b) => self.rest_at(b, self.coordinates(tool), self.carried()),
1886 None => {
1887 let t = self.legs.inverse(self.coordinates(tool)).unwrap_or([f64::NAN; 4]);
1888 (t, self.rigid_load(t, [0.0; 4]).2, [0.0; 4], [0.0; 4])
1889 }
1890 };
1891 state.clear();
1892 state.extend(t);
1893 state.extend([0.0; 4]);
1894 for k in 0..4 {
1895 let joint = &self.joints[k];
1896 let out = -gravity[k] - joint.output_torque(t[k], 0.0);
1898 let rotor = joint.ratio() * (t[k] + if self.elastic { joint.gearbox.static_twist(out) } else { 0.0 });
1899 if self.elastic {
1900 state.push(rotor);
1901 }
1902 torque[k] = joint.ripple.invert(out / joint.ratio(), rotor);
1903 }
1904 state.resize(self.turn_at(), 0.0);
1906 if self.amplifier.is_some() {
1907 state.extend([tool[3], 0.0]);
1908 }
1909 if self.bending.is_some() {
1911 state.extend(bend);
1912 state.extend([0.0; 4]);
1913 state.extend(lateral);
1914 state.extend([0.0; 4]);
1915 }
1916 }
1917
1918 fn derivatives(&self, s: &[f64], torque: &[f64], out: &mut [f64]) {
1919 let pose = (self.amplifier.is_some() || self.bending.is_some()).then(|| self.pose_at(s));
1922 if let (Some(pose), true) = (&pose, self.amplifier.is_some()) {
1923 let at = self.turn_at();
1924 out[at] = s[at + 1];
1925 out[at + 1] = (self.amplifier_torque_at(s, pose) + self.pushed::<1>(s, at + 1)[0]) / self.tool_inertia();
1926 }
1927 if !self.elastic {
1928 let (acc, ..) = self.rigid_solve(s, torque);
1929 let (_, rotor_speed) = self.rotors(s);
1930 let brakes = self.brakes(s);
1931 out[..4].copy_from_slice(&s[4..8]);
1932 out[4..8].copy_from_slice(&acc);
1933 for k in 0..4 {
1934 out[8 + k] = self.joints[k].brake.torque(self.brake_engaged, rotor_speed[k], brakes[k]).1;
1935 }
1936 if let Some(pose) = &pose {
1937 self.bend_rates(s, pose, acc, out);
1938 }
1939 return;
1940 }
1941 let (t, w) = self.arms(s);
1942 let (mass, velocity, gravity) = match &pose {
1943 Some(pose) => self.joint_load_at(s, pose),
1944 None => self.joint_load(s),
1945 };
1946 let (mut rhs, push) = ([0.0; 4], self.pushed_on_arms(s));
1947 for k in 0..4 {
1948 let joint = &self.joints[k];
1949 let (gear, rotor_acc, brake_rate) =
1950 joint.rotor(torque[k], s[8 + k], s[12 + k], t[k], w[k], s[16 + k], self.brake_engaged);
1951 rhs[k] = gear.output + gravity[k] - velocity[k] + joint.output_torque(t[k], w[k]) + push[k];
1952 out[8 + k] = s[12 + k];
1953 out[12 + k] = rotor_acc;
1954 out[16 + k] = brake_rate;
1955 }
1956 let acc = solve4(&mass, rhs).unwrap_or([f64::NAN; 4]);
1957 out[..4].copy_from_slice(&s[4..8]);
1958 out[4..8].copy_from_slice(&acc);
1959 if let Some(pose) = &pose {
1960 self.bend_rates(s, pose, acc, out);
1961 }
1962 }
1963
1964 fn tool_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
1965 let ((_, ew), (_, yv)) = (self.elbows(s), self.lateral(s));
1966 let (x, j, jy) = self.pose_at(s);
1967 let v: V4 = std::array::from_fn(|r| dot4(j[r], ew) + dot4(jy[r], yv));
1968 pos[..3].copy_from_slice(&x[..3]);
1969 vel[..3].copy_from_slice(&v[..3]);
1970 (pos[3], vel[3]) = self.turn(s);
1971 }
1972 fn set_tool_velocity(&self, s: &mut [f64], vel: &[f64]) {
1975 let (_, j, _) = self.pose_at(s);
1976 let w = solve4(&j, self.coordinates(vel)).unwrap_or([f64::NAN; 4]);
1977 s[4..8].copy_from_slice(&w);
1978 if self.bending.is_some() {
1979 let at = self.bend_at();
1980 s[at + 4..at + 8].fill(0.0);
1981 s[at + 12..at + 16].fill(0.0);
1982 }
1983 if self.elastic {
1984 for k in 0..4 {
1985 s[12 + k] = self.joints[k].ratio() * w[k];
1986 }
1987 }
1988 if self.amplifier.is_some() {
1989 let at = self.turn_at();
1990 s[at + 1] = vel[3];
1991 }
1992 }
1993 fn motor_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
1994 let (rotor, speed) = self.rotors(s);
1995 pos[..4].copy_from_slice(&rotor);
1996 vel[..4].copy_from_slice(&speed);
1997 }
1998
1999 fn feedforward_torque(&self, pos: &[f64], acc: &[f64], out: &mut [f64]) {
2002 let x = self.coordinates(pos);
2003 let t = self.legs.inverse(x).unwrap_or([f64::NAN; 4]);
2004 let j = self.legs.jacobian(t, x).unwrap_or([[f64::NAN; 4]; 4]);
2005 let (mass, _, gravity) = self.load_with(t, x, j, [0.0; 4], self.carried(), self.tool_inertia());
2006 let arm_acc = solve4(&j, self.coordinates(acc)).unwrap_or([f64::NAN; 4]);
2007 let at_arm = mul4(&mass, arm_acc);
2008 for k in 0..4 {
2009 let joint = &self.joints[k];
2010 out[k] = (at_arm[k] - gravity[k]) / joint.ratio() + joint.rotor_inertia * joint.ratio() * arm_acc[k];
2011 }
2012 }
2013
2014 fn feedforward_torque_moving(&self, pos: &[f64], vel: &[f64], acc: &[f64], out: &mut [f64]) {
2017 let x = self.coordinates(pos);
2018 let t = self.legs.inverse(x).unwrap_or([f64::NAN; 4]);
2019 let j = self.legs.jacobian(t, x).unwrap_or([[f64::NAN; 4]; 4]);
2020 let (xv, xa) = (self.coordinates(vel), self.coordinates(acc));
2021 let w = solve4(&j, xv).unwrap_or([f64::NAN; 4]);
2022 let bend = self.legs.velocity_term(t, x, w, xv).unwrap_or([f64::NAN; 4]);
2023 let arm_acc = solve4(&j, std::array::from_fn(|i| xa[i] - bend[i])).unwrap_or([f64::NAN; 4]);
2024 let (mass, velocity, gravity) = self.load_with(t, x, j, w, self.carried(), self.tool_inertia());
2025 let at_arm = mul4(&mass, arm_acc);
2026 for k in 0..4 {
2027 let joint = &self.joints[k];
2028 out[k] = (at_arm[k] + velocity[k] - gravity[k]) / joint.ratio()
2029 + joint.rotor_inertia * joint.ratio() * arm_acc[k];
2030 }
2031 }
2032
2033 fn steady_friction(&self, pos: &[f64], vel: &[f64], out: &mut [f64]) {
2039 let x = self.coordinates(pos);
2040 let t = self.legs.inverse(x).unwrap_or([f64::NAN; 4]);
2041 let j = self.legs.jacobian(t, x).unwrap_or([[f64::NAN; 4]; 4]);
2042 let w = solve4(&j, self.coordinates(vel)).unwrap_or([f64::NAN; 4]);
2043 let gravity = self.load_with(t, x, j, [0.0; 4], self.carried(), self.tool_inertia()).2;
2044 for k in 0..4 {
2045 let joint = &self.joints[k];
2046 let at_arm = joint.friction.torque(w[k]);
2047 let loss = joint.gearbox.loss_factor(at_arm - gravity[k], w[k]);
2048 out[k] = joint.shaft.torque(joint.ratio() * w[k]) + at_arm / (joint.ratio() * loss);
2049 }
2050 }
2051
2052 fn energy(&self, s: &[f64]) -> f64 {
2053 self.energy_parts(s).iter().sum()
2054 }
2055
2056 fn adopt_state(&self, old: &dyn Machine, old_state: &[f64]) -> Vec<f64> {
2063 let (mut pos, mut vel, mut before, mut after) = ([0.0; 4], [0.0; 4], [0.0; 4], [0.0; 4]);
2064 old.tool_state(old_state, &mut pos, &mut vel);
2065 old.inverse(&pos, &mut before);
2066 self.inverse(&pos, &mut after);
2067 let same = old_state.len() == self.state_len();
2068 if same && before == after {
2069 return old_state.to_vec();
2070 }
2071 let (mut slide, mut slide_vel) = (pos, vel);
2073 if same && self.amplifier.is_some() {
2074 (slide[3], slide_vel[3]) = self.slide_of(old_state, &self.pose_at(old_state));
2075 old.inverse(&slide, &mut before);
2076 self.inverse(&slide, &mut after);
2077 }
2078 let mut state = Vec::new();
2079 self.equilibrium(&slide, &mut state, &mut [0.0; 4]);
2080 self.set_tool_velocity(&mut state, &slide_vel);
2081 if same && self.amplifier.is_some() {
2082 let at = self.turn_at();
2083 (state[at], state[at + 1]) = (pos[3], vel[3]);
2084 }
2085 if same && self.elastic {
2086 let (mut rotor, mut speed) = ([0.0; 4], [0.0; 4]);
2087 old.motor_state(old_state, &mut rotor, &mut speed);
2088 for k in 0..4 {
2089 state[8 + k] = after[k] + rotor[k] - before[k];
2090 }
2091 }
2092 state
2093 }
2094
2095 fn set_payload_attached(&mut self, attached: bool) {
2096 self.payload_attached = attached;
2097 }
2098 fn set_brake_engaged(&mut self, engaged: bool) {
2099 self.brake_engaged = engaged;
2100 }
2101 fn substeps_wanted(&self, s: &[f64], _torque: &[f64], dt: f64, _substeps: u32) -> u32 {
2103 let (t, w) = self.arms(s);
2104 (0..t.len()).map(|k| self.joints[k].stop_substeps(t[k], w[k], dt)).max().unwrap_or(1)
2105 }
2106 fn set_tool_force(&mut self, force: &[f64]) -> bool {
2110 self.push = [force[0], force[1], force[2], force[3]];
2111 true
2112 }
2113
2114 fn after_step(&mut self, s: &mut [f64], _dt: f64) {
2116 if self.elastic {
2117 for k in 0..4 {
2118 self.joints[k].gearbox.commit(s[8 + k], s[k]);
2119 }
2120 }
2121 }
2122
2123 fn set_part_temperatures(&mut self, rises: &[f64]) {
2125 let Some(law) = &self.thermal else { return };
2126 if self.joints[0].gearbox.is_coupling() {
2127 return;
2128 }
2129 for (joint, rise) in self.joints.iter_mut().zip(rises) {
2130 joint.gearbox.efficiency = law.gearbox_efficiency(*rise);
2131 }
2132 }
2133
2134 fn setpoint_slack(&self) -> f64 {
2136 self.rest_slack
2137 }
2138
2139 fn unreachable(&self, tool: &[f64], slack: f64) -> Option<&'static str> {
2140 if tool.len() != 4 {
2141 return Some("error-target-out-of-range");
2142 }
2143 if !self.in_envelope(tool, slack) {
2144 return Some("error-delta-outside-envelope");
2145 }
2146 let x = self.coordinates(tool);
2147 let Some(t) = self.legs.inverse(x) else { return Some("error-delta-out-of-reach") };
2148 let (min, max) = self.joints[0].range;
2149 if t.iter().any(|a| *a < min || *a > max) {
2150 return Some("error-delta-joint-stop");
2151 }
2152 match self.legs.jacobian(t, x) {
2153 Some(j) if condition_number(&j) <= self.max_condition => None,
2154 _ => Some("error-delta-singularity"),
2155 }
2156 }
2157
2158 fn condition(&self, tool: &[f64]) -> Option<f64> {
2161 let x = self.coordinates(tool);
2162 let j = self.legs.inverse(x).and_then(|t| self.legs.jacobian(t, x));
2163 Some(j.map_or(f64::INFINITY, |j| condition_number(&j)))
2164 }
2165
2166 fn signal_infos(&self) -> Vec<SignalInfo> {
2167 let mut out = Vec::new();
2168 for (k, motor) in self.motors.iter().enumerate() {
2169 out.push(SignalInfo::new(format!("arm.{}.angle", motor.id), ARMS[k], "quantity-arm-angle", "rad"));
2170 out.push(SignalInfo::new(
2171 format!("gearbox.{}.output_torque", motor.id),
2172 motor.key,
2173 "quantity-gearbox-torque",
2174 "N m",
2175 ));
2176 }
2177 out.push(SignalInfo::new("kinematics.condition", "group-kinematics", "quantity-condition-number", ""));
2178 out.push(SignalInfo::new("plate.slide", "group-plate", "quantity-plate-slide", "m"));
2179 if self.amplifier.is_some() {
2180 out.push(SignalInfo::new("plate.amplifier_twist", "group-plate", "quantity-amplifier-twist", "rad"));
2181 }
2182 self.effect_infos(&mut out);
2183 out
2184 }
2185
2186 fn base_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
2189 let (t, _) = self.arms(s);
2190 let gear = self.gear_output(s, torque);
2191 for k in 0..4 {
2192 out.extend([t[k], gear[k]]);
2193 }
2194 let (x, j, _) = self.pose_at(s);
2195 out.push(condition_number(&j));
2196 out.push(2.0 * x[3]);
2197 if self.amplifier.is_some() {
2198 out.push(self.twist(s).0);
2199 }
2200 }
2201 fn effect_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
2202 self.view_signals(s, torque, out);
2203 }
2204 fn loss_powers(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
2205 self.loss_signals(&self.losses(s, torque), out);
2206 }
2207
2208 fn friction_contacts(&self) -> Vec<sim_core::FrictionContact> {
2210 (0..4).map(|k| sim_core::FrictionContact { id: JOINT_CONTACTS[k], owner_key: ARMS[k] }).collect()
2211 }
2212 fn friction_rotary(&self, _i: usize) -> bool {
2213 true
2214 }
2215 fn friction_curve(&self, i: usize, speed: f64, _load_scale: f64) -> [f64; 3] {
2216 self.joints.get(i).map_or([0.0; 3], |j| j.friction_split(speed))
2217 }
2218 fn friction_speed_limit(&self, i: usize, motor_speed: &[f64]) -> Option<f64> {
2220 Some(motor_speed.get(i)? / self.joints.get(i)?.ratio())
2221 }
2222
2223 fn thermal_parts(&self) -> Vec<ThermalPart> {
2225 if self.joints[0].gearbox.is_coupling() {
2226 return Vec::new();
2227 }
2228 [
2229 ("gearbox_1", "motor-arm-1"),
2230 ("gearbox_2", "motor-arm-2"),
2231 ("gearbox_3", "motor-arm-3"),
2232 ("gearbox_4", "motor-arm-4"),
2233 ]
2234 .into_iter()
2235 .enumerate()
2236 .map(|(k, (id, owner_key))| ThermalPart {
2237 id,
2238 kind: "gearbox",
2239 owner_key,
2240 scene_part: "gearbox",
2241 scene_index: k,
2242 })
2243 .collect()
2244 }
2245
2246 fn scene(&self, s: &[f64], out: &mut Scene) {
2247 let ((t, _), (y, _)) = (self.elbows(s), self.lateral(s));
2249 let (rotor, rotor_speed) = self.rotors(s);
2250 let (x, ..) = self.pose_moved(t, y);
2251 let (c, _) = self.turn(s);
2252 let p = [x[0], x[1], x[2]];
2253 out.parts.clear();
2254 out.labels.clear();
2255 let grey = [0.62, 0.64, 0.68];
2256 out.parts.push(Part::new(
2257 "base",
2258 Shape::Box { size: [2.4 * self.base_radius, 2.4 * self.base_radius, 0.04] },
2259 [0.0, 0.0, 0.1],
2260 grey,
2261 ));
2262 for k in 0..4 {
2263 let (cos, sin) = self.legs.azimuth[k];
2264 let (shoulder, arm_end) = self.arm(k, t, y);
2265 let at = |r: f64, z: f64| [r * cos, r * sin, z];
2266 out.parts.push(Part::new(
2267 sim_core::scene::MOTOR_PART,
2268 Shape::Box { size: [0.1, 0.1, 0.14] },
2269 at(self.base_radius, 0.17),
2270 [0.9, 0.45, 0.1],
2271 ));
2272 out.parts.push(Part::new(
2273 "gearbox",
2274 Shape::Box { size: [0.1, 0.1, 0.07] },
2275 at(self.base_radius, 0.055),
2276 [0.25, 0.25, 0.28],
2277 ));
2278 out.parts.push(
2279 Part::new(
2280 "rotor-bar",
2281 Shape::Box { size: [0.08, 0.004, 0.012] },
2282 at(self.base_radius, 0.245),
2283 [0.1, 0.1, 0.1],
2284 )
2285 .turned(rotor[k]),
2286 );
2287 out.parts.push(Part::new(
2288 "arm",
2289 Shape::Segment { to: arm_end, width: ARM_WIDTH },
2290 shoulder,
2291 [0.2, 0.22, 0.26],
2292 ));
2293 for (from, to) in self.legs.rods_moved(k, t[k], y[k], x, self.plate_radius, self.rod_spacing) {
2295 out.parts.push(Part::new("forearm", Shape::Segment { to, width: ROD_WIDTH }, from, [0.15, 0.15, 0.15]));
2296 }
2297 out.labels.push(Label {
2298 pos: at(self.base_radius, 0.32),
2299 owner_key: self.motors[k].key,
2300 value: rotor_speed[k] * 60.0 / std::f64::consts::TAU,
2301 unit_key: "unit-rpm",
2302 decimals: 0,
2303 });
2304 }
2305 for (from, to) in self.plate_bars(x) {
2306 out.parts.push(Part::new("plate-part", Shape::Segment { to, width: PLATE_WIDTH }, from, [0.55, 0.55, 0.6]));
2307 }
2308 out.parts.extend(self.on_carriage(p));
2309 let (from, to) = self.tool_bar(p, c);
2311 out.parts.push(Part::new("tool", Shape::Segment { to, width: TOOL_BAR_WIDTH }, from, [0.85, 0.75, 0.2]));
2312 out.labels.push(Label {
2313 pos: [p[0], p[1], p[2] - 0.2],
2314 owner_key: "axis-z",
2315 value: p[2],
2316 unit_key: "unit-m",
2317 decimals: 3,
2318 });
2319 }
2320
2321 fn scene_point(&self, tool_pose: &[f64]) -> Option<[f64; 3]> {
2323 Some([tool_pose[0], tool_pose[1], tool_pose[2]])
2324 }
2325
2326 fn collision_bodies(&self, s: &[f64]) -> Vec<sim_core::Aabb> {
2328 let (x, ..) = self.pose_at(s);
2329 sim_core::scene::scene_boxes(&self.on_carriage([x[0], x[1], x[2]]), &["carriage", "payload"])
2330 }
2331
2332 fn collision_capsules(&self, s: &[f64]) -> Vec<sim_core::Capsule> {
2336 let ((t, _), (y, _)) = (self.elbows(s), self.lateral(s));
2337 let (x, ..) = self.pose_moved(t, y);
2338 let capsule = |(from, to): (V3, V3), width: f64| sim_core::Capsule { from, to, radius: width / 2.0 };
2339 let mut out: Vec<_> = self.plate_bars(x).into_iter().map(|bar| capsule(bar, PLATE_WIDTH)).collect();
2340 for k in 0..4 {
2341 out.extend(
2342 self.legs
2343 .rods_moved(k, t[k], y[k], x, self.plate_radius, self.rod_spacing)
2344 .map(|rod| capsule(rod, ROD_WIDTH)),
2345 );
2346 out.push(capsule(self.arm(k, t, y), ARM_WIDTH));
2347 }
2348 out.push(capsule(self.tool_bar([x[0], x[1], x[2]], self.turn(s).0), TOOL_BAR_WIDTH));
2349 out
2350 }
2351
2352 fn trains(&self, tool_pose: &[f64]) -> Vec<Option<sim_core::Train>> {
2355 if !self.elastic {
2356 return Vec::new();
2357 }
2358 let whole = sim_components::control::rigid_inertias(self, tool_pose);
2359 self.joints.iter().zip(whole).map(|(j, whole)| j.train(whole)).collect()
2360 }
2361
2362 fn resonance_hz(&self, tool_pose: &[f64]) -> Option<f64> {
2365 self.modes_at(tool_pose, false).first().map(|mode| mode.0)
2366 }
2367
2368 fn mode_shape(&self, tool_pose: &[f64]) -> Option<(f64, Vec<f64>)> {
2371 let (hz, _, v) = self.modes_at(tool_pose, false).into_iter().next()?;
2372 let x = self.coordinates(tool_pose);
2373 let (j, jy) = self.legs.jacobians(self.legs.inverse(x)?, [0.0; 4], x)?;
2374 let block = |at: usize| -> V4 { std::array::from_fn(|k| v.get(at + k).copied().unwrap_or(0.0)) };
2376 let (root, tip, moves) =
2377 if self.bending.is_some() { (block(0), block(4), block(8)) } else { (block(0), block(0), [0.0; 4]) };
2378 let (a, b) = (mul4(&j, tip), mul4(&jy, moves));
2379 let largest = (0..3).fold(0f64, |m, k| m.max((a[k] + b[k]).abs()));
2380 let mut shape = vec![0.0; self.state_len()];
2381 for k in 0..4 {
2382 shape[k] = root[k] / largest;
2383 }
2384 if self.bending.is_some() {
2385 let at = self.bend_at();
2386 for k in 0..4 {
2387 shape[at + k] = (tip[k] - root[k]) / largest;
2388 shape[at + 8 + k] = moves[k] / largest;
2389 }
2390 }
2391 Some((hz, shape))
2392 }
2393
2394 fn modes(&self, tool_pose: &[f64]) -> Vec<Mode> {
2397 self.modes_with(tool_pose, false)
2398 }
2399
2400 fn modes_small_amplitude(&self, tool_pose: &[f64]) -> Vec<Mode> {
2403 self.modes_with(tool_pose, true)
2404 }
2405}
2406
2407const ROD_WIDTH: f64 = 0.014;
2410const TUBE_CENTROID: f64 = sim_components::beam::STATIC_SHAPE_MOMENT / sim_components::beam::STATIC_SHAPE_PARTICIPATION;
2414const TUBE_MOMENT: f64 = sim_components::beam::STATIC_SHAPE_MOMENT;
2415const ARM_WIDTH: f64 = 0.05;
2416const PLATE_WIDTH: f64 = 0.03;
2417const TOOL_BAR_WIDTH: f64 = 0.015;
2418
2419#[cfg(test)]
2420mod tests;