Skip to main content

sim_components/
program.rs

1//! Programs read into path pieces (`path::Piece`) for the path planner: a subset of G-code (DIN 66025 / ISO 6983), robot
2//! moves as CSV, and subsets of KUKA KRL and ABB RAPID. `read` picks the reader by the file's extension.
3//!
4//! G-code (`.nc`, `.ngc`, `.gcode`, `.g`, `.cnc`, `.tap`), one block per line:
5//! - G0 rapid, G1 line, G2 clockwise and G3 counterclockwise arc (seen from the plus side of the plane's normal),
6//!   centre by I, J, K (from the start, always incremental) or radius R (negative: the longer of the two arcs);
7//! - G17 (XY plane), G18 (ZX), G19 (YZ); G20 inch, G21 mm (the default); G90 absolute (the default), G91 incremental;
8//! - F the feed per minute, needed before the first G1, G2 or G3: the speed along the path, in length units for a block
9//!   with a linear axis and in degrees for a block that moves only rotary axes (A, B, C); where both move, the linear
10//!   axes' distance at F sets the time and the rotary axes follow in it. This is Siemens SINUMERIK's reading with its
11//!   default FGROUP (the geometry axes; a rotary axis in a mixed block is synchronised and has no F of its own;
12//!   Fanuc's, which counts degrees like mm in a mixed block, is not taken: no primary source). G2 or G3 with I, J, K and
13//!   no end is a full circle. F is modal and caps each piece at its own block's feed (`path::plan_feeds`, `Run::caps`):
14//!   the moves between two G0 are one run planned as one path, with no stop where the feed changes (a corner still
15//!   stops it, as it does without a feed); G0 runs at the axes' limits;
16//! - X, Y, Z (and A, B, C in degrees) move the axes of the same name (ids x, y, z, a, b, c); the start is where the
17//!   machine stands, an axis a block does not name stays;
18//! - G4 P<seconds> a dwell: the path stops at the end of the move before, stands P seconds (0 to `MAX_DWELL_S`) and goes
19//!   on (RS-274NGC's G4, as LinuxCNC reads it, but alone in its block; Siemens' G4 F and Fanuc's P in milliseconds are
20//!   not read). G61 exact path (corner tolerance 0 from here on: corners are stopped at, lines in one direction are
21//!   not), G64 (the config's `profile.corner_tolerance_m`, where LinuxCNC's G64 keeps the best speed at any deviation)
22//!   and G64 P<length> (that tolerance in the program's unit, G20/G21 apply; P0 is G64 alone, as in LinuxCNC). P bounds
23//!   the curve's distance from the two lines, where LinuxCNC's bounds it from the programmed corner: at a right angle the
24//!   curve passes up to sqrt(2) P from the corner. G61.1 and G64 Q are not read; Siemens' G64 takes no P. The mode that
25//!   governs a corner is the one in force for the block after it; a change of mode, like a dwell, ends the run, so the
26//!   corner at the change is stopped at (`Run::corner`, `Run::dwell_s`);
27//! - taken and without effect: N, O, M, S, T words, G40, G49, G54, G80, G94; comments in ( ) and after ;; % lines;
28//!   M2 and M30 end the program. Every other word or G code is refused with its line, and so is an arc that changes the
29//!   plane's third axis (a helix), whose start and end lie at different distances from its centre, or a word for an axis
30//!   the machine does not have.
31//!
32//! Robot moves as CSV (any other extension, when a line starts with Move): `MoveL,x,y,z` and `MoveJ,x,y,z` straight to
33//! the pose, `MoveC,via...,end...` on the circle through the via point to the end; one value per axis in the machine's
34//! units (m, rad), as a path file has them; at the axes' limits.
35//!
36//! KRL (`.src`): `PTP {X 100, Y 0, Z 500}`, `LIN {...}`, `CIRC {aux}, {end}` with mm and degrees, components left out
37//! kept from the point before (for a CIRC too, the auxiliary point's are not used: KUKA System Software 8.3, section
38//! 11.5.3); A, B, C, S, T, E1... move axes of those names where the machine has them and are left out
39//! otherwise. Where the machine's axes are x, y, z and a rotation vector rx, ry, rz (an arm in tool space), A, B, C are
40//! the orientation (R = Rz(A) Ry(B) Rx(C), KUKA's) and set rx, ry, rz. `$VEL.CP = v` (m/s) is the speed along the path
41//! of the LIN and CIRC moves after it; a PTP runs at the axes' limits.
42//!
43//! RAPID (`.mod`, `.prg`): `MoveL`, `MoveJ` and `MoveC` to robtargets given in place (`[[x, y, z], [q1, q2, q3, q4],
44//! ...]`) or declared (`CONST robtarget p10 := [[...]];`), positions in mm; where the machine has rx, ry, rz the
45//! orientation quaternion (q1 the scalar part) sets them. The speed: `v100` (the predefined speeddata, mm/s), `vmax`
46//! (the axes' limits), a speeddata given in place (`[150, 500, 5000, 1000]`, its TCP speed in mm/s) or declared (`CONST
47//! speeddata vfast := [...];`); the zone is left out. In both every other line or statement without a move is skipped;
48//! other move instructions (PTP_REL, SPLINE, MoveAbsJ, named KRL points) are refused. A PTP or MoveJ is a straight line
49//! in the machine's axes, as a MoveL, at the move's speed along it.
50//!
51//! A robot's speed (KRL's `$VEL.CP`, RAPID's TCP speed) is the tool centre's, the position alone, and the reorientation
52//! is limited by its own: `program.orientation_speed_rad_s` (default 500 degrees per second, the default of RAPID's
53//! `v_ori`), on a machine whose tool space has rx, ry, rz. A move takes the longer of the tool centre's distance over
54//! its speed and the angle between the two orientations over that rate, so a move that only reorients runs at the
55//! rate; the planner's cap along the path (whose length counts the rotation vector's radians with the metres) is the
56//! path's length over that time. A move with no speed (PTP, MoveJ, `vmax`) stays at the axes' limits. G-code keeps its
57//! feed rule above.
58
59use crate::path::Piece;
60use sim_core::AxisInfo;
61
62/// Moves planned as one path with no stop between them: the pieces, and the speed along the path each is capped at (axis
63/// units per second, over all axes, as `path::plan_feeds` takes it): `caps`, one per piece. `feed` is the highest of them,
64/// `None` where the run is at the axes' limits (and `caps` is empty).
65#[derive(Debug, Clone, PartialEq)]
66pub struct Run {
67    pub feed: Option<f64>,
68    pub caps: Vec<f64>,
69    pub pieces: Vec<Piece>,
70    /// The corner tolerance (m) of the G61 or G64 P in force for the run, `None` for the config's
71    /// (`profile.corner_tolerance_m`).
72    pub corner: Option<f64>,
73    /// A run with no pieces is a dwell (G4): the path stands this long (s) where the run before ended.
74    pub dwell_s: f64,
75}
76
77impl Run {
78    /// The cap of each piece, `None` where the run is at the axes' limits; a run built with a feed and no caps has it for all.
79    pub fn caps(&self) -> Option<Vec<f64>> {
80        self.feed
81            .map(|f| if self.caps.len() == self.pieces.len() { self.caps.clone() } else { vec![f; self.pieces.len()] })
82    }
83}
84
85/// The pieces of a program that plans as a path file does (`Sim::plan_path`): one run at the axes' limits in the config's
86/// corner tolerance. `None` for one to plan run by run (`Sim::plan_program`): with a feed, more runs, or a G61 or G64 P
87/// whose corner tolerance only `plan_program` takes.
88pub fn as_path(runs: &[Run]) -> Option<&[Piece]> {
89    match runs {
90        [run] if run.feed.is_none() && run.corner.is_none() => Some(&run.pieces),
91        _ => None,
92    }
93}
94
95/// The longest dwell (s) a G4 takes: the plan has a pose per profile cycle for it. This simulator's limit.
96pub const MAX_DWELL_S: f64 = 3600.0;
97
98/// A line of a program that cannot be read: its number (from 1), a translation key and the word or detail.
99#[derive(Debug, Clone, PartialEq)]
100pub struct ProgramError {
101    pub line: usize,
102    pub key: &'static str,
103    pub detail: String,
104}
105
106type Result<T> = std::result::Result<T, ProgramError>;
107
108fn fail<T>(line: usize, key: &'static str, detail: impl Into<String>) -> Result<T> {
109    Err(ProgramError { line, key, detail: detail.into() })
110}
111
112/// The program in `text`, read by the file's extension (see the module): G-code, KRL, RAPID, robot moves as CSV, else a
113/// path file (`path::parse`, one run at the axes' limits). Planned from `start`, on a machine with `axes`.
114pub fn read(file_name: &str, text: &str, axes: &[AxisInfo], start: &[f64]) -> Result<Vec<Run>> {
115    read_with(file_name, text, axes, start, ORIENTATION_SPEED)
116}
117
118/// `read` with the tool's reorientation speed `orientation_speed` (rad/s) for the robot programs on a machine whose tool
119/// has an orientation (`program.orientation_speed_rad_s`).
120pub fn read_with(
121    file_name: &str,
122    text: &str,
123    axes: &[AxisInfo],
124    start: &[f64],
125    orientation_speed: f64,
126) -> Result<Vec<Run>> {
127    let extension = file_name.rsplit_once('.').map_or("", |(_, e)| e).to_ascii_lowercase();
128    match extension.as_str() {
129        "nc" | "ngc" | "gcode" | "g" | "cnc" | "tap" => gcode(text, axes, start),
130        "src" => krl_with(text, axes, start, orientation_speed),
131        "mod" | "prg" => rapid_with(text, axes, start, orientation_speed),
132        _ if text.lines().any(|l| l.trim().to_ascii_lowercase().starts_with("move")) => robot_csv(text, axes, start),
133        _ => crate::path::parse(text)
134            .map(|pieces| vec![Run { feed: None, caps: Vec::new(), pieces, corner: None, dwell_s: 0.0 }])
135            .map_err(|line| ProgramError { line: 0, key: "program-error-word", detail: line }),
136    }
137}
138
139/// The index of the axis a program letter names (X: id "x"), if the machine has it.
140fn axis_of(axes: &[AxisInfo], letter: char) -> Option<usize> {
141    axes.iter().position(|a| a.id.len() == 1 && a.id.eq_ignore_ascii_case(&letter.to_string()))
142}
143
144/// Whether the arc whose plane is spanned by axes `a` then `b` (a to the right, b up, seen from the plus side of the
145/// normal a x b) is clockwise as `path` reads it: on two axes seen with the first to the right and the second up, on
146/// three from +z, for the x-z plane from -y, for the y-z plane from +x (by position: the first axis is x). `turning` is
147/// -1 for clockwise seen from a x b, +1 for counterclockwise.
148fn path_clockwise(a: usize, b: usize, turning: f64) -> bool {
149    // a x b = sign e_k; the path's viewing normal is +e_2, -e_1 or +e_0 for k = 2, 1, 0 (two axes: k = 2).
150    let cyclic = matches!((a, b), (0, 1) | (1, 2) | (2, 0));
151    let k = 3 - a - b;
152    let viewed = if k == 1 { -1.0 } else { 1.0 };
153    turning * if cyclic { 1.0 } else { -1.0 } * viewed < 0.0
154}
155
156fn cross(u: [f64; 3], v: [f64; 3]) -> [f64; 3] {
157    [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]]
158}
159
160/// The arc from `from` through `via` to `to` (two or three axes, by position): its centre and whether `path` reads it
161/// clockwise. `None` where the three points are on one line or so far out that the centre overflows.
162fn arc_through(from: &[f64], via: &[f64], to: &[f64]) -> Option<(Vec<f64>, bool)> {
163    let n = from.len();
164    if !(2..=3).contains(&n) {
165        return None;
166    }
167    let p = |x: &[f64]| [x[0], x[1], if n == 3 { x[2] } else { 0.0 }];
168    let (s, v, e) = (p(from), p(via), p(to));
169    let (u, w) = ([v[0] - s[0], v[1] - s[1], v[2] - s[2]], [e[0] - s[0], e[1] - s[1], e[2] - s[2]]);
170    let normal = cross(u, w);
171    let nn = normal.iter().map(|x| x * x).sum::<f64>();
172    let scale = u.iter().chain(&w).map(|x| x * x).sum::<f64>();
173    if nn <= 1e-18 * scale * scale {
174        return None;
175    }
176    // Circumcentre: s + ((|u|^2 w - |w|^2 u) x n) / (2 |n|^2).
177    let (uu, ww) = (u.iter().map(|x| x * x).sum::<f64>(), w.iter().map(|x| x * x).sum::<f64>());
178    let m = cross([uu * w[0] - ww * u[0], uu * w[1] - ww * u[1], uu * w[2] - ww * u[2]], normal);
179    let centre: Vec<f64> = (0..n).map(|i| s[i] + m[i] / (2.0 * nn)).collect();
180    // Points near f64's range overflow the squares above: no centre to compute with.
181    if !centre.iter().all(|c| c.is_finite()) {
182        return None;
183    }
184    // The travel turns about `normal`; the path's viewing normal is +z, else -y, else +x.
185    let viewing = if normal[2].abs() > 1e-12 * nn.sqrt() {
186        [0.0, 0.0, 1.0]
187    } else if normal[1].abs() > 1e-12 * nn.sqrt() {
188        [0.0, -1.0, 0.0]
189    } else {
190        [1.0, 0.0, 0.0]
191    };
192    let along: f64 = normal.iter().zip(viewing).map(|(a, b)| a * b).sum();
193    Some((centre, along < 0.0))
194}
195
196/// Adds `piece` to the last run where that moves at `feed`, else to a new run.
197fn push(runs: &mut Vec<Run>, feed: Option<f64>, piece: Piece) {
198    push_by(runs, feed, piece, false);
199}
200
201/// `push`; with `joined` a piece with a feed also joins a run at another feed, keeping its own cap (G-code: the feed is
202/// modal and changes between blocks without a stop).
203fn push_by(runs: &mut Vec<Run>, feed: Option<f64>, piece: Piece, joined: bool) {
204    match runs.last_mut() {
205        Some(run) if run.feed == feed || (joined && run.feed.is_some() && feed.is_some()) => {
206            run.pieces.push(piece);
207            if let Some(f) = feed {
208                run.caps.push(f);
209                run.feed = run.feed.map(|g| g.max(f));
210            }
211        }
212        _ => runs.push(Run { feed, caps: feed.into_iter().collect(), pieces: vec![piece], corner: None, dwell_s: 0.0 }),
213    }
214}
215
216/// G-code (see the module).
217pub fn gcode(text: &str, axes: &[AxisInfo], start: &[f64]) -> Result<Vec<Run>> {
218    let mut pos = start.to_vec();
219    let (mut absolute, mut inch, mut plane, mut motion, mut feed) = (true, false, 17, None::<u32>, None::<(f64, f64)>);
220    let mut runs = Vec::new();
221    // G61 (exact stop: tolerance 0) and G64 (the config's, or its P) as the modal corner tolerance; `split` where the next
222    // move starts a new run, after a change of it or a dwell.
223    let (mut corner, mut split) = (None::<f64>, false);
224    for (n, raw) in text.lines().enumerate() {
225        let line = n + 1;
226        // Comments in brackets and after a semicolon.
227        let mut clean = String::new();
228        let mut depth = 0;
229        for c in raw.chars() {
230            match c {
231                '(' => depth += 1,
232                ')' if depth > 0 => depth -= 1,
233                ';' if depth == 0 => break,
234                c if depth == 0 && !c.is_whitespace() => clean.push(c.to_ascii_uppercase()),
235                _ => {}
236            }
237        }
238        if clean.is_empty() || clean.starts_with('%') {
239            continue;
240        }
241        // Words: a letter and a number.
242        let mut words: Vec<(char, f64, &str)> = Vec::new();
243        let mut rest = clean.as_str();
244        while let Some(letter) = rest.chars().next() {
245            let after = letter.len_utf8();
246            let end = rest[after..].find(|c: char| c.is_ascii_alphabetic()).map_or(rest.len(), |i| i + after);
247            let (word, number) = (&rest[..end], &rest[after..end]);
248            match number.parse::<f64>() {
249                Ok(v) if letter.is_ascii_alphabetic() && v.is_finite() => words.push((letter, v, word)),
250                _ => return fail(line, "program-error-word", word),
251            }
252            rest = &rest[end..];
253        }
254        let mut moving = false;
255        let mut ends = false;
256        let (mut target, mut centre_offset, mut radius) = (pos.clone(), [None::<f64>; 3], None::<f64>);
257        let (mut dwell, mut mode, mut p) = (false, None::<Option<f64>>, None::<(f64, &str)>);
258        // Modal words first: units and distances apply to the whole block.
259        for &(letter, v, word) in &words {
260            if letter == 'G' {
261                match v {
262                    4.0 => dwell = true,
263                    61.0 => mode = Some(Some(0.0)),
264                    64.0 => mode = Some(None),
265                    20.0 => inch = true,
266                    21.0 => inch = false,
267                    90.0 => absolute = true,
268                    91.0 => absolute = false,
269                    17.0 | 18.0 | 19.0 => plane = v as u32,
270                    0.0 | 1.0 | 2.0 | 3.0 => motion = Some(v as u32),
271                    40.0 | 49.0 | 54.0 | 80.0 | 94.0 => {}
272                    _ => return fail(line, "program-error-word", word),
273                }
274            }
275        }
276        let length = if inch { 0.0254 } else { 0.001 };
277        for &(letter, v, word) in &words {
278            match letter {
279                'G' | 'N' | 'O' | 'S' | 'T' => {}
280                'M' => ends |= v == 2.0 || v == 30.0,
281                // The feed as per second: length units, and degrees as radians for a block that only turns rotary axes.
282                'F' if v > 0.0 => feed = Some((v * length / 60.0, v.to_radians() / 60.0)),
283                'X' | 'Y' | 'Z' | 'A' | 'B' | 'C' => {
284                    let Some(i) = axis_of(axes, letter) else { return fail(line, "program-error-axis", word) };
285                    let scale = if axes[i].unit == "rad" { std::f64::consts::PI / 180.0 } else { length };
286                    target[i] = if absolute { v * scale } else { target[i] + v * scale };
287                    moving = true;
288                }
289                'I' | 'J' | 'K' => centre_offset[(letter as u8 - b'I') as usize] = Some(v * length),
290                'R' => radius = Some(v * length),
291                'P' => p = Some((v, word)),
292                _ => return fail(line, "program-error-word", word),
293            }
294        }
295        // A full circle (G2/G3 with I, J, K and no end) moves too.
296        moving |= matches!(motion, Some(2 | 3)) && centre_offset.iter().any(Option::is_some);
297        // P is the dwell's seconds (G4) or the corner tolerance in the program's length unit (G64): RS-274NGC's (LinuxCNC);
298        // neither Siemens' G4 F nor Fanuc's G4 P in milliseconds is read.
299        let g64 = words.iter().any(|&(letter, v, _)| letter == 'G' && v == 64.0);
300        match p {
301            None if dwell => return fail(line, "program-error-p", clean),
302            Some((_, word)) if !dwell && !g64 => return fail(line, "program-error-word", word),
303            Some(_) if dwell && (g64 || moving) => return fail(line, "program-error-p", clean),
304            // LinuxCNC: G64 P0 is G64 alone.
305            Some((v, _)) if g64 && v >= 0.0 => mode = Some((v > 0.0).then_some(v * length)),
306            Some((v, _)) if dwell && (0.0..=MAX_DWELL_S).contains(&v) => {}
307            Some(_) => return fail(line, "program-error-p", clean),
308            None => {}
309        }
310        // The mode in force for the block's moves: a corner is governed by the mode of the block that follows it. A change
311        // starts a new run, so the corner at the change is stopped at (a path planned as one has one tolerance);
312        // LinuxCNC's G-code reference does not say what governs that corner.
313        if let Some(m) = mode.filter(|m| *m != corner) {
314            (corner, split) = (m, true);
315        }
316        if let (true, Some((seconds, _))) = (dwell, p) {
317            runs.push(Run { feed: None, caps: Vec::new(), pieces: Vec::new(), corner, dwell_s: seconds });
318            split = true;
319        }
320        if moving {
321            let Some(kind) = motion else { return fail(line, "program-error-motion", clean) };
322            let rate = if kind == 0 {
323                None
324            } else {
325                let (linear, rotary) =
326                    feed.ok_or_else(|| ProgramError { line, key: "program-error-feed", detail: clean.clone() })?;
327                Some(path_feed(axes, &pos, &target, linear, rotary))
328            };
329            let pieces = if kind < 2 {
330                vec![Piece::Line(target.clone())]
331            } else {
332                arc_block(line, axes, &pos, &target, plane, kind == 2, centre_offset, radius)?
333            };
334            for piece in pieces {
335                if std::mem::take(&mut split) {
336                    let caps = rate.into_iter().collect();
337                    runs.push(Run { feed: rate, caps, pieces: vec![piece], corner, dwell_s: 0.0 });
338                } else {
339                    push_by(&mut runs, rate, piece, true);
340                    if let Some(run) = runs.last_mut() {
341                        run.corner = corner;
342                    }
343                }
344            }
345            pos = target;
346        }
347        if ends {
348            break;
349        }
350    }
351    Ok(runs)
352}
353
354/// The speed along the path (over all axes, as `path::plan_at` takes it) that moves `from` to `to` at the F of the
355/// block: `linear` m/s for the linear axes' distance, else `rotary` rad/s for the rotary axes' (a block that only
356/// turns), and where both move the linear axes set the time and the rotary ones follow in it.
357fn path_feed(axes: &[AxisInfo], from: &[f64], to: &[f64], linear: f64, rotary: f64) -> f64 {
358    let (mut lin, mut rot) = (0.0, 0.0);
359    for (i, a) in axes.iter().enumerate() {
360        let d = (to[i] - from[i]).powi(2);
361        if a.unit == "rad" { rot += d } else { lin += d }
362    }
363    if lin > 0.0 {
364        linear * (lin + rot).sqrt() / lin.sqrt()
365    } else if rot > 0.0 {
366        rotary
367    } else {
368        linear
369    }
370}
371
372/// The arc of a G2 (`clockwise`) or G3 block in `plane` from `from` to `to`, its centre from the offsets I, J, K or
373/// the radius R, in the plane G17, G18 or G19 states (`Piece::Arc::plane`); a full circle (`to` at `from`, centre by I,
374/// J, K) as three arcs of 120 degrees, which a full turn's end cannot tell from no turn at all.
375#[allow(clippy::too_many_arguments)]
376fn arc_block(
377    line: usize,
378    axes: &[AxisInfo],
379    from: &[f64],
380    to: &[f64],
381    plane: u32,
382    clockwise: bool,
383    offset: [Option<f64>; 3],
384    radius: Option<f64>,
385) -> Result<Vec<Piece>> {
386    // The plane's axes, the first to the right and the second up seen from the plus side of the normal, and their
387    // offset letters.
388    let (a, b) = match plane {
389        17 => ('X', 'Y'),
390        18 => ('Z', 'X'),
391        _ => ('Y', 'Z'),
392    };
393    let letters = format!("G{plane}");
394    let (Some(ia), Some(ib)) = (axis_of(axes, a), axis_of(axes, b)) else {
395        return fail(line, "program-error-axis", letters);
396    };
397    // Every other axis stays: a helix, or a turn of A, B, C on the way, is not an arc of the path.
398    if (0..from.len()).any(|i| i != ia && i != ib && (to[i] - from[i]).abs() > 1e-12) {
399        return fail(line, "program-error-helix", letters);
400    }
401    let (sa, sb, ea, eb) = (from[ia], from[ib], to[ia], to[ib]);
402    let (ca, cb) = match radius {
403        Some(r) => {
404            let (da, db) = (ea - sa, eb - sb);
405            let d = (da * da + db * db).sqrt();
406            if d == 0.0 || r.abs() < d / 2.0 * (1.0 - 1e-9) {
407                return fail(line, "program-error-arc", format!("R{}", r * 1e3));
408            }
409            let h = (r * r - d * d / 4.0).max(0.0).sqrt();
410            // Clockwise with R > 0 (the shorter arc) has its centre to the right of the chord.
411            let side = if clockwise == (r > 0.0) { 1.0 } else { -1.0 };
412            ((sa + ea) / 2.0 + side * h * db / d, (sb + eb) / 2.0 - side * h * da / d)
413        }
414        None => {
415            let letter = |c: char| offset[(c as u8 - b'X') as usize].unwrap_or(0.0);
416            (sa + letter(a), sb + letter(b))
417        }
418    };
419    let (r0, r1) = ((sa - ca).hypot(sb - cb), (ea - ca).hypot(eb - cb));
420    if r0 == 0.0 || (r0 - r1).abs() > 1e-4 * r0 + 1e-6 {
421        return fail(line, "program-error-arc", format!("{:.4} / {:.4} mm", r0 * 1e3, r1 * 1e3));
422    }
423    let mut centre = from.to_vec();
424    (centre[ia], centre[ib]) = (ca, cb);
425    let turning = if clockwise { -1.0 } else { 1.0 };
426    let clockwise = path_clockwise(ia, ib, turning);
427    // The plane's normal is the third of x, y, z by position: it is what a half turn, whose end lies opposite its start,
428    // has no other way to tell the planner (G18 and G19 half turns lie in the x-z and y-z planes).
429    let plane = (ia < 3 && ib < 3).then(|| std::array::from_fn(|k| if k == 3 - ia - ib { 1.0 } else { 0.0 }));
430    if (ea - sa).hypot(eb - sb) > 1e-12 * r0 {
431        return Ok(vec![Piece::Arc { to: to.to_vec(), centre, clockwise, plane }]);
432    }
433    let start = (sb - cb).atan2(sa - ca);
434    Ok((1..=3)
435        .map(|k| {
436            let mut end = to.to_vec();
437            if k < 3 {
438                let angle = start + turning * k as f64 * 2.0 * std::f64::consts::PI / 3.0;
439                (end[ia], end[ib]) = (ca + r0 * angle.cos(), cb + r0 * angle.sin());
440            }
441            Piece::Arc { to: end, centre: centre.clone(), clockwise, plane }
442        })
443        .collect())
444}
445
446/// Robot moves as CSV (see the module).
447pub fn robot_csv(text: &str, axes: &[AxisInfo], start: &[f64]) -> Result<Vec<Run>> {
448    let mut pos = start.to_vec();
449    let mut runs = Vec::new();
450    for (n, raw) in text.lines().enumerate() {
451        let line = n + 1;
452        let raw = raw.trim();
453        if raw.is_empty() || raw.starts_with('#') {
454            continue;
455        }
456        let fields: Vec<&str> = raw.split(',').map(str::trim).collect();
457        let numbers: Option<Vec<f64>> =
458            fields[1..].iter().map(|v| v.parse().ok().filter(|x: &f64| x.is_finite())).collect();
459        let Some(numbers) = numbers else { return fail(line, "program-error-word", raw) };
460        let k = axes.len();
461        let piece = match fields[0].to_ascii_lowercase().as_str() {
462            "movel" | "movej" if numbers.len() == k => Piece::Line(numbers),
463            "movec" if numbers.len() == 2 * k => circle(line, &pos, &numbers[..k], &numbers[k..])?,
464            _ => return fail(line, "program-error-word", raw),
465        };
466        pos = match &piece {
467            Piece::Line(to) | Piece::Arc { to, .. } | Piece::Spline(to) => to.clone(),
468        };
469        push(&mut runs, None, piece);
470    }
471    Ok(runs)
472}
473
474/// The arc from `from` through `via` to `to`; on more than three axes on the first three, the others carried along.
475fn circle(line: usize, from: &[f64], via: &[f64], to: &[f64]) -> Result<Piece> {
476    let n = from.len().min(3);
477    match arc_through(&from[..n], &via[..n], &to[..n]) {
478        Some((centre, clockwise)) => {
479            // The plane of the three points: a half turn through them (end opposite start) is in no other plane.
480            let at = |p: &[f64]| [p[0], p[1], p.get(2).copied().unwrap_or(0.0)];
481            let (s, v, e) = (at(from), at(via), at(to));
482            let normal = cross([v[0] - s[0], v[1] - s[1], v[2] - s[2]], [e[0] - s[0], e[1] - s[1], e[2] - s[2]]);
483            let size = normal.iter().map(|x| x * x).sum::<f64>().sqrt();
484            Ok(Piece::Arc { to: to.to_vec(), centre, clockwise, plane: (n == 3).then(|| normal.map(|x| x / size)) })
485        }
486        None => fail(line, "program-error-arc", format!("{via:?}")),
487    }
488}
489
490/// The pose a robot position gives (`components`: name and value, mm and degrees): `from` with the axes of those
491/// names set; names the machine has no axis of are left out.
492fn robot_pose(axes: &[AxisInfo], from: &[f64], components: &[(String, f64)]) -> Vec<f64> {
493    let mut pose = from.to_vec();
494    for (name, v) in components {
495        if let Some(i) = axes.iter().position(|a| a.id.eq_ignore_ascii_case(name)) {
496            pose[i] = v * if axes[i].unit == "rad" { std::f64::consts::PI / 180.0 } else { 1e-3 };
497        }
498    }
499    pose
500}
501
502/// The indices of the axes rx, ry, rz, where the machine's tool has an orientation as a rotation vector.
503fn rotation_axes(axes: &[AxisInfo]) -> Option<[usize; 3]> {
504    let at = |id: &str| axes.iter().position(|a| a.id == id);
505    Some([at("rx")?, at("ry")?, at("rz")?])
506}
507
508/// KUKA's A, B, C (degrees) of a rotation vector: R = Rz(A) Ry(B) Rx(C).
509fn abc_of(r: [f64; 3]) -> [f64; 3] {
510    let m = crate::rigid::exp(r);
511    [m[1][0].atan2(m[0][0]), (-m[2][0]).clamp(-1.0, 1.0).asin(), m[2][1].atan2(m[2][2])].map(f64::to_degrees)
512}
513
514/// The rotation vector of KUKA's A, B, C (degrees).
515fn rotation_of_abc([a, b, c]: [f64; 3]) -> [f64; 3] {
516    crate::rigid::log(&crate::rigid::rpy([c.to_radians(), b.to_radians(), a.to_radians()]))
517}
518
519/// The tool's reorientation speed a robot program runs at by default (rad/s): 500 degrees per second, the default of
520/// ABB's `v_ori` (RAPID speeddata); `program.orientation_speed_rad_s` sets it.
521pub const ORIENTATION_SPEED: f64 = 500.0 * std::f64::consts::PI / 180.0;
522
523/// The config's `program.orientation_speed_rad_s` (above 0), `ORIENTATION_SPEED` where it has none: the value the front
524/// ends pass to `read_with`, as the simulator's own path run does.
525pub fn orientation_speed_of(cfg: &sim_core::Config) -> std::result::Result<f64, sim_core::ConfigError> {
526    let key = "program.orientation_speed_rad_s";
527    if cfg.get(key).is_ok() { cfg.positive(key) } else { std::result::Result::Ok(ORIENTATION_SPEED) }
528}
529
530/// The angle (rad) of the arc through `via` from `from` to `to` about `centre`, on the first three axes: the two
531/// parts from the start to `via` and from `via` to the end, each taken as at most a half turn.
532fn arc_angle(from: &[f64], via: &[f64], to: &[f64], centre: &[f64]) -> f64 {
533    let n = from.len().min(3);
534    let at = |p: &[f64]| (0..n).map(|i| p[i] - centre[i]).collect::<Vec<f64>>();
535    let angle = |a: &[f64], b: &[f64]| {
536        let (dot, size) = (a.iter().zip(b).map(|(x, y)| x * y).sum::<f64>(), (norm(a) * norm(b)).max(1e-300));
537        (dot / size).clamp(-1.0, 1.0).acos()
538    };
539    let (a, v, b) = (at(from), at(via), at(to));
540    angle(&a, &v) + angle(&v, &b)
541}
542
543fn norm(a: &[f64]) -> f64 {
544    a.iter().map(|x| x * x).sum::<f64>().sqrt()
545}
546
547/// The cap along the path (the planner's units: the length counts the rotation vector's radians with the metres) of a
548/// piece that a robot program runs at the tool centre's speed `v` (`None`: the axes' limits) while the orientation
549/// (the axes `rotation`, a rotation vector) turns at no more than `omega` rad/s (RAPID's `v_ori`): the piece takes
550/// the longer of d / v for the tool centre's distance d (the axes that are not the rotation's, along the arc through
551/// `via` on an arc) and theta / omega for the angle theta between the two orientations, and its length over that time
552/// is the cap. A move that only reorients (d = 0) runs at `omega`. Without a rotation, `v` itself.
553fn tcp_cap(
554    rotation: Option<[usize; 3]>,
555    from: &[f64],
556    piece: &Piece,
557    via: Option<&[f64]>,
558    v: Option<f64>,
559    omega: f64,
560) -> Option<f64> {
561    let v = v?;
562    let Some(rotation) = rotation else { return Some(v) };
563    let (Piece::Line(to) | Piece::Arc { to, .. } | Piece::Spline(to)) = piece;
564    let others = |from_axis: usize| -> f64 {
565        (from_axis..from.len()).filter(|i| !rotation.contains(i)).map(|i| (to[i] - from[i]).powi(2)).sum::<f64>()
566    };
567    let position = match (piece, via) {
568        (Piece::Arc { centre, .. }, Some(via)) => {
569            let r = norm(&from.iter().zip(centre).take(3).map(|(f, c)| f - c).collect::<Vec<f64>>());
570            (r * arc_angle(from, via, to, centre)).hypot(others(3).sqrt())
571        }
572        _ => others(0).sqrt(),
573    };
574    use crate::rigid::{exp, log, matmul, transpose};
575    let (a, b) = (rotation.map(|i| from[i]), rotation.map(|i| to[i]));
576    let turn = log(&matmul(&exp(b), &transpose(&exp(a))));
577    let theta = (turn[0] * turn[0] + turn[1] * turn[1] + turn[2] * turn[2]).sqrt();
578    let chord = (0..3).map(|k| (b[k] - a[k]).powi(2)).sum::<f64>().sqrt();
579    let time = (position / v).max(theta / omega);
580    if time > 0.0 && time.is_finite() { Some(position.hypot(chord) / time) } else { Some(v) }
581}
582
583/// KUKA KRL (see the module).
584pub fn krl(text: &str, axes: &[AxisInfo], start: &[f64]) -> Result<Vec<Run>> {
585    krl_with(text, axes, start, ORIENTATION_SPEED)
586}
587
588/// `krl` with the tool's reorientation speed `orientation_speed` (rad/s).
589pub fn krl_with(text: &str, axes: &[AxisInfo], start: &[f64], orientation_speed: f64) -> Result<Vec<Run>> {
590    let mut pos = start.to_vec();
591    let mut runs = Vec::new();
592    // The orientation as KUKA's A, B, C, where the machine has rx, ry, rz: components left out are kept.
593    let rotation = rotation_axes(axes);
594    let mut abc = rotation.map(|r| abc_of(r.map(|i| start[i])));
595    let mut speed = None;
596    let mut last: Option<Option<f64>> = None;
597    for (n, raw) in text.lines().enumerate() {
598        let line = n + 1;
599        let code = raw.split(';').next().unwrap_or("").trim();
600        if let Some(value) = code.to_ascii_uppercase().strip_prefix("$VEL.CP") {
601            let value = value.trim().strip_prefix('=').map(str::trim).and_then(|v| v.parse::<f64>().ok());
602            speed = Some(value.filter(|v| *v > 0.0 && v.is_finite()).ok_or_else(|| ProgramError {
603                line,
604                key: "program-error-word",
605                detail: code.to_string(),
606            })?);
607            continue;
608        }
609        let keyword: String = code.chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '_').collect();
610        let keyword = keyword.to_ascii_uppercase();
611        if !matches!(keyword.as_str(), "PTP" | "LIN" | "CIRC") {
612            if ["PTP_", "LIN_", "CIRC_", "SPLINE", "SPL", "SLIN", "SCIRC", "SPTP"]
613                .iter()
614                .any(|k| keyword.starts_with(k))
615            {
616                return fail(line, "program-error-word", code);
617            }
618            continue;
619        }
620        // The aggregates in braces: {X 100, Y 0, Z 500} or {E6POS: X 100, ...}.
621        let mut aggregates = Vec::new();
622        let mut rest = &code[keyword.len()..];
623        while let Some(open) = rest.find('{') {
624            let Some(close) = rest[open..].find('}') else { return fail(line, "program-error-word", code) };
625            let inner = &rest[open + 1..open + close];
626            let inner = inner.split_once(':').map_or(inner, |(_, r)| r);
627            let mut components = Vec::new();
628            for part in inner.split(',').map(str::trim).filter(|p| !p.is_empty()) {
629                let (name, value) = part.split_once(char::is_whitespace).unwrap_or((part, ""));
630                let Some(v) = value.trim().parse::<f64>().ok().filter(|v| v.is_finite()) else {
631                    return fail(line, "program-error-word", part);
632                };
633                components.push((name.to_string(), v));
634            }
635            aggregates.push(components);
636            rest = &rest[open + close + 1..];
637        }
638        // A pose with its orientation from A, B, C where the machine has rx, ry, rz (the aux point's is not used).
639        let mut oriented = |from: &[f64], components: &[(String, f64)]| {
640            let mut pose = robot_pose(axes, from, components);
641            if let (Some(rotation), Some(abc)) = (rotation, abc.as_mut()) {
642                for (name, v) in components {
643                    if let Some(k) = ["A", "B", "C"].iter().position(|c| name.eq_ignore_ascii_case(c)) {
644                        abc[k] = *v;
645                    }
646                }
647                for (i, r) in rotation.into_iter().zip(rotation_of_abc(*abc)) {
648                    pose[i] = r;
649                }
650            }
651            pose
652        };
653        let (piece, via, feed) = match (keyword.as_str(), aggregates.as_slice()) {
654            ("PTP", [end]) => (Piece::Line(oriented(&pos, end)), None, None),
655            ("LIN", [end]) => (Piece::Line(oriented(&pos, end)), None, speed),
656            ("CIRC", [aux, end]) => {
657                let via = robot_pose(axes, &pos, aux);
658                let to = oriented(&pos, end);
659                (circle(line, &pos, &via, &to)?, Some(via), speed)
660            }
661            _ => return fail(line, "program-error-named", code),
662        };
663        let capped = tcp_cap(rotation, &pos, &piece, via.as_deref(), feed, orientation_speed);
664        pos = match &piece {
665            Piece::Line(to) | Piece::Arc { to, .. } | Piece::Spline(to) => to.clone(),
666        };
667        // Moves at the same programmed speed are one run, whatever each one's cap along the path is.
668        push_by(&mut runs, capped, piece, last == Some(feed));
669        last = Some(feed);
670    }
671    Ok(runs)
672}
673
674/// ABB RAPID (see the module).
675pub fn rapid(text: &str, axes: &[AxisInfo], start: &[f64]) -> Result<Vec<Run>> {
676    rapid_with(text, axes, start, ORIENTATION_SPEED)
677}
678
679/// `rapid` with the tool's reorientation speed `orientation_speed` (rad/s).
680pub fn rapid_with(text: &str, axes: &[AxisInfo], start: &[f64], orientation_speed: f64) -> Result<Vec<Run>> {
681    // Statements end at ';'; a '!' starts a comment to the end of its line. Each statement keeps the line it starts on.
682    let mut statements: Vec<(usize, String)> = Vec::new();
683    let mut current = (0, String::new());
684    for (n, raw) in text.lines().enumerate() {
685        let code = raw.split('!').next().unwrap_or("");
686        for (i, piece) in code.split(';').enumerate() {
687            if current.1.trim().is_empty() {
688                current.0 = n + 1;
689            }
690            if i > 0 {
691                statements.push(std::mem::take(&mut current));
692                current.0 = n + 1;
693            }
694            current.1.push_str(piece);
695            current.1.push(' ');
696        }
697    }
698    // The numbers of a bracket of numbers, `[a, b, ...]`.
699    let numbers = |text: &str| -> Option<Vec<f64>> {
700        let inner = text.trim().strip_prefix('[')?;
701        inner.split(']').next()?.split(',').map(|v| v.trim().parse().ok().filter(|v: &f64| v.is_finite())).collect()
702    };
703    // The [x, y, z] of a robtarget (mm), and its orientation [q1, q2, q3, q4] as "q1".."q4" where it has one.
704    let position = |target: &str| -> Option<Vec<(String, f64)>> {
705        let inner = target.trim().strip_prefix('[')?;
706        let place = numbers(inner)?;
707        if place.len() != 3 {
708            return None;
709        }
710        let mut out: Vec<(String, f64)> = ["x", "y", "z"].iter().map(|s| s.to_string()).zip(place).collect();
711        let rest = inner.split_once(']').map_or("", |(_, r)| r).trim_start().trim_start_matches(',');
712        if let Some(q) = numbers(rest).filter(|q| q.len() == 4) {
713            out.extend(["q1", "q2", "q3", "q4"].iter().map(|s| s.to_string()).zip(q));
714        }
715        Some(out)
716    };
717    let rotation = rotation_axes(axes);
718    // A robtarget's pose: its position, and its orientation where the machine has rx, ry, rz.
719    let oriented = |from: &[f64], components: &[(String, f64)]| {
720        let mut pose = robot_pose(axes, from, components);
721        let q: Vec<f64> = components.iter().filter(|(n, _)| n.starts_with('q')).map(|(_, v)| *v).collect();
722        let size = q.iter().map(|v| v * v).sum::<f64>().sqrt();
723        if let (Some(rotation), true) = (rotation, q.len() == 4 && size > 0.0) {
724            let r = crate::rigid::from_quaternion([q[0], q[1], q[2], q[3]].map(|v| v / size));
725            for (i, r) in rotation.into_iter().zip(r) {
726                pose[i] = r;
727            }
728        }
729        pose
730    };
731    let mut named: std::collections::HashMap<String, Vec<(String, f64)>> = Default::default();
732    // Declared speeddata: the TCP speed, m/s.
733    let mut speeds: std::collections::HashMap<String, f64> = Default::default();
734    let mut pos = start.to_vec();
735    let mut runs = Vec::new();
736    let mut last: Option<Option<f64>> = None;
737    for (line, statement) in statements {
738        let statement = statement.split_whitespace().collect::<Vec<_>>().join(" ");
739        let words: Vec<&str> = statement.split(' ').collect();
740        if let Some(at) = words.iter().position(|w| w.eq_ignore_ascii_case("speeddata")) {
741            let declaration = words[at + 1..].join(" ");
742            if let Some((name, value)) = declaration.split_once(":=") {
743                let Some(v) = numbers(value).and_then(|v| v.first().copied()).filter(|v| *v > 0.0) else {
744                    return fail(line, "program-error-word", statement);
745                };
746                speeds.insert(name.trim().to_string(), v * 1e-3);
747            }
748            continue;
749        }
750        if let Some(at) = words.iter().position(|w| w.eq_ignore_ascii_case("robtarget")) {
751            let declaration = words[at + 1..].join(" ");
752            if let Some((name, value)) = declaration.split_once(":=") {
753                let Some(p) = position(value) else { return fail(line, "program-error-word", statement) };
754                named.insert(name.trim().to_string(), p);
755            }
756            continue;
757        }
758        // A statement may begin with lines that end without a semicolon (PROC main()): the move is where its word is.
759        let Some(at) = words.iter().position(|w| w.to_ascii_lowercase().starts_with("move")) else { continue };
760        let (instruction, args_text) = (words[at], words[at + 1..].join(" "));
761        // Arguments at the top level, split at commas outside brackets.
762        let args_text = args_text.trim();
763        let (mut args, mut depth, mut from) = (Vec::new(), 0, 0);
764        for (i, c) in args_text.char_indices() {
765            match c {
766                '[' => depth += 1,
767                ']' => depth -= 1,
768                ',' if depth == 0 => {
769                    args.push(args_text[from..i].trim());
770                    from = i + 1;
771                }
772                _ => {}
773            }
774        }
775        args.push(args_text[from..].trim());
776        let target = |arg: &str| -> Result<Vec<(String, f64)>> {
777            let arg = arg.split('\\').next().unwrap_or(arg).trim();
778            position(arg).or_else(|| named.get(arg).cloned()).ok_or_else(|| ProgramError {
779                line,
780                key: "program-error-named",
781                detail: arg.to_string(),
782            })
783        };
784        // The speed along the path (m/s): `vmax` or none given, the axes' limits.
785        let speed = |arg: Option<&&str>| -> Result<Option<f64>> {
786            let Some(arg) = arg.map(|a| a.split('\\').next().unwrap_or(a).trim()) else { return Ok(None) };
787            if arg.eq_ignore_ascii_case("vmax") {
788                return Ok(None);
789            }
790            let predefined = arg.strip_prefix(['v', 'V']).and_then(|n| n.parse::<f64>().ok());
791            let given = numbers(arg).and_then(|v| v.first().copied());
792            match predefined.or(given).map(|mm| mm * 1e-3).or_else(|| speeds.get(arg).copied()) {
793                Some(v) if v > 0.0 && v.is_finite() => Ok(Some(v)),
794                _ => fail(line, "program-error-named", arg),
795            }
796        };
797        let (piece, via, feed) = match instruction.to_ascii_lowercase().as_str() {
798            "movel" | "movej" => (Piece::Line(oriented(&pos, &target(args[0])?)), None, speed(args.get(1))?),
799            "movec" if args.len() >= 2 => {
800                let via = robot_pose(axes, &pos, &target(args[0])?);
801                let to = oriented(&pos, &target(args[1])?);
802                (circle(line, &pos, &via, &to)?, Some(via), speed(args.get(2))?)
803            }
804            _ => return fail(line, "program-error-word", instruction.to_string()),
805        };
806        let capped = tcp_cap(rotation, &pos, &piece, via.as_deref(), feed, orientation_speed);
807        pos = match &piece {
808            Piece::Line(to) | Piece::Arc { to, .. } | Piece::Spline(to) => to.clone(),
809        };
810        push_by(&mut runs, capped, piece, last == Some(feed));
811        last = Some(feed);
812    }
813    Ok(runs)
814}
815
816#[cfg(test)]
817mod tests {
818    use super::*;
819    use std::f64::consts::PI;
820
821    fn axis(id: &'static str) -> AxisInfo {
822        AxisInfo { id, key: "", unit: "m", min: -1.0, max: 1.0, max_vel: 1.0, max_acc: 10.0, max_jerk: 1000.0 }
823    }
824
825    /// Length of a planned path: the sum of its steps.
826    fn length(axes: &[AxisInfo], start: &[f64], pieces: &[Piece]) -> f64 {
827        let points = crate::path::plan(axes, start, pieces, 1e-3, 0.0, crate::path::ARC_SLACK).unwrap();
828        let mut last = start.to_vec();
829        let mut total = 0.0;
830        for (_, p) in &points {
831            total += p.iter().zip(&last).map(|(a, b)| (a - b).powi(2)).sum::<f64>().sqrt();
832            last = p.clone();
833        }
834        total
835    }
836
837    /// A quarter circle in G-code: from (0, 0) G2 X10 Y10 I10 J0 in mm has its centre at (10, 0) mm, radius 10 mm, and
838    /// turns clockwise from 180 to 90 degrees: a quarter, 10 pi / 2 = 15.708 mm long. G3 to the same end goes the other
839    /// way round, three quarters, 47.124 mm. R10 gives the same centre (the shorter arc, to the right of the chord for
840    /// G2), R-10 the longer arc around (0, 10). Measured on the path the planner runs.
841    #[test]
842    fn a_gcode_arc_has_its_centre_and_length() {
843        let axes = [axis("x"), axis("y")];
844        let start = [0.0, 0.0];
845        let arc = |text: &str| -> (Vec<f64>, bool) {
846            let runs = gcode(text, &axes, &start).unwrap();
847            match &runs[0].pieces[0] {
848                Piece::Arc { centre, clockwise, .. } => (centre.clone(), *clockwise),
849                p => panic!("{p:?}"),
850            }
851        };
852        for (text, centre, turn, long) in [
853            ("G21 G17 F600\nG2 X10 Y10 I10 J0", [0.01, 0.0], true, PI / 2.0),
854            ("F600\nG3 X10 Y10 I10", [0.01, 0.0], false, 1.5 * PI),
855            ("F600\nG2 X10 Y10 R10", [0.01, 0.0], true, PI / 2.0),
856            ("F600\nG2 X10 Y10 R-10", [0.0, 0.01], true, 1.5 * PI),
857        ] {
858            let (c, clockwise) = arc(text);
859            assert!(c.iter().zip(centre).all(|(a, b)| (a - b).abs() < 1e-12) && clockwise == turn, "{text}: {c:?}");
860            let runs = gcode(text, &axes, &start).unwrap();
861            let l = length(&axes, &start, &runs[0].pieces);
862            assert!((l - 0.01 * long).abs() < 1e-5, "{text}: {l} m against {}", 0.01 * long);
863        }
864        // F600 mm/min is 0.01 m/s.
865        assert!((gcode("G1 X1 F600", &axes, &start).unwrap()[0].feed.unwrap() - 0.01).abs() < 1e-15);
866    }
867
868    /// F per minute is mm for linear axes and degrees for a block with rotary axes only. With x (m) and c (rad):
869    /// `G1 X10 F600` is 10 mm at 10 mm/s, 1 s: path speed 0.01. `G1 C90 F3600` is pi/2 rad at 3600 deg/min = pi/3
870    /// rad/s, 1.5 s. `G1 X10 C90 F600` takes 1 s for the 10 mm, so the path of length sqrt(0.01^2 + (pi/2)^2) runs at
871    /// that length per second.
872    #[test]
873    fn feed_is_per_minute_in_mm_or_degrees() {
874        let mut c = axis("c");
875        c.unit = "rad";
876        let axes = [axis("x"), c];
877        let feed = |text: &str| gcode(text, &axes, &[0.0, 0.0]).unwrap()[0].feed.unwrap();
878        assert!((feed("G1 X10 F600") - 0.01).abs() < 1e-15);
879        assert!((feed("G1 C90 F3600") - PI / 3.0).abs() < 1e-12);
880        assert!((feed("G1 X10 C90 F600") - (0.01f64.powi(2) + (PI / 2.0).powi(2)).sqrt()).abs() < 1e-12);
881        // Planned (axes quick enough that the ramps take a few ms: v / a + a / j at most 1.05 + 1 ms), the three take 1,
882        // 1.5 and 1 s.
883        let quick = axes.map(|a| AxisInfo { max_vel: 10.0, max_acc: 1e3, max_jerk: 1e6, ..a });
884        for (text, time) in [("G1 X10 F600", 1.0), ("G1 C90 F3600", 1.5), ("G1 X10 C90 F600", 1.0)] {
885            let runs = gcode(text, &quick, &[0.0, 0.0]).unwrap();
886            let caps = runs[0].caps().unwrap();
887            let points =
888                crate::path::plan_feeds(&quick, &[0.0, 0.0], &runs[0].pieces, &caps, 1e-3, 0.0, crate::path::ARC_SLACK)
889                    .unwrap();
890            let planned = points[points.len() - 1].0;
891            assert!(planned >= time && planned <= time + 4e-3, "{text}: {planned} s");
892        }
893    }
894
895    /// A feed that changes between blocks is a cap per piece inside one run, with no stop between: `F600 G1 X10 / F1200 G1
896    /// X20 / F600 G1 X30` is 10 mm at 10 mm/s, 10 mm at 20 mm/s and 10 mm at 10 mm/s: 1 + 0.5 + 1 = 2.5 s (the ramps between
897    /// the speeds add a few ms: 0.01 m/s over a jerk of 1000 m/s^3 takes 2 sqrt(0.01 / 1000) = 6.3 ms), and the path
898    /// passes x = 10 mm at the lower feed, 10 mm/s, not at rest.
899    #[test]
900    fn a_feed_that_changes_between_blocks_is_a_cap_per_piece_in_one_run() {
901        let axes = [axis("x"), axis("y")];
902        let runs = gcode(
903            "F600
904G1 X10
905F1200
906G1 X20
907F600
908G1 X30",
909            &axes,
910            &[0.0; 2],
911        )
912        .unwrap();
913        assert_eq!(runs.len(), 1);
914        let caps = runs[0].caps().unwrap();
915        assert!(caps.iter().zip([0.01, 0.02, 0.01]).all(|(a, b)| (a - b).abs() < 1e-15) && runs[0].feed == Some(0.02));
916        let points =
917            crate::path::plan_feeds(&axes, &[0.0; 2], &runs[0].pieces, &caps, 1e-3, 0.0, crate::path::ARC_SLACK)
918                .unwrap();
919        let (time, k) = (points[points.len() - 1].0, points.iter().position(|(_, p)| p[0] >= 0.01).unwrap());
920        let speed = (points[k + 1].1[0] - points[k - 1].1[0]) / 2e-3;
921        assert!((time - 2.5).abs() < 0.03 && (speed - 0.01).abs() < 1e-4, "{time} s, {speed} m/s at 10 mm");
922    }
923
924    /// `F600 / G1 X1 / G2 I10` is 1 mm, then a full circle of radius 10 mm: 0.001 + 2 pi 0.01 m on the planned path, which
925    /// closes where the circle starts, (1, 0) mm, and reaches x = 21 mm and y = 10 and -10 mm on the way.
926    #[test]
927    fn a_full_circle_is_planned() {
928        let axes = [axis("x"), axis("y")];
929        let runs = gcode(
930            "F600
931G1 X1
932G2 I10",
933            &axes,
934            &[0.0; 2],
935        )
936        .unwrap();
937        let pieces = &runs[0].pieces;
938        assert_eq!(pieces.len(), 4);
939        let l = length(&axes, &[0.0; 2], pieces);
940        assert!((l - (0.001 + 2.0 * PI * 0.01)).abs() < 1e-5, "{l}");
941        let points = crate::path::plan(&axes, &[0.0; 2], pieces, 1e-3, 0.0, crate::path::ARC_SLACK).unwrap();
942        let end = &points[points.len() - 1].1;
943        assert!((end[0] - 0.001).abs() < 1e-12 && end[1].abs() < 1e-12, "ends at {end:?}");
944        // The poses (some 1 mm apart) reach the circle's far side and both of its extremes in y.
945        let most = |f: &dyn Fn(&[f64]) -> f64| points.iter().map(|(_, p)| f(p)).fold(f64::NEG_INFINITY, f64::max);
946        let (x, up, down) = (most(&|p| p[0]), most(&|p| p[1]), most(&|p| -p[1]));
947        assert!([x - 0.021, up - 0.01, down - 0.01].iter().all(|d| d.abs() < 2e-4), "{x} {up} {down}");
948    }
949
950    /// A KRL CIRC whose end leaves out a component keeps it from the point before, not from the auxiliary point: from
951    /// (0, 0, 100) mm through {X 100, Y 100, Z 200} to {X 200, Y 0} ends at z = 100 mm, on the circle through the three
952    /// points, and the planned path ends there.
953    #[test]
954    fn a_krl_circ_keeps_a_component_left_out_of_its_end_from_the_point_before() {
955        let axes = [axis("x"), axis("y"), axis("z")];
956        let runs = krl("LIN {X 0, Y 0, Z 100}\nCIRC {X 100, Y 100, Z 200}, {X 200, Y 0}", &axes, &[0.0; 3]).unwrap();
957        let pieces: Vec<Piece> = runs.iter().flat_map(|r| r.pieces.clone()).collect();
958        let Piece::Arc { to, .. } = &pieces[1] else { panic!("{pieces:?}") };
959        assert!(to.iter().zip([0.2, 0.0, 0.1]).all(|(a, b)| (a - b).abs() < 1e-12), "{to:?}");
960        let points = crate::path::plan(&axes, &[0.0; 3], &pieces, 1e-3, 0.0, crate::path::ARC_SLACK).unwrap();
961        let end = &points[points.len() - 1].1;
962        assert!(end.iter().zip([0.2, 0.0, 0.1]).all(|(a, b)| (a - b).abs() < 1e-9), "{end:?}");
963    }
964
965    /// The other planes and units: G18 on a gantry of x and z: G2 is clockwise seen from +y, so counterclockwise seen
966    /// from -y, where x is to the right and z up as the path reads two axes. G20 reads inches: X1 is 25.4 mm. G91 adds.
967    #[test]
968    fn gcode_planes_units_and_increments() {
969        let xz = [axis("x"), axis("z")];
970        let runs = gcode("G18 G20 F10\nG2 X1 Z1 I1 K0", &xz, &[0.0, 0.0]).unwrap();
971        let Piece::Arc { to, centre, clockwise, .. } = &runs[0].pieces[0] else { panic!() };
972        assert!(!clockwise && (to[0] - 0.0254).abs() < 1e-12 && (centre[0] - 0.0254).abs() < 1e-12 && centre[1] == 0.0);
973        // Seen from -y, G2 from (0, 0) to (25.4, 25.4) mm around (25.4, 0) is the three-quarter way: 3/4 2 pi 25.4 mm.
974        let l = length(&xz, &[0.0, 0.0], &runs[0].pieces);
975        assert!((l - 1.5 * PI * 0.0254).abs() < 1e-5, "{l}");
976        let runs = gcode("G91 G0 X10\nX10 Z-5", &xz, &[0.1, 0.1]).unwrap();
977        assert_eq!(runs[0].feed, None);
978        let Piece::Line(end) = &runs[0].pieces[1] else { panic!() };
979        assert!((end[0] - 0.12).abs() < 1e-15 && (end[1] - 0.095).abs() < 1e-15, "{end:?}");
980    }
981
982    /// Half turns on three axes lie in the plane the program states: G18 from (10, 0, 0) mm to (-10, 0, 0) around the origin
983    /// is in the x-z plane (y stays 0, z reaches the radius 10 mm), where the first plane holding the start's radius would
984    /// have been x-y. The three points of a MoveC (-0.5, 0, 0), (0, 0, 0.5), (0.5, 0, 0) say x-z too (their normal is
985    /// (1, 0, 1) x (2, 0, 0) = (0, 2, 0)), and the circle through them reaches z = 0.5.
986    #[test]
987    fn a_half_turn_on_three_axes_lies_in_the_plane_the_program_states() {
988        let axes = [axis("x"), axis("y"), axis("z")];
989        let reach = |start: &[f64], pieces: &[Piece]| {
990            let points = crate::path::plan(&axes, start, pieces, 1e-3, 0.0, crate::path::ARC_SLACK).unwrap();
991            points.iter().fold((0f64, 0f64), |(y, z), (_, p)| (y.max(p[1].abs()), z.max(p[2].abs())))
992        };
993        let start = [0.01, 0.0, 0.0];
994        let runs = gcode(
995            "G18 F600
996G2 X-10 Z0 I-10 K0",
997            &axes,
998            &start,
999        )
1000        .unwrap();
1001        assert!(matches!(&runs[0].pieces[0], Piece::Arc { plane: Some(n), .. } if *n == [0.0, 1.0, 0.0]));
1002        let (y, z) = reach(&start, &runs[0].pieces);
1003        assert!(y < 1e-12 && (z - 0.01).abs() < 1e-4, "y {y} m, z {z} m");
1004        let runs = robot_csv(
1005            "MoveL,-0.5,0,0
1006MoveC,0,0,0.5,0.5,0,0",
1007            &axes,
1008            &[0.0; 3],
1009        )
1010        .unwrap();
1011        let (y, z) = reach(&[0.0; 3], &runs[0].pieces);
1012        assert!(y < 1e-12 && (z - 0.5).abs() < 1e-3, "y {y} m, z {z} m");
1013    }
1014
1015    /// What G-code the reader does not take is refused with its line.
1016    #[test]
1017    fn unsupported_gcode_is_refused_by_line() {
1018        let axes = [axis("x"), axis("y"), axis("z")];
1019        let error = |text: &str| gcode(text, &axes, &[0.0; 3]).unwrap_err();
1020        assert_eq!(error("G0 X1\nG41"), ProgramError { line: 2, key: "program-error-word", detail: "G41".into() });
1021        assert_eq!(error("G1 X1").key, "program-error-feed");
1022        assert_eq!(error("F100\nG2 X10 Y0 Z5 I5").key, "program-error-helix");
1023        assert_eq!(error("F100\nG2 X10 I3").key, "program-error-arc");
1024        assert_eq!(gcode("G0 A1", &axes[..2], &[0.0; 2]).unwrap_err().key, "program-error-axis");
1025        // Comments, line numbers and switching functions pass; M30 ends the program.
1026        let runs = gcode("%\nN10 G0 X1 (to the side) ; rapid\nM3 S1000\nM30\nG0 X2", &axes, &[0.0; 3]).unwrap();
1027        let line = vec![Piece::Line(vec![0.001, 0.0, 0.0])];
1028        assert_eq!(runs, vec![Run { feed: None, caps: vec![], pieces: line, corner: None, dwell_s: 0.0 }]);
1029    }
1030
1031    /// G61, G64 and G64 P are modal and each change starts a run, with the tolerance in force for the block that follows
1032    /// the corner: G61 is 0, G64 the config's (`None`), G64 P0.5 in mm 0.0005 m and in inch (G20) P0.02 is 0.02 x 0.0254 =
1033    /// 0.000508 m. Without a change the moves stay one run.
1034    #[test]
1035    fn g61_and_g64_set_the_corner_tolerance_by_run() {
1036        let axes = [axis("x"), axis("y"), axis("z")];
1037        let read = |text: &str| gcode(text, &axes, &[0.0; 3]).unwrap();
1038        let corners = |text: &str| read(text).iter().map(|r| (r.corner, r.pieces.len())).collect::<Vec<_>>();
1039        assert_eq!(corners("F6000\nG1 X10\nG1 Y10\nG1 X0"), [(None, 3)]);
1040        assert_eq!(
1041            corners("F6000\nG1 X10\nG1 Y10\nG61\nG1 X0\nG64 P0.5\nG1 Y0\nG1 X5\nG64\nG1 Y5"),
1042            [(None, 2), (Some(0.0), 1), (Some(0.0005), 2), (None, 1)]
1043        );
1044        // The same mode again is no change; the unit of P is the program's.
1045        assert_eq!(corners("F6000\nG61\nG1 X10\nG61\nG1 Y10"), [(Some(0.0), 2)]);
1046        // G64 P0 is G64 alone (LinuxCNC), not G61.
1047        assert_eq!(corners("F6000\nG61\nG1 X10\nG64 P0\nG1 Y10"), [(Some(0.0), 1), (None, 1)]);
1048        let inch = read("F100\nG20 G64 P0.02\nG1 X1")[0].corner.unwrap();
1049        assert!((inch - 0.000508).abs() < 1e-15, "{inch}");
1050        // P with G64 in the block of the move: the mode governs that move.
1051        assert_eq!(corners("F6000\nG1 X10\nG64 P1 G1 Y10")[1], (Some(0.001), 1));
1052    }
1053
1054    /// G4 P<s> is a run of its own with no pieces and the time; the moves after it are a run of their own, so the path
1055    /// stops before and after it. G4 without P, with a negative P or one beyond an hour, with a move in its block, and
1056    /// a P with no G4 or G64 are refused with their line.
1057    #[test]
1058    fn g4_is_a_dwell_run_and_wrong_p_is_refused() {
1059        let axes = [axis("x"), axis("y"), axis("z")];
1060        let runs = gcode("F6000\nG1 X10\nG4 P0.5\nG1 X20", &axes, &[0.0; 3]).unwrap();
1061        assert_eq!(runs.len(), 3, "{runs:?}");
1062        assert_eq!((runs[0].pieces.len(), runs[0].dwell_s), (1, 0.0));
1063        assert_eq!((runs[1].pieces.len(), runs[1].dwell_s, runs[1].feed), (0, 0.5, None));
1064        assert_eq!((runs[2].pieces.len(), runs[2].dwell_s), (1, 0.0));
1065        assert!((runs[2].feed.unwrap() - 0.1).abs() < 1e-12);
1066        for text in ["G4", "G4 P-1", "G4 P7200", "G0 X1\nG4 P1 X5", "G4 P1 G64", "G64 P-1"] {
1067            assert_eq!(gcode(text, &axes, &[0.0; 3]).unwrap_err().key, "program-error-p", "{text}");
1068        }
1069        assert_eq!(gcode("G0 X1\nP5", &axes, &[0.0; 3]).unwrap_err().key, "program-error-word");
1070    }
1071
1072    /// Robot programs: MoveC through (0, 1) from (-1, 0) to (1, 0) is the upper half circle around (0, 0), clockwise as
1073    /// the path sees two axes; KRL and RAPID give the same in mm.
1074    #[test]
1075    fn robot_programs_read_lines_and_circles() {
1076        let axes = [axis("x"), axis("y")];
1077        let half = Piece::Arc { to: vec![1.0, 0.0], centre: vec![0.0, 0.0], clockwise: true, plane: None };
1078        let csv = robot_csv("MoveL,-1,0\nMoveC,0,1,1,0", &axes, &[0.0, 0.0]).unwrap();
1079        assert_eq!(csv[0].pieces, vec![Piece::Line(vec![-1.0, 0.0]), half.clone()]);
1080        let close = |a: &Piece, b: &Piece| match (a, b) {
1081            (Piece::Arc { to, centre, clockwise, .. }, Piece::Arc { to: t2, centre: c2, clockwise: w2, .. }) => {
1082                to.iter().chain(centre).zip(t2.iter().chain(c2)).all(|(x, y)| (x - y).abs() < 1e-12) && clockwise == w2
1083            }
1084            (Piece::Line(a), Piece::Line(b)) => a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-12),
1085            _ => false,
1086        };
1087        let src =
1088            "DEF demo()\n  PTP {X -1000, Y 0, Z 500, A 0, B 90, C 0} ; start\n  CIRC {X 0, Y 1000}, {X 1000, Y 0}\nEND";
1089        let kuka = krl(src, &axes, &[0.0, 0.0]).unwrap();
1090        assert!(
1091            close(&kuka[0].pieces[0], &Piece::Line(vec![-1.0, 0.0])) && close(&kuka[0].pieces[1], &half),
1092            "{kuka:?}"
1093        );
1094        let module = "MODULE m\n CONST robtarget p1 := [[0,1000,0],[1,0,0,0],[0,0,0,0],[9E9,9E9,9E9,9E9,9E9,9E9]];\n PROC main()\n  MoveL [[-1000,0,0],[1,0,0,0],[0,0,0,0],[9E9,9E9,9E9,9E9,9E9,9E9]], v100, z10, tool0;\n  MoveC p1, [[1000,0,0],[1,0,0,0],[0,0,0,0],[9E9,9E9,9E9,9E9,9E9,9E9]], v100, fine, tool0; ! half\n ENDPROC\nENDMODULE";
1095        let abb = rapid(module, &axes, &[0.0, 0.0]).unwrap();
1096        assert!(close(&abb[0].pieces[0], &Piece::Line(vec![-1.0, 0.0])) && close(&abb[0].pieces[1], &half), "{abb:?}");
1097        assert_eq!(rapid("MoveAbsJ jpos, v100, fine, tool0;", &axes, &[0.0; 2]).unwrap_err().key, "program-error-word");
1098        assert_eq!(krl("PTP HOME", &axes, &[0.0; 2]).unwrap_err().key, "program-error-named");
1099        // The circle is the half turn: pi m long on the planned path.
1100        assert!((length(&axes, &[-1.0, 0.0], &[half]) - PI).abs() < 1e-4);
1101    }
1102
1103    /// Robot programs carry their speeds and, on an arm in tool space (axes x, y, z, rx, ry, rz), their orientations.
1104    /// RAPID: v100 is 100 mm/s, 0.1 m/s; a speeddata declared as [250, 500, 5000, 1000] 0.25 m/s; vmax the axes' limits.
1105    /// The quaternion [cos 45°, 0, 0, sin 45°] is a quarter turn about z, the rotation vector (0, 0, pi / 2). KRL:
1106    /// `$VEL.CP = 0.2` is 0.2 m/s for the LIN after it, a PTP runs at the axes' limits; A 90 (B 0, C 0) is Rz(90°), the
1107    /// same quarter turn; positions in mm.
1108    #[test]
1109    fn robot_programs_carry_their_speeds_and_orientations() {
1110        let axes = ["x", "y", "z", "rx", "ry", "rz"].map(axis);
1111        let half = std::f64::consts::FRAC_1_SQRT_2;
1112        let module = format!(
1113            "MODULE m\n VAR speeddata vfast := [250, 500, 5000, 1000];\n PROC main()\n  MoveL [[100,0,0],[{half},0,0,{half}],\
1114             [0,0,0,0],[9E9,9E9,9E9,9E9,9E9,9E9]], v100, z10, tool0;\n  MoveL [[200,0,0],[1,0,0,0],[0,0,0,0],\
1115             [9E9,9E9,9E9,9E9,9E9,9E9]], vfast, fine, tool0;\n  MoveJ [[0,0,0],[1,0,0,0],[0,0,0,0],[9E9,9E9,9E9,9E9,9E9,9E9]], \
1116             vmax, fine, tool0;\n ENDPROC\nENDMODULE"
1117        );
1118        let runs = rapid(&module, &axes, &[0.0; 6]).unwrap();
1119        // The cap along the path is the path's length (the 0.1 m and the quarter turn's pi / 2 rad, counted together) over
1120        // the move's time: 0.1 m at 0.1 m/s takes 1 s, 0.1 m at 0.25 m/s 0.4 s, and the quarter turn at 500 degrees per
1121        // second only 0.18 s, so the tool centre's speed sets the time.
1122        let length = 0.1_f64.hypot(PI / 2.0);
1123        let feeds: Vec<_> = runs.iter().map(|r| r.feed).collect();
1124        assert!(
1125            feeds[0].is_some_and(|f| (f - length / 1.0).abs() < 1e-12)
1126                && feeds[1].is_some_and(|f| (f - length / 0.4).abs() < 1e-12)
1127                && feeds[2].is_none(),
1128            "{feeds:?}"
1129        );
1130        let Piece::Line(turned) = &runs[0].pieces[0] else { panic!() };
1131        assert!(
1132            turned.iter().zip([0.1, 0.0, 0.0, 0.0, 0.0, PI / 2.0]).all(|(a, b)| (a - b).abs() < 1e-12),
1133            "{turned:?}"
1134        );
1135        let src = "DEF demo()\n  PTP {X 0, Y 0, Z 0}\n  $VEL.CP = 0.2\n  LIN {X 100, A 90}\nEND";
1136        let runs = krl(src, &axes, &[0.0; 6]).unwrap();
1137        // 0.1 m at 0.2 m/s takes 0.5 s, longer than the quarter turn's 0.18 s.
1138        assert!(runs[0].feed.is_none() && runs[1].feed.is_some_and(|f| (f - length / 0.5).abs() < 1e-12));
1139        let Piece::Line(turned) = &runs[1].pieces[0] else { panic!() };
1140        assert!(
1141            turned.iter().zip([0.1, 0.0, 0.0, 0.0, 0.0, PI / 2.0]).all(|(a, b)| (a - b).abs() < 1e-12),
1142            "{turned:?}"
1143        );
1144        let unknown = rapid("MoveL [[0,0,0],[1,0,0,0]], vslow, fine, tool0;", &axes, &[0.0; 6]).unwrap_err();
1145        assert_eq!((unknown.key, unknown.detail.as_str()), ("program-error-named", "vslow"));
1146    }
1147
1148    /// The tool centre's speed and the reorientation's are limited on their own (`tcp_cap`): a move takes the longer of
1149    /// its two times. 0.1 m at 1 m/s takes 0.1 s, the quarter turn (pi / 2 rad) at 500 degrees per second (8.7266 rad/s)
1150    /// 0.18 s: the move takes 0.18 s, and the cap along the path (0.1 m and pi / 2 rad counted together) is its length
1151    /// over that. A move that only reorients (v100, the position kept) runs at the 500 degrees per second: the cap is the
1152    /// rate itself, as the rotation vector's length is the angle. With 90 degrees per second the same move takes 1 s.
1153    #[test]
1154    fn a_robot_move_with_a_turn_takes_the_longer_of_the_two_times() {
1155        let axes = ["x", "y", "z", "rx", "ry", "rz"].map(axis);
1156        let half = std::f64::consts::FRAC_1_SQRT_2;
1157        let module = |x: u32, speed: &str| {
1158            format!("MoveL [[{x},0,0],[{half},0,0,{half}],[0,0,0,0],[9E9,9E9,9E9,9E9,9E9,9E9]], {speed}, fine, tool0;")
1159        };
1160        let cap = |text: &str, omega: f64| rapid_with(text, &axes, &[0.0; 6], omega).unwrap()[0].feed.unwrap();
1161        let omega = ORIENTATION_SPEED;
1162        // To the rounding of the two ways of writing it (an ulp of 8.7 is 1.8e-15).
1163        assert!((omega - 500.0_f64.to_radians()).abs() < 1e-14);
1164        let time = (PI / 2.0) / omega;
1165        assert!((time - 0.18).abs() < 1e-12);
1166        assert!((cap(&module(100, "v1000"), omega) * 0.18 - 0.1_f64.hypot(PI / 2.0)).abs() < 1e-12);
1167        assert!((cap(&module(0, "v100"), omega) - omega).abs() < 1e-12);
1168        let slow = 90.0_f64.to_radians();
1169        assert!((cap(&module(0, "v100"), slow) - slow).abs() < 1e-12);
1170    }
1171
1172    /// The extension picks the reader; a path file stays a path file.
1173    #[test]
1174    fn the_extension_picks_the_reader() {
1175        let axes = [axis("x"), axis("y")];
1176        assert!((read("part.NC", "F60\nG1 X10", &axes, &[0.0; 2]).unwrap()[0].feed.unwrap() - 0.001).abs() < 1e-15);
1177        assert_eq!(
1178            read("p.csv", "line,0.1,0.2", &axes, &[0.0; 2]).unwrap()[0].pieces,
1179            vec![Piece::Line(vec![0.1, 0.2])]
1180        );
1181        assert_eq!(
1182            read("p.csv", "MoveJ,0.1,0.2", &axes, &[0.0; 2]).unwrap()[0].pieces,
1183            vec![Piece::Line(vec![0.1, 0.2])]
1184        );
1185    }
1186}