Skip to main content

machine_overhead_crane/
lib.rs

1//! Overhead crane: a bridge travelling on a runway (x), a trolley travelling along the bridge's girder (y), a hoist on
2//! the trolley winding the rope on its drum, and the load hanging from the rope's end as a spherical pendulum on an
3//! elastic rope. Each drive is a servo motor behind a gearbox, its wheel or drum the lever (`joint::RotaryJoint` with a
4//! `transmission::Converter`): the motor turns i / r rad per metre of travel or of rope.
5//!
6//! The tool is the hook as the drives place it: the bridge's x, the trolley's y and the height z the drum's rope gives
7//! the empty hook (m); the sway is the load's own (signals `load.*`, verdict residual-sway). The rope leaves the trolley's sheave at
8//! T = (x_b, y_t, H) (`crane.rope_exit_height_m`) and runs straight to the load's point P (hook and load one point mass):
9//!
10//! ```text
11//! L = |P - T|, u = (P - T) / L                   the rope's length and direction, sheave to load
12//! e = L - l                                      its stretch over its free length l, paid out by the drum
13//! t = EA e / l + c / l (L' - l')  if e > 0, else 0, and never below 0 (the rope goes slack: it cannot push)
14//! V = EA e^2 / (2 l)                             its elastic energy while taut
15//! ```
16//!
17//! The rope pulls the load with -t u, the trolley with t u (its x on the bridge, its y on the trolley; its z goes into
18//! the rails), and the drum, through dV/dl, with t (1 + e / (2 l)) out (the damper's share as it is): the sway acts
19//! back on both travel drives and the swing's stretch on the hoist. Equations of motion, rigid drives with the
20//! rotors' inertia at the axis (i^2 J_rotor), the gearbox's efficiency on the power it passes (`Gearbox::loss_factor`):
21//!
22//! ```text
23//! (m_b + m_t) x'' = drive_x + t u_x - F_roll,x + stops      m_t y'' = drive_y + t u_y - F_roll,y + stops
24//! J_drum / r^2 l'' = drive_l + t (1 + e / (2 l)) + stops    m P'' = -t u - m g e_z
25//! F_roll = w N tanh(v / v_s), N = (wheels' mass) g + t (-u_z)   (effects.guide_friction)
26//! ```
27//!
28//! The pendulum's small swing has the period 2 pi sqrt(L / g) (`Machine::resonance_hz`, which the input shaper follows
29//! with effects.shaper_follows_pose: the period of the rope's length where the plan stands, so a move that hoists while
30//! it travels is shaped for the length as it changes). At rest the load hangs under the sheave on a rope stretched by
31//! its weight, l = L / (1 + m g / EA); the motor angles of a pose (`inverse`) count on the empty hook's weight alone
32//! (`kinematic_stretch`), so the drum stands still when the payload goes on or off. Pick and set-down are quasi-static
33//! (`after_step`), or, with effects.floor_contact, the load stands on the floor until the rope carries it (`motion`).
34//! With effects.rope_stretch off the rope is rigid, L = l, its tension the constraint force (`motion`); with the floor,
35//! the load stands on it with the rope slack, and a rope that comes taut lifts it at once (`after_step`).
36//!
37//! What the model leaves out: the rope's bending at the sheave and the load's own turning (a bulky load twisting on its
38//! sling: the load is a point mass).
39//!
40//! Four further effects, each its own switch (off: the model above, exactly), solved together by one mass matrix
41//! (`full.rs`) over the coordinates x_c (bridge), y, l, the hook block's point P1 (3), with the effects the sling's span
42//! d = P2 - P1 (3) and the bridge's yaw psi; the rigid rope there is the constraint L = l on these coordinates, its
43//! tension the multiplier:
44//!
45//! - effects.rope_mass: a rope of mass mu per metre (`rope.mass_per_m_kg_m`, 0.0035 d^2 kg/m for a steel wire rope of d mm).
46//!   A straight rope of free length l from the sheave S to P1, its material's velocity linear along it from v_A = v_S + l'
47//!   u (the rope runs off the sheave at the drum's speed) to v_P, has the kinetic energy
48//!   K = mu l / 6 (|v_A|^2 + v_A . v_P + |v_P|^2); the rope wound on the drum, mu (capacity - l) of it, moves with the
49//!   trolley and the drum's surface, K = mu (capacity - l) (|v_S|^2 + l'^2) / 2. Its weight is
50//!   V = mu g [l (H + z_P) / 2 + (capacity - l) H] (the hanging part at its middle). Lagrange's equations (the mass mu l
51//!   grows with the paid-out l, so d/dt of the momentum has the mu l' terms and dK/dl is a force on the drum) give the
52//!   mass matrix and the speed terms of `full.rs`; nothing is booked as loss. The tension differs along the rope by the
53//!   weight below: at the drum the load's weight plus mu g times the height hanging, (m + mu l) g, at the hook m g; the
54//!   signal `rope.tension` is the drum's end (the highest), `rope.shortfall` is judged at the hook's end.
55//! - effects.hook_block: the hook block (`crane.hook_mass_kg`) hangs on the rope at P1, the load under it at P2 = P1 + d
56//!   on a sling of length l_s (`crane.sling_length_m`): a spherical double pendulum. The sling is a rope of the main
57//!   rope's EA and damping, t_s = EA e_s / l_s + c e_s' / l_s, e_s = |d| - l_s, never below 0 and 0 while e_s <= 0: it
58//!   goes slack where the load stands on the floor and the hook block goes lower, or in a bounce, and takes the jerk in
59//!   its stretch when it comes taut again. Signals of the load (sway, position) are P2's.
60//! - effects.joint_elasticity: each drive is the elastic joint other machines use (`RotaryJoint::rotor`): the gearbox's
61//!   stiffness, damping and backlash between the rotor (an angle and a speed of its own) and the wheel or drum.
62//! - effects.bridge_skew: the bridge a rigid girder on two end carriages, each with a drive of the bridge's motor config
63//!   (the bridge's command shared equally between them), the wheels' lateral stiffness holding the yaw psi =
64//!   (x_B - x_A) / gauge with the moment k_psi psi, k_psi = k_lat b^2 / 2. The trolley at y on the girder is at x = x_c +
65//!   psi (y - y_c); its place shares the load between the two sides.
66//!
67//! With effects.floor_contact the standing load rubs on the floor with Coulomb friction mu_f N (smoothed over
68//! `crane.rolling_smoothing_m_s`), N the floor's push; the rigid rope respects the floor too (`motion`).
69
70use sim_components::catalog::motor_config;
71use sim_components::joint::RotaryJoint;
72use sim_components::mech::{HardStop, ShaftFriction, ThermalFeedback};
73use sim_components::rigid::{V3, add, dot};
74use sim_components::transmission::Converter;
75use sim_core::{
76    AxisInfo, Config, ConfigError, ENERGY_PARTS, LOSS_PREFIX, Label, Machine, MachineEntry, MotorInfo, Part,
77    RatingCheck, Scene, Shape, SignalInfo, TORQUE_PARTS, ThermalPart,
78};
79use std::f64::consts::TAU;
80
81mod full;
82
83pub static ENTRY: MachineEntry = MachineEntry {
84    id: "overhead-crane",
85    key: "machine-overhead-crane",
86    default_config: include_str!("../config/crane.toml"),
87    i18n: &[("en", include_str!("../i18n/en.ftl")), ("de", include_str!("../i18n/de.ftl"))],
88    build,
89    suite_configs,
90};
91
92const G: f64 = 9.80665;
93
94/// Effects that take energy out or put it in; the standard suite runs with them off.
95pub const LOSSY_EFFECTS: [&str; 8] = [
96    "guide_friction",
97    "rope_damping",
98    "motor_friction",
99    "gearbox_drag",
100    "gearbox_lost_motion",
101    "gearbox_efficiency",
102    "torque_ripple",
103    "holding_brake",
104];
105
106/// The default config with every loss switched off.
107pub fn lossless_config() -> Config {
108    let mut cfg = ENTRY.config();
109    for effect in LOSSY_EFFECTS {
110        cfg.set_text(&format!("effects.{effect} = false")).unwrap();
111    }
112    cfg.set_text("crane.stop_damping_n_s_m = 0.0").unwrap();
113    cfg.set_text("hoist.stop_damping_n_s_m = 0.0").unwrap();
114    cfg
115}
116
117/// Loss-free elastic and rigid ropes, with and without the payload. Gravity stays on: without it the load has nothing
118/// to hang by.
119fn suite_configs() -> Vec<Config> {
120    [(true, true), (true, false), (false, true), (false, false)]
121        .into_iter()
122        .map(|(elastic, payload)| {
123            let mut cfg = lossless_config();
124            cfg.set_text(&format!("effects.rope_stretch = {elastic}")).unwrap();
125            cfg.set_text(&format!("effects.payload = {payload}")).unwrap();
126            cfg
127        })
128        .collect()
129}
130
131/// The shipped config with the input shaper on (the travel moves shaped against the sway, its period following the
132/// rope's length): what `sim-cli verdicts overhead-crane --set effects.input_shaping=true` runs.
133pub fn shaped_config() -> Config {
134    let mut cfg = ENTRY.config();
135    cfg.set_text("effects.input_shaping = true").unwrap();
136    cfg
137}
138
139fn build(cfg: &Config) -> Result<Box<dyn Machine>, ConfigError> {
140    sim_components::base::mount(cfg, Box::new(Crane::new(cfg)?))
141}
142
143const MOTOR_IDS: [&str; 3] = ["bridge", "trolley", "hoist"];
144const MOTOR_KEYS: [&str; 3] = ["motor-bridge", "motor-trolley", "motor-hoist"];
145const GEARBOX_IDS: [&str; 3] = ["gearbox_bridge", "gearbox_trolley", "gearbox_hoist"];
146const AXIS_IDS: [&str; 3] = ["x", "y", "z"];
147const AXIS_KEYS: [&str; 3] = ["axis-x", "axis-y", "axis-z"];
148
149/// The state: bridge x, trolley y, the rope's free length l, their rates; the load's place P and its speed; the three
150/// brakes' deflections. With the new effects more follow (`Layout`): the bridge's yaw, its rate and the second carriage's
151/// brake; the sling's span and its rate; the rotors' angles and speeds.
152const RATES: usize = 3;
153const LOAD: usize = 6;
154const LOAD_SPEED: usize = 9;
155const BRAKES: usize = 12;
156const STATE_LEN: usize = 15;
157/// How far over the floor (m), and how fast up from it (m/s), the payload on the sling still stands: its height and speed
158/// P1 + d, P1' + d' round by an ulp of P1's.
159const FLOOR_ROUNDING: f64 = 1e-12;
160/// The hook block's and the payload's boxes as the scene draws them, centred on their points (m, x y z).
161const HOOK_BOX: V3 = [0.12, 0.08, 0.16];
162const PAYLOAD_BOX: V3 = [0.6, 0.6, 0.4];
163
164/// Where the states of the new effects sit, and the generalised coordinates of `full.rs`.
165#[derive(Debug, Clone)]
166struct Layout {
167    /// effects.bridge_skew: the state index of the yaw psi (then psi', the second carriage's brake).
168    skew: Option<usize>,
169    /// effects.hook_block: the sling's span d = P2 - P1 from the hook block to the payload, and its rate.
170    sling: Option<usize>,
171    /// effects.joint_elasticity: the rotors' angles, then their speeds (one each per drive).
172    rotor: Option<usize>,
173    /// Number of drives (3, and the second bridge carriage's with the skew) and of states.
174    drives: usize,
175    len: usize,
176    /// Per generalised coordinate: its place in the state and its rate's.
177    pos: Vec<usize>,
178    vel: Vec<usize>,
179}
180
181impl Layout {
182    fn new(skew: bool, sling: bool, elastic: bool) -> Self {
183        let mut len = STATE_LEN;
184        let drives = 3 + skew as usize;
185        let mut pos: Vec<usize> = vec![0, 1, 2, LOAD, LOAD + 1, LOAD + 2];
186        let mut vel: Vec<usize> = vec![RATES, RATES + 1, RATES + 2, LOAD_SPEED, LOAD_SPEED + 1, LOAD_SPEED + 2];
187        let mut take = |n: usize| {
188            len += n;
189            len - n
190        };
191        let sk = skew.then(|| take(3));
192        let sl = sling.then(|| take(6));
193        let ro = elastic.then(|| take(2 * drives));
194        if let Some(a) = sl {
195            pos.extend([a, a + 1, a + 2]);
196            vel.extend([a + 3, a + 4, a + 5]);
197        }
198        if let Some(k) = sk {
199            pos.push(k);
200            vel.push(k + 1);
201        }
202        Self { skew: sk, sling: sl, rotor: ro, drives, len, pos, vel }
203    }
204}
205
206/// The bridge on two end carriages (effects.bridge_skew).
207#[derive(Debug, Clone, Copy)]
208struct Skew {
209    /// The rails' distance, the girder's yaw inertia m_b gauge^2 / 12, the wheels' holding moment per rad and its damper.
210    gauge: f64,
211    inertia: f64,
212    stiffness: f64,
213    damping: f64,
214}
215
216fn sub(a: V3, b: V3) -> V3 {
217    [a[0] - b[0], a[1] - b[1], a[2] - b[2]]
218}
219
220fn norm(a: V3) -> f64 {
221    dot(a, a).sqrt()
222}
223
224/// The rope at one moment.
225#[derive(Debug, Clone, Copy)]
226pub struct Rope {
227    /// Its length L from the sheave to the load, and the unit vector u along it.
228    pub length: f64,
229    pub u: V3,
230    /// L' and the stretch e = L - l.
231    pub rate: f64,
232    pub stretch: f64,
233    /// The tension on its ends (on the load and the trolley), its pull on the drum (dV/dl plus the damper), and the
234    /// damper's share of both.
235    pub tension: f64,
236    pub drum: f64,
237    pub damper: f64,
238}
239
240/// The accelerations and gearbox forces of one moment.
241struct Motion {
242    /// x'', y'', l''.
243    acc: [f64; 3],
244    load_acc: V3,
245    /// Per drive: the force into its gearbox (after the rotor's acceleration) and out of it, at the axis (N).
246    into: [f64; 3],
247    out: [f64; 3],
248    brake_rates: [f64; 3],
249    /// What the rope gives each axis (its pull, the drum's for the hoist) and the rolling resistance (N).
250    rope: [f64; 3],
251    rolling: [f64; 3],
252    /// The floor's push on the load (N), 0 unless it stands on it, and the power its friction takes (W).
253    floor_force: f64,
254    floor_power: f64,
255    rope_state: Rope,
256    /// What `full.rs` solved besides: per drive and per generalised coordinate.
257    full: Option<Box<full::Extra>>,
258}
259
260#[derive(Clone)]
261pub struct Crane {
262    /// Bridge, trolley, hoist: each in N and m at its axis.
263    drives: [RotaryJoint; 3],
264    /// The masses each axis moves (bridge with trolley, trolley, the drum's inertia at the rope).
265    masses: [f64; 3],
266    bridge: f64,
267    trolley: f64,
268    hook: f64,
269    payload: f64,
270    attached: bool,
271    /// The payload went on or off since the last step: `after_step` sets the rope to its weight.
272    picked: bool,
273    /// What that took out of the energy over the last step (W), booked with `power.other`.
274    pick_loss: f64,
275    /// effects.floor_contact: the height of the load's point when it stands on the floor (`crane.floor_height_m`).
276    floor: Option<f64>,
277    /// Coulomb friction coefficient between the standing load and the floor.
278    floor_friction: f64,
279    /// crane.hook_block_friction_coefficient: the hook block rubbing along the payload's faces.
280    hook_friction: f64,
281    height: f64,
282    /// Where the girder's middle is along the trolley's y (the yaw turns about it).
283    y_centre: f64,
284    /// The rope's mass per metre (effects.rope_mass; 0 off) and the rope the drum holds.
285    rope_mass: f64,
286    capacity: f64,
287    /// effects.hook_block: the sling's length.
288    sling: Option<f64>,
289    /// effects.hook_block with the floor: the payload was let go and is a free body in the equations (its place P2 = P1 +
290    /// d, the span's coordinates, its weight and the contacts of the floor and the hook block the only forces on it: it
291    /// falls, lands on the floor, stands, the hook block meets its box, `faces`) until the next pick. A pick takes it
292    /// where it is if the sling reaches it (`reach` at most the sling's length: `in_place`), else this one is gone and
293    /// the next load appears under the hook block (`appear`), as the first pick's did.
294    free: bool,
295    in_place: bool,
296    appear: bool,
297    /// The length of the span at the last `after_step` while the payload is a mass in the equations (m).
298    reach: f64,
299    /// effects.joint_elasticity.
300    elastic_drives: bool,
301    /// effects.bridge_skew: the yaw and the second end carriage's drive (the first is `drives[0]`).
302    skew: Option<Skew>,
303    side_b: Option<RotaryJoint>,
304    /// One of the four effects above is on: the motion is `full.rs`'s.
305    full: bool,
306    layout: Layout,
307    /// effects.rope_stretch: the elastic rope; off, the rigid reference.
308    elastic: bool,
309    ea: f64,
310    damping: f64,
311    t_min: f64,
312    t_max: f64,
313    rolling: f64,
314    rolling_smoothing: f64,
315    g: f64,
316    sway_limit: f64,
317    brake_limit: f64,
318    drum_radius: f64,
319    strokes: [f64; 2],
320    dwelling: bool,
321    brake_engaged: bool,
322    /// An obstacle's push on the contact coordinates (`contact_state`: the load's point, and with the hook block the
323    /// payload's), held until changed; empty for none.
324    push: Vec<f64>,
325    thermal: Option<ThermalFeedback>,
326    axes: Vec<AxisInfo>,
327    motors: Vec<MotorInfo>,
328}
329
330impl Crane {
331    pub fn new(cfg: &Config) -> Result<Self, ConfigError> {
332        let stops = |table: &str| -> Result<HardStop, ConfigError> {
333            Ok(if cfg.bool("effects.hard_stops")? {
334                HardStop {
335                    stiffness: cfg.positive(&format!("{table}.stop_stiffness_n_m"))?,
336                    damping: cfg.non_negative(&format!("{table}.stop_damping_n_s_m"))?,
337                }
338            } else {
339                HardStop { stiffness: 0.0, damping: 0.0 }
340            })
341        };
342        let wheel_radii = [cfg.positive("crane.bridge_wheel_radius_m")?, cfg.positive("crane.trolley_wheel_radius_m")?];
343        let strokes = [cfg.positive("crane.bridge_stroke_m")?, cfg.positive("crane.trolley_stroke_m")?];
344        let drum_radius = cfg.positive("hoist.drum_radius_m")?;
345        let levers = [wheel_radii[0], wheel_radii[1], drum_radius];
346        let ranges = [(0.0, strokes[0]), (0.0, strokes[1]), (0.0, cfg.positive("hoist.capacity_m")?)];
347        let tables = ["crane", "crane", "hoist"];
348        // What each drive's wheel or drum moves rigidly, at its travel: the mesh friction's bristle is capped by the
349        // lighter of it and the rotor (`Converter::apply_to`); the load hangs on the elastic rope.
350        let (bridge, trolley) = (cfg.positive("crane.bridge_mass_kg")?, cfg.positive("crane.trolley_mass_kg")?);
351        let masses =
352            [bridge + trolley, trolley, cfg.positive("hoist.drum_inertia_kgm2")? / (drum_radius * drum_radius)];
353        let mut drives = Vec::new();
354        for k in 0..3 {
355            // Each drive with its own motor, gearbox and drive tables (`[motor.hoist]` over `[motor]`).
356            let own = motor_config(cfg, MOTOR_IDS[k])?;
357            let mut joint = RotaryJoint::with(&own, ShaftFriction::NONE, stops(tables[k])?, ranges[k])?;
358            Converter {
359                lever: levers[k],
360                stiffness: f64::INFINITY,
361                backlash: 0.0,
362                efficiency: 1.0,
363                inertia: 0.0,
364                damping_ratio: 0.0,
365            }
366            .apply_to(&own, &mut joint, masses[k])?;
367            drives.push(joint);
368        }
369        let drives: [RotaryJoint; 3] = drives.try_into().map_err(|_| ConfigError::Invalid("motor".into()))?;
370        let height = cfg.positive("crane.rope_exit_height_m")?;
371        let (min, max) = (cfg.f64s("workspace.tool_min")?, cfg.f64s("workspace.tool_max")?);
372        let inside = |k: usize, lo: f64, hi: f64| min[k] >= lo && max[k] <= hi && min[k] < max[k];
373        if min.len() != 3 || max.len() != 3 || !inside(0, 0.0, strokes[0]) || !inside(1, 0.0, strokes[1]) {
374            return Err(ConfigError::Invalid("workspace.tool_max".into()));
375        }
376        if !(inside(2, 0.0, height) && height - min[2] < ranges[2].1) {
377            return Err(ConfigError::Invalid("workspace.tool_min".into()));
378        }
379        let axes = (0..3)
380            .map(|k| {
381                let get = |what: &str, rate: &str| cfg.positive(&format!("axis.{}.max_{what}_m_{rate}", AXIS_IDS[k]));
382                Ok(AxisInfo {
383                    id: AXIS_IDS[k],
384                    key: AXIS_KEYS[k],
385                    unit: "m",
386                    min: min[k],
387                    max: max[k],
388                    max_vel: get("velocity", "s")?,
389                    max_acc: get("acceleration", "s2")?,
390                    max_jerk: get("jerk", "s3")?,
391                })
392            })
393            .collect::<Result<Vec<_>, ConfigError>>()?;
394        let t_min = cfg.non_negative("rope.min_tension_n")?;
395        let t_max = cfg.positive("rope.breaking_load_n")? / cfg.positive("rope.safety_factor")?;
396        let hoist = motor_config(cfg, "hoist")?;
397        let flag = |name: &str| -> Result<bool, ConfigError> {
398            let key = format!("effects.{name}");
399            Ok(cfg.get(&key).is_ok() && cfg.bool(&key)?)
400        };
401        let (rope_mass_on, hook_block, elastic_drives, skew_on) =
402            (flag("rope_mass")?, flag("hook_block")?, flag("joint_elasticity")?, flag("bridge_skew")?);
403        let full = rope_mass_on || hook_block || elastic_drives || skew_on;
404        let mass_per_m = cfg.non_negative("rope.mass_per_m_kg_m")?;
405        let sling = cfg.positive("crane.sling_length_m")?;
406        let (gauge, wheelbase) = (cfg.positive("crane.bridge_gauge_m")?, cfg.positive("crane.bridge_wheelbase_m")?);
407        let lateral = cfg.positive("crane.bridge_wheel_lateral_stiffness_n_m")?;
408        let ratio = cfg.non_negative("crane.bridge_skew_damping_ratio")?;
409        let yaw_inertia = bridge * gauge * gauge / 12.0;
410        let yaw_stiffness = lateral * wheelbase * wheelbase / 2.0;
411        let skew = skew_on.then(|| Skew {
412            gauge,
413            inertia: yaw_inertia,
414            stiffness: yaw_stiffness,
415            damping: if cfg.bool("effects.guide_friction").unwrap_or(false) {
416                2.0 * ratio * (yaw_stiffness * yaw_inertia).sqrt()
417            } else {
418                0.0
419            },
420        });
421        let side_b = skew.is_some().then(|| drives[0].clone());
422        Ok(Self {
423            floor_friction: cfg.non_negative("crane.floor_friction_coefficient")?,
424            hook_friction: cfg.non_negative("crane.hook_block_friction_coefficient")?,
425            y_centre: 0.5 * strokes[1],
426            rope_mass: if rope_mass_on { mass_per_m } else { 0.0 },
427            capacity: cfg.positive("hoist.capacity_m")?,
428            sling: hook_block.then_some(sling),
429            elastic_drives,
430            layout: Layout::new(skew.is_some(), hook_block, elastic_drives),
431            skew,
432            side_b,
433            full,
434            masses,
435            drives,
436            bridge,
437            trolley,
438            hook: cfg.positive("crane.hook_mass_kg")?,
439            payload: if cfg.bool("effects.payload")? { cfg.non_negative("crane.payload_kg")? } else { 0.0 },
440            attached: true,
441            free: false,
442            in_place: false,
443            appear: false,
444            reach: 0.0,
445            picked: false,
446            pick_loss: 0.0,
447            floor: if cfg.bool("effects.floor_contact")? {
448                Some(cfg.non_negative("crane.floor_height_m")?)
449            } else {
450                None
451            },
452            height,
453            elastic: cfg.bool("effects.rope_stretch")?,
454            ea: cfg.positive("rope.ea_n")?,
455            damping: if cfg.bool("effects.rope_damping")? {
456                cfg.non_negative("rope.specific_damping_n_s")?
457            } else {
458                0.0
459            },
460            t_min,
461            t_max,
462            rolling: if cfg.bool("effects.guide_friction")? {
463                cfg.non_negative("crane.rolling_coefficient")?
464            } else {
465                0.0
466            },
467            rolling_smoothing: cfg.positive("crane.rolling_smoothing_m_s")?,
468            g: if cfg.bool("effects.gravity")? { G } else { 0.0 },
469            sway_limit: cfg.positive("crane.residual_sway_max_m")?,
470            brake_limit: hoist.non_negative("motor.brake_torque_nm")? / cfg.positive("hoist.brake_safety_factor")?,
471            drum_radius,
472            strokes,
473            dwelling: false,
474            brake_engaged: false,
475            push: Vec::new(),
476            thermal: ThermalFeedback::from_config(cfg)?,
477            axes,
478            motors: (0..3).map(|k| MotorInfo { id: MOTOR_IDS[k], key: MOTOR_KEYS[k] }).collect(),
479        })
480    }
481
482    /// Hook and, while attached, payload.
483    /// An obstacle's push (`set_tool_force`) on the hook's point and, with the hook block, on the payload's (N).
484    fn push_on(&self) -> (V3, V3) {
485        let at = |k: usize| self.push.get(k).copied().unwrap_or(0.0);
486        ([at(0), at(1), at(2)], [at(3), at(4), at(5)])
487    }
488
489    pub fn load_mass(&self) -> f64 {
490        self.hook + if self.attached { self.payload } else { 0.0 }
491    }
492
493    /// The rope's stretch factor at rest under the load's weight (and half the free rope's, which hangs on the load: the
494    /// spring's tension is the mean of its two ends'): L = l (1 + (m g + mu g l / 2) / EA).
495    fn rest_stretch(&self, l: f64) -> f64 {
496        if self.elastic { 1.0 + (self.load_mass() * self.g + 0.5 * self.rope_mass * self.g * l) / self.ea } else { 1.0 }
497    }
498
499    /// The pull on the drum of `mass` hanging at rest on the free length `l` under the sheave (N): the rope's tension at
500    /// the hook's end t = (mass + mu l / 2) g on the spring (its mean), with the spring's dV/dl share t (1 + e / 2l), e =
501    /// t l / EA, and the other half of the hanging rope's weight, mu g L / 2.
502    fn rest_pull(&self, l: f64, mass: f64) -> f64 {
503        let t = (mass + 0.5 * self.rope_mass * l) * self.g;
504        let e = if self.elastic { t * l / self.ea } else { 0.0 };
505        t * (1.0 + e / (2.0 * l)) + 0.5 * self.rope_mass * self.g * (l + e)
506    }
507
508    /// The payload's mass while it hangs on the hook.
509    fn payload_mass(&self) -> f64 {
510        if self.attached { self.payload } else { 0.0 }
511    }
512
513    /// The payload's mass while it is a mass in the equations: on the hook, or let go and free (`free`).
514    fn body_mass(&self) -> f64 {
515        if self.attached || self.free { self.payload } else { 0.0 }
516    }
517
518    /// How far the payload is from the hook block at the end of a step (`after_step`), where the next grip finds it:
519    /// within the sling's length it is picked where it lies (`set_payload_attached`). Taken before the step's landing on
520    /// the floor, a payload let go under a stretched sling (1.0017 m) and set on the floor 0.35 m below the hook block
521    /// in that step counted as out of reach, and the grip made it a new payload under the hook block at the hook
522    /// block's speed: 250 / 2 x 0.0102^2 = 0.013 J booked.
523    fn measure_reach(&mut self, s: &[f64]) {
524        if self.body_mass() > 0.0 {
525            self.reach = self.payload_span(s).map_or(0.0, |(d, _)| norm(d));
526        }
527    }
528
529    /// Where the payload hangs at rest under the hook block when it goes on there (`after_step`): plumb at the sling's
530    /// stretched length, or standing on the floor where that is lower, with the sling slack.
531    fn appear_span(&self, s: &[f64]) -> V3 {
532        let rest = self.sling_rest().unwrap_or(0.0);
533        [0.0, 0.0, self.floor.map_or(-rest, |floor| (-rest).max(floor - s[LOAD + 2]))]
534    }
535
536    /// The stretch the motor angles count on (`inverse`, `forward`): the empty hook's, whatever hangs on it. So the
537    /// motors stand still when the payload goes on or off, as a hoist's drum does, and the payload hangs lower than the
538    /// pose by its own stretch, m g L / EA (6.8 mm for the 250 kg on 4 m of rope; `setpoint_slack`). Counting the payload
539    /// in would step the hoist's setpoint by that much when the hook lets go, and the drum, paying it out faster than the
540    /// hook can fall, would slacken the rope.
541    fn kinematic_stretch(&self) -> f64 {
542        if self.elastic { 1.0 + self.hook * self.g / self.ea } else { 1.0 }
543    }
544
545    /// The small swing's angular frequency of a rope of length L; `None` without gravity. The point load on a rope of mass
546    /// mu per metre: w^2 = g (m + mu L / 2) / (L (m + mu L / 3)) (sqrt(g / L) for a light rope); with the hook block and a
547    /// payload on its sling the lower root of m1 l1 l2 w^4 - (m1 + m2) g (l1 + l2) w^2 + (m1 + m2) g^2 = 0.
548    pub fn sway_omega(&self, length: f64) -> Option<f64> {
549        self.sway_omegas(length).map(|(lower, _)| lower)
550    }
551
552    /// `sway_omega` and, with the hook block and a payload on its sling, the double pendulum's upper root, where hook
553    /// block and payload swing against each other.
554    fn sway_omegas(&self, length: f64) -> Option<(f64, Option<f64>)> {
555        if !(self.g > 0.0 && length > 0.0) {
556            return None;
557        }
558        if let Some(l2) = self.sling_rest().filter(|_| self.payload_mass() > 0.0) {
559            let (m1, m2, g) = (self.hook, self.payload_mass(), self.g);
560            let b = (m1 + m2) * g * (length + l2);
561            let root = (b * b - 4.0 * m1 * length * l2 * (m1 + m2) * g * g).sqrt();
562            let w2 = |sign: f64| ((b + sign * root) / (2.0 * m1 * length * l2)).sqrt();
563            return Some((w2(-1.0), Some(w2(1.0))));
564        }
565        let (m, rope) = (self.load_mass(), self.rope_mass * length);
566        Some(((self.g / length * (1.0 + rope / (2.0 * m)) / (1.0 + rope / (3.0 * m))).sqrt(), None))
567    }
568
569    /// effects.bridge_skew: the girder's yaw, which no loop holds (the carriages share the bridge's command, its loop
570    /// holds their mean, x_c): the girder's m_b g^2 / 12 and the trolley's m_t d^2 (at d from the middle, `y` the trolley's
571    /// place) on the wheels' k_psi and damper; rigid with the rotors' R g^2 / 2 on the yaw (R = J i^2 per carriage), elastic
572    /// those on the rotors' differential delta, tied to the yaw by the gearboxes' k g^2 / 2 and c g^2 / 2 on psi - delta.
573    fn skew_modes(&self, y: f64) -> Vec<sim_core::Mode> {
574        let Some(skew) = self.skew else { return Vec::new() };
575        let (j, d, half) = (&self.drives[0], y - self.y_centre, 0.5 * skew.gauge * skew.gauge);
576        let (yaw, rotors) = (skew.inertia + self.trolley * d * d, j.reflected_inertia() * half);
577        let modes = sim_components::chain::matrix_modes;
578        if !self.elastic_drives {
579            return modes(&[yaw + rotors], &[skew.stiffness], &[skew.damping], 1);
580        }
581        let (k, c) = (j.gearbox.stiffness * half, j.gearbox.damping * half);
582        modes(&[yaw, 0.0, 0.0, rotors], &[skew.stiffness + k, -k, -k, k], &[skew.damping + c, -c, -c, c], 2)
583    }
584
585    /// The modes along the rope and of the elastic drives with the motors held (the convention of `Machine::modes`), at
586    /// the drum's free length l of the pose. Along the rope, down positive: the drum (with effects.joint_elasticity, on
587    /// the hoist gearbox's k_g and damper, its J / r^2 and the wound rope mu (capacity - l)), the hook (the hook block
588    /// with effects.hook_block, else hook and payload) and the payload on its sling. The elastic rope's V = EA e^2 / 2l, e
589    /// = L - l, linearised at the rest stretch: K = EA / l [L^2 / l^2, -L / l; -L / l, 1] on (l, L), its damper c / l on
590    /// L' - l', and its own mass mu l / 6 [2, 1; 1, 2] (K = mu l / 6 (l'^2 + l' L' + L'^2), the drum's end at l'); the rigid
591    /// rope ties the hook to the drum (all of mu l with it). The sling EA / l_s and c / l_s between hook block and payload.
592    /// Held rigid drives hold the drum. The travels with effects.joint_elasticity: each axis on its gearbox (both
593    /// carriages' with effects.bridge_skew) with what it carries, its own masses, the wound rope and the free rope's mu l
594    /// / 3 at the sheave; the load on its pendulum stays behind (its swing's stiffness m g / L is 1e-4 of the gearbox's).
595    fn held_modes(&self, l: f64) -> Vec<sim_core::Mode> {
596        let modes = sim_components::chain::matrix_modes;
597        let (mu, j) = (self.rope_mass, &self.drives[2]);
598        let (sling, m2) = match self.sling {
599            Some(ls) if self.payload_mass() > 0.0 => (Some(ls), self.payload_mass()),
600            _ => (None, 0.0),
601        };
602        let m1 = self.load_mass() - m2;
603        // Coordinates: [drum], [hook on the elastic rope], [payload on the sling]. On the rigid rope the hook moves with
604        // the drum, or is held with it.
605        let (drum, hook) = (self.elastic_drives, self.elastic);
606        let at_hook = drum as usize;
607        let n = drum as usize + hook as usize + sling.is_some() as usize;
608        let (mut m, mut k, mut c) = (vec![0.0; n * n], vec![0.0; n * n], vec![0.0; n * n]);
609        let put = |a: &mut Vec<f64>, r: usize, col: usize, v: f64| a[r * n + col] += v;
610        if drum {
611            put(&mut m, 0, 0, self.masses[2] + mu * (self.capacity - l));
612            put(&mut k, 0, 0, j.gearbox.stiffness);
613            put(&mut c, 0, 0, j.gearbox.damping);
614        }
615        if self.elastic {
616            let length = l * self.rest_stretch(l);
617            let (ea, damper) = (self.ea / l, self.damping / l);
618            put(&mut m, at_hook, at_hook, m1 + mu * l / 3.0);
619            put(&mut k, at_hook, at_hook, ea);
620            put(&mut c, at_hook, at_hook, damper);
621            if drum {
622                let r = length / l;
623                put(&mut m, 0, 0, mu * l / 3.0);
624                put(&mut k, 0, 0, ea * r * r);
625                put(&mut c, 0, 0, damper);
626                for (a, b) in [(0, 1), (1, 0)] {
627                    put(&mut m, a, b, mu * l / 6.0);
628                    put(&mut k, a, b, -ea * r);
629                    put(&mut c, a, b, -damper);
630                }
631            }
632        } else if drum {
633            put(&mut m, 0, 0, m1 + mu * l);
634        }
635        if let Some(ls) = sling {
636            // Between the payload and the hook, which is held where neither the rope nor the drum gives.
637            let (p, (ks, cs)) = (n - 1, (self.ea / ls, self.damping / ls));
638            put(&mut m, p, p, m2);
639            put(&mut k, p, p, ks);
640            put(&mut c, p, p, cs);
641            if hook || drum {
642                let q = if hook { at_hook } else { 0 };
643                for (a, b, sign) in [(q, q, 1.0), (p, q, -1.0), (q, p, -1.0)] {
644                    put(&mut k, a, b, sign * ks);
645                    put(&mut c, a, b, sign * cs);
646                }
647            }
648        }
649        let mut out = if n > 0 { modes(&m, &k, &c, n) } else { Vec::new() };
650        if self.elastic_drives {
651            // The travels: the bridge's on both carriages' gearboxes with the skew.
652            let rope = mu * (self.capacity - l) + mu * l / 3.0;
653            let carriages = if self.skew.is_some() { 2.0 } else { 1.0 };
654            for (d, mass) in [(0, self.bridge + self.trolley + rope), (1, self.trolley + rope)] {
655                let (box_, k) = (&self.drives[d].gearbox, if d == 0 { carriages } else { 1.0 });
656                out.extend(modes(&[mass], &[k * box_.stiffness], &[k * box_.damping], 1));
657            }
658        }
659        out
660    }
661
662    /// The bridge's yaw and its rate (0 without effects.bridge_skew).
663    fn yaw(&self, s: &[f64]) -> (f64, f64) {
664        self.layout.skew.map_or((0.0, 0.0), |k| (s[k], s[k + 1]))
665    }
666
667    /// Where the rope leaves the trolley: on a girder yawed by psi the trolley at y is at x = x_c + psi (y - y_c).
668    fn sheave(&self, s: &[f64]) -> V3 {
669        let (psi, _) = self.yaw(s);
670        [s[0] + psi * (s[1] - self.y_centre), s[1], self.height]
671    }
672
673    /// The sheave's velocity.
674    fn sheave_speed(&self, s: &[f64]) -> V3 {
675        let (psi, rate) = self.yaw(s);
676        [s[RATES] + rate * (s[1] - self.y_centre) + psi * s[RATES + 1], s[RATES + 1], 0.0]
677    }
678
679    /// The rope's geometry at a state, and with effects.rope_stretch its tension; the rigid rope's tension comes from
680    /// the motion (`motion`), and is 0 here.
681    pub fn rope(&self, s: &[f64]) -> Rope {
682        let d = sub([s[LOAD], s[LOAD + 1], s[LOAD + 2]], self.sheave(s));
683        let length = norm(d);
684        let u = if length > 0.0 { d.map(|v| v / length) } else { [0.0, 0.0, -1.0] };
685        let vs = self.sheave_speed(s);
686        let relative = [s[LOAD_SPEED] - vs[0], s[LOAD_SPEED + 1] - vs[1], s[LOAD_SPEED + 2]];
687        let rate = dot(u, relative);
688        let (l, l_rate) = (s[2], s[RATES + 2]);
689        let stretch = length - l;
690        let (mut tension, mut drum, mut damper) = (0.0, 0.0, 0.0);
691        if self.elastic && stretch > 0.0 {
692            let spring = self.ea * stretch / l;
693            tension = (spring + self.damping / l * (rate - l_rate)).max(0.0);
694            damper = tension - spring;
695            drum = spring * (1.0 + stretch / (2.0 * l)) + damper;
696        }
697        Rope { length, u, rate, stretch, tension, drum, damper }
698    }
699
700    /// The accelerations at a state under the motor torques. Each axis k: a_k = (eta_k D_k + F_k + p_k) / (M_k +
701    /// eta_k J_k), D the drive's force through the gearbox, F the stops and the rolling, p the rope's pull, eta the
702    /// gearbox's loss factor at the power it passes (from a first pass with eta = 1, as on every rigid drive).
703    ///
704    /// The rigid rope (effects.rope_stretch off) keeps L = l: its tension t is what makes L'' = l''. With each a_k =
705    /// alpha_k + beta_k t (beta = (u_x, u_y, 1) / (M + eta J)) and the load's P'' = -t u / m - g e_z,
706    /// L'' = u . (P'' - T'') + (|d'|^2 - (u . d')^2) / L, d' = P' - T', is linear in t:
707    /// t = (kappa - g u_z - u_x alpha_x - u_y alpha_y - alpha_l) / (1 / m + u_x beta_x + u_y beta_y + beta_l).
708    /// It is a bilateral constraint: where the load would leave the rope slack, t comes out below zero (the rope
709    /// pushes). The reference for a taut rope; the elastic model is the one that goes slack.
710    fn motion(&self, s: &[f64], torque: &[f64]) -> Motion {
711        if self.full {
712            return self.full_motion(s, torque);
713        }
714        let mut rope = self.rope(s);
715        // An obstacle's push on the load (`set_tool_force`), beside its weight; in the rigid rope's tension too.
716        let push = self.push_on().0;
717        let m = self.load_mass();
718        let u = rope.u;
719        let (mut drive, mut brake_rates) = ([0.0; 3], [0.0; 3]);
720        for k in 0..3 {
721            let j = &self.drives[k];
722            let (q, v) = (s[k], s[RATES + k]);
723            (drive[k], brake_rates[k]) =
724                j.rigid_drive(torque[k], j.ratio() * q, j.ratio() * v, s[BRAKES + k], self.brake_engaged);
725        }
726        let d_rate = [s[LOAD_SPEED] - s[RATES], s[LOAD_SPEED + 1] - s[RATES + 1], s[LOAD_SPEED + 2]];
727        let kappa = (dot(d_rate, d_rate) - rope.rate * rope.rate) / rope.length;
728        // The rigid rope with the floor: the load that would sink stands on it (`stand`), its rope slack (a gap beyond
729        // rounding) or taut.
730        let stand = self.floor.filter(|&floor| !self.elastic && s[LOAD + 2] <= floor && s[LOAD_SPEED + 2] <= 0.0);
731        let slack = rope.stretch < -1e-6;
732        let speed_h = [s[LOAD_SPEED], s[LOAD_SPEED + 1]];
733        // One pass: the rolling at tension `t_roll`, the gearboxes' loss factors `loss`: (tension, rolling, a, the
734        // standing rigid load's floor push and friction).
735        let pass = |t_roll: f64, loss: [f64; 3]| -> (f64, [f64; 3], [f64; 3], Option<(f64, [f64; 2])>) {
736            let down = t_roll * -u[2];
737            let wheels = [(self.bridge + self.trolley) * self.g + down, self.trolley * self.g + down];
738            let mut rolling = [0.0; 3];
739            for k in 0..2 {
740                rolling[k] = self.rolling * wheels[k].max(0.0) * (s[RATES + k] / self.rolling_smoothing).tanh();
741            }
742            let (mut alpha, mut beta) = ([0.0; 3], [0.0; 3]);
743            for k in 0..3 {
744                let j = &self.drives[k];
745                let denominator = self.masses[k] + loss[k] * j.reflected_inertia();
746                let force = -rolling[k] + j.output_torque(s[k], s[RATES + k]);
747                alpha[k] = (loss[k] * drive[k] + force) / denominator;
748                beta[k] = [u[0], u[1], 1.0][k] / denominator;
749            }
750            let mut floor = None;
751            let tension = if self.elastic {
752                rope.tension
753            } else {
754                let free = (kappa - self.g * u[2] + dot(u, push) / m - u[0] * alpha[0] - u[1] * alpha[1] - alpha[2])
755                    / (1.0 / m + u[0] * beta[0] + u[1] * beta[1] + beta[2]);
756                if stand.is_some() && (slack || (push[2] - free * u[2]) / m - self.g < 0.0) {
757                    // Standing: the floor holds the load's height (a_z = 0), so L'' = l'' gives t from the horizontal
758                    // part alone, t (u_x^2 + u_y^2 + ...) = kappa + u . F / m - u_x alpha_x - u_y alpha_y - alpha_l, F the
759                    // floor's friction, which takes the floor's push N = m g + t u_z. A slack rope pulls nothing.
760                    let denominator = (u[0] * u[0] + u[1] * u[1]) / m + u[0] * beta[0] + u[1] * beta[1] + beta[2];
761                    let base = kappa - u[0] * alpha[0] - u[1] * alpha[1] - alpha[2];
762                    let (mut t, mut n, mut f) = (0.0, m * self.g, [0.0; 2]);
763                    for _ in 0..6 {
764                        t = if slack {
765                            0.0
766                        } else {
767                            ((base + (u[0] * (f[0] + push[0]) + u[1] * (f[1] + push[1])) / m) / denominator).max(0.0)
768                        };
769                        n = (m * self.g + t * u[2] - push[2]).max(0.0);
770                        f = self.floor_friction_force(n, speed_h);
771                    }
772                    floor = Some((n, f));
773                    t
774                } else {
775                    free
776                }
777            };
778            let pull = [tension * u[0], tension * u[1], if self.elastic { rope.drum } else { tension }];
779            let acc = std::array::from_fn(|k| {
780                alpha[k] + pull[k] / (self.masses[k] + loss[k] * self.drives[k].reflected_inertia())
781            });
782            (tension, rolling, acc, floor)
783        };
784        let guess = if self.elastic { rope.tension } else { m * self.g * -u[2] };
785        // The loss factors of the torques going in, which depend on the accelerations they give: to the fixed point
786        // (`mech::settled_loss`), from the loss-free pass, the rigid rope's tension along.
787        let mut first_tension = guess;
788        let loss = sim_components::mech::settled_loss([1.0; 3], |loss| {
789            let (tension, _, acc, _) = pass(first_tension, *loss);
790            first_tension = tension;
791            std::array::from_fn(|k| {
792                let j = &self.drives[k];
793                j.gearbox.loss_factor(drive[k] - j.reflected_inertia() * acc[k], s[RATES + k])
794            })
795        });
796        // The rigid rope's tension depends on the loss factors (the hoist's eta moves it by some percent) and on the
797        // rolling, which takes the tension: iterated to the fixed point (the rolling changes the tension by some 1e-5 of
798        // itself, so three passes reach 1e-12). The losses are booked with the rolling of the last pass.
799        let (tension, rolling, acc, floor_info) = if self.elastic {
800            pass(first_tension, loss)
801        } else {
802            let mut t = pass(first_tension, loss).0;
803            let mut last = pass(t, loss);
804            for _ in 0..8 {
805                if (last.0 - t).abs() <= 1e-12 * (1.0 + t.abs()) {
806                    break;
807                }
808                t = last.0;
809                last = pass(t, loss);
810            }
811            last
812        };
813        if !self.elastic {
814            (rope.tension, rope.drum) = (tension, tension);
815        }
816        let into: [f64; 3] = std::array::from_fn(|k| drive[k] - self.drives[k].reflected_inertia() * acc[k]);
817        let out = std::array::from_fn(|k| loss[k] * into[k]);
818        let mut load_acc =
819            [(push[0] - tension * u[0]) / m, (push[1] - tension * u[1]) / m, (push[2] - tension * u[2]) / m - self.g];
820        // The floor under the load (one-sided: it pushes, never pulls): standing on it and sinking, the floor takes
821        // what keeps the load at its height, and its friction (Coulomb, smoothed) acts along it.
822        let standing = if self.elastic {
823            self.floor.is_some_and(|floor| s[LOAD + 2] <= floor && s[LOAD_SPEED + 2] <= 0.0 && load_acc[2] < 0.0).then(
824                || {
825                    let n = -m * load_acc[2];
826                    (n, self.floor_friction_force(n, speed_h))
827                },
828            )
829        } else {
830            floor_info
831        };
832        let (mut floor_force, mut floor_power) = (0.0, 0.0);
833        if let Some((n, f)) = standing {
834            floor_force = n;
835            load_acc[2] = 0.0;
836            if self.elastic {
837                load_acc[0] += f[0] / m;
838                load_acc[1] += f[1] / m;
839            } else {
840                load_acc[0] = (push[0] - tension * u[0] + f[0]) / m;
841                load_acc[1] = (push[1] - tension * u[1] + f[1]) / m;
842            }
843            floor_power = -(f[0] * speed_h[0] + f[1] * speed_h[1]);
844        }
845        let pull = [tension * u[0], tension * u[1], rope.drum];
846        Motion {
847            acc,
848            load_acc,
849            into,
850            out,
851            brake_rates,
852            rope: pull,
853            rolling,
854            floor_force,
855            floor_power,
856            rope_state: rope,
857            full: None,
858        }
859    }
860
861    /// Puts the rope's lower end on the rope's line at `length` from the sheave and its speed along it to the drum's
862    /// (the rope's own factor `factor` of the paid-out speed), the speed across the rope kept.
863    fn place_on_rope(&self, s: &mut [f64], length: f64, factor: f64) {
864        let (rope, sheave, trolley) = (self.rope(s), self.sheave(s), self.sheave_speed(s));
865        let speed = [s[LOAD_SPEED], s[LOAD_SPEED + 1], s[LOAD_SPEED + 2]];
866        let along = dot(rope.u, trolley) + s[RATES + 2] * factor - dot(rope.u, speed);
867        for k in 0..3 {
868            s[LOAD + k] = sheave[k] + rope.u[k] * length;
869            s[LOAD_SPEED + k] += rope.u[k] * along;
870        }
871    }
872
873    /// The floor's Coulomb friction on the standing load that pushes it with `n` and slides at the horizontal speed `v`
874    /// (N): mu n tanh(|v| / v_s) against the motion, smoothed over `crane.rolling_smoothing_m_s` like the wheels'.
875    fn floor_friction_force(&self, n: f64, v: [f64; 2]) -> [f64; 2] {
876        self.coulomb(self.floor_friction, n, v)
877    }
878
879    /// Coulomb friction mu n tanh(|v| / v_s) against the horizontal speed `v`, as `floor_friction_force` has it.
880    fn coulomb(&self, mu: f64, n: f64, v: [f64; 2]) -> [f64; 2] {
881        let speed = v[0].hypot(v[1]);
882        if speed == 0.0 || mu == 0.0 {
883            return [0.0; 2];
884        }
885        let f = -mu * n * (speed / self.rolling_smoothing).tanh() / speed;
886        [f * v[0], f * v[1]]
887    }
888
889    /// The load's horizontal offset from under the sheave and its rate.
890    fn sway(&self, s: &[f64]) -> ([f64; 2], [f64; 2]) {
891        let (sheave, speed) = (self.sheave(s), self.sheave_speed(s));
892        let (load, v) = self.lower(s);
893        ([load[0] - sheave[0], load[1] - sheave[1]], [v[0] - speed[0], v[1] - speed[1]])
894    }
895
896    /// The sway's amplitude, sqrt(d^2 + (d' / w)^2) of the horizontal offset d at w = sqrt(g / L): where a free
897    /// pendulum swinging like this would turn back.
898    pub fn sway_amplitude(&self, s: &[f64]) -> f64 {
899        let (d, rate) = self.sway(s);
900        let offset = d[0].hypot(d[1]);
901        match self.sway_omega(self.rope(s).length) {
902            Some(w) => (offset * offset + (rate[0].hypot(rate[1]) / w).powi(2)).sqrt(),
903            None => offset,
904        }
905    }
906
907    /// The rope's pull `drum` on the drum at the hoist's motor (N m): what its brake holds.
908    fn brake_load(&self, drum: f64) -> f64 {
909        drum.abs() / self.drives[2].ratio()
910    }
911
912    /// Per drive the powers lost in its motor's friction with the brake and in its gearbox; then the wheels' rolling of
913    /// bridge and trolley, the rope's damper, the stops, and what the ripple gives off. And per drive the gearbox's loss
914    /// as a torque at the rotor.
915    fn losses(&self, s: &[f64], torque: &[f64], motion: &Motion) -> ([f64; 11], [f64; 3]) {
916        if let Some(extra) = &motion.full {
917            return self.full_losses(s, torque, motion, extra);
918        }
919        let mut powers = [0.0; 11];
920        let mut at_rotor = [0.0; 3];
921        for k in 0..3 {
922            let j = &self.drives[k];
923            let (q, v) = (s[k], s[RATES + k]);
924            let [_, stop, shaft, drag] = j.losses(q, v, j.ratio() * v, s[BRAKES + k], self.brake_engaged);
925            at_rotor[k] = (motion.into[k] - motion.out[k]) / j.ratio();
926            powers[2 * k] = shaft;
927            powers[2 * k + 1] = (motion.into[k] - motion.out[k]) * v + drag;
928            powers[9] += stop;
929            powers[10] += (torque[k] - j.ripple.apply(torque[k], j.ratio() * q)) * j.ratio() * v;
930        }
931        powers[10] += self.pick_loss + motion.floor_power;
932        powers[6] = motion.rolling[0] * s[RATES];
933        powers[7] = motion.rolling[1] * s[RATES + 1];
934        let rope = &motion.rope_state;
935        powers[8] = rope.damper * (rope.rate - s[RATES + 2]);
936        (powers, at_rotor)
937    }
938
939    fn energy_parts(&self, s: &[f64]) -> [f64; 3] {
940        if self.full {
941            return self.full_energy(s);
942        }
943        let m = self.load_mass();
944        let v = [s[LOAD_SPEED], s[LOAD_SPEED + 1], s[LOAD_SPEED + 2]];
945        let mut kinetic = 0.5 * m * dot(v, v);
946        let mut elastic = 0.0;
947        for k in 0..3 {
948            let j = &self.drives[k];
949            kinetic += 0.5 * (self.masses[k] + j.reflected_inertia()) * s[RATES + k].powi(2);
950            elastic += j.stop_energy(s[k]);
951        }
952        let stretch = self.rope(s).stretch;
953        if self.elastic && stretch > 0.0 {
954            elastic += 0.5 * self.ea * stretch * stretch / s[2];
955        }
956        [kinetic, m * self.g * s[LOAD + 2], elastic]
957    }
958}
959
960impl Machine for Crane {
961    /// Bridge (at the middle of its girder), trolley, hook block, load on its sling and the rope (the free rope a point of
962    /// its mass at its middle, moving with the mean of its ends' material: the exact momentum of a linear velocity; the
963    /// wound rope at the sheave) as points; the drives' spin, and the wound rope's turning with the drum, are left out.
964    fn frame_momentum(&self, s: &[f64]) -> Option<sim_core::FrameMomentum> {
965        let mut f = sim_core::FrameMomentum { gravity: [0.0, 0.0, -self.g], ..Default::default() };
966        let add_point = sim_components::base::add_point;
967        add_point(&mut f, self.bridge, [s[0], 0.5 * self.strokes[1], self.height], [s[RATES], 0.0, 0.0]);
968        let (sheave, sheave_speed) = (self.sheave(s), self.sheave_speed(s));
969        add_point(&mut f, self.trolley, sheave, sheave_speed);
970        let load = [s[LOAD], s[LOAD + 1], s[LOAD + 2]];
971        let speed = [s[LOAD_SPEED], s[LOAD_SPEED + 1], s[LOAD_SPEED + 2]];
972        let hook = if self.sling.is_some() { self.hook } else { self.load_mass() };
973        add_point(&mut f, hook, load, speed);
974        if self.sling.is_some() && self.body_mass() > 0.0 {
975            let (place, v) = self.body(s);
976            add_point(&mut f, self.body_mass(), place, v);
977        }
978        if self.rope_mass > 0.0 {
979            // The free rope's top end runs off the sheave at the drum's speed along the rope; the wound rope at the sheave.
980            let (u, paid) = (self.rope(s).u, s[RATES + 2]);
981            let mid = std::array::from_fn(|k| 0.5 * (sheave[k] + load[k]));
982            let v = std::array::from_fn(|k| 0.5 * (sheave_speed[k] + paid * u[k] + speed[k]));
983            add_point(&mut f, self.rope_mass * s[2], mid, v);
984            add_point(&mut f, self.rope_mass * (self.capacity - s[2]), sheave, sheave_speed);
985        }
986        Some(f)
987    }
988
989    fn axes(&self) -> &[AxisInfo] {
990        &self.axes
991    }
992    fn motors(&self) -> &[MotorInfo] {
993        &self.motors
994    }
995
996    /// The rope's highest tension against its rating, how far it fell below the least (none: no slack), the sway left
997    /// at a dwell, and the rope's pull on the hoist's brake.
998    fn rating_checks(&self) -> Vec<RatingCheck> {
999        let check =
1000            |check, signal: &str, motor, limit| RatingCheck { check, signal: signal.into(), motor, limit, life: false };
1001        vec![
1002            check("rope-max-tension", "rope.tension", Some(2), self.t_max),
1003            check("rope-min-tension", "rope.shortfall", Some(2), 0.0),
1004            check("residual-sway", "load.residual_sway", None, self.sway_limit),
1005            check("hoist-brake", "hoist.brake_load", Some(2), self.brake_limit),
1006        ]
1007    }
1008
1009    /// Bridge and trolley under the load, the rope's free length that the empty hook stretches to H - z.
1010    fn inverse(&self, tool: &[f64], motors: &mut [f64]) {
1011        let l = (self.height - tool[2]) / self.kinematic_stretch();
1012        for (k, q) in [tool[0], tool[1], l].into_iter().enumerate() {
1013            motors[k] = self.drives[k].ratio() * q;
1014        }
1015    }
1016
1017    fn forward(&self, motors: &[f64], tool: &mut [f64]) {
1018        let q: Vec<f64> = (0..3).map(|k| motors[k] / self.drives[k].ratio()).collect();
1019        tool[..3].copy_from_slice(&[q[0], q[1], self.height - q[2] * self.kinematic_stretch()]);
1020    }
1021
1022    fn state_len(&self) -> usize {
1023        self.layout.len
1024    }
1025
1026    fn equilibrium(&self, tool: &[f64], state: &mut Vec<f64>, torque: &mut [f64]) {
1027        if self.full {
1028            return self.full_equilibrium(tool, state, torque);
1029        }
1030        // The drum where the motors stand for the pose (`inverse`), the load on it at its own stretch: it hangs below the
1031        // pose by what the payload stretches the rope more than the empty hook.
1032        let l = (self.height - tool[2]) / self.kinematic_stretch();
1033        let load = self.height - l * self.rest_stretch(l);
1034        state.clear();
1035        state.extend([tool[0], tool[1], l, 0.0, 0.0, 0.0, tool[0], tool[1], load]);
1036        state.resize(STATE_LEN, 0.0);
1037        // The rigid rope holds the load's weight as it is.
1038        let drum = if self.elastic { self.rope(state).drum } else { self.load_mass() * self.g };
1039        let pull = [0.0, 0.0, drum];
1040        for k in 0..3 {
1041            let j = &self.drives[k];
1042            // At rest the gearbox holds the axis against the rope and the stops.
1043            let held = -pull[k] - j.output_torque(state[k], 0.0);
1044            torque[k] = j.ripple.invert(held / j.ratio(), j.ratio() * state[k]);
1045        }
1046    }
1047
1048    fn derivatives(&self, s: &[f64], torque: &[f64], out: &mut [f64]) {
1049        if self.full {
1050            return self.full_derivatives(s, torque, out);
1051        }
1052        let motion = self.motion(s, torque);
1053        out[..3].copy_from_slice(&s[RATES..RATES + 3]);
1054        out[RATES..RATES + 3].copy_from_slice(&motion.acc);
1055        out[LOAD..LOAD + 3].copy_from_slice(&s[LOAD_SPEED..LOAD_SPEED + 3]);
1056        out[LOAD_SPEED..LOAD_SPEED + 3].copy_from_slice(&motion.load_acc);
1057        out[BRAKES..BRAKES + 3].copy_from_slice(&motion.brake_rates);
1058    }
1059
1060    /// Where the drives put the hook (`forward` of their angles): the bridge's x, the trolley's y, the height the drum's
1061    /// rope gives the empty hook. The load's sway and its bounce on the rope are not in the tool pose (a crane is
1062    /// positioned by its drives, as its following error and settling say); they have their own signals and the verdict
1063    /// residual-sway.
1064    fn tool_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
1065        let stretch = self.kinematic_stretch();
1066        pos[..3].copy_from_slice(&[s[0], s[1], self.height - s[2] * stretch]);
1067        vel[..3].copy_from_slice(&[s[RATES], s[RATES + 1], -s[RATES + 2] * stretch]);
1068    }
1069
1070    /// Everything moves with the load: bridge and trolley under it, the drum paying out as the rope at its rest stretch.
1071    fn set_tool_velocity(&self, s: &mut [f64], vel: &[f64]) {
1072        s[RATES..RATES + 3].copy_from_slice(&[vel[0], vel[1], -vel[2] / self.kinematic_stretch()]);
1073        s[LOAD_SPEED..LOAD_SPEED + 3].copy_from_slice(&vel[..3]);
1074        if let Some(r0) = self.layout.rotor {
1075            let nd = self.layout.drives;
1076            let axis = [s[RATES], s[RATES + 1], s[RATES + 2], s[RATES]];
1077            for d in 0..nd {
1078                s[r0 + nd + d] = self.drive(d).ratio() * axis[d];
1079            }
1080        }
1081    }
1082
1083    /// The motors' angles: the rotors' with the elastic drives (the bridge's the mean of its two carriages'), else the
1084    /// travels times the ratios.
1085    fn motor_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
1086        if let Some(r0) = self.layout.rotor {
1087            let nd = self.layout.drives;
1088            for k in 0..3 {
1089                (pos[k], vel[k]) = (s[r0 + k], s[r0 + nd + k]);
1090            }
1091            if nd == 4 {
1092                pos[0] = 0.5 * (s[r0] + s[r0 + 3]);
1093                vel[0] = 0.5 * (s[r0 + nd] + s[r0 + nd + 3]);
1094            }
1095            return;
1096        }
1097        for k in 0..3 {
1098            pos[k] = self.drives[k].ratio() * s[k];
1099            vel[k] = self.drives[k].ratio() * s[RATES + k];
1100        }
1101    }
1102
1103    fn feedforward_torque(&self, pos: &[f64], acc: &[f64], out: &mut [f64]) {
1104        self.feedforward_torque_moving(pos, &[0.0; 3], acc, out);
1105    }
1106
1107    /// The rigid model: the load carried along with the trolley (no sway), the rope at its rest stretch; the rope's
1108    /// tension m (g + z'') on the drum with its dV/dl share. Its speed asks nothing (the motor angles are linear in the
1109    /// pose but for the stretch).
1110    fn feedforward_torque_moving(&self, pos: &[f64], _vel: &[f64], acc: &[f64], out: &mut [f64]) {
1111        let m = self.load_mass();
1112        let tension = m * (self.g + acc[2]);
1113        let l = (self.height - pos[2]) / self.kinematic_stretch();
1114        let stretch = if self.elastic { l * tension / self.ea } else { 0.0 };
1115        // The rope's own mass (effects.rope_mass): all of it travels with the trolley, the hanging part's weight and
1116        // inertia pull on the drum, the wound part turns with it.
1117        let (rope, wound) = (self.rope_mass * self.capacity, self.rope_mass * (self.capacity - l));
1118        let drum = tension * (1.0 + stretch / (2.0 * l)) + self.rope_mass * l * (self.g + acc[2]);
1119        let axis_acc = [acc[0], acc[1], -acc[2] / self.kinematic_stretch()];
1120        let force = [
1121            (self.masses[0] + m + rope) * acc[0],
1122            (self.masses[1] + m + rope) * acc[1],
1123            (self.masses[2] + wound) * axis_acc[2] - drum,
1124        ];
1125        for k in 0..3 {
1126            let j = &self.drives[k];
1127            // The bridge's two carriages' rotors turn for the one command (shared equally).
1128            let rotors = if k == 0 && self.skew.is_some() { 2.0 } else { 1.0 };
1129            out[k] = force[k] / j.ratio() + rotors * j.rotor_inertia * j.ratio() * axis_acc[k];
1130        }
1131    }
1132
1133    /// At a steady speed: the motor shaft's friction and, through the gearbox as `motion` takes it, the wheels' rolling
1134    /// under the load hanging still.
1135    fn steady_friction(&self, pos: &[f64], vel: &[f64], out: &mut [f64]) {
1136        let mut held = [0.0; 3];
1137        self.feedforward_torque(pos, &[0.0; 3], &mut held);
1138        let down = self.load_mass() * self.g;
1139        let wheels = [(self.bridge + self.trolley) * self.g + down, self.trolley * self.g + down, 0.0];
1140        let speeds = [vel[0], vel[1], -vel[2] / self.kinematic_stretch()];
1141        for (k, j) in self.drives.iter().enumerate() {
1142            let (i, v) = (j.ratio(), speeds[k]);
1143            let rolling = self.rolling * wheels[k] * (v / self.rolling_smoothing).tanh();
1144            let shaft = if k == 0 && self.skew.is_some() { 2.0 } else { 1.0 } * j.shaft.torque(i * v);
1145            out[k] = shaft + rolling / (i * j.gearbox.loss_factor(i * held[k] + rolling, v));
1146        }
1147    }
1148
1149    fn energy(&self, s: &[f64]) -> f64 {
1150        self.energy_parts(s).iter().sum()
1151    }
1152
1153    /// With the hook block and the floor a payload let go stays in the machine as a free body (`free`); a pick takes it
1154    /// where it is when the sling reaches it (`in_place`), else this payload is gone and the next appears under the hook
1155    /// block (`appear`). Without them it leaves with the grip, as the payload of a pick did.
1156    fn set_payload_attached(&mut self, attached: bool) {
1157        if attached == self.attached {
1158            return;
1159        }
1160        self.picked = true;
1161        if attached {
1162            self.in_place = self.free && self.sling.is_some_and(|ls| self.reach <= ls);
1163            self.appear = self.free && !self.in_place;
1164            self.free = false;
1165        } else {
1166            self.free = self.payload > 0.0 && self.sling.is_some() && self.floor.is_some();
1167        }
1168        self.attached = attached;
1169    }
1170
1171    /// With the hook block and the floor: the payload stands on the floor under the hook block (`after_step`), so a hook
1172    /// block hanging lower over the floor than the two boxes' half heights (0.28 m, `full::faces`) would already be
1173    /// inside it, which pushing it out would make energy.
1174    fn refuses_pick(&self, tool_pose: &[f64]) -> Option<&'static str> {
1175        let floor = self.floor.filter(|_| self.layout.sling.is_some())?;
1176        (tool_pose.len() == 3 && tool_pose[2] - floor < 0.5 * (HOOK_BOX[2] + PAYLOAD_BOX[2]))
1177            .then_some("error-pick-hook-in-payload")
1178    }
1179
1180    /// Pick and set-down are quasi-static: a load slung on the floor goes on as the hoist takes its weight up slowly,
1181    /// and comes off as it is set down. So once the payload went on or off, the load moves along the rope to where the
1182    /// rope's free length holds the new mass at rest, L = l (1 + m g / EA), and its speed along the rope to the drum's
1183    /// (the rest across the rope, its sway, is kept). Not done, the rope would snatch the new load from rest (to twice its
1184    /// weight) and fling the empty hook up off a slack rope. What that changes in the energy (the floor's share of the
1185    /// lift, some 0.1 J) is booked with `power.other` over this step.
1186    ///
1187    /// With effects.floor_contact the floor is modelled where the load stands on it (`motion`: the floor force N >= 0,
1188    /// N = -m a_z of the free load, which then stays at `crane.floor_height_m`): a payload's mass goes on without a jump
1189    /// of the rope (the floor carries it), the rope's tension takes the weight over as the drum winds (the snatch of a
1190    /// fast lift is the rope's stretch at the drum's speed, t = EA e / l, until t |u_z| = m g), and a slack rope on
1191    /// lowering leaves the load standing. The load's fall onto the floor is plastic: its downward speed is lost
1192    /// (m v^2 / 2, booked with `power.other`). Above the floor the pick is quasi-static as before.
1193    ///
1194    /// The standing load rubs on the floor with Coulomb friction mu_f N (`motion`), N the floor's push; the plain rigid rope
1195    /// respects the floor too: its load stands with the rope slack (the drum paying out, nothing pulls), and where the rope
1196    /// comes taut (L > l) the load is lifted to l at once with its speed along the rope made the drum's, a plastic
1197    /// impact whose energy is booked with `power.other`. With the sling the payload's point is the one that stands.
1198    fn after_step(&mut self, s: &mut [f64], dt: f64) {
1199        self.pick_loss = 0.0;
1200        if let Some(r0) = self.layout.rotor {
1201            for d in 0..self.layout.drives {
1202                let (pos, _) = self.travel(s, d);
1203                self.drive_mut(d).gearbox.commit(s[r0 + d], pos);
1204            }
1205        }
1206        let picked = std::mem::take(&mut self.picked);
1207        let in_place = std::mem::take(&mut self.in_place);
1208        // The payload carried through the grip where it is (let go: free; picked again where it lies): it keeps its
1209        // place and speed when the rope takes the hook block to its new rest.
1210        let keep = self.free || in_place;
1211        if !picked && self.floor.is_none() && self.faces(s).is_empty() {
1212            self.measure_reach(s);
1213            return;
1214        }
1215        let (before, empty) = (self.energy(s), self.body_mass() == 0.0);
1216        if let (true, Some(a0)) = (empty || (picked && self.attached && !in_place), self.layout.sling) {
1217            // The payload goes on plumb under the hook block at its speed, the sling at its rest stretch (the sling at
1218            // rest when it was picked: what the payload's energy was counted at); turning the sling into the rope's line
1219            // here would lift the payload and spin it at the rope's rate, energy from nowhere. Nothing on it, the sling
1220            // rests plumb at its length. Neither below the floor: a payload picked there stands on it, the sling slack,
1221            // and the empty sling's span follows the floor so that the payload is counted where it stands. A payload let
1222            // go is a body of the equations and stays where it is; one picked where it lies likewise (`in_place`).
1223            let [x, y, z] = self.appear_span(s);
1224            s[a0..a0 + 6].copy_from_slice(&[x, y, z, 0.0, 0.0, 0.0]);
1225        }
1226        self.appear = false;
1227        let mut standing = false;
1228        if let Some(floor) = self.floor {
1229            let (low, low_v) = self.body(s);
1230            // P2 = P1 + d rounds: the sling's payload stands within 1e-12 m of the floor.
1231            standing = low[2] <= floor + FLOOR_ROUNDING;
1232            if standing && (low[2] < floor || low_v[2] < 0.0) {
1233                // With the sling the payload stands (its span shortens, the sling going slack), not the hook block.
1234                let (at, rate, (base, base_v)) = match self.layout.sling {
1235                    Some(a0) if self.body_mass() > 0.0 => (a0 + 2, a0 + 5, (s[LOAD + 2], s[LOAD_SPEED + 2])),
1236                    _ => (LOAD + 2, LOAD_SPEED + 2, (0.0, 0.0)),
1237                };
1238                s[at] = floor - base;
1239                if low_v[2] < 0.0 {
1240                    s[rate] = -base_v;
1241                }
1242            }
1243        }
1244        // The hook block's box into the payload's within this step, through its top, its bottom or a side (`faces`; the
1245        // top first where both qualify, else the shallowest): plastic, put back on that face (the payload where it is; a
1246        // payload that fell onto the hook block's top is put back up on it, the hook block where it is) and the two at
1247        // one speed across it: on the top the payload's where it stands on the floor, else their common momentum's.
1248        // Booked with the pick's loss. Only what came in within this step: a hook block already deeper (a payload
1249        // picked under a hook block hanging lower than 0.28 m over it) is left as it was, which pushing it out would
1250        // make energy.
1251        let landed = self
1252            .faces(s)
1253            .into_iter()
1254            .filter(|f| (f.depth > 0.0 || f.rate > 0.0) && f.depth <= f.rate.max(0.0) * dt + FLOOR_ROUNDING)
1255            .min_by(|a, b| (a.k != 2).cmp(&(b.k != 2)).then(a.depth.total_cmp(&b.depth)));
1256        if let Some(f) = landed {
1257            let k = f.k;
1258            match self.layout.sling.filter(|_| self.body_mass() > 0.0) {
1259                Some(a0) => {
1260                    let from_above = k == 2 && f.sigma < 0.0;
1261                    if !from_above {
1262                        s[LOAD + k] += f.sigma * f.depth;
1263                    }
1264                    s[a0 + k] -= f.sigma * f.depth;
1265                    let (v1, v2) = (s[LOAD_SPEED + k], s[LOAD_SPEED + k] + s[a0 + 3 + k]);
1266                    let (m1, m2) = (self.hook, self.body_mass());
1267                    let v = if standing && k == 2 && !from_above { v2 } else { (m1 * v1 + m2 * v2) / (m1 + m2) };
1268                    (s[LOAD_SPEED + k], s[a0 + 3 + k]) = (v, 0.0);
1269                }
1270                None => {
1271                    s[LOAD + k] += f.sigma * f.depth;
1272                    s[LOAD_SPEED + k] = 0.0;
1273                }
1274            }
1275        }
1276        if self.floor.is_some() && !self.elastic && self.rope(s).stretch > 1e-9 {
1277            // The taut rope lifts the hook block alone: the payload stays where it is, its span (an elastic sling) taking
1278            // the move; carried along it was lifted with it, through its own landing or off the floor.
1279            let before: Vec<f64> = (0..3).flat_map(|k| [s[LOAD + k], s[LOAD_SPEED + k]]).collect();
1280            self.place_on_rope(s, s[2], 1.0);
1281            if let Some(a0) = self.layout.sling {
1282                for k in 0..3 {
1283                    s[a0 + k] -= s[LOAD + k] - before[2 * k];
1284                    s[a0 + 3 + k] -= s[LOAD_SPEED + k] - before[2 * k + 1];
1285                }
1286            }
1287        }
1288        // Not on a slack rope: the hook block rests on something (the payload set down), nothing hangs on the rope.
1289        if picked && !standing && self.rope(s).stretch >= 0.0 {
1290            if self.layout.rotor.is_some() {
1291                // The hoist's gearbox takes the new weight as quasi-statically as the rope: the servo holds the rotor,
1292                // the drum gives by the change of the static twist (0.78 mm for the 250 kg at the shipped stiffness).
1293                let j = &self.drives[2];
1294                let old = self.load_mass() + if self.attached { -self.payload } else { self.payload };
1295                let twist =
1296                    |mass: f64, l: f64| j.gearbox.static_twist(-self.rest_pull(l, mass) - j.output_torque(l, 0.0));
1297                let shift = twist(self.load_mass(), s[2]) - twist(old, s[2]);
1298                s[2] -= shift;
1299            }
1300            let factor = self.rest_stretch(s[2]);
1301            let carried = self.layout.sling.filter(|_| keep && self.body_mass() > 0.0).map(|a0| (a0, self.body(s)));
1302            self.place_on_rope(s, s[2] * factor, factor);
1303            if let Some((a0, (place, speed))) = carried {
1304                for k in 0..3 {
1305                    s[a0 + k] = place[k] - s[LOAD + k];
1306                    s[a0 + 3 + k] = speed[k] - s[LOAD_SPEED + k];
1307                }
1308            }
1309        }
1310        self.pick_loss += (before - self.energy(s)) / dt;
1311        self.measure_reach(s);
1312    }
1313
1314    /// What the gearboxes' hysteresis carries between steps (elastic drives only).
1315    fn memory(&self) -> Vec<f64> {
1316        if !self.elastic_drives {
1317            return Vec::new();
1318        }
1319        sim_components::mech::Gearbox::anchors(self.drives.iter().chain(self.side_b.iter()).map(|j| &j.gearbox))
1320    }
1321    fn set_memory(&mut self, memory: &[f64]) {
1322        if self.elastic_drives {
1323            sim_components::mech::Gearbox::set_anchors(
1324                self.drives.iter_mut().chain(self.side_b.iter_mut()).map(|j| &mut j.gearbox),
1325                memory,
1326            );
1327        }
1328    }
1329    fn set_dwelling(&mut self, dwelling: bool) {
1330        self.dwelling = dwelling;
1331    }
1332    fn set_brake_engaged(&mut self, engaged: bool) {
1333        self.brake_engaged = engaged;
1334    }
1335    /// A stop met within the step (`HardStop::substeps`, `RotaryJoint::stop_substeps`).
1336    fn substeps_wanted(&self, s: &[f64], _torque: &[f64], dt: f64, _substeps: u32) -> u32 {
1337        if self.full {
1338            let at = |d: usize| (self.travel(s, d), self.drive(d));
1339            return (0..self.layout.drives)
1340                .map(at)
1341                .map(|((pos, speed), j)| j.stop_substeps(pos, speed, dt))
1342                .max()
1343                .unwrap_or(1);
1344        }
1345        (0..3).map(|k| self.drives[k].stop_substeps(s[k], s[RATES + k], dt)).max().unwrap_or(1)
1346    }
1347    /// The push acts where the parts that touch are: on the hook's point (with it the payload under it), and with the
1348    /// hook block on the hook block's and the payload's at the sling's end (`push_on`); its power is the crash row.
1349    fn set_tool_force(&mut self, force: &[f64]) -> bool {
1350        self.push.clear();
1351        self.push.extend_from_slice(force);
1352        true
1353    }
1354    fn contact_axes(&self) -> usize {
1355        if self.sling.is_some() { 6 } else { 3 }
1356    }
1357    /// The hook's point P (the payload hangs on it, 0.3 m below), and with the hook block the payload's P2 = P1 + d.
1358    fn contact_state(&self, s: &[f64], pos: &mut [f64], vel: &mut [f64]) {
1359        pos[..3].copy_from_slice(&s[LOAD..LOAD + 3]);
1360        vel[..3].copy_from_slice(&s[LOAD_SPEED..LOAD_SPEED + 3]);
1361        if let Some(a) = self.layout.sling {
1362            for k in 0..3 {
1363                (pos[3 + k], vel[3 + k]) = (s[LOAD + k] + s[a + k], s[LOAD_SPEED + k] + s[a + 3 + k]);
1364            }
1365        }
1366    }
1367    fn contact_placed(&self, s: &[f64], at: &[f64], out: &mut Vec<f64>) {
1368        out.clear();
1369        out.extend_from_slice(s);
1370        out[LOAD..LOAD + 3].copy_from_slice(&at[..3]);
1371        if let Some(a) = self.layout.sling {
1372            for k in 0..3 {
1373                out[a + k] = at[3 + k] - at[k];
1374            }
1375        }
1376    }
1377
1378    /// The gearboxes, in the order of `thermal_parts`.
1379    fn set_part_temperatures(&mut self, rises: &[f64]) {
1380        let Some(law) = &self.thermal else { return };
1381        for (drive, rise) in self.drives.iter_mut().filter(|d| !d.coupled).zip(rises) {
1382            drive.gearbox.efficiency = law.gearbox_efficiency(*rise) * drive.extra_efficiency;
1383            drive.shaft.set_oil(law.viscosity_factor(*rise));
1384        }
1385        // The second carriage's gearbox is the bridge's twin and warms with it.
1386        if let (Some(b), Some(rise)) = (self.side_b.as_mut(), rises.first()) {
1387            b.gearbox.efficiency = law.gearbox_efficiency(*rise) * b.extra_efficiency;
1388            b.shaft.set_oil(law.viscosity_factor(*rise));
1389        }
1390    }
1391
1392    /// The payload's own stretch on the longest rope (`kinematic_stretch`), and the default's 0.1 mm.
1393    fn setpoint_slack(&self) -> f64 {
1394        (self.height - self.axes[2].min) * self.payload * self.g / self.ea + 1e-4
1395    }
1396
1397    /// The load's sway on its rope at the pose: sqrt(g / L) / (2 pi), L = H - z.
1398    fn resonance_hz(&self, tool_pose: &[f64]) -> Option<f64> {
1399        self.sway_omega(self.height - tool_pose[2]).map(|w| w / TAU)
1400    }
1401
1402    /// The swing of `resonance_hz` and, with the hook block, the double pendulum's upper mode (`sway_omegas`), with the
1403    /// trolley held as `resonance_hz` has it (the swing has no damper of its own); the load's bounce on the elastic rope
1404    /// (and the sling), with effects.joint_elasticity the drives' modes, with the motors held (`held_modes`); with
1405    /// effects.bridge_skew the girder's yaw (`skew_modes`). Lowest first.
1406    fn modes(&self, tool_pose: &[f64]) -> Vec<sim_core::Mode> {
1407        let length = self.height - tool_pose[2];
1408        let (lower, upper) = self.sway_omegas(length).map_or((None, None), |(lower, upper)| (Some(lower), upper));
1409        let mut out: Vec<sim_core::Mode> =
1410            [lower, upper].into_iter().flatten().map(|w| sim_core::Mode { hz: w / TAU, damping: 0.0 }).collect();
1411        out.extend(self.held_modes(length / self.kinematic_stretch()));
1412        out.extend(self.skew_modes(tool_pose[1]));
1413        out.sort_by(|a, b| a.hz.total_cmp(&b.hz));
1414        out
1415    }
1416
1417    /// The swings alone (the shaper acts on them, not on the bounce, the drives or the skew): the load's, and with the
1418    /// hook block the double pendulum's upper one.
1419    fn sway_modes(&self, tool_pose: &[f64]) -> Vec<sim_core::Mode> {
1420        let (lower, upper) = self.sway_omegas(self.height - tool_pose[2]).map_or((None, None), |(l, u)| (Some(l), u));
1421        [lower, upper].into_iter().flatten().map(|w| sim_core::Mode { hz: w / TAU, damping: 0.0 }).collect()
1422    }
1423
1424    fn signal_infos(&self) -> Vec<SignalInfo> {
1425        let mut out = vec![
1426            SignalInfo::new("rope.tension", "group-rope", "quantity-rope-tension", "N"),
1427            SignalInfo::new("rope.shortfall", "group-rope", "quantity-rope-shortfall", "N"),
1428            SignalInfo::new("rope.length", "group-rope", "quantity-rope-length", "m"),
1429            SignalInfo::new("load.sway_angle", "group-load", "quantity-sway-angle", "rad"),
1430            SignalInfo::new("load.sway", "group-load", "quantity-sway", "m"),
1431            SignalInfo::new("load.residual_sway", "group-load", "quantity-residual-sway", "m"),
1432            SignalInfo::new("load.floor_force", "group-load", "quantity-floor-force", "N"),
1433            SignalInfo::new("hoist.brake_load", "group-hoist", "quantity-brake-load", "N m"),
1434        ];
1435        if self.sling.is_some() {
1436            out.push(SignalInfo::new("load.sling_angle", "group-load", "quantity-sling-angle", "rad"));
1437        }
1438        if self.skew.is_some() {
1439            out.extend([
1440                SignalInfo::new("bridge.skew_angle", "group-bridge", "quantity-skew-angle", "rad"),
1441                SignalInfo::new("bridge.travel_a", "group-bridge", "quantity-bridge-travel", "m"),
1442                SignalInfo::new("bridge.travel_b", "group-bridge", "quantity-bridge-travel", "m"),
1443                SignalInfo::new("bridge.torque_a", "group-bridge", "quantity-bridge-torque", "N m"),
1444                SignalInfo::new("bridge.torque_b", "group-bridge", "quantity-bridge-torque", "N m"),
1445            ]);
1446        }
1447        for motor in &self.motors {
1448            out.extend(TORQUE_PARTS.map(|part| {
1449                SignalInfo::new(
1450                    format!("motor.{}.torque_{part}", motor.id),
1451                    motor.key,
1452                    &format!("quantity-torque-{part}"),
1453                    "N m",
1454                )
1455            }));
1456        }
1457        for k in 0..3 {
1458            out.push(SignalInfo::new(
1459                format!("{LOSS_PREFIX}shaft_{}", MOTOR_IDS[k]),
1460                MOTOR_KEYS[k],
1461                "quantity-shaft-friction-power",
1462                "W",
1463            ));
1464            let quantity =
1465                if self.drives[k].coupled { "quantity-coupling-loss-power" } else { "quantity-gearbox-loss-power" };
1466            out.push(SignalInfo::new(format!("{LOSS_PREFIX}gearbox_{}", MOTOR_IDS[k]), MOTOR_KEYS[k], quantity, "W"));
1467        }
1468        out.push(SignalInfo::new(
1469            format!("{LOSS_PREFIX}rolling_bridge"),
1470            "group-bridge",
1471            "quantity-friction-power",
1472            "W",
1473        ));
1474        out.push(SignalInfo::new(
1475            format!("{LOSS_PREFIX}rolling_trolley"),
1476            "group-trolley",
1477            "quantity-friction-power",
1478            "W",
1479        ));
1480        out.push(SignalInfo::new(format!("{LOSS_PREFIX}rope"), "group-rope", "quantity-damping-power", "W"));
1481        out.push(SignalInfo::new(format!("{LOSS_PREFIX}hard_stops"), "group-crane", "quantity-damping-power", "W"));
1482        out.push(SignalInfo::new(format!("{LOSS_PREFIX}other"), "loss-other", "quantity-power-given-off", "W"));
1483        out.extend(ENERGY_PARTS.map(|part| {
1484            SignalInfo::new(format!("energy.{part}"), "group-energy", &format!("quantity-energy-{part}"), "J")
1485        }));
1486        out
1487    }
1488
1489    fn base_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
1490        // The rigid rope's tension is the motion's; `half` below adds the rope's weight to it.
1491        let mut rope = self.rope(s);
1492        if !self.elastic {
1493            rope.tension = self.motion(s, torque).rope_state.tension;
1494            rope.drum = rope.tension;
1495        }
1496        let (d, _) = self.sway(s);
1497        let offset = d[0].hypot(d[1]);
1498        let residual = if self.dwelling { self.sway_amplitude(s) } else { 0.0 };
1499        let floor = if self.floor.is_some() { self.motion(s, torque).floor_force } else { 0.0 };
1500        // With the rope's own mass the tension grows down to up by the weight below: the signal is the drum's end
1501        // (the highest), the shortfall is judged at the hook's end (the least); `rope.tension` is their mean.
1502        let half = 0.5 * self.rope_mass * self.g * (self.height - s[LOAD + 2]);
1503        out.extend([
1504            rope.tension + half,
1505            (self.t_min - (rope.tension - half)).max(0.0),
1506            rope.length,
1507            offset.atan2(self.height - self.lower(s).0[2]),
1508            offset,
1509            residual,
1510            floor,
1511            self.brake_load(rope.drum + half),
1512        ]);
1513        if let Some(sl) = self.sling_state(s) {
1514            out.push(sl.u[2].abs().min(1.0).acos());
1515        }
1516        if let (Some(_), Some(i)) = (self.skew, self.layout.skew) {
1517            let torque_of = |d: usize| {
1518                let j = self.drive(d);
1519                let rotor = self.layout.rotor.map_or(j.ratio() * self.travel(s, d).0, |r0| s[r0 + d]);
1520                j.ripple.apply(self.command(torque, d), rotor)
1521            };
1522            out.extend([s[i], self.travel(s, 0).0, self.travel(s, 3).0, torque_of(0), torque_of(3)]);
1523        }
1524    }
1525
1526    /// Torque breakdown per motor: inertia (the axis's own mass and rotor), gravity (the rope's pull on the axis: the
1527    /// load's weight on the hoist, the swing's pull on the travel drives), friction (motor shaft, brake, gearbox loss,
1528    /// the wheels' rolling), the rest (ripple, stops). Then the loss powers and the energies.
1529    fn effect_signals(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
1530        let motion = self.motion(s, torque);
1531        let (powers, at_rotor) = self.losses(s, torque, &motion);
1532        for k in 0..3 {
1533            let j = &self.drives[k];
1534            let a = motion.acc[k];
1535            let (speed, rotor_acc) = match (&motion.full, self.layout.rotor) {
1536                (Some(ex), Some(r0)) => (s[r0 + self.layout.drives + k], j.rotor_inertia * ex.rotor_acc[k]),
1537                _ => (j.ratio() * s[RATES + k], j.rotor_inertia * j.ratio() * a),
1538            };
1539            let held = j.brake.torque(self.brake_engaged, speed, s[BRAKES + k]).0;
1540            let parts = [
1541                self.masses[k] * a / j.ratio() + rotor_acc,
1542                -motion.rope[k] / j.ratio(),
1543                j.shaft.torque(speed) + held + at_rotor[k] + motion.rolling[k] / j.ratio(),
1544            ];
1545            out.extend(parts);
1546            out.push(torque[k] - parts.iter().sum::<f64>());
1547        }
1548        out.extend(powers);
1549        out.extend(self.energy_parts(s));
1550    }
1551    fn loss_powers(&self, s: &[f64], torque: &[f64], out: &mut Vec<f64>) {
1552        out.extend(self.losses(s, torque, &self.motion(s, torque)).0);
1553    }
1554
1555    fn thermal_parts(&self) -> Vec<ThermalPart> {
1556        (0..3)
1557            .filter(|k| !self.drives[*k].coupled)
1558            .enumerate()
1559            .map(|(i, k)| ThermalPart {
1560                id: GEARBOX_IDS[k],
1561                kind: "gearbox",
1562                owner_key: MOTOR_KEYS[k],
1563                scene_part: "gearbox",
1564                scene_index: i,
1565            })
1566            .collect()
1567    }
1568
1569    /// The runway's rails on their columns, the bridge's girder, the trolley with its drum, each drive's motor and
1570    /// gearbox, the rope coloured by its tension against the load's weight, the hook and the load under it.
1571    fn scene(&self, s: &[f64], out: &mut Scene) {
1572        out.parts.clear();
1573        out.labels.clear();
1574        // The rigid rope's tension needs the torques, which a scene does not have: it shows the load's weight.
1575        let mut rope = self.rope(s);
1576        if !self.elastic {
1577            rope.tension = self.load_mass() * self.g;
1578        }
1579        let (xc, y, h) = (s[0], s[1], self.height);
1580        // The trolley is on the girder, which a skew turns: at the sheave's x.
1581        let x = self.sheave(s)[0];
1582        let span = self.strokes[1];
1583        let (steel, dark) = ([0.55, 0.57, 0.6], [0.25, 0.25, 0.28]);
1584        let rail = h + 0.25;
1585        // The steel as boxes (a segment is a flat strip, for belts and the rope): rails on their columns, the girder.
1586        let length = self.strokes[0] + 1.0;
1587        for side in [-0.3, span + 0.3] {
1588            let rails = Shape::Box { size: [length, 0.15, 0.15] };
1589            out.parts.push(Part::new("rail", rails, [0.5 * self.strokes[0], side, rail], steel));
1590            for end in [-0.5, self.strokes[0] + 0.5] {
1591                let column = Shape::Box { size: [0.2, 0.2, rail - 0.075] };
1592                out.parts.push(Part::new("column", column, [end, side, 0.5 * (rail - 0.075)], steel));
1593            }
1594        }
1595        let yellow = [0.85, 0.65, 0.1];
1596        let (psi, _) = self.yaw(s);
1597        if self.skew.is_some() {
1598            // The girder yawed by psi (x = x_c + psi (y - y_c)): drawn upright along z, turned by -psi, then laid flat.
1599            let girder = Shape::Box { size: [0.3, 0.35, span + 0.9] };
1600            let mut part = Part::new("bridge", girder, [xc, -(rail + 0.25), 0.5 * span], yellow).turned(-psi);
1601            part.lay_flat();
1602            out.parts.push(part);
1603        } else {
1604            let girder = Shape::Box { size: [0.3, span + 0.9, 0.35] };
1605            out.parts.push(Part::new("bridge", girder, [xc, 0.5 * span, rail + 0.25], yellow));
1606        }
1607        out.parts.push(Part::new("trolley", Shape::Box { size: [0.6, 0.5, 0.3] }, [x, y, h + 0.15], dark));
1608        out.parts.push(
1609            Part::new(
1610                "drum",
1611                Shape::Cylinder { radius: self.drum_radius, length: 0.4 },
1612                [x + 0.15, y, h + 0.15],
1613                [0.75, 0.75, 0.78],
1614            )
1615            .turned(s[2] / self.drum_radius),
1616        );
1617        // Each drive: motor, its rotor's bar, gearbox; the bridge's at the girder's end, the others on the trolley.
1618        let side_a = self.travel(s, 0).0;
1619        let places = [[side_a - 0.45, -0.3, rail + 0.15], [x - 0.45, y + 0.15, h + 0.15], [x + 0.45, y, h + 0.15]];
1620        for (k, place) in places.iter().enumerate() {
1621            let j = &self.drives[k];
1622            out.parts.push(Part::new(
1623                sim_core::scene::MOTOR_PART,
1624                Shape::Box { size: [0.14, 0.14, 0.14] },
1625                add(*place, [0.0, 0.0, 0.2]),
1626                [0.9, 0.45, 0.1],
1627            ));
1628            out.parts.push(
1629                Part::new(
1630                    "rotor-bar",
1631                    Shape::Box { size: [0.12, 0.006, 0.02] },
1632                    add(*place, [0.0, 0.0, 0.3]),
1633                    [0.1; 3],
1634                )
1635                .turned(j.ratio() * s[k]),
1636            );
1637            out.parts.push(Part::new("gearbox", Shape::Box { size: [0.1, 0.1, 0.1] }, *place, dark));
1638            out.labels.push(Label {
1639                pos: add(*place, [0.0, 0.0, 0.45]),
1640                owner_key: MOTOR_KEYS[k],
1641                value: j.ratio() * s[RATES + k] * 60.0 / TAU,
1642                unit_key: "unit-rpm",
1643                decimals: 0,
1644            });
1645        }
1646        let load = [s[LOAD], s[LOAD + 1], s[LOAD + 2]];
1647        let sway = self.sway(s);
1648        let weight = (self.load_mass() * self.g).max(1.0);
1649        out.parts.push(
1650            Part::new("rope", Shape::Segment { to: load, width: 0.04 }, self.sheave(s), sim_core::scene::BELT_COLOR)
1651                .highlighted(((rope.tension - weight) / weight).clamp(-1.0, 1.0) as f32),
1652        );
1653        out.parts.push(Part::new("hook", Shape::Box { size: HOOK_BOX }, load, [0.9, 0.75, 0.1]));
1654        if self.attached && self.payload > 0.0 {
1655            // With the sling the payload hangs at its end (its centre there, the sling a line to the hook block).
1656            let place = if self.sling.is_some() {
1657                let low = self.lower(s).0;
1658                out.parts.push(Part::new(
1659                    "sling",
1660                    Shape::Segment { to: low, width: 0.02 },
1661                    load,
1662                    sim_core::scene::BELT_COLOR,
1663                ));
1664                low
1665            } else {
1666                add(load, [0.0, 0.0, -0.3])
1667            };
1668            out.parts.push(Part::new("payload", Shape::Box { size: PAYLOAD_BOX }, place, [0.2, 0.5, 0.75]));
1669        }
1670        if self.free {
1671            let place = self.body(s).0;
1672            out.parts.push(Part::new("payload-set-down", Shape::Box { size: PAYLOAD_BOX }, place, [0.2, 0.5, 0.75]));
1673        }
1674        out.labels.push(Label {
1675            pos: add(self.sheave(s), [0.0, 0.0, -0.5 * rope.length]),
1676            owner_key: "group-rope",
1677            value: rope.tension,
1678            unit_key: "unit-n",
1679            decimals: 0,
1680        });
1681        out.labels.push(Label {
1682            pos: add(load, [0.4, 0.0, 0.0]),
1683            owner_key: "group-load",
1684            value: sway.0[0].hypot(sway.0[1]) * 1e3,
1685            unit_key: "unit-mm",
1686            decimals: 0,
1687        });
1688    }
1689
1690    fn scene_point(&self, tool: &[f64]) -> Option<[f64; 3]> {
1691        Some([tool[0], tool[1], tool[2]])
1692    }
1693    fn collision_bodies(&self, s: &[f64]) -> Vec<sim_core::Aabb> {
1694        let mut scene = Scene::default();
1695        self.scene(s, &mut scene);
1696        sim_core::scene::scene_boxes(&scene.parts, &["hook", "payload"])
1697    }
1698}
1699
1700#[cfg(test)]
1701mod tests;
1702#[cfg(test)]
1703mod tests_full;