Skip to main content

machine_crank_cam/
disc.rs

1//! A disc cam: a cam disc turned by the motor through its gearbox, and a roller follower on a straight slide above it,
2//! held on the disc by a return spring and its weight, as in packaging, assembly and textile machines where a servo
3//! turns the disc instead of a line shaft. The joint is the disc's angle theta (rad). The follower's lift s(theta) is
4//! the disc's lift law, segments of VDI 2143 laws over the disc's angle (`[[disc.segment]]`, `sim_components::cam`)
5//! over one turn, back where it began.
6//!
7//! The follower's axis is offset by e (`follower.offset_m`) from the disc's centre; its roller of radius r_r touches
8//! the disc, whose base circle has radius r_b: the roller's centre runs on the pitch curve, s0 + s above the centre with
9//! s0 = sqrt((r_b + r_r)^2 - e^2). Its pressure angle, between the follower's axis and the common normal at the
10//! contact:
11//!
12//!   tan(phi) = (s' - e) / (s0 + s),    s' = ds / dtheta,
13//!
14//! for a disc turning so that the follower rises with theta (a positive offset lowers the angle on the rise).
15//!
16//! The follower (mass m with the tool on it, `effects.payload`) is pressed down by its spring, F0 + k s
17//! (`follower.spring_preload_n`, `spring_n_m`), and its weight m g: the contact force along the normal is
18//! N = (m s'' + F0 + k s + m g) / cos(phi), with the follower's acceleration s'' = s''(theta) theta'^2 + s'(theta)
19//! theta''. The disc feels J(theta) = J_disc + m s'^2, the speed term m s' s'' theta'^2 and the spring's and weight's
20//! torque (F0 + k s + m g) s' (the potential F0 s + k s^2 / 2 + m g s). The guide takes N sin(phi) across.
21//!
22//! `effects.follower_lift_off` (off as shipped) lets the follower leave the disc. Its lift is then s_f = s(theta) + g,
23//! g the gap (the roller's centre above the pitch curve; negative: pressed into the disc), a passive joint after the
24//! disc's angle (`Mechanism::passive_joints`, no spring of its own). The follower's speed is v = s' theta' + g'. With
25//! T = J_disc theta'^2 / 2 + m v^2 / 2, the potential V = (F0 + m g) s_f + k s_f^2 / 2 and the guide's friction F_f =
26//! mu tanh(v / 1 mm/s) against v, Lagrange's equations are
27//!
28//!   (J_disc + m s'^2) theta'' + m s' g'' + m s' s'' theta'^2 + (F0 + k s_f + m g + F_f) s' = torque,
29//!   m s' theta'' + m g'' + m s'' theta'^2 + F0 + k s_f + m g + F_f = F_c.
30//!
31//! F_c, the contact force's component along the follower's axis, is the one force that acts on g alone: the disc's
32//! surface moves by s' d theta, the roller by s' d theta + d g, so its virtual work is F_c d g (the disc feels F_c s'
33//! through the mass coupling). The contact is one-sided, with the depth d = -g pressed in: the steel line contact of the
34//! roller (width l, `follower.roller_width_m`) gives d = 3.84e-5 Q^0.9 / l^0.8 (mm, N, mm; Palmgren's roller contact,
35//! Harris and Kotzalas, Rolling Bearing Analysis), Q = (d l^0.8 / 3.84e-5)^(1 / 0.9) and its stiffness dQ/dd = Q / (0.9
36//! d) (4e8 N/m at 160 N and 14 mm), its energy the integral, 9 / 19 d Q. A damper at the share zeta of critical with
37//! that stiffness, c_d = 2 zeta sqrt(Q / (0.9 d) m) (`follower.contact_damping_ratio`), adds c_d d': F_c = max(0, Q +
38//! c_d d'), 0 for d <= 0, so the force on the disc is never negative and, as c_d falls to 0 with d, does not jump at
39//! the touch. The damper's power (F_c - Q) d' (the clamp's included) is the loss `loss_power` books, and F_f v the
40//! guide's, so the energy budget closes through an impact (the damper takes the normal speed out). In free flight (g >
41//! 0) the follower moves under its spring, its weight and the guide's friction alone and meets the disc again where g
42//! reaches 0. At rest it sits pressed in by its load (`Mechanism::passive_rest`, 0.45 um under 160 N). The contact
43//! force along the normal is F_c / cos phi (signal `follower.contact_force`); the gap is the passive joint's signal
44//! `follower.gap` (negative: pressed in), with the flag `follower.off_disc`. The feedforward knows the follower on the
45//! disc (g = 0), as a drive does.
46//!
47//! Signals: the follower's lift, speed and acceleration, the contact force, the pressure angle, the guide's load
48//! across and J(theta) (with the lift-off also the gap and its flag); the contact force and the pressure angle are
49//! judged against `ratings.disc_max_contact_force_n` and `ratings.disc_max_pressure_angle_deg`.
50
51use crate::{axis, gravity, machine, master, payload};
52use sim_components::cam::{Cam, Law, Segment};
53use sim_components::chain::Mechanism;
54use sim_components::joint::RotaryJoint;
55use sim_core::{CamMaster, Config, ConfigError, Label, Machine, Part, RatingCheck, Scene, Shape, SignalInfo};
56use std::f64::consts::TAU;
57
58pub struct DiscCam {
59    /// The lift law over one turn of the disc.
60    pub lift: Cam,
61    pub base_radius: f64,
62    pub roller_radius: f64,
63    pub offset: f64,
64    pub j_disc: f64,
65    /// The follower's own mass, the tool on it (payload) apart.
66    pub m_follower: f64,
67    pub payload: f64,
68    pub attached: bool,
69    pub spring: f64,
70    pub preload: f64,
71    pub g: f64,
72    /// The electronic cam that turns the disc at its speed with cam.run: one turn over one turn of the master.
73    pub cam: Cam,
74    pub master: Option<CamMaster>,
75    /// With effects.follower_lift_off: the roller's width, the contact's damping ratio, the guide's friction.
76    pub lift_off: Option<LiftOff>,
77    limits: [f64; 2],
78}
79
80/// The follower's one-sided contact with the disc and its guide's friction (`effects.follower_lift_off`).
81#[derive(Debug, Clone, Copy, PartialEq)]
82pub struct LiftOff {
83    /// The roller's width, m (`follower.roller_width_m`), for its line contact.
84    pub width: f64,
85    /// The contact damper as a share of critical damping with the follower's mass (`follower.contact_damping_ratio`).
86    pub zeta: f64,
87    /// The guide's Coulomb friction, N (`follower.guide_friction_n`).
88    pub friction: f64,
89}
90
91/// The speed at which the guide's friction reaches its full level (tanh), m/s.
92const GUIDE_SMOOTHING: f64 = 1e-3;
93
94/// Palmgren's line contact of steel, d = PALMGREN Q^0.9 / l^0.8 in m, N, m: 3.84e-5 mm N^-0.9 mm^0.8, times 1e-3 m/mm
95/// over 1000^0.8 for l in m.
96const PALMGREN: f64 = 3.84e-8 / 251.188_643_150_958;
97
98impl LiftOff {
99    /// The depth pressed in under the load `q`, m.
100    pub(crate) fn depth(&self, q: f64) -> f64 {
101        PALMGREN * q.max(0.0).powf(0.9) / self.width.powf(0.8)
102    }
103    /// The load at the depth `d` (0 for d <= 0), N, and the contact's stiffness there, N/m.
104    pub(crate) fn load(&self, d: f64) -> [f64; 2] {
105        if d <= 0.0 {
106            return [0.0; 2];
107        }
108        let q = (d * self.width.powf(0.8) / PALMGREN).powf(1.0 / 0.9);
109        [q, q / (0.9 * d)]
110    }
111}
112
113pub fn build(cfg: &Config) -> Result<Box<dyn Machine>, ConfigError> {
114    let joint = RotaryJoint::from_config(cfg)?;
115    let disc = DiscCam::from_config(cfg)?;
116    let theta = axis(cfg, "disc", "axis-disc", "rad", joint.range)?;
117    machine(cfg, disc, (joint, None, "rad"), theta, true)
118}
119
120impl DiscCam {
121    pub fn from_config(cfg: &Config) -> Result<Self, ConfigError> {
122        let lift = Cam::from_config(cfg, "disc")?;
123        // One turn of the disc, back to the base circle: the law repeats with the disc.
124        if (lift.period - TAU).abs() > 1e-6 || lift.advance.abs() > 1e-9 {
125            return Err(ConfigError::Invalid("disc.segment (one turn, 2 pi rad, rising by 0 in all)".into()));
126        }
127        let (base_radius, roller_radius) =
128            (cfg.positive("disc.base_radius_m")?, cfg.positive("follower.roller_radius_m")?);
129        let offset = cfg.f64("follower.offset_m")?;
130        if offset.abs() >= base_radius + roller_radius {
131            return Err(ConfigError::Invalid("follower.offset_m".into()));
132        }
133        let cam = Cam::from_segments(&[Segment { master: TAU, slave: TAU, law: Law::Linear }])
134            .expect("one turn at constant speed");
135        let master = master(cfg, TAU * cfg.positive("disc.turns_per_min")? / 60.0, cam.period)?;
136        Ok(DiscCam {
137            lift,
138            base_radius,
139            roller_radius,
140            offset,
141            j_disc: cfg.positive("disc.inertia_kgm2")?,
142            m_follower: cfg.positive("follower.mass_kg")?,
143            payload: payload(cfg)?,
144            attached: true,
145            spring: cfg.non_negative("follower.spring_n_m")?,
146            preload: cfg.non_negative("follower.spring_preload_n")?,
147            g: gravity(cfg)?,
148            cam,
149            master,
150            lift_off: if cfg.bool("effects.follower_lift_off")? {
151                Some(LiftOff {
152                    width: cfg.positive("follower.roller_width_m")?,
153                    zeta: cfg.non_negative("follower.contact_damping_ratio")?,
154                    friction: cfg.non_negative("follower.guide_friction_n")?,
155                })
156            } else {
157                None
158            },
159            limits: [
160                cfg.f64("ratings.disc_max_contact_force_n").unwrap_or(f64::INFINITY),
161                cfg.f64("ratings.disc_max_pressure_angle_deg").map_or(f64::INFINITY, f64::to_radians),
162            ],
163        })
164    }
165
166    fn m(&self) -> f64 {
167        self.m_follower + if self.attached { self.payload } else { 0.0 }
168    }
169
170    /// The roller centre's height above the disc's centre on the base circle, s0 = sqrt((r_b + r_r)^2 - e^2).
171    pub fn s0(&self) -> f64 {
172        let pitch = self.base_radius + self.roller_radius;
173        (pitch * pitch - self.offset * self.offset).sqrt()
174    }
175
176    /// The pressure angle at the disc's angle, rad (the module's formula).
177    pub fn pressure_angle(&self, theta: f64) -> f64 {
178        let [s, s1, ..] = self.lift.at(theta);
179        ((s1 - self.offset) / (self.s0() + s)).atan()
180    }
181
182    /// The spring's and the weight's force on the follower, down, N.
183    fn held(&self, s: f64) -> f64 {
184        self.preload + self.spring * s + self.m() * self.g
185    }
186
187    /// The contact force along the normal and the guide's load across, N, at the disc's angle, speed and acceleration.
188    pub fn loads(&self, theta: f64, speed: f64, acc: f64) -> [f64; 2] {
189        let [s, s1, s2, _] = self.lift.at(theta);
190        let phi = self.pressure_angle(theta);
191        let along = self.m() * (s2 * speed * speed + s1 * acc) + self.held(s);
192        let contact = along / phi.cos();
193        [contact, contact * phi.sin()]
194    }
195
196    /// The contact force along the follower's axis F_c and its elastic part Q, N, at the gap g and its rate g' (both 0
197    /// off the disc and without `effects.follower_lift_off`).
198    pub fn contact_force(&self, g: f64, gd: f64) -> [f64; 2] {
199        let Some(lo) = self.lift_off else { return [0.0; 2] };
200        let [q, stiffness] = lo.load(-g);
201        let damper = 2.0 * lo.zeta * (stiffness * self.m()).sqrt() * -gd;
202        [(q + damper).max(0.0), q]
203    }
204
205    /// The guide's friction force against the follower's speed v, N.
206    fn guide_friction(&self, v: f64) -> f64 {
207        self.lift_off.map_or(0.0, |lo| lo.friction * (v / GUIDE_SMOOTHING).tanh())
208    }
209
210    /// The gap, its rate and its acceleration from the joints' q, q' and q''; 0 where they hold the disc's angle only
211    /// (the rigid feedforward's checks).
212    fn gap(q: &[f64], qd: &[f64], qdd: &[f64]) -> [f64; 3] {
213        let at = |x: &[f64]| x.get(1).copied().unwrap_or(0.0);
214        [at(q), at(qd), at(qdd)]
215    }
216}
217
218impl Mechanism for DiscCam {
219    /// In the scene's frame: the follower (with the tool on it) lifting on its axis, the disc and the rotor turning
220    /// about -y. Its spring pushes on the frame on the base: nothing from outside.
221    fn frame_momentum(&self, q: &[f64], qd: &[f64], rotor_spin: &[f64]) -> Option<sim_core::FrameMomentum> {
222        let [s, s1, ..] = self.lift.at(q[0]);
223        let mut f = sim_core::FrameMomentum { gravity: [0.0, 0.0, -self.g], ..Default::default() };
224        let [g, gd, _] = Self::gap(q, qd, &[]);
225        let at = [self.offset, 0.0, self.s0() + s + g];
226        sim_components::base::add_point(&mut f, self.m(), at, [0.0, 0.0, s1 * qd[0] + gd]);
227        sim_components::base::add_spin(&mut f, [0.0, -1.0, 0.0], self.j_disc, qd[0]);
228        f.angular[1] -= rotor_spin[0];
229        Some(f)
230    }
231    fn dynamics(&self, q: &[f64], qd: &[f64], mass: &mut [f64], bias: &mut [f64]) {
232        let [s, s1, s2, _] = self.lift.at(q[0]);
233        let m = self.m();
234        mass[0] = self.j_disc + m * s1 * s1;
235        bias[0] = m * s1 * s2 * qd[0] * qd[0] + self.held(s) * s1;
236        if self.lift_off.is_some() {
237            // With the gap as a joint: the matrix and forces of the doc comment (the disc first).
238            let [g, gd, _] = Self::gap(q, qd, &[]);
239            let push = self.held(s + g) + self.guide_friction(s1 * qd[0] + gd);
240            (mass[1], mass[2], mass[3]) = (m * s1, m * s1, m);
241            bias[0] = m * s1 * s2 * qd[0] * qd[0] + push * s1;
242            bias[1] = m * s2 * qd[0] * qd[0] + push - self.contact_force(g, gd)[0];
243        }
244    }
245    fn potential(&self, q: &[f64]) -> f64 {
246        let g = q.get(1).copied().unwrap_or(0.0);
247        let s = self.lift.at(q[0])[0] + g;
248        let contact = self.lift_off.map_or(0.0, |lo| 9.0 / 19.0 * -g * lo.load(-g)[0]);
249        (self.preload + self.m() * self.g) * s + 0.5 * self.spring * s * s + contact
250    }
251    fn passive_joints(&self) -> Vec<(f64, f64)> {
252        self.lift_off.map(|_| (0.0, 0.0)).into_iter().collect()
253    }
254    fn passive_signals(&self) -> Vec<SignalInfo> {
255        let gap = SignalInfo::new("follower.gap", "group-follower", "quantity-follower-gap", "m");
256        self.lift_off.map(|_| gap).into_iter().collect()
257    }
258    /// The gap joint has no damper of its own: the contact's is `loss_row`'s.
259    fn passive_loss_row(&self) -> Option<(&'static str, &'static str)> {
260        None
261    }
262    /// Pressed in by the spring's and the weight's force: Q(d) = F0 + k (s - d) + m g, by fixed point (k d is some 1e-5
263    /// of Q, so the second step is exact to 1e-10 of d).
264    fn passive_rest(&self, q: &[f64]) -> Vec<f64> {
265        let Some(lo) = self.lift_off else { return Vec::new() };
266        let s = self.lift.at(q[0])[0];
267        let mut d = 0.0;
268        for _ in 0..3 {
269            d = lo.depth(self.held(s - d));
270        }
271        vec![-d]
272    }
273    /// The contact damper's and the guide's friction power, as a row of the loss budget.
274    fn loss_row(&self) -> Option<(&'static str, &'static str)> {
275        self.lift_off.map(|_| ("follower_contact", "group-follower"))
276    }
277    /// (F_c - c_s d) d' with d' = -g', and F_f v: the damper's (the clamp's included) and the guide's, W.
278    fn loss_power(&self, q: &[f64], qd: &[f64]) -> f64 {
279        let [g, gd, _] = Self::gap(q, qd, &[]);
280        let [force, spring] = self.contact_force(g, gd);
281        let v = self.lift.at(q[0])[1] * qd[0] + gd;
282        -(force - spring) * gd + self.guide_friction(v) * v
283    }
284    fn forward(&self, q: &[f64], tool: &mut [f64]) {
285        tool[0] = q[0];
286    }
287    fn set_payload_attached(&mut self, attached: bool) {
288        self.attached = attached;
289    }
290    /// The speed term of J(theta) needs the feedforward's speed terms.
291    fn tool_is_joints(&self) -> bool {
292        false
293    }
294    fn cam(&self) -> Option<CamMaster> {
295        self.master
296    }
297    fn cam_at(&self, master: f64, out: &mut [[f64; 4]]) {
298        out[0] = self.cam.at(master);
299    }
300    fn cam_curve(&self) -> Option<sim_core::CamCurve> {
301        let cam = self.cam.clone();
302        Some(std::sync::Arc::new(move |master, out: &mut [[f64; 4]]| out[0] = cam.at(master)))
303    }
304
305    fn signal_infos(&self) -> Vec<SignalInfo> {
306        [
307            ("follower.lift", "group-follower", "quantity-position", "m"),
308            ("follower.speed", "group-follower", "quantity-speed", "m/s"),
309            ("follower.acceleration", "group-follower", "quantity-acceleration", "m/s²"),
310            ("follower.contact_force", "group-follower", "quantity-contact-force", "N"),
311            ("follower.pressure_angle", "group-follower", "quantity-pressure-angle", "rad"),
312            ("follower.guide_load", "group-follower", "quantity-guide-load", "N"),
313            ("disc.inertia", "group-disc", "quantity-disc-inertia", "kg m²"),
314        ]
315        .into_iter()
316        .chain(self.lift_off.map(|_| ("follower.off_disc", "group-follower", "quantity-follower-off-disc", "")))
317        .map(|(id, owner, quantity, unit)| SignalInfo::new(id, owner, quantity, unit))
318        .collect()
319    }
320    fn signals(&self, q: &[f64], qd: &[f64], qdd: &[f64], _force: &[f64], out: &mut Vec<f64>) {
321        let [s, s1, s2, _] = self.lift.at(q[0]);
322        let [g, gd, gdd] = Self::gap(q, qd, qdd);
323        let [mut contact, mut guide] = self.loads(q[0], qd[0], qdd[0]);
324        if self.lift_off.is_some() {
325            // The contact's force, never below zero; the plan's (no gap in the state) is the rigid one, cut at zero.
326            let (cos, sin) = (self.pressure_angle(q[0]).cos(), self.pressure_angle(q[0]).sin());
327            let along = if q.len() > 1 { self.contact_force(g, gd)[0] } else { (contact * cos).max(0.0) };
328            (contact, guide) = (along / cos, along / cos * sin);
329        }
330        out.extend([
331            s + g,
332            s1 * qd[0] + gd,
333            s2 * qd[0] * qd[0] + s1 * qdd[0] + gdd,
334            contact,
335            self.pressure_angle(q[0]),
336            guide,
337            self.j_disc + self.m() * s1 * s1,
338        ]);
339        if self.lift_off.is_some() {
340            // Off: the contact carries nothing (in flight, or leaving with its damper's pull cut off).
341            out.push(f64::from(contact == 0.0));
342        }
343    }
344    fn rating_checks(&self) -> Vec<RatingCheck> {
345        [("disc-contact-force", "follower.contact_force"), ("disc-pressure-angle", "follower.pressure_angle")]
346            .into_iter()
347            .zip(self.limits)
348            .filter(|(_, limit)| limit.is_finite())
349            .map(|((check, signal), limit)| RatingCheck {
350                check,
351                signal: signal.into(),
352                motor: None,
353                limit,
354                life: false,
355            })
356            .collect()
357    }
358
359    fn collision_parts(&self) -> &'static [&'static str] {
360        &["follower", "payload"]
361    }
362
363    /// Seen from the front: the disc at the origin with a mark that turns with it, the roller on it at the follower's
364    /// offset and lift, the follower above; the motor behind the disc.
365    fn scene(&self, q: &[f64], rotors: &[f64], rotor_speeds: &[f64], out: &mut Scene) {
366        let (r, e) = (self.base_radius, self.offset);
367        let s = self.lift.at(q[0])[0] + q.get(1).copied().unwrap_or(0.0);
368        let roller = [e, 0.0, self.s0() + s];
369        out.parts.push(Part::new("disc", Shape::Cylinder { radius: r, length: 0.02 }, [0.0; 3], [0.45, 0.47, 0.5]));
370        out.parts.push(
371            Part::new("disc-mark", Shape::Box { size: [r, 0.004, 0.1 * r] }, [0.0, -0.012, 0.0], [0.1, 0.1, 0.1])
372                .turned(q[0]),
373        );
374        out.parts.push(Part::new(
375            "roller",
376            Shape::Cylinder { radius: self.roller_radius, length: 0.02 },
377            roller,
378            [0.2, 0.22, 0.26],
379        ));
380        let top = [e, 0.0, roller[2] + 0.15];
381        // A rod as a box, so that it is the follower's collision box (`collision_parts`).
382        out.parts.push(Part::new(
383            "follower",
384            Shape::Box { size: [0.02, 0.02, 0.15] },
385            [e, 0.0, roller[2] + 0.075],
386            [0.75, 0.75, 0.78],
387        ));
388        if self.attached && self.payload > 0.0 {
389            out.parts.push(Part::new("payload", Shape::Box { size: [0.06, 0.06, 0.04] }, top, [0.2, 0.7, 0.3]));
390        }
391        out.parts.push(Part::new(
392            sim_core::scene::MOTOR_PART,
393            Shape::Cylinder { radius: 0.05, length: 0.12 },
394            [0.0, 0.12, 0.0],
395            [0.9, 0.45, 0.1],
396        ));
397        out.parts.push(Part::new(
398            "gearbox",
399            Shape::Box { size: [0.1, 0.06, 0.1] },
400            [0.0, 0.06, 0.0],
401            [0.25, 0.25, 0.28],
402        ));
403        out.parts.push(
404            Part::new("rotor-bar", Shape::Box { size: [0.07, 0.004, 0.012] }, [0.0, 0.19, 0.0], [0.1, 0.1, 0.1])
405                .turned(rotors[0]),
406        );
407        out.labels.push(Label {
408            pos: [0.0, 0.0, r + 0.08],
409            owner_key: "motor-joint-1",
410            value: rotor_speeds[0] * 60.0 / TAU,
411            unit_key: "unit-rpm",
412            decimals: 0,
413        });
414        out.labels.push(Label { pos: top, owner_key: "group-follower", value: s, unit_key: "unit-m", decimals: 4 });
415    }
416    fn scene_point(&self, tool: &[f64]) -> Option<[f64; 3]> {
417        Some([self.offset, 0.0, self.s0() + self.lift.at(tool[0])[0] + 0.15])
418    }
419}