sylva-rs 2.0.0

Terrestrial and airborne laser scanning processing for forest ecology and remote sensing research.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
// Sylva: LiDAR processing for forest ecology and remote sensing research.
// Copyright (C) 2026 Tim Devereux, The University of Queensland.
// Free software under the GNU General Public License v3.0 or later;
// see the LICENSE file. There is no warranty, to the extent permitted by law.
//! RIEGL `.rxp` reading through RiVLib's `libscanifc`, loaded at runtime.
//!
//! RiVLib is proprietary and cannot be redistributed. The library is located
//! from `RIVLIB_PATH` / `RIVLIB_HOME`, an explicit path, or the usual install
//! locations (`~/.local/lib`, `~/opt`, `/opt`, `/usr/local/lib`, ...).
//!
//! Points come back in the scanner's own coordinate system (SOCS) with the
//! scanner at the origin. Runs of echoes sharing a timestamp form one pulse,
//! which is how [`Shots`] are recovered.

use std::ffi::{c_char, c_void, CString};
use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock};

use libloading::{Library, Symbol};

use crate::error::{Error, Result};
use crate::pointcloud::Attr;
use crate::shots::reconstruct::{reconstruct_misses, MissReport};
use crate::{Point, PointCloud, Shots};

// The types below describe RiVLib's C interface to Rust. `#[repr(C)]` lays a
// struct out exactly as a C compiler would, field by field with C's padding,
// so the library can write into it; without it Rust is free to reorder fields.
// The `extern "C" fn` types are function pointers with C's calling
// convention, and they are `unsafe` because nothing in Rust can check that the
// signature we have written here matches the one inside the shared library —
// that is on us, against `scanifc.h`.

#[repr(C)]
#[derive(Clone, Copy, Default)]
struct Xyz32 {
    x: f32,
    y: f32,
    z: f32,
}

#[repr(C)]
#[derive(Clone, Copy, Default)]
struct Attributes {
    amplitude: f32,
    reflectance: f32,
    deviation: u16,
    flags: u16,
    background_radiation: f32,
}

type Handle = *mut c_void;
type OpenFn = unsafe extern "C" fn(*const c_char, i32, *mut Handle) -> i32;
type ReadFn = unsafe extern "C" fn(Handle, u32, *mut Xyz32, *mut Attributes, *mut u64, *mut u32, *mut i32) -> i32;
type CloseFn = unsafe extern "C" fn(Handle) -> i32;
type LastErrorFn = unsafe extern "C" fn(*mut c_char, u32, *mut u32) -> i32;

/// Echo type stored in the low two bits of `flags`: the pulse's only echo.
pub const ECHO_SINGLE: u16 = 0;
/// First of several echoes of a pulse.
pub const ECHO_FIRST: u16 = 1;
/// An echo between the first and last of a pulse.
pub const ECHO_INTERIOR: u16 = 2;
/// Last of several echoes of a pulse.
pub const ECHO_LAST: u16 = 3;
pub(crate) const FLAG_PSEUDO_ECHO: u16 = 1 << 4;

/// The library, loaded once and kept for the life of the process.
///
/// `OnceLock` is initialised on first use and never again; the `Mutex` inside
/// it means two threads opening an `.rxp` at the same time cannot both start
/// loading; the `Option` is "not loaded yet". Keeping it alive matters: the
/// function pointers taken from it are only valid while the library is open.
static LIBRARY: OnceLock<Mutex<Option<Library>>> = OnceLock::new();

/// Directories searched for `libscanifc`, in order.
pub fn search_roots() -> Vec<PathBuf> {
    let mut roots = Vec::new();
    for var in ["RIVLIB_PATH", "RIVLIB_HOME"] {
        if let Ok(v) = std::env::var(var) {
            roots.push(PathBuf::from(v));
        }
    }
    if let Some(home) = std::env::var_os("HOME").map(PathBuf::from) {
        roots.push(home.join(".local/lib"));
        roots.push(home.join(".local"));
        roots.push(home.join("lib"));
        roots.push(home.join("opt"));
        roots.push(home);
    }
    roots.push(PathBuf::from("/opt"));
    roots.push(PathBuf::from("/usr/local/lib"));
    roots.push(PathBuf::from("/usr/local"));
    roots.push(PathBuf::from("/usr/lib"));
    roots
}

