Skip to main content

sim_app/
session.rs

1//! The simulation in its own thread, on its own clock. The interface sends requests and reads
2//! samples from a channel; it never blocks the physics, and the physics never waits for a frame.
3
4use sim_components::{Command, LimitViolation, Sim};
5use sim_core::{AxisInfo, Config, ConfigError, Label, MachineEntry, MotorInfo, Scene, SignalInfo};
6use std::collections::VecDeque;
7use std::sync::mpsc::{Sender, TryRecvError, channel};
8use std::sync::{Arc, Mutex};
9use std::thread::JoinHandle;
10use std::time::{Duration, Instant};
11
12#[derive(Debug, Clone)]
13pub enum Request {
14    Command(Command),
15    /// A changed config for the running simulation: parameters and effect switches.
16    Reconfigure(Config),
17    Pause(bool),
18    /// Simulated seconds per real second: 1 is real time, below 1 slow motion.
19    Speed(f64),
20    /// How many times larger the 3D view draws the parts' deflections (`Scene::exaggeration`).
21    Exaggeration(f64),
22    /// The 3D view shows the machine swinging in its mode (`mode_scene`) in place of the live state, which waits.
23    Mode(bool),
24    /// The mode `mode_scene` shows: one picked from the mode list (`insight::mode_views`), or `None` for the one the
25    /// machine gives (`Machine::mode_shape`).
26    ModeShape(Option<crate::insight::ShownMode>),
27    Quit,
28}
29
30#[derive(Debug, Clone)]
31pub enum Event {
32    /// One row of every signal, in the order of the signal list.
33    Sample(Vec<f64>),
34    Scene(Scene),
35    /// The travelled path starts anew at this place in the scene: the machine has taken a trajectory. `None`
36    /// ends it: the machine was reconfigured, started its cycle, or has no place for its tool in the scene.
37    TrailStart(Option<[f64; 3]>),
38    /// Where the tool has been since, in order: a point per 0.1 mm of travel, from every simulation step.
39    Trail(Vec<[f64; 3]>),
40    /// A refused command, as a translation key and a detail.
41    Refused(&'static str, String),
42    Limits(Vec<LimitViolation>),
43    /// The answer to `Request::Reconfigure`, one for each: the config was taken, with the axis limits that
44    /// ask too much of the motors under it, or it was refused, with a translation key and a detail.
45    Configured(Result<Vec<LimitViolation>, (&'static str, String)>),
46}
47
48/// Samples the interface may be behind by: ten seconds at real time. Beyond that the oldest are dropped.
49pub const BACKLOG: usize = 10_000;
50
51/// Points of the travelled path that are kept: 10 m of travel. Beyond that the oldest are dropped.
52pub const TRAIL: usize = 100_000;
53
54/// Adds points to a travelled path and keeps the newest `TRAIL` of it.
55pub fn extend_trail(trail: &mut Vec<[f64; 3]>, points: &[[f64; 3]]) {
56    trail.extend_from_slice(points);
57    trail.drain(..trail.len().saturating_sub(TRAIL));
58}
59
60/// A point of the travelled path with what the 3D view may colour it by: the nearest point of the path the plan drew,
61/// in the scene, and how fast the tool went; and the simulated time it was passed, for cutting the path at the
62/// timeline's time.
63#[derive(Debug, Clone, Copy, PartialEq)]
64pub struct TrailPoint {
65    pub at: [f64; 3],
66    pub planned: [f64; 3],
67    pub speed: f64,
68    pub time: f64,
69}
70
71/// How many of the newest setpoints the travelled path is measured against (`Runner::trail_point`): 0.2 s of path at
72/// one per profile cycle of 1 ms, far more than any tool lags behind its plan.
73const DRAWN: usize = 200;
74
75/// Where on the piece from `a` to `b` the point nearest `p` is (0 at `a`, 1 at `b`), and how far that is from `p`.
76fn nearest_on_piece(p: &[f64], a: &[f64], b: &[f64]) -> (f64, f64) {
77    let length: f64 = a.iter().zip(b).map(|(a, b)| (b - a) * (b - a)).sum();
78    let along: f64 = p.iter().zip(a).zip(b).map(|((p, a), b)| (p - a) * (b - a)).sum();
79    let along = if length > 0.0 { (along / length).clamp(0.0, 1.0) } else { 0.0 };
80    let distance = (0..p.len()).map(|i| (a[i] + along * (b[i] - a[i]) - p[i]).powi(2)).sum::<f64>().sqrt();
81    (along, distance)
82}
83
84/// What only the window reads, apart from `Event`s (which the model drains): the travelled path's points with
85/// their speed and plan, and whether the machine tells a mode to show.
86#[derive(Debug, Default)]
87pub struct ViewNews {
88    /// The path started anew since the last read: what the window holds of it ends.
89    pub restarted: bool,
90    pub trail: Vec<TrailPoint>,
91    pub has_mode: bool,
92}
93
94/// Swings per second of the mode in the 3D view: slowed down to about one, so that the eye can follow it.
95pub const MODE_SHOWN_HZ: f64 = 1.0;
96/// How far the mode's amplitude swings, in m, per time the view draws the deflections larger, and at most: the
97/// shape moves by it whichever of carriage and tool moves most (`Machine::mode_shape`). A few millimetres read on a
98/// machine of metres, and up to a tenth of a metre the parts still hang together.
99pub const MODE_TRAVEL: f64 = 0.004;
100pub const MODE_TRAVEL_MOST: f64 = 0.1;
101
102/// The machine at rest at its planned pose plus its mode (`Machine::mode_shape`) swinging at `MODE_SHOWN_HZ`,
103/// `seconds` after it started, with the mode's true frequency as a label by the tool. `exaggeration` scales the
104/// whole shape through its amplitude, and the scene draws it at true scale (`Scene::exaggeration` 1): the scene
105/// draws the carriage's part of the shape at true scale and only the lean larger, which would distort the shape.
106/// `None` where the machine tells no mode. With `picked` (a mode of the mode list) that mode at its own pose, its
107/// shape complex: the state swings as rest + a (re sin + im cos), every part with its own phase.
108pub fn mode_scene(
109    sim: &Sim,
110    exaggeration: f64,
111    seconds: f64,
112    picked: Option<&crate::insight::ShownMode>,
113) -> Option<Scene> {
114    let machine = &sim.machine;
115    let (pose, hz, re, im) = match picked.filter(|p| p.re.len() == machine.state_len()) {
116        Some(p) => (p.pose.as_slice(), p.hz, p.re.clone(), p.im.clone()),
117        None => {
118            let (hz, shape) = machine.mode_shape(sim.control.planned_pos())?;
119            let n = shape.len();
120            (sim.control.planned_pos(), hz, shape, vec![0.0; n])
121        }
122    };
123    let (mut state, mut torque) = (Vec::new(), vec![0.0; machine.motors().len()]);
124    machine.equilibrium(pose, &mut state, &mut torque);
125    let (sin, cos) = (std::f64::consts::TAU * MODE_SHOWN_HZ * seconds).sin_cos();
126    let amplitude = (MODE_TRAVEL * exaggeration).min(MODE_TRAVEL_MOST);
127    state.iter_mut().zip(re.iter().zip(&im)).for_each(|(s, (r, i))| *s += amplitude * (r * sin + i * cos));
128    let mut scene = Scene { exaggeration: 1.0, ..Scene::default() };
129    machine.scene(&state, &mut scene);
130    let (mut pos, mut vel) = (vec![0.0; pose.len()], vec![0.0; pose.len()]);
131    machine.tool_state(&state, &mut pos, &mut vel);
132    (scene.tool, scene.planned) = (machine.scene_point(&pos), machine.scene_point(pose));
133    let at = scene.tool.unwrap_or_default();
134    // The live values drawn from the swinging state would show the swing, not the machine: only the mode's label.
135    scene.labels.clear();
136    scene.labels.push(Label {
137        pos: [at[0] + 0.1, at[1], at[2]],
138        owner_key: "ui-view-mode-label",
139        value: hz,
140        unit_key: "unit-hz",
141        decimals: 1,
142    });
143    Some(scene)
144}
145
146/// What the simulation has produced and the interface has not read yet. It is bounded, so that a window
147/// that stalls costs samples and not memory: of the samples the newest `BACKLOG` are kept, of the scenes
148/// the newest, of the travelled path the newest `TRAIL` points. Answers to requests are few and are all kept.
149#[derive(Debug, Default)]
150pub struct Outbox {
151    events: VecDeque<Event>,
152    samples: usize,
153}
154
155impl Outbox {
156    pub fn push(&mut self, event: Event) {
157        match &event {
158            Event::Scene(_) => self.events.retain(|waiting| !matches!(waiting, Event::Scene(_))),
159            // The points that wait belong to the path that ends here.
160            Event::TrailStart(_) => self.events.retain(|waiting| !matches!(waiting, Event::Trail(_))),
161            Event::Trail(points) => {
162                if let Some(Event::Trail(waiting)) =
163                    self.events.iter_mut().find(|waiting| matches!(waiting, Event::Trail(_)))
164                {
165                    return extend_trail(waiting, points);
166                }
167            }
168            Event::Sample(_) if self.samples == BACKLOG => {
169                let oldest = self.events.iter().position(|waiting| matches!(waiting, Event::Sample(_)));
170                oldest.and_then(|at| self.events.remove(at));
171            }
172            Event::Sample(_) => self.samples += 1,
173            _ => {}
174        }
175        self.events.push_back(event);
176    }
177
178    pub fn drain(&mut self) -> Vec<Event> {
179        self.samples = 0;
180        self.events.drain(..).collect()
181    }
182}
183
184/// The simulation and the handling of requests, without any thread or clock. The session thread
185/// drives it; tests drive it directly, which makes them exact.
186pub struct Runner {
187    pub sim: Sim,
188    entry: &'static MachineEntry,
189    /// Base steps between two samples: one sample per millisecond.
190    sample_every: u64,
191    /// A drive has tripped and this has been reported.
192    tripped: bool,
193    /// A monitor's trip (`Controller::fault`) and the stop after it have been reported.
194    fault_told: bool,
195    stop_told: bool,
196    /// The last point reported of the travelled path; `None` while none is recorded.
197    trail: Option<[f64; 3]>,
198    /// The travelled path still grows: its trajectory runs. Finished, it stays shown as it is.
199    recording: bool,
200    /// The points of `Event::Trail` since the session thread last took them, with their speed and plan, and whether
201    /// the path started anew meanwhile (`ViewNews`).
202    pub trail_points: Vec<TrailPoint>,
203    pub trail_restarted: bool,
204    /// The setpoints of the path so far, a new one per profile cycle, the newest `DRAWN`, and the simulated time the
205    /// newest is for: the path the plan has drawn, which the travelled path is measured against.
206    drawn: VecDeque<Vec<f64>>,
207    drawn_at: f64,
208}
209
210impl Runner {
211    pub fn new(entry: &'static MachineEntry, cfg: &Config) -> Result<Self, ConfigError> {
212        let sim = Sim::new(entry, cfg)?;
213        let sample_every = (1e-3 / sim.dt).round().max(1.0) as u64;
214        Ok(Self {
215            sim,
216            entry,
217            sample_every,
218            tripped: false,
219            fault_told: false,
220            stop_told: false,
221            trail: None,
222            recording: false,
223            trail_points: Vec::new(),
224            trail_restarted: false,
225            drawn: VecDeque::new(),
226            drawn_at: 0.0,
227        })
228    }
229
230    pub fn handle(&mut self, request: Request, events: &mut Vec<Event>) {
231        match request {
232            Request::Command(command) => {
233                // A path the machine takes starts the travelled path anew, a cycle ends it; refused, neither.
234                let (path, cycle) = (matches!(command, Command::Trajectory(_)), matches!(command, Command::StartCycle));
235                match self.sim.command(command) {
236                    Err(e) => events.push(Event::Refused(e.key, String::new())),
237                    Ok(()) if path || cycle => {
238                        self.start_trail(if path { self.sim.tool_point() } else { None }, events)
239                    }
240                    // Another command ends the path only if it ends the trajectory (drives off). A stop after the
241                    // segment or an enable is taken while it runs and leaves it running.
242                    Ok(()) => self.recording &= self.sim.control.busy(),
243                }
244            }
245            Request::Reconfigure(cfg) => {
246                let answer = self.sim.reconfigure(self.entry, &cfg);
247                if answer.is_ok() {
248                    self.start_trail(None, events);
249                }
250                events.push(Event::Configured(match answer {
251                    Ok(()) => Ok(self.sim.limit_violations.clone()),
252                    Err(e) => Err((e.key(), e.detail().into())),
253                }));
254            }
255            Request::Pause(_)
256            | Request::Speed(_)
257            | Request::Exaggeration(_)
258            | Request::Mode(_)
259            | Request::ModeShape(_)
260            | Request::Quit => {}
261        }
262    }
263
264    fn start_trail(&mut self, at: Option<[f64; 3]>, events: &mut Vec<Event>) {
265        // Nothing to end where nothing is recorded: a parameter edit on a machine that runs no path.
266        self.drawn.clear();
267        if at.is_some() || self.trail.is_some() {
268            events.push(Event::TrailStart(at));
269            let first = at.map(|at| self.trail_point(at));
270            self.trail_restarted = true;
271            self.trail_points.clear();
272            self.trail_points.extend(first);
273        }
274        self.trail = at;
275        self.recording = at.is_some();
276    }
277
278    /// A point of the travelled path, with the nearest point of the path the plan has drawn and the tool's speed now.
279    /// The plan is the setpoints the drives follow, after input shaping, as the cycle analysis measures the path error:
280    /// the plan before shaping runs ahead of it by the shaper's delay on purpose, which is not an error. Its newest
281    /// setpoint is carried on by its speed to now: it changes once per profile cycle (1 ms), and the tool between two
282    /// stood up to its speed times the cycle from the last (0.8 mm at 0.8 m/s), which read as error where there was
283    /// none. Measured to the path and not to where the plan is now, the error is the one the path error peak of the
284    /// path's analysis is the largest of: a tool on the path but behind the plan is not off it.
285    /// The speed is the length of the speeds of the axes in m; a turning axis adds nothing.
286    fn trail_point(&self, at: [f64; 3]) -> TrailPoint {
287        let axes = self.sim.machine.axes().len();
288        let (mut pos, mut vel) = (vec![0.0; axes], vec![0.0; axes]);
289        self.sim.machine.tool_state(&self.sim.state, &mut pos, &mut vel);
290        let control = &self.sim.control;
291        let ahead = if self.drawn.is_empty() { 0.0 } else { self.sim.time() - self.drawn_at };
292        let lead: Vec<f64> = control.set_pos.iter().zip(&control.set_vel).map(|(p, v)| p + v * ahead).collect();
293        let (mut nearest, mut off) = ((&lead, &lead, 0.0), nearest_on_piece(&pos, &lead, &lead).1);
294        let mut newer = &lead;
295        for older in self.drawn.iter().rev() {
296            let (along, distance) = nearest_on_piece(&pos, older, newer);
297            if distance < off {
298                (nearest, off) = ((older, newer, along), distance);
299            }
300            newer = older;
301        }
302        let (a, b, along) = nearest;
303        let nearest: Vec<f64> = a.iter().zip(b).map(|(a, b)| a + along * (b - a)).collect();
304        let planned = self.sim.machine.scene_point(&nearest).unwrap_or(at);
305        TrailPoint {
306            at,
307            planned,
308            speed: crate::insight::linear_speed(
309                self.sim.machine.axes().iter().zip(&vel).map(|(a, v)| (a.unit == "m", *v)),
310            ),
311            time: self.sim.time(),
312        }
313    }
314
315    /// Runs whole base steps for `seconds` of simulated time and reports the samples.
316    pub fn advance(&mut self, seconds: f64, events: &mut Vec<Event>) {
317        let mut travelled = Vec::new();
318        for _ in 0..(seconds / self.sim.dt).round() as u64 {
319            self.sim.step();
320            // A new setpoint, for the time at the start of the step (the profile runs first in it).
321            if self.recording && self.drawn.back() != Some(&self.sim.control.set_pos) {
322                if self.drawn.len() == DRAWN {
323                    self.drawn.pop_front();
324                }
325                self.drawn.push_back(self.sim.control.set_pos.clone());
326                self.drawn_at = self.sim.time() - self.sim.dt;
327            }
328            if let (true, Some(last), Some(tool)) = (self.recording, self.trail, self.sim.tool_point())
329                && (0..3).map(|i| (tool[i] - last[i]).powi(2)).sum::<f64>() > 1e-8
330            {
331                travelled.push(tool);
332                let point = self.trail_point(tool);
333                self.trail_points.push(point);
334                self.trail = Some(tool);
335            }
336            // The trajectory is through: the path ends with it.
337            self.recording &= self.sim.control.busy();
338            if self.sim.step.is_multiple_of(self.sample_every) {
339                let mut sample = Vec::new();
340                self.sim.sample(&mut sample);
341                events.push(Event::Sample(sample));
342            }
343            // A trip takes every drive off, which otherwise shows only as a machine that stops. Said once
344            // per trip; the drives stay tripped until they are enabled.
345            let tripped = self.sim.control.drives.iter().any(|drive| drive.tripped);
346            if tripped && !self.tripped {
347                events.push(Event::Refused("ui-drive-tripped", String::new()));
348            }
349            self.tripped = tripped;
350            // A monitor's trip (effects.drive_monitoring): which, and each drive's fault reaction, at once while the
351            // axes ramp down or coast; then how far each axis went until the machine stood.
352            if let Some(fault) = &self.sim.control.fault {
353                let motors = self.sim.machine.motors();
354                if !self.fault_told {
355                    let detail = format!("{}, {:.3} s", motors[fault.drive].id, fault.time);
356                    events.push(Event::Refused("ui-drive-fault", detail));
357                    events.push(Event::Refused(fault.monitor.key(), String::new()));
358                    for (k, motor) in motors.iter().enumerate() {
359                        events.push(Event::Refused(self.sim.control.fault_reaction(k).key(), motor.id.to_string()));
360                    }
361                    self.fault_told = true;
362                }
363                if let (Some(stopped), false) = (fault.stopped, self.stop_told) {
364                    let axes = self.sim.machine.axes();
365                    let distances: Vec<String> = axes
366                        .iter()
367                        .zip(&fault.stopping)
368                        .map(|(axis, d)| format!("{} {:.1} m{}", axis.id, d * 1e3, axis.unit))
369                        .collect();
370                    events
371                        .push(Event::Refused("ui-drive-stopped", format!("{stopped:.3} s; {}", distances.join(", "))));
372                    self.stop_told = true;
373                }
374            } else {
375                (self.fault_told, self.stop_told) = (false, false);
376            }
377        }
378        if !travelled.is_empty() {
379            events.push(Event::Trail(travelled));
380        }
381        // Bounded as the path is, for a runner whose points nobody takes (the tests).
382        self.trail_points.drain(..self.trail_points.len().saturating_sub(TRAIL));
383    }
384}
385
386/// How many pieces each axis's travel is cut into (`travel_lines`): enough for a turning axis's arc to read as one.
387const TRAVEL_STEPS: usize = 24;
388
389/// Each axis's travel as a line in the scene: where the tool goes (`Machine::scene_point`) as that axis alone runs
390/// from its `min` to its `max` with the others at `pose`. Axes that do not move the tool in the scene (no mapping, or
391/// less than a millimetre) and limits that are not numbers have none; the lines come with the index of their axis.
392pub fn travel_lines(machine: &dyn sim_core::Machine, pose: &[f64]) -> Vec<(usize, Vec<[f64; 3]>)> {
393    let mut lines = Vec::new();
394    for (i, axis) in machine.axes().iter().enumerate().filter(|(i, _)| *i < pose.len()) {
395        if !(axis.min.is_finite() && axis.max.is_finite() && axis.max > axis.min) {
396            continue;
397        }
398        let line: Option<Vec<[f64; 3]>> = (0..=TRAVEL_STEPS)
399            .map(|k| {
400                let mut at = pose.to_vec();
401                at[i] = axis.min + (axis.max - axis.min) * k as f64 / TRAVEL_STEPS as f64;
402                machine.scene_point(&at)
403            })
404            .collect();
405        // How far the line strays from its first point: a turning axis whose end meets its start still has reach.
406        let reach = line.as_ref().map_or(0.0, |l| {
407            l.iter().map(|p| (0..3).map(|c| (p[c] - l[0][c]).powi(2)).sum::<f64>().sqrt()).fold(0.0, f64::max)
408        });
409        if let Some(line) = line.filter(|_| reach >= 1e-3) {
410            lines.push((i, line));
411        }
412    }
413    lines
414}
415
416pub struct Session {
417    requests: Sender<Request>,
418    events: Arc<Mutex<Outbox>>,
419    thread: JoinHandle<()>,
420    news: Arc<Mutex<ViewNews>>,
421    pub signals: Vec<SignalInfo>,
422    pub axes: Vec<AxisInfo>,
423    /// Where each axis's travel lies in the scene (`travel_lines`) with the other axes where the machine started, with
424    /// the index of the axis: for the 3D view's travel limits.
425    pub travel: Vec<(usize, Vec<[f64; 3]>)>,
426    pub motors: Vec<MotorInfo>,
427    /// Per motor: linear (m, m/s, N), `Machine::motor_linear`.
428    pub motor_linear: Vec<bool>,
429}
430
431impl Session {
432    pub fn start(entry: &'static MachineEntry, cfg: &Config) -> Result<Self, ConfigError> {
433        let mut runner = Runner::new(entry, cfg)?;
434        let signals = runner.sim.signal_infos();
435        let (axes, motors) = (runner.sim.machine.axes().to_vec(), runner.sim.machine.motors().to_vec());
436        let motor_linear = (0..motors.len()).map(|k| runner.sim.machine.motor_linear(k)).collect();
437        let travel = travel_lines(runner.sim.machine.as_ref(), runner.sim.control.planned_pos());
438        let (requests, inbox) = channel();
439        let events = Arc::new(Mutex::new(Outbox::default()));
440        let outbox = events.clone();
441        let news = Arc::new(Mutex::new(ViewNews::default()));
442        let window_news = news.clone();
443        if let Ok(mut outbox) = outbox.lock() {
444            outbox.push(Event::Limits(runner.sim.limit_violations.clone()));
445        }
446        let thread = std::thread::spawn(move || {
447            let (mut paused, mut speed, mut owed, mut exaggeration) = (false, 1.0, 0.0, 1.0);
448            // When the mode started showing; meanwhile the simulation waits.
449            let mut mode: Option<Instant> = None;
450            let mut picked: Option<crate::insight::ShownMode> = None;
451            let (mut last, mut last_scene) = (Instant::now(), Instant::now() - Duration::from_secs(1));
452            let mut batch = Vec::new();
453            loop {
454                loop {
455                    match inbox.try_recv() {
456                        // Asked to end, or nobody is left to ask.
457                        Ok(Request::Quit) | Err(TryRecvError::Disconnected) => return,
458                        Ok(Request::Pause(on)) => paused = on,
459                        Ok(Request::Speed(factor)) => speed = factor.clamp(0.0, 100.0),
460                        Ok(Request::Exaggeration(factor)) => exaggeration = factor.clamp(1.0, 1.0e4),
461                        Ok(Request::Mode(on)) => mode = if on { mode.or(Some(Instant::now())) } else { None },
462                        Ok(Request::ModeShape(shape)) => picked = shape,
463                        Ok(other) => runner.handle(other, &mut batch),
464                        Err(TryRecvError::Empty) => break,
465                    }
466                }
467                // The wall clock only decides how many steps are due; the core never sees it.
468                let now = Instant::now();
469                if !paused && mode.is_none() {
470                    owed += (now - last).as_secs_f64() * speed;
471                }
472                last = now;
473                // A machine too slow for the requested speed falls behind instead of piling up work.
474                owed = f64::min(owed, 0.05);
475                let whole = (owed / runner.sim.dt).floor() * runner.sim.dt;
476                runner.advance(whole, &mut batch);
477                owed -= whole;
478                if now - last_scene > Duration::from_millis(8) {
479                    let swinging = mode.and_then(|since| {
480                        mode_scene(&runner.sim, exaggeration, since.elapsed().as_secs_f64(), picked.as_ref())
481                    });
482                    let scene = swinging.unwrap_or_else(|| {
483                        let mut scene = Scene { exaggeration, ..Scene::default() };
484                        runner.sim.scene(&mut scene);
485                        scene.planned = runner.sim.machine.scene_point(runner.sim.control.planned_pos());
486                        scene
487                    });
488                    batch.push(Event::Scene(scene));
489                    last_scene = now;
490                    if let Ok(mut news) = news.lock() {
491                        news.has_mode = picked.is_some()
492                            || runner.sim.machine.mode_shape(runner.sim.control.planned_pos()).is_some();
493                    }
494                }
495                if let Ok(mut news) = news.lock() {
496                    if std::mem::take(&mut runner.trail_restarted) {
497                        (news.restarted, news.trail) = (true, Vec::new());
498                    }
499                    news.trail.append(&mut runner.trail_points);
500                    let over = news.trail.len().saturating_sub(TRAIL);
501                    news.trail.drain(..over);
502                }
503                // Held only to move the batch over: the interface never makes the physics wait for a frame.
504                let Ok(mut outbox) = outbox.lock() else { return };
505                batch.drain(..).for_each(|event| outbox.push(event));
506                drop(outbox);
507                // Paused and not swinging in a mode, nothing moves: look for requests less often, so that a paused
508                // machine in a window that idles (`update_mode` in main.rs) costs next to no processor time.
509                std::thread::sleep(Duration::from_millis(if paused && mode.is_none() { 20 } else { 1 }));
510            }
511        });
512        Ok(Self { requests, events, thread, news: window_news, signals, axes, travel, motors, motor_linear })
513    }
514
515    /// The travelled path's points with their speed and plan since the last call, whether the path started anew
516    /// before them (`ViewNews`), and whether the machine tells a mode to show. Never waits long.
517    pub fn view_news(&self) -> ViewNews {
518        let take = |news: &mut ViewNews| ViewNews {
519            restarted: std::mem::take(&mut news.restarted),
520            trail: std::mem::take(&mut news.trail),
521            has_mode: news.has_mode,
522        };
523        self.news.lock().map(|mut news| take(&mut news)).unwrap_or_default()
524    }
525
526    /// Everything the simulation has produced since the last call, less what `Outbox` dropped. Never waits.
527    pub fn drain(&self) -> Vec<Event> {
528        self.events.lock().map(|mut events| events.drain()).unwrap_or_default()
529    }
530
531    /// The simulation thread is gone. Nobody asked it to end while the session lives, so it panicked.
532    pub fn ended(&self) -> bool {
533        self.thread.is_finished()
534    }
535
536    pub fn send(&self, request: Request) {
537        let _ = self.requests.send(request);
538    }
539}
540
541impl Drop for Session {
542    /// The thread is told to end and left to it. Waiting for it here would hold up the window for as long
543    /// as the steps it is in the middle of take, when the machine is switched.
544    fn drop(&mut self) {
545        self.send(Request::Quit);
546    }
547}
548
549#[cfg(test)]
550mod tests {
551    use super::*;
552    use std::time::{Duration, Instant};
553
554    /// A reader that is behind: the queue used to grow without bound. It keeps the newest samples, the
555    /// newest scene and every answer.
556    #[test]
557    fn a_reader_that_is_behind_costs_samples_and_not_memory() {
558        let mut outbox = Outbox::default();
559        outbox.push(Event::Refused("first", String::new()));
560        for n in 0..3 * BACKLOG {
561            outbox.push(Event::Sample(vec![n as f64]));
562            if n % 8 == 0 {
563                outbox.push(Event::Scene(Scene::default()));
564            }
565            if n == BACKLOG {
566                outbox.push(Event::Configured(Ok(Vec::new())));
567            }
568            assert!(outbox.events.len() <= BACKLOG + 3);
569        }
570        let events = outbox.drain();
571        let samples: Vec<f64> =
572            events.iter().filter_map(|e| if let Event::Sample(s) = e { Some(s[0]) } else { None }).collect();
573        assert_eq!(
574            (samples.len(), samples[0], samples[BACKLOG - 1]),
575            (BACKLOG, (2 * BACKLOG) as f64, (3 * BACKLOG - 1) as f64)
576        );
577        assert!(samples.windows(2).all(|w| w[1] == w[0] + 1.0), "the samples that are left are out of order");
578        assert_eq!(events.iter().filter(|e| matches!(e, Event::Scene(_))).count(), 1);
579        assert!(
580            matches!(events[0], Event::Refused("first", _))
581                && events.iter().any(|e| matches!(e, Event::Configured(Ok(_))))
582        );
583        // Read, the queue starts anew.
584        outbox.push(Event::Sample(vec![0.0]));
585        assert_eq!(outbox.drain().len(), 1);
586    }
587
588    /// The same through a session whose reader sleeps: what it then reads is bounded and ends with the
589    /// newest state, and the simulation thread was never held up.
590    #[test]
591    fn a_session_whose_reader_sleeps_still_delivers_the_newest_state() {
592        let entry = sim_machines::MACHINES[0];
593        let session = Session::start(entry, &entry.config()).unwrap();
594        session.send(Request::Speed(100.0));
595        std::thread::sleep(Duration::from_millis(1500));
596        let events = session.drain();
597        let times: Vec<f64> =
598            events.iter().filter_map(|e| if let Event::Sample(s) = e { Some(s[0]) } else { None }).collect();
599        assert!(times.len() <= BACKLOG && events.len() <= BACKLOG + 2, "{} events waited", events.len());
600        assert_eq!(events.iter().filter(|e| matches!(e, Event::Scene(_))).count(), 1);
601        std::thread::sleep(Duration::from_millis(100));
602        let newer: Vec<f64> =
603            session.drain().iter().filter_map(|e| if let Event::Sample(s) = e { Some(s[0]) } else { None }).collect();
604        // What was read first reaches up to where the next read goes on: nothing newer was dropped.
605        assert!(
606            !newer.is_empty() && (newer[0] - times[times.len() - 1] - 1e-3).abs() < 1e-9,
607            "{:?} then {:?}",
608            times.last(),
609            newer.first()
610        );
611    }
612
613    /// Dropping a session (switching machine) does not wait for the simulation thread. With steps that
614    /// take long, the join it used to do held the window up for as long as the thread was busy.
615    #[test]
616    fn dropping_a_session_does_not_wait_for_its_thread() {
617        let entry = sim_machines::MACHINES[0];
618        let mut slow = entry.config();
619        slow.set_text("sim.substeps = 1000").unwrap();
620        let session = Session::start(entry, &slow).unwrap();
621        std::thread::sleep(Duration::from_millis(300));
622        let start = Instant::now();
623        drop(session);
624        assert!(start.elapsed() < Duration::from_millis(20), "dropping the session took {:?}", start.elapsed());
625    }
626}