1use crate::crank::slider_motion;
57use crate::{Table, axis, gravity, machine, master, payload};
58use sim_components::cam::Cam;
59use sim_components::chain::Mechanism;
60use sim_components::joint::RotaryJoint;
61use sim_core::{CamMaster, Config, ConfigError, Label, Machine, Part, RatingCheck, Scene, Shape, SignalInfo};
62use std::f64::consts::{FRAC_PI_2, PI, TAU};
63
64pub struct TogglePress {
65 pub a: f64,
67 pub b: f64,
68 pub r: f64,
69 pub c: f64,
70 pub t0: f64,
72 pub centre: [f64; 2],
74 pub j_crank: f64,
75 pub m_pin: f64,
77 pub m_upper: f64,
79 pub m_knee: f64,
81 pub m_ram: f64,
83 pub payload: f64,
84 pub attached: bool,
85 pub g: f64,
86 pub(crate) process: Option<Table>,
87 pub smoothing: f64,
89 pub frame: Option<f64>,
91 pub crank_torque: f64,
93 pub rated_force: f64,
95 pub cam: Option<(Cam, CamMaster)>,
96 branch: f64,
98 limits: [f64; 3],
100}
101
102#[derive(Debug, Clone, Copy)]
105pub struct Pose {
106 pub pin: [f64; 2],
107 pub knee: [f64; 2],
108 pub phi: [f64; 3],
109 pub x: [f64; 3],
110}
111
112pub fn build(cfg: &Config) -> Result<Box<dyn Machine>, ConfigError> {
113 let joint = RotaryJoint::from_config(cfg)?;
114 let press = TogglePress::from_config(cfg)?;
115 for k in 0..=400 {
118 let q = joint.range.0 + (joint.range.1 - joint.range.0) * k as f64 / 400.0;
119 let p = press.pose(q);
120 if !(p.phi[1].is_finite() && p.x[0].is_finite() && p.phi[1].abs() < 50.0) {
121 return Err(ConfigError::Invalid("crank.radius_m".into()));
122 }
123 }
124 let q = axis(cfg, "crank", "axis-crank", "rad", joint.range)?;
125 machine(cfg, press, (joint, None, "rad"), q, false)
126}
127
128fn dot(u: [f64; 2], v: [f64; 2]) -> f64 {
129 u[0] * v[0] + u[1] * v[1]
130}
131
132impl TogglePress {
133 pub fn from_config(cfg: &Config) -> Result<Self, ConfigError> {
134 let (a, b) = (cfg.positive("toggle.upper_link_m")?, cfg.positive("toggle.lower_link_m")?);
135 let (r, c) = (cfg.positive("crank.radius_m")?, cfg.positive("rod.length_m")?);
136 if b < a {
137 return Err(ConfigError::Invalid("toggle.lower_link_m".into()));
138 }
139 let share = |key: &str| -> Result<f64, ConfigError> {
140 let s = cfg.non_negative(key)?;
141 if s > 1.0 { Err(ConfigError::Invalid(key.into())) } else { Ok(s) }
142 };
143 let (rod_share, knee_share) = (share("rod.crank_end_share")?, share("toggle.lower_link_knee_share")?);
144 let (rod, lower) = (cfg.non_negative("rod.mass_kg")?, cfg.non_negative("toggle.lower_link_mass_kg")?);
145 let t0 = cfg.f64("crank.angle_at_dead_centre_deg")?.to_radians();
146 if !(0.0..PI).contains(&t0) || t0 == 0.0 {
147 return Err(ConfigError::Invalid("crank.angle_at_dead_centre_deg".into()));
148 }
149 let cam = Cam::from_config(cfg, "cam")?;
150 let master = master(cfg, cam.period * cfg.positive("crank.strokes_per_min")? / 60.0, cam.period)?;
151 let crank_torque = (cfg.positive("drive.peak_torque_nm")?
152 * cfg.positive("gearbox.ratio")?
153 * cfg.positive("gearbox.efficiency")?)
154 .min(match cfg.get("ratings.gearbox_max_torque_nm") {
155 Ok(_) => cfg.positive("ratings.gearbox_max_torque_nm")?,
156 Err(_) => f64::INFINITY,
157 });
158 let centre = [c - r * t0.cos(), -a - r * t0.sin()];
159 let mut press = TogglePress {
160 a,
161 b,
162 r,
163 c,
164 t0,
165 centre,
166 j_crank: cfg.positive("crank.inertia_kgm2")?,
167 m_pin: rod_share * rod,
168 m_upper: cfg.non_negative("toggle.upper_link_mass_kg")?,
169 m_knee: (1.0 - rod_share) * rod + knee_share * lower,
170 m_ram: cfg.positive("ram.mass_kg")? + (1.0 - knee_share) * lower,
171 payload: payload(cfg)?,
172 attached: true,
173 g: gravity(cfg)?,
174 process: if cfg.bool("effects.process_force")? {
175 Some(Table::from_config(cfg, "process.distance_m", "process.force_n")?)
176 } else {
177 None
178 },
179 smoothing: cfg.positive("process.smoothing_m_s")?,
180 frame: if cfg.bool("effects.frame_stretch")? {
181 Some(cfg.positive("frame.stretch_stiffness_n_m")?)
182 } else {
183 None
184 },
185 crank_torque,
186 rated_force: cfg.positive("ratings.rated_press_force_n")?,
187 cam: master.map(|m| (cam, m)),
188 branch: 1.0,
189 limits: ["link_max_force_n", "rod_max_force_n", "frame_max_deflection_m"]
190 .map(|k| cfg.f64(&format!("ratings.{k}")).unwrap_or(f64::INFINITY)),
191 };
192 let to_knee = [-centre[0], -a - centre[1]];
194 let (gamma, delta) = (to_knee[1].atan2(to_knee[0]), press.crank_delta(to_knee));
195 let wrap = |x: f64| (x + PI).rem_euclid(TAU) - PI;
196 press.branch = if wrap(gamma + delta - t0).abs() < wrap(gamma - delta - t0).abs() { 1.0 } else { -1.0 };
197 Ok(press)
198 }
199
200 fn crank_delta(&self, to_knee: [f64; 2]) -> f64 {
202 let e = to_knee[0].hypot(to_knee[1]);
203 ((self.r * self.r + e * e - self.c * self.c) / (2.0 * self.r * e)).acos()
204 }
205
206 pub fn pose(&self, q: f64) -> Pose {
208 let (a, r, c) = (self.a, self.r, self.c);
209 let (s, co) = (self.t0 + q).sin_cos();
210 let pin = [self.centre[0] + r * co, self.centre[1] + r * s];
211 let (pq, pqq) = ([-r * s, r * co], [-r * co, -r * s]);
212 let d = pin[0].hypot(pin[1]);
213 let phi = pin[1].atan2(pin[0]) - ((a * a + d * d - c * c) / (2.0 * a * d)).acos() + FRAC_PI_2;
214 let (sp, cp) = phi.sin_cos();
215 let knee = [a * sp, -a * cp];
216 let (kp, kpp) = ([a * cp, a * sp], [-a * sp, a * cp]);
217 let dk = [knee[0] - pin[0], knee[1] - pin[1]];
218 let den = dot(dk, kp);
219 let phi1 = dot(dk, pq) / den;
220 let e = [kp[0] * phi1 - pq[0], kp[1] * phi1 - pq[1]];
221 let phi2 = -(dot(e, e) + dot(dk, [kpp[0] * phi1 * phi1 - pqq[0], kpp[1] * phi1 * phi1 - pqq[1]])) / den;
222 let [x, xp, xpp] = slider_motion(a, self.b, phi);
223 Pose { pin, knee, phi: [phi, phi1, phi2], x: [x, xp * phi1, xpp * phi1 * phi1 + xp * phi2] }
224 }
225
226 pub fn crank_angle(&self, distance: f64, before: bool) -> Option<f64> {
230 let (a, b) = (self.a, self.b);
231 let x = a + b - distance;
232 let cos = (a * a + x * x - b * b) / (2.0 * a * x);
233 if !(distance >= 0.0 && x > b - a && cos.abs() <= 1.0 + 1e-12) {
234 return None;
235 }
236 let cos = cos.clamp(-1.0, 1.0);
237 let phi = if before { cos.acos() } else { -cos.acos() };
238 let knee = [a * phi.sin(), -a * phi.cos()];
239 let to_knee = [knee[0] - self.centre[0], knee[1] - self.centre[1]];
240 let delta = self.crank_delta(to_knee);
241 let t = to_knee[1].atan2(to_knee[0]) + self.branch * delta;
242 delta.is_finite().then(|| (t - self.t0 + PI).rem_euclid(TAU) - PI)
243 }
244
245 fn m_x(&self) -> f64 {
246 self.m_ram + if self.attached { self.payload } else { 0.0 }
247 }
248
249 fn j_knee(&self) -> f64 {
251 (self.m_upper / 3.0 + self.m_knee) * self.a * self.a
252 }
253
254 pub fn inertia(&self, q: f64) -> f64 {
256 let p = self.pose(q);
257 self.j_crank + self.m_pin * self.r * self.r + self.j_knee() * p.phi[1] * p.phi[1] + self.m_x() * p.x[1] * p.x[1]
258 }
259
260 pub fn holding_torque(&self, q: f64, force: f64) -> f64 {
262 force * self.pose(q).x[1]
263 }
264
265 pub fn capacity(&self, q: f64) -> f64 {
267 let ratio = self.pose(q).x[1].abs();
268 if ratio * self.rated_force <= self.crank_torque { self.rated_force } else { self.crank_torque / ratio }
269 }
270
271 pub fn press_force_at(&self, d: f64) -> f64 {
274 let Some(table) = &self.process else { return 0.0 };
275 let Some(k) = self.frame else { return table.at(d) };
276 if table.at.len() < 2 {
277 return table.at(d + table.value[0] / k).min(table.value[0]);
278 }
279 for i in 0..table.at.len() - 1 {
280 let (a0, a1, v0, v1) = (table.at[i], table.at[i + 1], table.value[i], table.value[i + 1]);
281 let slope = (v1 - v0) / (a1 - a0);
282 let f = (v0 + slope * (d - a0)) / (1.0 - slope / k);
283 let u = d + f / k;
284 if f >= 0.0 && u >= a0 && u <= a1 {
285 return f;
286 }
287 }
288 0.0
289 }
290
291 pub fn press_force(&self, q: f64, speed: f64) -> (f64, f64) {
294 if self.process.is_none() {
295 return (0.0, 0.0);
296 }
297 let p = self.pose(q);
298 let share = (1.0 + p.x[1] * speed / self.smoothing).clamp(0.0, 1.0);
299 let force = self.press_force_at(self.a + self.b - p.x[0]) * share;
300 (force, self.frame.map_or(0.0, |k| force / k))
301 }
302
303 pub fn link_forces(&self, q: f64, speed: f64, acc: f64) -> [f64; 3] {
308 let (a, b) = (self.a, self.b);
309 let p = self.pose(q);
310 let (force, _) = self.press_force(q, speed);
311 let ram_acc = p.x[2] * speed * speed + p.x[1] * acc;
312 let (sp, cp) = p.phi[0].sin_cos();
313 let w = p.x[0] - a * cp;
314 let lower = (self.m_x() * (ram_acc - self.g) + force) * b / w;
315 let (phi_v, phi_a) = (p.phi[1] * speed, p.phi[2] * speed * speed + p.phi[1] * acc);
316 let across = (-self.m_upper * self.g * a * sp / 2.0 - self.m_upper * a * a / 3.0 * phi_a) / a;
317 let knee_acc = [a * cp * phi_a - a * sp * phi_v * phi_v, a * sp * phi_a + a * cp * phi_v * phi_v];
318 let (ua, na) = ([sp, -cp], [cp, sp]);
319 let ub = [-a * sp / b, -w / b];
320 let ur = [(p.knee[0] - p.pin[0]) / self.c, (p.knee[1] - p.pin[1]) / self.c];
321 let rhs: Vec<f64> = (0..2)
322 .map(|k| self.m_knee * (knee_acc[k] + if k == 1 { self.g } else { 0.0 }) - across * na[k] + lower * ub[k])
323 .collect();
324 let det = ua[0] * ur[1] - ua[1] * ur[0];
325 let upper = (rhs[0] * ur[1] - rhs[1] * ur[0]) / det;
326 let rod = (ua[0] * rhs[1] - ua[1] * rhs[0]) / det;
327 [upper, lower, rod]
328 }
329}
330
331impl Mechanism for TogglePress {
332 fn frame_momentum(&self, q: &[f64], qd: &[f64], rotor_spin: &[f64]) -> Option<sim_core::FrameMomentum> {
336 use sim_components::base::{add_point, add_spin};
337 let (p, w) = (self.pose(q[0]), qd[0]);
338 let at = |v: [f64; 2]| [v[0], 0.0, v[1]];
339 let (force, _) = self.press_force(q[0], w);
340 let ram = -p.x[0];
341 let mut f = sim_core::FrameMomentum {
342 gravity: [0.0, 0.0, -self.g],
343 external: [0.0, 0.0, force],
344 external_at: [0.0, 0.0, ram],
345 ..Default::default()
346 };
347 let (s, c) = (self.t0 + q[0]).sin_cos();
348 add_point(&mut f, self.m_pin, at(p.pin), [-self.r * s * w, 0.0, self.r * c * w]);
349 let phi_v = p.phi[1] * w;
350 let knee_v = [self.a * p.phi[0].cos() * phi_v, 0.0, self.a * p.phi[0].sin() * phi_v];
351 add_point(&mut f, self.m_knee, at(p.knee), knee_v);
352 add_point(&mut f, self.m_upper, at([p.knee[0] / 2.0, p.knee[1] / 2.0]), knee_v.map(|v| v / 2.0));
353 add_spin(&mut f, [0.0, -1.0, 0.0], self.m_upper * self.a * self.a / 12.0, phi_v);
354 add_point(&mut f, self.m_x(), [0.0, 0.0, ram], [0.0, 0.0, -p.x[1] * w]);
355 add_spin(&mut f, [0.0, -1.0, 0.0], self.j_crank, w);
356 f.angular[1] -= rotor_spin[0];
357 Some(f)
358 }
359 fn dynamics(&self, q: &[f64], qd: &[f64], mass: &mut [f64], bias: &mut [f64]) {
360 let p = self.pose(q[0]);
361 mass[0] = self.inertia(q[0]);
362 let gravity = self.g
363 * (-self.m_x() * p.x[1]
364 + (self.m_knee + self.m_upper / 2.0) * self.a * p.phi[0].sin() * p.phi[1]
365 + self.m_pin * self.r * (self.t0 + q[0]).cos());
366 bias[0] = (self.j_knee() * p.phi[1] * p.phi[2] + self.m_x() * p.x[1] * p.x[2]) * qd[0] * qd[0] + gravity;
367 }
368 fn potential(&self, q: &[f64]) -> f64 {
369 let p = self.pose(q[0]);
370 self.g
371 * (self.m_pin * p.pin[1]
372 - (self.m_knee + self.m_upper / 2.0) * self.a * p.phi[0].cos()
373 - self.m_x() * p.x[0])
374 }
375 fn set_payload_attached(&mut self, attached: bool) {
376 self.attached = attached;
377 }
378 fn tool_is_joints(&self) -> bool {
380 false
381 }
382 fn has_process(&self) -> bool {
383 self.process.is_some()
384 }
385 fn process_torque(&self, q: &[f64], qd: &[f64], out: &mut [f64]) {
386 out[0] -= self.press_force(q[0], qd[0]).0 * self.pose(q[0]).x[1];
387 }
388 fn cam(&self) -> Option<CamMaster> {
389 self.cam.as_ref().map(|(_, m)| *m)
390 }
391 fn cam_at(&self, master: f64, out: &mut [[f64; 4]]) {
392 if let Some((cam, _)) = &self.cam {
393 out[0] = cam.at(master);
394 }
395 }
396 fn cam_curve(&self) -> Option<sim_core::CamCurve> {
397 let cam = self.cam.as_ref()?.0.clone();
398 Some(std::sync::Arc::new(move |master, out: &mut [[f64; 4]]| out[0] = cam.at(master)))
399 }
400
401 fn signal_infos(&self) -> Vec<SignalInfo> {
402 [
403 ("ram.height", "group-ram", "quantity-height-above-bdc", "m"),
404 ("ram.speed", "group-ram", "quantity-speed", "m/s"),
405 ("ram.acceleration", "group-ram", "quantity-acceleration", "m/s²"),
406 ("toggle.ratio", "group-toggle", "quantity-transmission-ratio", "m/rad"),
407 ("press.force", "group-process", "quantity-process-force", "N"),
408 ("press.capacity", "group-process", "quantity-force-capacity", "N"),
409 ("press.capacity_use", "group-process", "quantity-capacity-use", ""),
410 ("frame.deflection", "group-frame", "quantity-frame-deflection", "m"),
411 ("toggle.upper_link_force", "group-upper-link", "quantity-link-force", "N"),
412 ("toggle.lower_link_force", "group-lower-link", "quantity-link-force", "N"),
413 ("rod.force", "group-rod", "quantity-rod-force", "N"),
414 ("crank.inertia", "group-crank", "quantity-reflected-inertia", "kg m²"),
415 ]
416 .into_iter()
417 .map(|(id, owner, quantity, unit)| SignalInfo::new(id, owner, quantity, unit))
418 .collect()
419 }
420 fn signals(&self, q: &[f64], qd: &[f64], qdd: &[f64], force: &[f64], out: &mut Vec<f64>) {
422 self.signals_with_jerk(q, qd, qdd, &[0.0], force, out);
423 }
424 fn reads_jerk(&self) -> bool {
427 self.process.is_some() && self.frame.is_some()
428 }
429 fn signals_with_jerk(&self, q: &[f64], qd: &[f64], qdd: &[f64], qddd: &[f64], _force: &[f64], out: &mut Vec<f64>) {
430 let p = self.pose(q[0]);
431 let (force, stretch) = self.press_force(q[0], qd[0]);
432 let capacity = self.capacity(q[0]);
433 let [upper, lower, rod] = self.link_forces(q[0], qd[0], qdd[0]);
434 let (h, at) = (1e-7, |q: f64, w: f64| self.press_force(q, w).1);
436 let (q, w, a) = (q[0], qd[0], qdd[0]);
437 let stretch_rate =
438 (at(q + h, w) - at(q - h, w)) / (2.0 * h) * w + (at(q, w + h) - at(q, w - h)) / (2.0 * h) * a;
439 let (k, s) = (1e-5, at(q, w));
442 let stretch_acc = (at(q + k, w) - 2.0 * s + at(q - k, w)) / (k * k) * w * w
443 + (at(q + k, w + k) - at(q + k, w - k) - at(q - k, w + k) + at(q - k, w - k)) / (2.0 * k * k) * w * a
444 + (at(q, w + k) - 2.0 * s + at(q, w - k)) / (k * k) * a * a
445 + (at(q + h, w) - at(q - h, w)) / (2.0 * h) * a
446 + (at(q, w + h) - at(q, w - h)) / (2.0 * h) * qddd[0];
447 out.extend([
448 self.a + self.b - p.x[0] + stretch,
449 -p.x[1] * w + stretch_rate,
451 -(p.x[2] * w * w + p.x[1] * a) + stretch_acc,
452 p.x[1],
453 force,
454 capacity,
455 force / capacity,
456 stretch,
457 upper,
458 lower,
459 rod,
460 self.inertia(q),
461 ]);
462 }
463 fn rating_checks(&self) -> Vec<RatingCheck> {
464 let [link, rod, frame] = self.limits;
465 [
466 ("press-capacity", "press.capacity_use", 1.0),
467 ("upper-link-force", "toggle.upper_link_force", link),
468 ("lower-link-force", "toggle.lower_link_force", link),
469 ("rod-force", "rod.force", rod),
470 ("frame-deflection", "frame.deflection", frame),
471 ]
472 .into_iter()
473 .filter(|(_, _, limit)| limit.is_finite())
474 .map(|(check, signal, limit)| RatingCheck { check, signal: signal.into(), motor: None, limit, life: false })
475 .collect()
476 }
477
478 fn collision_parts(&self) -> &'static [&'static str] {
479 &["ram", "payload"]
480 }
481
482 fn scene(&self, q: &[f64], rotors: &[f64], rotor_speeds: &[f64], out: &mut Scene) {
485 let (a, b, r) = (self.a, self.b, self.r);
486 let p = self.pose(q[0]);
487 let (_, stretch) = self.press_force(q[0], 0.0);
488 let at = |v: [f64; 2]| [v[0], 0.0, v[1]];
489 let ram = -(p.x[0] - stretch);
490 let grey = [0.62, 0.64, 0.68];
491 let bottom = -(a + b) - 0.12;
492 out.parts.push(Part::new("crown", Shape::Box { size: [0.3, 0.12, 0.05] }, [0.0, 0.0, 0.04], grey));
493 out.parts.push(Part::new("bed", Shape::Box { size: [0.3, 0.12, 0.05] }, [0.0, 0.0, bottom], grey));
494 out.parts.push(Part::new(
495 "column",
496 Shape::Segment { to: [-0.17, 0.0, bottom], width: 0.04 },
497 [-0.17, 0.0, 0.04],
498 grey,
499 ));
500 out.parts.push(Part::new(
501 "upper-link",
502 Shape::Segment { to: at(p.knee), width: 0.03 },
503 [0.0; 3],
504 [0.75, 0.75, 0.78],
505 ));
506 out.parts.push(Part::new(
507 "lower-link",
508 Shape::Segment { to: [0.0, 0.0, ram], width: 0.03 },
509 at(p.knee),
510 [0.75, 0.75, 0.78],
511 ));
512 out.parts.push(Part::new("rod", Shape::Segment { to: at(p.knee), width: 0.025 }, at(p.pin), [0.6, 0.6, 0.64]));
513 let centre = at(self.centre);
514 out.parts.push(Part::new(
515 "crank",
516 Shape::Cylinder { radius: 1.25 * r, length: 0.03 },
517 centre,
518 [0.45, 0.47, 0.5],
519 ));
520 out.parts.push(
521 Part::new(
522 "crank-arm",
523 Shape::Box { size: [r, 0.004, 0.2 * r] },
524 [(centre[0] + p.pin[0]) / 2.0, -0.02, (centre[2] + p.pin[1]) / 2.0],
525 [0.1, 0.1, 0.1],
526 )
527 .turned(self.t0 + q[0]),
528 );
529 out.parts.push(Part::new(
530 "ram",
531 Shape::Box { size: [0.12, 0.1, 0.06] },
532 [0.0, 0.0, ram - 0.03],
533 [0.2, 0.22, 0.26],
534 ));
535 if self.attached && self.payload > 0.0 {
536 out.parts.push(Part::new(
537 "payload",
538 Shape::Box { size: [0.08, 0.08, 0.04] },
539 [0.0, 0.0, ram - 0.08],
540 [0.2, 0.7, 0.3],
541 ));
542 }
543 out.parts.push(Part::new(
544 sim_core::scene::MOTOR_PART,
545 Shape::Cylinder { radius: 0.05, length: 0.12 },
546 [centre[0], 0.12, centre[2]],
547 [0.9, 0.45, 0.1],
548 ));
549 out.parts.push(Part::new(
550 "gearbox",
551 Shape::Box { size: [0.1, 0.06, 0.1] },
552 [centre[0], 0.06, centre[2]],
553 [0.25, 0.25, 0.28],
554 ));
555 out.parts.push(
556 Part::new(
557 "rotor-bar",
558 Shape::Box { size: [0.07, 0.004, 0.012] },
559 [centre[0], 0.19, centre[2]],
560 [0.1, 0.1, 0.1],
561 )
562 .turned(rotors[0]),
563 );
564 out.labels.push(Label {
565 pos: [centre[0], 0.0, centre[2] + 1.25 * r + 0.08],
566 owner_key: "motor-joint-1",
567 value: rotor_speeds[0] * 60.0 / TAU,
568 unit_key: "unit-rpm",
569 decimals: 0,
570 });
571 out.labels.push(Label {
572 pos: [0.15, 0.0, ram],
573 owner_key: "group-ram",
574 value: a + b + ram,
575 unit_key: "unit-m",
576 decimals: 5,
577 });
578 }
579 fn scene_point(&self, tool: &[f64]) -> Option<[f64; 3]> {
580 Some([0.0, 0.0, -self.pose(tool[0]).x[0]])
581 }
582}