const LIB_NAMES: &[&str] = &["libscanifc-mt.so", "libscanifc.so", "scanifc-mt.dll", "libscanifc-mt.dylib"];

/// Look for one of `names` in `dir`, descending `depth` levels into
/// RiVLib-looking subdirectories.
pub(crate) fn search_dir(dir: &Path, depth: usize, names: &[&str]) -> Option<PathBuf> {
    if !dir.is_dir() {
        return None;
    }
    for name in names {
        let p = dir.join(name);
        if p.is_file() {
            return Some(p);
        }
    }
    if depth == 0 {
        return None;
    }
    let mut entries: Vec<PathBuf> = std::fs::read_dir(dir).ok()?.flatten().map(|e| e.path()).filter(|p| p.is_dir()).collect();
    entries.sort();
    for e in entries {
        let n = e.file_name().and_then(|n| n.to_str()).unwrap_or("");
        if n.to_ascii_lowercase().contains("rivlib") || n == "lib" || depth >= 2 {
            if let Some(p) = search_dir(&e, depth - 1, names) {
                return Some(p);
            }
        }
    }
    None
}

/// Locate `libscanifc`.
pub fn find_rivlib(hint: Option<&Path>) -> Result<PathBuf> {
    if let Some(h) = hint {
        if h.is_file() {
            return Ok(h.to_path_buf());
        }
        if let Some(p) = search_dir(h, 3, LIB_NAMES) {
            return Ok(p);
        }
    }
    for root in search_roots() {
        if root.is_file() {
            return Ok(root);
        }
        if let Some(p) = search_dir(&root, 3, LIB_NAMES) {
            return Ok(p);
        }
    }
    Err(Error::Riegl(
        "libscanifc not found. Download RiVLib from RIEGL and set RIVLIB_PATH to the extracted \
         directory (containing lib/libscanifc-mt.so)"
            .into(),
    ))
}

/// Run `f` with the loaded library, loading it the first time.
///
/// `f: impl FnOnce(&Library) -> Result<T>` is a callback run once; writing it
/// this way rather than returning the library keeps the lock held for exactly
/// as long as the call, and keeps the library private to this module.
fn with_library<T>(hint: Option<&Path>, f: impl FnOnce(&Library) -> Result<T>) -> Result<T> {
    let cell = LIBRARY.get_or_init(|| Mutex::new(None));
    // The lock is released when `guard` goes out of scope at the end of the
    // function; there is no explicit unlock to forget.
    let mut guard = cell.lock().unwrap();
    if guard.is_none() {
        let path = find_rivlib(hint)?;
        // SAFETY: RiVLib is a well-behaved C library with no init side effects.
        let lib = unsafe { Library::new(&path) }.map_err(|e| Error::Riegl(format!("{}: {e}", path.display())))?;
        *guard = Some(lib);
    }
    f(guard.as_ref().unwrap())
}

/// Options for [`read_rxp`] / [`read_rxp_shots`].
#[derive(Debug, Clone)]
pub struct RxpOptions {
    /// Explicit RiVLib directory or library file.
    pub library: Option<PathBuf>,
    /// Drop pseudo echoes (flag bit 4).
    pub drop_pseudo_echoes: bool,
    /// Minimum range (m); RiSCAN's default export drops `< 0.5`.
    pub min_range: f64,
    /// Maximum range (m); points farther than this are dropped. Infinite by default.
    pub max_range: f64,
    /// Keep every `stride`-th point (1 = all). Splits multi-echo pulses;
    /// prefer `shot_stride` for pulse data.
    pub stride: usize,
    /// Keep every `shot_stride`-th pulse with all its echoes (1 = all).
    pub shot_stride: usize,
    /// Read at most this many points.
    pub max_points: Option<usize>,
    /// Echo selection: `all`, `first`, `last`, `single`.
    pub echoes: String,
    /// Multiple-time-around resolution (RiSCAN-like conversion); see
    /// [`super::rxp_mta`]. The default tries the shim and falls back to plain
    /// `libscanifc` reading when it is not built.
    pub mta: super::rxp_mta::MtaOptions,
    /// Recover the pulses that returned nothing from the timing and geometry
    /// of those that did ([`crate::shots::reconstruct`]); `shot_stride` then
    /// counts fired pulses, recorded or not. Only `read_rxp_shots` carries them,
    /// with MTA resolution first where the shim is built.
    pub fill_missing: bool,
    /// First and last zenith of the mirror sweep (degrees) for `fill_missing`,
    /// from the scan pattern; `None` takes the extremes recorded.
    pub zenith_range: Option<(f64, f64)>,
}

