Skip to main content

sim_core/
machine.rs

1//! The machine interface: the one trait a kinematics has to implement.
2
3use crate::{Config, ConfigError, Scene};
4
5/// A tool-side axis. `key` is a translation key, `id` is used in signal ids and config paths.
6#[derive(Debug, Clone)]
7pub struct AxisInfo {
8    pub id: &'static str,
9    pub key: &'static str,
10    pub unit: &'static str,
11    pub min: f64,
12    pub max: f64,
13    pub max_vel: f64,
14    pub max_acc: f64,
15    pub max_jerk: f64,
16}
17
18#[derive(Debug, Clone)]
19pub struct MotorInfo {
20    pub id: &'static str,
21    pub key: &'static str,
22}
23
24/// One scope trace and one PLC variable. The label is built from two translation keys.
25#[derive(Debug, Clone, PartialEq)]
26pub struct SignalInfo {
27    pub id: String,
28    pub owner_key: String,
29    pub quantity_key: String,
30    pub unit: String,
31}
32
33impl SignalInfo {
34    pub fn new(id: impl Into<String>, owner_key: &str, quantity_key: &str, unit: &str) -> Self {
35        Self { id: id.into(), owner_key: owner_key.into(), quantity_key: quantity_key.into(), unit: unit.into() }
36    }
37}
38
39/// The parts of a motor's torque that a machine can report as the signals `motor.<id>.torque_<part>` (N m), with
40/// the quantity keys `quantity-torque-<part>`: what accelerates the moved masses and the rotors, what holds them
41/// against gravity, what friction takes (guides, shafts, gearbox losses, idlers, cable chain), and the rest (belt
42/// elasticity and vibration, ripple, tooth meshing, process force, end stops). The rest is the motor torque less
43/// the other three, so the four add up to the motor torque.
44pub const TORQUE_PARTS: [&str; 4] = ["inertia", "gravity", "friction", "rest"];
45/// Signals whose id starts with this are powers lost (W) in one place of the machine: a friction contact, a damper,
46/// the gearbox. Together with the energy signals they close the machine's energy balance: the work of the motor
47/// torques equals the change of `energy.*` plus the time integral of every `power.*`.
48pub const LOSS_PREFIX: &str = "power.";
49/// The machine's energy split, as the signals `energy.<part>` (J), quantity keys `quantity-energy-<part>`. They add up
50/// to `Machine::energy`.
51pub const ENERGY_PARTS: [&str; 3] = ["kinetic", "potential", "elastic"];
52/// What the signals of a friction contact end with, after its id (`<id>.friction_<part>`): its sliding speed, its
53/// force split into Coulomb, viscous and stiction parts (they add up to the signal `<id>.friction`), and the factor
54/// its levels are scaled with by the load.
55pub const FRICTION_SIGNALS: [&str; 5] = ["speed", "coulomb", "viscous", "stiction", "load_scale"];
56
57/// A friction contact with a Coulomb, viscous and Stribeck model, for the friction view: the id its signals start
58/// with (see `FRICTION_SIGNALS`) and who it belongs to, as a translation key.
59#[derive(Debug, Clone, PartialEq)]
60pub struct FrictionContact {
61    pub id: &'static str,
62    pub owner_key: &'static str,
63}
64
65/// A belt section for the belt view: the id its signals start with, `<id>.tension` (N) and `<id>.stretch` (m, its
66/// length less that of its belt unstretched), who it is as a translation key, and the tension it has at rest.
67#[derive(Debug, Clone, PartialEq)]
68pub struct BeltSection {
69    pub id: &'static str,
70    pub owner_key: &'static str,
71    pub pretension: f64,
72}
73
74/// The kinds of part that can warm with their loss power (`ThermalPart`); each has the config keys
75/// `thermal.<kind>_resistance_k_w`, `thermal.<kind>_time_constant_s` and `thermal.<kind>_max_rise_k`, and the quantity
76/// key `quantity-<kind>-temperature`.
77pub const THERMAL_KINDS: [&str; 3] = ["gearbox", "guide", "belt"];
78/// What the simulation calls the temperature rise of a `ThermalPart` (`temperature.<id>`, K).
79pub const TEMPERATURE_PREFIX: &str = "temperature.";
80
81/// A part that warms with one of the machine's loss powers, `power.<id>`, with effects.part_heating: of which kind
82/// (`THERMAL_KINDS`), who it belongs to as a translation key, and which part of the scene shows it: the
83/// `scene_index`-th part with the id `scene_part`.
84#[derive(Debug, Clone, PartialEq, Default)]
85pub struct ThermalPart {
86    pub id: &'static str,
87    pub kind: &'static str,
88    pub owner_key: &'static str,
89    pub scene_part: &'static str,
90    pub scene_index: usize,
91}
92
93/// A rating of one of the machine's own parts that the cycle is judged against (`Machine::rating_checks`), beside the
94/// checks every machine gets from its motors, drives, gearbox, guides and belts. The analysis follows the signal `signal`
95/// (one of `signal_infos`, among the base signals) over the measured pass.
96#[derive(Debug, Clone, PartialEq)]
97pub struct RatingCheck {
98    /// The verdict's id; its label is the translation key `check-<check>`.
99    pub check: &'static str,
100    pub signal: String,
101    pub motor: Option<usize>,
102    pub limit: f64,
103    /// `false`: the highest |signal| over the pass has to stay at or below `limit`. `true`: the signal is a damage
104    /// rate, the share of the part's life used per hour, and the life in hours, 1 / its mean over the pass (Palmgren
105    /// and Miner), has to reach `limit`; such a check's id ends in "-life" and is one of `analysis::AT_LEAST`.
106    pub life: bool,
107}
108
109/// A motor's elastic drive train as the time-optimal plan allows for it (`Machine::trains`), reduced to two masses on a
110/// spring: the rotor's side and the load's, referred to the motor.
111#[derive(Debug, Clone, Copy, PartialEq)]
112pub struct Train {
113    /// The load's frequency against the motor held, sqrt(k / J_load), Hz.
114    pub hz: f64,
115    /// The load's share of the motor's rigid inertia, J_load / (J_load + J_rotor side).
116    pub load_share: f64,
117}
118
119impl Train {
120    /// From the train's stiffness at the motor with the load held (N m/rad), the inertia on the motor's side of it and
121    /// the motor's whole rigid inertia (kg m^2). `None` for a train with no stiffness to tell or no load beyond it.
122    pub fn of(stiffness: f64, rotor_side: f64, whole: f64) -> Option<Self> {
123        let load = whole - rotor_side;
124        (stiffness > 0.0 && stiffness.is_finite() && load > 0.0 && whole.is_finite())
125            .then(|| Self { hz: (stiffness / load).sqrt() / std::f64::consts::TAU, load_share: load / whole })
126    }
127}
128
129/// A structural mode of a machine at a pose, from `Machine::modes`.
130#[derive(Debug, Clone, Copy, PartialEq)]
131pub struct Mode {
132    /// Its undamped natural frequency, Hz.
133    pub hz: f64,
134    /// Its damping ratio; 0 where the machine tells none.
135    pub damping: f64,
136}
137
138/// What everything that moves on a machine's base does to it, for effects.base_compliance (`Machine::frame_momentum`).
139/// In the frame of the tool pose's x, y and z (m; an axis the machine lacks stands at 0), about its origin. A part whose
140/// mass does not change may leave out what of it does not move (its mass at a joint, the frame's own): the base takes
141/// the load against that at rest at the start pose, so a constant cancels.
142#[derive(Debug, Clone, Copy, Default, PartialEq)]
143pub struct FrameMomentum {
144    /// The sum of m v of the moving parts, N s.
145    pub linear: [f64; 3],
146    /// The sum of r x m v + I w about the origin, N m s, turning rotors, pulleys and links included.
147    pub angular: [f64; 3],
148    /// The moving mass and its first moment, the sum of m r: kg and kg m.
149    pub mass: f64,
150    pub first_moment: [f64; 3],
151    /// Gravity in this frame, m/s^2; zero with effects.gravity off.
152    pub gravity: [f64; 3],
153    /// A force from outside on the moving parts (a process force from a workpiece on the floor), N, and where it
154    /// acts, m.
155    pub external: [f64; 3],
156    pub external_at: [f64; 3],
157}
158
159/// The tool axes a base's motion moves (`Machine::base_shift`): those with these ids, by translation [x, y, z] and by
160/// tilt about [x, y, z].
161pub const BASE_AXES: [[&str; 3]; 2] = [["x", "y", "z"], ["rx", "ry", "rz"]];
162
163/// An electronic cam's curve as `Machine::cam_at` reads it, on its own (`Machine::cam_curve`): each slave at a master
164/// position, as [s, s', s'', s'''].
165pub type CamCurve = std::sync::Arc<dyn Fn(f64, &mut [[f64; 4]]) + Send + Sync>;
166
167/// The master of an electronic cam that a machine runs as its cycle instead of `[[cycle.segment]]` (`Machine::cam`): its
168/// steady speed (its unit per second), its travel per pass of the cycle, and how long it takes from rest to that speed
169/// and back (a sin^2 ramp, `sim_components::cam::master_at`).
170#[derive(Debug, Clone, Copy, PartialEq, serde::Serialize, serde::Deserialize)]
171pub struct CamMaster {
172    pub speed: f64,
173    pub period: f64,
174    pub ramp_s: f64,
175}
176
177pub trait Machine: Send {
178    /// For effects.base_compliance: the momentum, mass and outside force of everything that moves on the base at state
179    /// `state` (see `FrameMomentum`). The base takes the rate of change of the momentum back, and the weight and the
180    /// outside force. `None` where the machine cannot tell; then it cannot stand on a compliant base.
181    fn frame_momentum(&self, _state: &[f64]) -> Option<FrameMomentum> {
182        None
183    }
184    /// For effects.base_compliance: how far the tool pose moves at `tool_pose` when the base moves by `shift`
185    /// (translation [x, y, z] in m and a small tilt [x, y, z] in rad about `pivot`, in the frame of `FrameMomentum`),
186    /// written into `out` (as long as the axes). By default the axes x, y, z take the move of the tool point at the
187    /// pose's x, y, z, u + theta x (r - pivot), and a rotary axis with an id of `BASE_AXES[1]`, or `c` (about z), the
188    /// tilt; a machine whose tool axes are its joints moves nothing.
189    fn base_shift(&self, tool_pose: &[f64], pivot: [f64; 3], shift: &[f64; 6], out: &mut [f64]) {
190        let axes = self.axes();
191        let find = |ids: [&str; 3], k: usize| axes.iter().position(|a| a.id == ids[k]);
192        let r: [f64; 3] = std::array::from_fn(|k| find(BASE_AXES[0], k).map_or(0.0, |i| tool_pose[i]) - pivot[k]);
193        let t = [shift[3], shift[4], shift[5]];
194        let moved = [t[1] * r[2] - t[2] * r[1], t[2] * r[0] - t[0] * r[2], t[0] * r[1] - t[1] * r[0]];
195        out.iter_mut().for_each(|o| *o = 0.0);
196        for k in 0..3 {
197            if let Some(i) = find(BASE_AXES[0], k) {
198                out[i] = shift[k] + moved[k];
199            }
200            if let Some(i) = find(BASE_AXES[1], k).or(if k == 2 { find(["", "", "c"], 2) } else { None }) {
201                out[i] = t[k];
202            }
203        }
204    }
205
206    /// The ratings of the machine's own parts (ball screw, rack, strain wave gear, ...) that its cycle is judged
207    /// against. Empty where it has none beyond the common ones.
208    fn rating_checks(&self) -> Vec<RatingCheck> {
209        Vec::new()
210    }
211
212    fn axes(&self) -> &[AxisInfo];
213    fn motors(&self) -> &[MotorInfo];
214    /// Whether motor `motor` is a linear motor: its angle, speed and torque signals are then m, m/s and N, and the
215    /// "motor-speed" verdict's value is m/s. False by default, a rotary motor.
216    fn motor_linear(&self, _motor: usize) -> bool {
217        false
218    }
219    /// Tool pose to motor shaft angles, and back. Both are pure kinematics.
220    fn inverse(&self, tool: &[f64], motors: &mut [f64]);
221    fn forward(&self, motors: &[f64], tool: &mut [f64]);
222
223    fn state_len(&self) -> usize;
224    /// The state at rest at a tool pose, and the motor torques that hold it there.
225    fn equilibrium(&self, tool: &[f64], state: &mut Vec<f64>, torque: &mut [f64]);
226    fn derivatives(&self, state: &[f64], torque: &[f64], out: &mut [f64]);
227    fn tool_state(&self, state: &[f64], pos: &mut [f64], vel: &mut [f64]);
228    /// What a load-side scale reads: the carriage (the tool) against the frame it is mounted on, so a frame's sway
229    /// and a tool's lean are not in it. By default the tool state, in the room, as `tool_state` reports it.
230    fn scale_state(&self, state: &[f64], pos: &mut [f64], vel: &mut [f64]) {
231        self.tool_state(state, pos, vel);
232    }
233    /// Gives a state at rest (see `equilibrium`) the tool speeds `vel`: everything that moves with the
234    /// tool, motors included, moves along as the kinematics say.
235    fn set_tool_velocity(&self, state: &mut [f64], vel: &[f64]);
236    fn motor_state(&self, state: &[f64], pos: &mut [f64], vel: &mut [f64]);
237    /// Motor torques from the rigid model for a tool pose and acceleration, including gravity.
238    fn feedforward_torque(&self, tool_pos: &[f64], tool_acc: &[f64], out: &mut [f64]);
239    /// `feedforward_torque` with the tool's speed too, for what the speed asks of the motors (the centripetal and
240    /// Coriolis part of the torque): from a kinematics that is not linear, and from a mass matrix that changes with the
241    /// pose (an arm in joint space, whose motor angles are linear in its joints, has them too). The controller uses
242    /// this one; the default leaves the speed out, which is exact only where the motor angles are linear in the tool
243    /// pose and the inertia the motors see does not change with it (a gantry, one linear axis).
244    fn feedforward_torque_moving(&self, tool_pos: &[f64], _tool_vel: &[f64], tool_acc: &[f64], out: &mut [f64]) {
245        self.feedforward_torque(tool_pos, tool_acc, out);
246    }
247    /// The motor torques of the same rigid, loss-free model at motor angles, speeds and accelerations: what fitting a
248    /// trace in the motors' own coordinates needs (`identify::fit_joints`). By default through the tool: its pose by
249    /// `forward`, its speed and acceleration by central differences along the motors' motion over ±0.1 ms, then
250    /// `feedforward_torque_moving`. A machine whose `feedforward_torque_moving` leaves out the speed terms of a
251    /// kinematics that is not linear overrides this.
252    fn rigid_motor_torque(&self, angle: &[f64], speed: &[f64], acc: &[f64], out: &mut [f64]) {
253        let (h, n) = (1e-4, self.axes().len());
254        let at = |s: f64| {
255            let motors: Vec<f64> = (0..angle.len()).map(|k| angle[k] + s * speed[k] + 0.5 * s * s * acc[k]).collect();
256            let mut tool = vec![0.0; n];
257            self.forward(&motors, &mut tool);
258            tool
259        };
260        let (before, pos, after) = (at(-h), at(0.0), at(h));
261        let vel: Vec<f64> = (0..n).map(|i| (after[i] - before[i]) / (2.0 * h)).collect();
262        let tool_acc: Vec<f64> = (0..n).map(|i| (after[i] - 2.0 * pos[i] + before[i]) / (h * h)).collect();
263        self.feedforward_torque_moving(&pos, &vel, &tool_acc, out);
264    }
265    /// Where a trace's row has the load of an elastic drive train, per motor in motor radians: the twist of the train
266    /// that the motor `torque` holds, less what the rotor's own acceleration `acc` takes (the motor's angle less where
267    /// the rigid model puts the motor for the load's pose). Zeros by default: the trains are rigid. For fitting a trace
268    /// (`identify::fit_joints`), with `rigid_split_torque`.
269    fn twist(&self, _torque: &[f64], _acc: &[f64], out: &mut [f64]) {
270        out.fill(0.0);
271    }
272    /// `twist` with the motors at `angle` (motor radians, the trace's): behind a screw whose stiffness follows its nut,
273    /// the train's spring where the nut is, on the shaft's point the rotor has turned to it. By default `twist`, for a
274    /// machine whose trains have one stiffness along the stroke.
275    fn twist_at(&self, _angle: &[f64], torque: &[f64], acc: &[f64], out: &mut [f64]) {
276        self.twist(torque, acc, out)
277    }
278    /// `rigid_motor_torque` with the load at `angle`, `speed`, `acc` (where the rigid model puts the motors for it) and
279    /// the rotors at their own acceleration `rotor_acc`: what an elastic train (`twist`) needs. By default the rigid
280    /// torques at the load's motion, the rotors turning with it.
281    fn rigid_split_torque(&self, angle: &[f64], speed: &[f64], acc: &[f64], _rotor_acc: &[f64], out: &mut [f64]) {
282        self.rigid_motor_torque(angle, speed, acc, out);
283    }
284    /// The tension of each belt section (N, in the order of `belt_sections`) that the loss-free rigid model of
285    /// `feedforward_torque` gives at a tool pose and acceleration: what the belt has to pull on the moved masses (not
286    /// on the pulleys and rotors, which the motors turn), shared out so that the belt keeps its length. Linear in the
287    /// acceleration. Appends nothing where the machine has no belt sections to tell.
288    fn rigid_tensions(&self, _tool_pos: &[f64], _tool_acc: &[f64], _out: &mut Vec<f64>) {}
289    /// `rigid_tensions` with the tool's velocity too, for machines whose carriages accelerate with the speed (a delta's
290    /// rods turn: h'' = J^-1 (p'' - J_x^-1 w)). By default the speed does not matter.
291    fn rigid_tensions_moving(&self, tool_pos: &[f64], tool_vel: &[f64], tool_acc: &[f64], out: &mut Vec<f64>) {
292        let _ = tool_vel;
293        self.rigid_tensions(tool_pos, tool_acc, out)
294    }
295    /// The band [least, most] (N) the time-optimal plan keeps `rigid_tensions` within, where the machine has it from
296    /// its own parts (cables between winches and a platform); `None`: `ratings.belt_min_tension_n` and `belt_max_tension_n`.
297    fn tension_band(&self) -> Option<[f64; 2]> {
298        None
299    }
300    /// The load of each guide that reports `axis.<id>.guide_load` (N, in that order) in the loss-free rigid model at a
301    /// tool pose and acceleration, as [rest, moving] for the load rest + |moving|: `moving` linear in the acceleration
302    /// and zero without. The time-optimal plan keeps it within `ratings.guide_max_load_n`. Appends nothing where the
303    /// machine does not tell.
304    fn rigid_guide_loads(&self, _tool_pos: &[f64], _tool_acc: &[f64], _out: &mut Vec<[f64; 2]>) {}
305    /// The steady friction of the guides (and other sliding contacts the motors drive, not the motors' own shafts and
306    /// gearboxes) as torque at each motor (in the order of `motors`), while the tool at `tool_pos` moves along `tool_dir`
307    /// (its rate per unit of path): [c, b] for c + b v at the speed v along the path, positive where the motor has to
308    /// give positive torque against it. For the time-optimal plan. Appends nothing where the machine does not tell.
309    fn rigid_friction(&self, _tool_pos: &[f64], _tool_dir: &[f64], _out: &mut Vec<[f64; 2]>) {}
310    /// What `rigid_friction`'s c + b v leaves out near a standstill, the Stribeck rise: per motor a [level, speed] for each
311    /// contact it drives, the torque level exp(-(v / speed)^2) more at the speed v along the path (the friction is then
312    /// c + sum level exp(..) + b v; level signed as c, speed in the path's units, above 0). For the time-optimal plan,
313    /// which holds the room for it at the most it takes over the speeds up to v. Appends nothing where the machine has no
314    /// rise (the default).
315    fn rigid_friction_rise(&self, _tool_pos: &[f64], _tool_dir: &[f64], _out: &mut Vec<Vec<[f64; 2]>>) {}
316    /// The friction torque at each motor (N m, in the order of `motors`, into `out`) while the tool at `tool_pos` moves
317    /// steadily at `tool_vel`: every friction of the machine's own model at that speed (guides at their steady sliding
318    /// level, the motor shaft, the gearbox's drag, the joints, idlers, screws, the cable chain), carried to the motor as
319    /// the rigid model carries a load (through the ratios, and the efficiencies where the motor drives). Positive where
320    /// the motor has to give positive torque against it. For the friction feedforward from the machine's model
321    /// (`drive.friction_feedforward_model = "machine"`). Zero by default: a machine that tells no friction.
322    fn steady_friction(&self, _tool_pos: &[f64], _tool_vel: &[f64], out: &mut [f64]) {
323        out.fill(0.0);
324    }
325
326    /// What limits the time-optimal plan among the machine's own parts: per check of `rating_checks` (in its order) the
327    /// value of its signal in the loss-free rigid model at a tool pose, speed and acceleration (a screw's speed, its
328    /// force, a rack's feed force), or NaN where the rigid model does not give it (a life, a sync error). The plan keeps
329    /// each value within its check's limit. Appends nothing where the machine does not tell (no row is planned).
330    fn rigid_checks(&self, _tool_pos: &[f64], _tool_vel: &[f64], _tool_acc: &[f64], _out: &mut Vec<f64>) {}
331    /// Kinetic plus potential energy, for the conservation check.
332    fn energy(&self, state: &[f64]) -> f64;
333    fn set_payload_attached(&mut self, attached: bool);
334    /// The rigid bodies whose inertial parameters a trace can be fitted for (`identify::fit_joints`), by name: the links
335    /// of a URDF chain. None by default.
336    fn links(&self) -> Vec<String> {
337        Vec::new()
338    }
339    /// Changes link `link`'s inertial parameters about its joint's frame, from those it was built with: mass, first
340    /// moment and inertia all times `factor`, then `moment` (kg m, in its frame) added to the first moment with mass
341    /// and inertia about the frame kept. The rigid torques are linear in each, which the fit takes its columns from.
342    /// (1, [0; 3]) restores it. Nothing by default.
343    fn set_link_change(&mut self, _link: usize, _factor: f64, _moment: [f64; 3]) {}
344    /// Told every step whether the cycle dwells at a target, for machines with a process force there.
345    fn set_dwelling(&mut self, _dwelling: bool) {}
346    /// An external force on the contact coordinates (`contact_state`, by default the tool's: one component per axis, N,
347    /// or N m on a rotary axis; the generalised force of each), held until changed: an obstacle's push on the parts
348    /// that can touch it (effects.crash). Returns whether the machine takes it; by default `false` (not supported), and
349    /// the push then acts on the motors through the rigid kinematics. The force's power is not in the machine's loss
350    /// rows: the simulation integrates it as the obstacles' work (the budget's crash row), F . the contact coordinates'
351    /// rates. Machines that take it put its generalised forces into their equations beyond their transmissions, at every
352    /// stage of the integration (`tool_force_on_rates`): the machine files' `ConfigMachine`, the joint machines
353    /// (`chain::JointMachine`) and most machine crates. The default stays where the machine's equations are another's
354    /// that does not take it.
355    fn set_tool_force(&mut self, _force: &[f64]) -> bool {
356        false
357    }
358    /// How many contact coordinates an obstacle's push acts on (`set_tool_force`): by default the tool's axes. A machine
359    /// whose parts that can touch do not move with its tool alone (a load swinging under it, a dancer the web holds)
360    /// gives coordinates of their own.
361    fn contact_axes(&self) -> usize {
362        self.axes().len()
363    }
364    /// The contact coordinates and their rates at state `s`: by default the tool's (`tool_state`). The rates are linear
365    /// in the state's rates.
366    fn contact_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
367        self.tool_state(s, pos, vel)
368    }
369    /// A state from `s` with the contact coordinates at `at`, the parts placed there for the slopes of an obstacle's
370    /// clearance along them: by default the rest at the tool pose `at` (`equilibrium`).
371    fn contact_placed(&self, _s: &[f64], at: &[f64], out: &mut Vec<f64>) {
372        let mut torque = vec![0.0; self.motors().len()];
373        self.equilibrium(at, out, &mut torque);
374    }
375    /// How many times finer still than the simulation's own refinement under a push on the contact coordinates
376    /// (`Sim`'s `PUSH_SUBSTEPS`) a base step with one is to be taken: where the contact's spring holds a coordinate far
377    /// lighter than the load's (a leaning axis pushed through its lever). 1 by default.
378    fn push_substeps(&self) -> u32 {
379        1
380    }
381    /// Told every step whether the drives are disabled, for machines with holding brakes.
382    fn set_brake_engaged(&mut self, _engaged: bool) {}
383    /// How many parts the coming base step `dt` (s), taken in `substeps` sub-steps, is to have each sub-step cut into,
384    /// at least 1, from its start state `s` and the motors' torques: for what changes faster than a sub-step resolves
385    /// (a gearbox's efficiency switch held near zero power at a large torque, `mech::fade_substeps`; a joint's stop met
386    /// within the step, `mech::STOP_SUBSTEPS`). The model is the same; only its integration is finer
387    /// (`integrate::advance_refined`). 1 by default.
388    fn substeps_wanted(&self, _s: &[f64], _torque: &[f64], _dt: f64, _substeps: u32) -> u32 {
389        1
390    }
391    /// Actuators that a valve moves and no drive (pneumatic cylinders): each one's id and the valve command it starts
392    /// with (+1 extend, -1 retract, 0 the closed centre of a 5/3 valve), for a cycle segment's `valves` and `wait`. None
393    /// by default.
394    fn valves(&self) -> Vec<(String, f64)> {
395        Vec::new()
396    }
397    /// Told every step the command of valve `valve` (of `valves`); the valve switches after its own delay.
398    fn set_valve(&mut self, _valve: usize, _command: f64) {}
399    /// Valve `valve`'s end-position sensors, [retracted, extended], each after its delay.
400    fn end_sensors(&self, _valve: usize) -> [bool; 2] {
401        [false; 2]
402    }
403    /// Called after every base step, for what happens at once and not by integration (a belt tooth that jumps):
404    /// the machine may change `state` and must report what that took out of its energy among its loss powers
405    /// over this step of `dt` seconds, so that the energy budget closes.
406    fn after_step(&mut self, _state: &mut [f64], _dt: f64) {}
407    /// What the machine carries from one step to the next outside `state` (the gearboxes' hysteresis anchors that
408    /// `after_step` moves on, a numerical inverse's last solution), as a fixed count of numbers: a snapshot of the
409    /// simulation keeps them and sets them back with `set_memory`. None by default.
410    fn memory(&self) -> Vec<f64> {
411        Vec::new()
412    }
413    /// Sets back what `memory` gave.
414    fn set_memory(&mut self, _memory: &[f64]) {}
415    /// With effects.thermal_feedback: the temperature rise (K) of each part of `thermal_parts`, in that order, for
416    /// the friction and losses that change with it.
417    fn set_part_temperatures(&mut self, _rises: &[f64]) {}
418
419    /// Per motor at a tool pose its elastic drive train (`Train`), for the time-optimal plan to keep back the speed the
420    /// train's twist adds to the motor's: `None`, or no entry, where the train is rigid (no allowance).
421    fn trains(&self, _tool_pose: &[f64]) -> Vec<Option<Train>> {
422        Vec::new()
423    }
424
425    /// The lowest structural resonance at a tool pose, for a controller that sets its input shaper by it.
426    /// `None` where the machine has none to tell.
427    fn resonance_hz(&self, _tool_pose: &[f64]) -> Option<f64> {
428        None
429    }
430    /// The mode `resonance_hz` reports at a tool pose: its frequency in Hz and its shape, a direction in the state
431    /// (as long as it, positions only, rates zero). The equilibrium at that pose plus a small amplitude times the
432    /// shape, drawn with `scene`, shows how the machine moves in that mode; one unit of amplitude moves the tool by
433    /// 1 m along its first axis. `None` where the machine tells no resonance.
434    fn mode_shape(&self, _tool_pose: &[f64]) -> Option<(f64, Vec<f64>)> {
435        None
436    }
437    /// Every structural mode the machine knows at a tool pose, lowest first: for a second input shaper, the resonance
438    /// over an axis's stroke (`sim-cli modes`) and the app's plot of it. By default the one of `resonance_hz`, its
439    /// damping unknown (0).
440    fn modes(&self, tool_pose: &[f64]) -> Vec<Mode> {
441        self.resonance_hz(tool_pose).map(|hz| Mode { hz, damping: 0.0 }).into_iter().collect()
442    }
443    /// The same modes as `modes` for small vibrations: where a joint's gearbox has hysteresis (`gearbox_lost_motion`),
444    /// the stiffness it shows at a reversal is K1 + sigma, not the large-amplitude K1 `modes` uses. A shaper for the
445    /// move's own swing takes `modes` (the twists of the move are far above the hysteresis loop); one for the residual
446    /// ringing below about 1e-4 rad at the joint takes these. By default the same as `modes`.
447    fn modes_small_amplitude(&self, tool_pose: &[f64]) -> Vec<Mode> {
448        self.modes(tool_pose)
449    }
450    /// The modes an input shaper that follows the pose takes beyond the first (`profile.shaper_modes`, the shaping
451    /// optimiser's second shaper), lowest first: by default `modes`. A machine whose `modes` hold modes the shaper does
452    /// not act on (a crane's bounce of the load on its rope) gives the ones it does (the swing, and the hook block's
453    /// upper swing).
454    fn sway_modes(&self, tool_pose: &[f64]) -> Vec<Mode> {
455        self.modes(tool_pose)
456    }
457    /// With effects.belt_wrap: the angle (rad) by which the belt wraps each driven pulley at a tool pose, from the places
458    /// of the pulleys and idlers, in the order of `motors`; NaN for a motor that drives no belt. Empty where the machine
459    /// gives no belt geometry or the effect is off: then `ratings.belt_teeth_in_mesh` stands for the teeth in mesh.
460    fn belt_wraps(&self, _tool_pose: &[f64]) -> Vec<f64> {
461        Vec::new()
462    }
463
464    /// Why a tool pose within the axis ranges cannot be gone to, as a translation key: out of reach of the
465    /// kinematics, outside the working envelope, beyond a joint's stop. `slack` (m) widens the envelope at its
466    /// edges, as it widens the axis ranges for a setpoint at rest. `None` where it can; machines whose workspace is
467    /// the box of their axis ranges keep this default.
468    fn unreachable(&self, _tool_pose: &[f64], _slack: f64) -> Option<&'static str> {
469        None
470    }
471
472    /// Why the payload cannot be picked up with the tool at rest at `tool_pose` (a cycle segment that attaches it), as a
473    /// translation key: the machine's own physical reason (a hook block that would hang inside the payload). `None`
474    /// where it can, by default.
475    fn refuses_pick(&self, _tool_pose: &[f64]) -> Option<&'static str> {
476        None
477    }
478
479    /// The 2-norm condition number of the kinematics' Jacobian at a tool pose, for the workspace map: 1 where the
480    /// motors move the tool equally well in every direction, larger towards a singularity, `f64::INFINITY` out of reach
481    /// of the kinematics (whatever the envelope and the joints' stops say, which `unreachable` tells). `None` for a
482    /// machine that has no map to show: one whose motor angles are a linear function of the tool pose.
483    fn condition(&self, _tool_pose: &[f64]) -> Option<f64> {
484        None
485    }
486
487    /// How far the setpoint of the machine at rest may be from the pose of its tool, m: the setpoint is where the
488    /// motors stand, and what belts and gears give way under the load they hold puts the tool off it. The controller
489    /// takes paths and trajectories that start or run this far beyond the travel range or the envelope. 0.1 mm by
490    /// default (12 and 46 um on the gantry holding its Z axis).
491    fn setpoint_slack(&self) -> f64 {
492        1e-4
493    }
494
495    /// An electronic cam the controller runs as the cycle: the master's motion, `None` for a machine whose cycle is its
496    /// `[[cycle.segment]]`. Each pass is one `period` of the master once it is up to speed; a stop runs it down.
497    fn cam(&self) -> Option<CamMaster> {
498        None
499    }
500    /// With `cam`: each tool axis (the slaves) at the master position `master`, as [s, s', s'', s'''], the rates over
501    /// the master.
502    fn cam_at(&self, _master: f64, _out: &mut [[f64; 4]]) {}
503    /// With `cam`: the curve `cam_at` reads, apart from the machine, so that it still reads the same once the config
504    /// has changed (the input shaper reads the plan of past cycles off it). `None` without a cam.
505    fn cam_curve(&self) -> Option<crate::CamCurve> {
506        None
507    }
508    /// A dual-drive gantry: the two motors that drive its axis side by side, the master first, for the drives'
509    /// synchronisation (`gantry.sync`). `None` without one.
510    fn gantry_motors(&self) -> Option<[usize; 2]> {
511        None
512    }
513
514    /// Signals beyond axis and motor positions, speeds and torques, which every machine gets for free: first those
515    /// of `base_signals`, then those of `effect_signals`.
516    fn signal_infos(&self) -> Vec<SignalInfo>;
517    /// The machine's own signals but those of the effect views; cheap enough to be asked for every step.
518    fn base_signals(&self, state: &[f64], torque: &[f64], out: &mut Vec<f64>);
519    /// The signals of the effect views (`TORQUE_PARTS`, `LOSS_PREFIX`, `ENERGY_PARTS`, `FRICTION_SIGNALS`, belt
520    /// stretch), appended after those of `base_signals`. They cost about one more evaluation of the machine's
521    /// derivatives, so they are asked for only where they are recorded or added up.
522    fn effect_signals(&self, _state: &[f64], _torque: &[f64], _out: &mut Vec<f64>) {}
523    /// The loss powers alone, the signals `power.*` in their order among the signals, without the rest of
524    /// `effect_signals`: what warms the parts every step (`thermal_parts`). Empty where the machine reports none.
525    fn loss_powers(&self, _state: &[f64], _torque: &[f64], _out: &mut Vec<f64>) {}
526    /// Every signal of `signal_infos`.
527    fn signals(&self, state: &[f64], torque: &[f64], out: &mut Vec<f64>) {
528        self.base_signals(state, torque, out);
529        self.effect_signals(state, torque, out);
530    }
531    fn scene(&self, state: &[f64], out: &mut Scene);
532    /// Where the scene draws the tool when it is at `tool_pose`, in scene coordinates, so that a front end can
533    /// draw a path of the tool into the scene. `None` for a machine that has no such mapping.
534    fn scene_point(&self, _tool_pose: &[f64]) -> Option<[f64; 3]> {
535        None
536    }
537    /// The parts of the machine that can hit an obstacle of the config, as boxes in scene coordinates at `state`. By
538    /// default the tool alone, as a point where `scene_point` puts it (none without that mapping); a machine names
539    /// the boxes of its scene that move with the tool through `scene::scene_boxes`.
540    fn collision_bodies(&self, state: &[f64]) -> Vec<crate::Aabb> {
541        let n = self.axes().len();
542        let (mut pos, mut vel) = (vec![0.0; n], vec![0.0; n]);
543        self.tool_state(state, &mut pos, &mut vel);
544        self.scene_point(&pos).map(|centre| crate::Aabb { centre, size: [0.0; 3] }).into_iter().collect()
545    }
546    /// The slanted parts of the machine that can hit an obstacle (rods, arms, shafts), as capsules in scene coordinates
547    /// at `state`, beside the boxes of `collision_bodies`. None by default.
548    fn collision_capsules(&self, _state: &[f64]) -> Vec<crate::Capsule> {
549        Vec::new()
550    }
551    /// The capsules the planning check of the machine's own parts looks at (`collision::check_path`): by default those
552    /// of `collision_capsules`. A machine whose links are not checked against obstacles can add them here.
553    fn self_collision_capsules(&self, state: &[f64]) -> Vec<crate::Capsule> {
554        self.collision_capsules(state)
555    }
556    /// Which of the machine's own parts belong together and so are not checked against each other, at `state`, with
557    /// `boxes` boxes (`collision_bodies`) and `capsules` capsules (`self_collision_capsules`): pairs of indices into
558    /// the boxes followed by the capsules. `None`, the default, takes the rule that parts which touch, overlap or lie
559    /// closer than `profile.min_clearance_m` to each other at the first pose checked are joined (a carriage on its
560    /// rail, a link at its joint) and every other pair is checked; that cannot see a collision of parts already in
561    /// contact at that pose. A machine that knows its parts' adjacency tells it exactly. The step of the simulation is
562    /// not touched: parts do not push each other there.
563    fn connected_bodies(&self, _state: &[f64], _boxes: usize, _capsules: usize) -> Option<Vec<(usize, usize)>> {
564        None
565    }
566
567    /// The friction contacts for the friction view. Empty where the machine tells none.
568    fn friction_contacts(&self) -> Vec<FrictionContact> {
569        Vec::new()
570    }
571    /// The steady sliding force of contact `i` at `speed`, with its levels scaled by `load_scale`, split into
572    /// [Coulomb, viscous, stiction]. It opposes a positive speed.
573    fn friction_curve(&self, _i: usize, _speed: f64, _load_scale: f64) -> [f64; 3] {
574        [0.0; 3]
575    }
576    /// Whether contact `i` is a rotary one (a joint's bearings): its speed signal is an angular speed (rad/s) and its
577    /// parts torques (N m), where a sliding one has m/s and N. The friction view draws the labels of its kind.
578    fn friction_rotary(&self, _i: usize) -> bool {
579        false
580    }
581    /// The speed (m/s, or rad/s for a rotary contact) up to which the friction view draws contact `i`'s curve, where
582    /// the machine knows it from the highest speed of each motor's rotor, `motor_speed` (rad/s, from its drive);
583    /// `None`: the owner axis's speed limit, or the fastest axis's.
584    fn friction_speed_limit(&self, _i: usize, _motor_speed: &[f64]) -> Option<f64> {
585        None
586    }
587
588    /// The belt sections for the belt view. Empty where the machine tells none.
589    fn belt_sections(&self) -> Vec<BeltSection> {
590        Vec::new()
591    }
592
593    /// The parts that warm with a loss power, for the thermal model and view. Empty where the machine tells none.
594    fn thermal_parts(&self) -> Vec<ThermalPart> {
595        Vec::new()
596    }
597
598    /// The resistance to ambient (K/W) and the time constant (s) of the thermal part `id`, where the machine works them
599    /// out from the part's own size (a belt: its surface and mass) in place of the config's `thermal.<kind>_resistance_k_w`
600    /// and `thermal.<kind>_time_constant_s`; `None`: the config's.
601    fn thermal_values(&self, _id: &str) -> Option<(f64, f64)> {
602        None
603    }
604
605    /// Carries a running state over to a machine rebuilt from a changed config.
606    fn adopt_state(&self, old: &dyn Machine, old_state: &[f64]) -> Vec<f64> {
607        let (n, motors) = (self.axes().len(), self.motors().len());
608        let (mut pos, mut vel) = (vec![0.0; n], vec![0.0; n]);
609        old.tool_state(old_state, &mut pos, &mut vel);
610        let (mut before, mut after) = (vec![0.0; motors], vec![0.0; motors]);
611        old.inverse(&pos, &mut before);
612        self.inverse(&pos, &mut after);
613        if old.state_len() == self.state_len() && before == after {
614            return old_state.to_vec();
615        }
616        // The model changed its states (rigid <-> elastic) or its kinematics (ratio, pulley radius), and the
617        // old motor and pulley angles belong to another tool pose now: kept, they would tear the belt. So the
618        // same tool pose and speed, with belts and gears as they are at rest there. The controller goes on
619        // with its motion, so a machine restarted at rest would be torn after a setpoint that is already moving.
620        let mut state = Vec::new();
621        self.equilibrium(&pos, &mut state, &mut vec![0.0; motors]);
622        self.set_tool_velocity(&mut state, &vel);
623        state
624    }
625}
626
627/// The generalised force of a force on the contact coordinates (`Machine::set_tool_force`, by default the tool's) on each of the
628/// state's rates `rates`: its virtual power per unit of each rate, F . d v / d s_j, with their rates v as
629/// `contact_state` gives them, linear in the state's rates (a unit step on each is exact). Its power on the rates is
630/// then F . v, what the simulation books as the obstacles' work. `None` where the force is zero.
631pub fn tool_force_on_rates<M: Machine + ?Sized>(
632    machine: &M,
633    s: &[f64],
634    force: &[f64],
635    rates: std::ops::Range<usize>,
636) -> Option<Vec<f64>> {
637    if force.iter().all(|f| *f == 0.0) {
638        return None;
639    }
640    let n = force.len();
641    let (mut pos, mut base, mut vel, mut at) = (vec![0.0; n], vec![0.0; n], vec![0.0; n], s.to_vec());
642    machine.contact_state(s, &mut pos, &mut base);
643    let on = |j: usize| -> f64 {
644        at[j] = s[j] + 1.0;
645        machine.contact_state(&at, &mut pos, &mut vel);
646        at[j] = s[j];
647        force.iter().zip(vel.iter().zip(&base)).map(|(f, (v, b))| f * (v - b)).sum()
648    };
649    Some(rates.map(on).collect())
650}
651
652/// One line of the registration list.
653pub struct MachineEntry {
654    pub id: &'static str,
655    pub key: &'static str,
656    pub default_config: &'static str,
657    /// (language code, translation file contents)
658    pub i18n: &'static [(&'static str, &'static str)],
659    pub build: fn(&Config) -> Result<Box<dyn Machine>, ConfigError>,
660    /// Configs without friction and other losses, on which the standard suite checks energy.
661    pub suite_configs: fn() -> Vec<Config>,
662}
663
664impl MachineEntry {
665    pub fn config(&self) -> Config {
666        Config::parse(self.default_config).expect("default config of a registered machine must parse")
667    }
668}