impl Default for RxpOptions {
    fn default() -> Self {
        RxpOptions {
            library: None,
            drop_pseudo_echoes: true,
            min_range: 0.5,
            max_range: f64::INFINITY,
            stride: 1,
            shot_stride: 1,
            max_points: None,
            echoes: "all".into(),
            mta: Default::default(),
            fill_missing: false,
            zenith_range: None,
        }
    }
}

struct RawRxp {
    xyz: Vec<Point>,
    amplitude: Vec<f32>,
    reflectance: Vec<f32>,
    deviation: Vec<u16>,
    flags: Vec<u16>,
    time_ns: Vec<u64>,
    /// Directions of the recovered no-return pulses (`fill_missing`).
    misses: Vec<Point>,
    report: Option<MissReport>,
}

fn read_raw(path: &Path, opts: &RxpOptions) -> Result<RawRxp> {
    with_library(opts.library.as_deref(), |lib| {
        // Look up the four C functions by name. The byte strings end in `\0`
        // because that is what C expects; `Symbol<OpenFn>` is a pointer to the
        // function, typed by the signatures declared at the top of this file.
        // SAFETY: symbol signatures follow scanifc.h from RiVLib.
        let (open, read, close, last_error) = unsafe {
            let open: Symbol<OpenFn> = lib.get(b"scanifc_point3dstream_open\0").map_err(|e| Error::Riegl(e.to_string()))?;
            let read: Symbol<ReadFn> = lib.get(b"scanifc_point3dstream_read\0").map_err(|e| Error::Riegl(e.to_string()))?;
            let close: Symbol<CloseFn> = lib.get(b"scanifc_point3dstream_close\0").map_err(|e| Error::Riegl(e.to_string()))?;
            let last_error: Symbol<LastErrorFn> = lib.get(b"scanifc_get_last_error\0").map_err(|e| Error::Riegl(e.to_string()))?;
            (open, read, close, last_error)
        };
        let describe = |code: i32| -> Error {
            let mut buf = vec![0u8; 1024];
            let mut size = 0u32;
            // SAFETY: buffer sizes are passed explicitly.
            unsafe { last_error(buf.as_mut_ptr() as *mut c_char, buf.len() as u32, &mut size) };
            let msg = String::from_utf8_lossy(&buf[..(size as usize).min(buf.len())]).trim_end_matches('\0').to_string();
            Error::Riegl(format!("{path:?}: scanifc error {code}: {msg}", path = path.display()))
        };
        let uri = CString::new(format!("file:{}", path.canonicalize().unwrap_or(path.to_path_buf()).display()))
            .map_err(|e| Error::Riegl(e.to_string()))?;
        let mut handle: Handle = std::ptr::null_mut();
        // SAFETY: valid C string and out-pointer.
        let rc = unsafe { open(uri.as_ptr(), 0, &mut handle) };
        if rc != 0 {
            return Err(describe(rc));
        }
        // RiVLib fills buffers we provide, a chunk of echoes at a time, rather
        // than allocating anything itself. These three are reused for the whole
        // file; `as_mut_ptr()` below hands the library their addresses.
        const CHUNK: usize = 1 << 18;
        let mut xyz_buf = vec![Xyz32::default(); CHUNK];
        let mut attr_buf = vec![Attributes::default(); CHUNK];
        let mut time_buf = vec![0u64; CHUNK];
        let mut raw = RawRxp { xyz: Vec::new(), amplitude: Vec::new(), reflectance: Vec::new(), deviation: Vec::new(), flags: Vec::new(), time_ns: Vec::new(), misses: Vec::new(), report: None };
        let mut counter = 0usize;
        // Pulses are runs of echoes sharing a timestamp.
        let mut pulse = 0usize;
        let mut last_time = u64::MAX;
        let mut registered = false;
        // With fill_missing every recorded pulse is kept here (time and the
        // direction of its first echo beyond min_range, before any other
        // filter) so the gaps between them can be found; the stride is
        // applied afterwards to the fired sequence. Each kept echo remembers
        // its pulse.
        let fill = opts.fill_missing;
        let (mut pulse_time, mut pulse_dir, mut echo_pulse): (Vec<u64>, Vec<Point>, Vec<u32>) = (Vec::new(), Vec::new(), Vec::new());
        loop {
            let mut got = 0u32;
            let mut eof = 0i32;
            // SAFETY: buffers are CHUNK long and `want` == CHUNK.
            let rc = unsafe { read(handle, CHUNK as u32, xyz_buf.as_mut_ptr(), attr_buf.as_mut_ptr(), time_buf.as_mut_ptr(), &mut got, &mut eof) };
            if rc != 0 {
                // SAFETY: handle was opened above.
                unsafe { close(handle) };
                return Err(describe(rc));
            }
            let n = got as usize;
            for i in 0..n {
                counter += 1;
                if time_buf[i] != last_time {
                    last_time = time_buf[i];
                    pulse += 1;
                    registered = false;
                }
                let a = attr_buf[i];
                let p = xyz_buf[i];
                let r = ((p.x as f64).powi(2) + (p.y as f64).powi(2) + (p.z as f64).powi(2)).sqrt();
                // A pulse that returned nothing still leaves a record: a
                // pseudo echo, or the scanner's own near-range echo a few
                // centimetres out (a VZ-2000i: 0.1-0.2 m, 2.4 million of them
                // in a rainforest tilt scan, nearly all alone on their pulse).
                // Neither makes the pulse a recorded one, so a pulse with no
                // other echo is left for the reconstruction to find by the
                // gap it leaves in the timing.
                if opts.drop_pseudo_echoes && a.flags & FLAG_PSEUDO_ECHO != 0 {
                    continue;
                }
                if r < opts.min_range {
                    continue;
                }
                if fill && !registered {
                    pulse_time.push(time_buf[i]);
                    pulse_dir.push([p.x as f64, p.y as f64, p.z as f64]);
                    registered = true;
                }
                if !fill && opts.shot_stride > 1 && pulse % opts.shot_stride != 0 {
                    continue;
                }
                if opts.stride > 1 && counter % opts.stride != 0 {
                    continue;
                }
                if r > opts.max_range {
                    continue;
                }
                let echo = a.flags & 3;
                let keep = match opts.echoes.as_str() {
                    "first" => echo == ECHO_FIRST || echo == ECHO_SINGLE,
                    "last" => echo == ECHO_LAST || echo == ECHO_SINGLE,
                    "single" => echo == ECHO_SINGLE,
                    _ => true,
                };
                if !keep {
                    continue;
                }
                raw.xyz.push([p.x as f64, p.y as f64, p.z as f64]);
                raw.amplitude.push(a.amplitude);
                raw.reflectance.push(a.reflectance);
                raw.deviation.push(a.deviation);
                raw.flags.push(a.flags);
                raw.time_ns.push(time_buf[i]);
                if fill {
                    echo_pulse.push((pulse_time.len() - 1) as u32);
                }
                if opts.max_points.map(|m| raw.xyz.len() >= m).unwrap_or(false) {
                    break;
                }
            }
            if n == 0 && eof == 0 {
                break;
            }
            if opts.max_points.map(|m| raw.xyz.len() >= m).unwrap_or(false) {
                break;
            }
        }
        // SAFETY: handle was opened above.
        unsafe { close(handle) };
        if fill {
            let rec = reconstruct_misses(&pulse_time, &pulse_dir, opts.zenith_range, opts.shot_stride);
            drop(pulse_time);
            drop(pulse_dir);
            if opts.shot_stride > 1 {
                let keep: Vec<bool> = echo_pulse.iter().map(|&p| rec.keep[p as usize]).collect();
                let mut k = keep.iter();
                raw.xyz.retain(|_| *k.next().unwrap());
                let mut k = keep.iter();
                raw.amplitude.retain(|_| *k.next().unwrap());
                let mut k = keep.iter();
                raw.reflectance.retain(|_| *k.next().unwrap());
                let mut k = keep.iter();
                raw.deviation.retain(|_| *k.next().unwrap());
                let mut k = keep.iter();
                raw.flags.retain(|_| *k.next().unwrap());
                let mut k = keep.iter();
                raw.time_ns.retain(|_| *k.next().unwrap());
            }
            raw.misses = rec.misses;
            raw.report = Some(rec.report);
        }
        Ok(raw)
    })
}

/// Read an `.rxp` file into a point cloud (SOCS frame) with `amplitude`,
/// `reflectance`, `deviation`, `echo_type` and `gps_time` (seconds) attributes.
///
/// With MTA resolution available ([`RxpOptions::mta`]) the cloud is converted
/// the way RiSCAN PRO does it and additionally carries `mta_zone`,
/// `return_number`, `number_of_returns`, `scan_line_index`, `shot_index_line`
/// and `mirror_facet`.
pub fn read_rxp(path: impl AsRef<Path>, opts: &RxpOptions) -> Result<PointCloud> {
    if mta_active(opts) {
        return super::rxp_mta::read_rxp_mta(path.as_ref(), opts, &opts.mta);
    }
    Ok(cloud_from_raw(read_raw(path.as_ref(), opts)?))
}

/// Whether these options resolve MTA: asked for, or left automatic with the
/// shim built.
fn mta_active(opts: &RxpOptions) -> bool {
    use super::rxp_mta::{find_shim, MtaMode};
    match opts.mta.mode {
        MtaMode::Off => false,
        MtaMode::On => true,
        MtaMode::Auto => find_shim(opts.mta.shim.as_deref()).is_ok(),
    }
}

fn cloud_from_raw(raw: RawRxp) -> PointCloud {
    let mut cloud = PointCloud::new(raw.xyz);
    cloud.attrs.insert("amplitude".into(), Attr::F32(raw.amplitude));
    cloud.attrs.insert("reflectance".into(), Attr::F32(raw.reflectance));
    cloud.attrs.insert("deviation".into(), Attr::U16(raw.deviation));
    cloud.attrs.insert("echo_type".into(), Attr::U8(raw.flags.iter().map(|f| (f & 3) as u8).collect()));
    cloud.attrs.insert("gps_time".into(), Attr::F64(raw.time_ns.iter().map(|&t| t as f64 * 1e-9).collect()));
    cloud
}

/// The MTA-resolved cloud with the echoes of each pulse next to each other,
/// pulses in the order they were fired.
///
/// The MTA reader writes echoes in the order the scanner recorded them, and
/// an echo resolved to zone 2 or beyond was recorded after a later pulse was
/// fired: it carries its own pulse's time and indices but sits among the
/// echoes of that later pulse. [`Shots::from_pointcloud`] joins only adjacent
/// points of equal time, so left as it is such a pulse would come out as two
/// shots, its far echo a first return of a pulse that was never fired. The
/// sort is stable on (`scan_line_index`, `shot_index_line`), the pulse's own
/// line and its position in it; lines are numbered -1, -2, ... in the order
/// scanned. A cloud without those attributes is returned as it is.
pub(crate) fn pulse_contiguous(cloud: PointCloud) -> PointCloud {
    let (Some(line), Some(shot)) = (cloud.attr_f64("scan_line_index"), cloud.attr_f64("shot_index_line")) else {
        return cloud;
    };
    // Line -1 is the first scanned, so the negated index grows with time.
    let key = |i: usize| (-(line[i] as i64), shot[i] as i64);
    if (1..cloud.len()).all(|i| key(i - 1) <= key(i)) {
        return cloud;
    }
    let mut idx: Vec<usize> = (0..cloud.len()).collect();
    idx.sort_by_key(|&i| key(i));
    cloud.take(&idx)
}

/// Read an `.rxp` file as pulses. Echoes sharing a timestamp form one shot.
/// With `fill_missing` the pulses that returned nothing follow the recorded
/// ones as echo-less shots, and the report says what was recovered.
pub fn read_rxp_shots_with_report(path: impl AsRef<Path>, opts: &RxpOptions) -> Result<(Shots, Option<MissReport>)> {
    if mta_active(opts) {
        if !opts.fill_missing {
            let cloud = pulse_contiguous(read_rxp(path, opts)?);
            return Ok((Shots::from_pointcloud(&cloud, [0.0, 0.0, 0.0]), None));
        }
        // The echoes assigned to their pulses by the MTA resolution first:
        // on the raw stream an echo filed under the wrong pulse leaves a
        // false miss (two per cent of a VZ-2000i rainforest scan). Every
        // pulse and echo is read so that the gaps between pulses are real;
        // the stride is applied to the fired sequence afterwards.
        let mut all = opts.clone();
        all.shot_stride = 1;
        all.stride = 1;
        all.max_points = None;
        all.echoes = "all".into();
        let cloud = pulse_contiguous(super::rxp_mta::read_rxp_mta(path.as_ref(), &all, &all.mta)?);
        let shots = Shots::from_pointcloud(&cloud, [0.0, 0.0, 0.0]);
        let times = shots.echo_attrs.get("gps_time").map(|a| a.to_f64()).ok_or_else(|| Error::invalid("the MTA stream carries no gps_time"))?;
        let time_ns: Vec<u64> = shots.echo_start.iter().map(|&s| (times[s] * 1e9).round().max(0.0) as u64).collect();
        let rec = reconstruct_misses(&time_ns, &shots.direction, opts.zenith_range, opts.shot_stride);
        let kept = if opts.shot_stride > 1 { shots.subset(&rec.keep) } else { shots };
        return with_misses(kept, rec.misses).map(|s| (s, Some(rec.report)));
    }
    let mut raw = read_raw(path.as_ref(), opts)?;
    let misses = std::mem::take(&mut raw.misses);
    let report = raw.report.take();
    let cloud = cloud_from_raw(raw);
    let shots = Shots::from_pointcloud(&cloud, [0.0, 0.0, 0.0]);
    with_misses(shots, misses).map(|s| (s, report))
}

/// The recovered misses appended to the recorded pulses as echo-less shots.
fn with_misses(shots: Shots, misses: Vec<Point>) -> Result<Shots> {
    if misses.is_empty() {
        return Ok(shots);
    }
    let n = misses.len();
    let empty = Shots {
        origin: vec![[0.0, 0.0, 0.0]; n],
        direction: misses,
        echo_start: vec![0; n],
        echo_count: vec![0; n],
        echo_range: Vec::new(),
        echo_attrs: shots.echo_attrs.iter().map(|(k, v)| (k.clone(), v.take(&[]))).collect(),
    };
    Shots::concatenate(&[&shots, &empty])
}

/// Read an `.rxp` file as pulses (see [`read_rxp_shots_with_report`]).
pub fn read_rxp_shots(path: impl AsRef<Path>, opts: &RxpOptions) -> Result<Shots> {
    read_rxp_shots_with_report(path, opts).map(|(s, _)| s)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn mta_echoes_are_gathered_into_their_pulses() {
        // Two lines. Pulse (line -1, shot 7) has a near echo recorded on it
        // and a far one (zone 2) recorded on shot 8, after shot 8's own near
        // echo; the last pulse of line -1 has a far echo recorded on the
        // first shot of line -2. As the MTA reader writes them:
        let rows: [(i32, i32, f64, f64); 7] = [
            (-1, 7, 1.0, 10.0),
            (-1, 8, 2.0, 5.0),
            (-1, 7, 1.0, 90.0), // late echo of shot 7
            (-1, 8, 2.0, 30.0),
            (-2, 0, 3.0, 4.0),
            (-1, 8, 2.0, 95.0), // late echo of the previous line's last pulse
            (-2, 1, 4.0, 6.0),
        ];
        let mut cloud = PointCloud::new(rows.iter().map(|r| [0.0, 0.0, r.3]).collect());
        cloud.attrs.insert("scan_line_index".into(), Attr::I32(rows.iter().map(|r| r.0).collect()));
        cloud.attrs.insert("shot_index_line".into(), Attr::I32(rows.iter().map(|r| r.1).collect()));
        cloud.attrs.insert("gps_time".into(), Attr::F64(rows.iter().map(|r| r.2).collect()));
        // Joined as recorded, the four pulses fall apart into seven shots.
        assert_eq!(Shots::from_pointcloud(&cloud, [0.0; 3]).n_shots(), 7);
        let sorted = pulse_contiguous(cloud.clone());
        assert_eq!(sorted.attr_f64("gps_time").unwrap(), vec![1.0, 1.0, 2.0, 2.0, 2.0, 3.0, 4.0]);
        let s = Shots::from_pointcloud(&sorted, [0.0; 3]);
        assert_eq!(s.echo_count, vec![2, 3, 1, 1]);
        assert_eq!(s.echo_range, vec![10.0, 90.0, 5.0, 30.0, 95.0, 4.0, 6.0]);
        // Already in order, or without the indices: untouched.
        assert_eq!(pulse_contiguous(sorted.clone()), sorted);
        let mut plain = cloud.clone();
        plain.attrs.remove("scan_line_index");
        assert_eq!(pulse_contiguous(plain.clone()), plain);
    }
}