wblidar 0.1.0

High-performance library for reading and writing LiDAR point cloud data (LAS, LAZ, COPC, PLY, E57)
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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
//! Unified frontend API for LiDAR point clouds.
//!
//! This module provides:
//! * [`PointCloud`]: an in-memory container shared across formats.
//! * [`LidarFormat`]: format enum with extension/signature detection.
//! * [`read`]/[`write()`]: generic path-based I/O helpers.

use std::fs::File;
use std::io::{BufReader, BufWriter, Read};
use std::path::Path;

use crate::copc::{CopcReader, CopcWriter, CopcWriterConfig};
use crate::crs::Crs;
use crate::e57::{E57Reader, E57Writer, E57WriterConfig};
use crate::io::{PointReader, PointWriter};
use crate::las::{LasReader, LasWriter, PointDataFormat, WriterConfig};
use crate::laz::{parse_laszip_vlr, LazReader, LazWriter, LazWriterConfig};
use crate::ply::{PlyEncoding, PlyReader, PlyWriter};
use crate::reproject::{
    points_in_place_to_epsg_with_options,
    points_to_epsg_with_options,
    points_to_epsg_with_options_and_progress,
    LidarReprojectOptions,
};
use wide::f64x4;
use crate::{Error, PointRecord, Result};

/// Unified in-memory LiDAR dataset.
#[derive(Debug, Clone, Default)]
pub struct PointCloud {
    /// Point records.
    pub points: Vec<PointRecord>,
    /// Optional CRS metadata associated with the dataset.
    pub crs: Option<Crs>,
}

/// Diagnostics emitted by tolerant decode/recovery paths during read.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct ReadDiagnostics {
    /// Number of Point14 layered chunks/nodes that required partial recovery.
    pub point14_partial_events: u64,
    /// Total points decoded from partially recovered Point14 chunks/nodes.
    pub point14_partial_decoded_points: u64,
    /// Total expected points from partially recovered Point14 chunks/nodes.
    pub point14_partial_expected_points: u64,
}

impl PointCloud {
    /// Read a point cloud from `path`, auto-detecting format.
    ///
    /// # Errors
    /// Returns an error if the file cannot be opened, parsed, or decoded.
    pub fn read<P: AsRef<Path>>(path: P) -> Result<Self> {
        read(path)
    }

    /// Write this point cloud to `path`, inferring output format from extension.
    ///
    /// # Errors
    /// Returns an error if extension-based format detection fails or encoding fails.
    pub fn write<P: AsRef<Path>>(&self, path: P) -> Result<()> {
        write_auto(self, path)
    }

    /// Write this point cloud to `path` in an explicitly selected format.
    ///
    /// # Errors
    /// Returns an error if the file cannot be created or encoded.
    pub fn write_as<P: AsRef<Path>>(&self, path: P, format: LidarFormat) -> Result<()> {
        write(self, path, format)
    }

    /// Assign a CRS to this point cloud using an EPSG code.
    ///
    /// Replaces the entire `crs` struct with a new `Crs` containing only the EPSG code.
    /// Any existing `wkt` field is cleared to ensure CRS consistency.
    pub fn assign_crs_epsg(&mut self, epsg: u32) {
        self.crs = Some(Crs {
            epsg: Some(epsg),
            wkt: None,
        });
    }

    /// Assign a CRS to this point cloud using WKT text.
    ///
    /// Replaces the entire `crs` struct with a new `Crs` containing only the WKT definition.
    /// Any existing `epsg` field is cleared to ensure CRS consistency.
    pub fn assign_crs_wkt(&mut self, wkt: &str) {
        self.crs = Some(Crs {
            epsg: None,
            wkt: Some(wkt.to_string()),
        });
    }

    /// Return a reprojected copy of this point cloud and updated CRS metadata.
    ///
    /// Source CRS is taken from `self.crs.epsg` and destination CRS is set to
    /// `dst_epsg` in the returned cloud.
    ///
    /// # Errors
    /// Returns an error when source CRS EPSG is missing or transformation fails.
    pub fn reprojected_to_epsg(&self, dst_epsg: u32) -> Result<Self> {
        self.reprojected_to_epsg_with_options(dst_epsg, &LidarReprojectOptions::default())
    }

    /// Return a reprojected copy of this point cloud and updated CRS metadata,
    /// using custom reprojection options.
    ///
    /// # Errors
    /// Returns an error when source CRS EPSG is missing or transformation fails.
    pub fn reprojected_to_epsg_with_options(
        &self,
        dst_epsg: u32,
        options: &LidarReprojectOptions,
    ) -> Result<Self> {
        let src_crs = self.crs.as_ref().ok_or_else(|| Error::Projection(
            "PointCloud reprojection requires source CRS metadata in cloud.crs".to_string(),
        ))?;

        let points = points_to_epsg_with_options(&self.points, src_crs, dst_epsg, options)?;
        Ok(Self {
            points,
            crs: Some(Crs::from_epsg(dst_epsg)),
        })
    }

    /// Return a reprojected copy of this point cloud while emitting progress
    /// updates in the range [0, 1] as points are completed.
    pub fn reprojected_to_epsg_with_options_and_progress<F>(
        &self,
        dst_epsg: u32,
        options: &LidarReprojectOptions,
        progress: F,
    ) -> Result<Self>
    where
        F: Fn(f64) + Send + Sync,
    {
        let src_crs = self.crs.as_ref().ok_or_else(|| Error::Projection(
            "PointCloud reprojection requires source CRS metadata in cloud.crs".to_string(),
        ))?;

        let points =
            points_to_epsg_with_options_and_progress(&self.points, src_crs, dst_epsg, options, progress)?;
        Ok(Self {
            points,
            crs: Some(Crs::from_epsg(dst_epsg)),
        })
    }

    /// Reproject this point cloud in place and update CRS metadata to `dst_epsg`.
    ///
    /// # Errors
    /// Returns an error when source CRS EPSG is missing or transformation fails.
    pub fn reproject_in_place_to_epsg(&mut self, dst_epsg: u32) -> Result<()> {
        self.reproject_in_place_to_epsg_with_options(dst_epsg, &LidarReprojectOptions::default())
    }

    /// Reproject this point cloud in place and update CRS metadata to `dst_epsg`,
    /// using custom reprojection options.
    ///
    /// # Errors
    /// Returns an error when source CRS metadata is missing or transformation fails.
    pub fn reproject_in_place_to_epsg_with_options(
        &mut self,
        dst_epsg: u32,
        options: &LidarReprojectOptions,
    ) -> Result<()> {
        let crs = self.crs.as_mut().ok_or_else(|| Error::Projection(
            "PointCloud reprojection requires source CRS metadata in cloud.crs".to_string(),
        ))?;
        points_in_place_to_epsg_with_options(&mut self.points, crs, dst_epsg, options)
    }
}

/// Supported LiDAR file formats in the unified API.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LidarFormat {
    /// LAS (uncompressed).
    Las,
    /// LAZ (LASzip-compressed LAS).
    Laz,
    /// COPC (Cloud Optimized Point Cloud, usually `.copc.las`).
    Copc,
    /// PLY (ASCII or binary).
    Ply,
    /// E57.
    E57,
}

impl LidarFormat {
    /// Detect format from extension and file signature.
    ///
    /// # Errors
    /// Returns an error when the format cannot be identified.
    pub fn detect<P: AsRef<Path>>(path: P) -> Result<Self> {
        let path = path.as_ref();
        if let Some(ext_format) = detect_by_extension(path) {
            return Ok(ext_format);
        }

        let mut f = File::open(path)?;
        let mut sig = [0u8; 16];
        let n = f.read(&mut sig)?;
        let s = &sig[..n];

        if s.starts_with(b"ply\n") {
            return Ok(Self::Ply);
        }
        if s.starts_with(crate::e57::E57_SIGNATURE) {
            return Ok(Self::E57);
        }
        if s.starts_with(b"LASF") {
            let lower = path.to_string_lossy().to_ascii_lowercase();
            if lower.ends_with(".copc.las") || lower.ends_with(".copc.laz") {
                return Ok(Self::Copc);
            }
            if lower.ends_with(".laz") {
                return Ok(Self::Laz);
            }
            return Ok(Self::Las);
        }

        Err(Error::InvalidValue {
            field: "format",
            detail: format!("unable to detect LiDAR format for path: {}", path.display()),
        })
    }
}

/// Read a point cloud from `path`, auto-detecting input format.
///
/// # Errors
/// Returns an error if detection, parsing, or decoding fails.
pub fn read<P: AsRef<Path>>(path: P) -> Result<PointCloud> {
    read_with_diagnostics(path).map(|(cloud, _diag)| cloud)
}

/// Read a point cloud from `path`, returning both cloud data and diagnostics.
///
/// # Errors
/// Returns an error if detection, parsing, or decoding fails.
pub fn read_with_diagnostics<P: AsRef<Path>>(path: P) -> Result<(PointCloud, ReadDiagnostics)> {
    let path = path.as_ref();
    match LidarFormat::detect(path)? {
        LidarFormat::Las => {
            let mut reader = LasReader::new(BufReader::new(File::open(path)?))?;
            let crs = reader.crs().cloned();
            let points = reader.read_all()?;
            Ok((PointCloud { points, crs }, ReadDiagnostics::default()))
        }
        LidarFormat::Laz => {
            let laz_file = File::open(path)?;
            let mut reader = match LazReader::new(BufReader::new(laz_file)) {
                Ok(r) => r,
                Err(e) => {
                    if is_unexpected_eof(&e) && laz_declares_point14(path)? {
                        return Err(Error::Unimplemented(
                            "standard LASzip Point14 layered stream detected, but arithmetic layered decoding is not yet implemented in wblidar standard backend",
                        ));
                    }
                    return Err(e);
                }
            };
            let crs = reader.crs().cloned();
            let points = match reader.read_all() {
                Ok(p) => p,
                Err(e) => {
                    if is_unexpected_eof(&e) && laz_declares_point14(path)? {
                        return Err(Error::Unimplemented(
                            "standard LASzip Point14 layered stream detected, but arithmetic layered decoding is not yet implemented in wblidar standard backend",
                        ));
                    }
                    return Err(e);
                }
            };
            let (events, decoded, expected) = reader.point14_partial_recovery_stats();
            Ok((
                PointCloud { points, crs },
                ReadDiagnostics {
                    point14_partial_events: events,
                    point14_partial_decoded_points: decoded,
                    point14_partial_expected_points: expected,
                },
            ))
        }
        LidarFormat::Copc => {
            // Read COPC points through node traversal.
            let mut reader = CopcReader::new(BufReader::new(File::open(path)?))?;
            let points = reader.read_all_nodes()?;

            // Re-read LAS header/VLRs to extract CRS metadata.
            let las_reader = LasReader::new(BufReader::new(File::open(path)?))?;
            let crs = las_reader.crs().cloned();
            let (events, decoded, expected) = reader.point14_partial_recovery_stats();

            Ok((
                PointCloud { points, crs },
                ReadDiagnostics {
                    point14_partial_events: events,
                    point14_partial_decoded_points: decoded,
                    point14_partial_expected_points: expected,
                },
            ))
        }
        LidarFormat::Ply => {
            let mut reader = PlyReader::new(BufReader::new(File::open(path)?))?;
            let points = reader.read_all()?;
            Ok((PointCloud { points, crs: None }, ReadDiagnostics::default()))
        }
        LidarFormat::E57 => {
            let mut reader = E57Reader::new(BufReader::new(File::open(path)?))?;
            let points = reader.read_all()?;
            Ok((PointCloud { points, crs: None }, ReadDiagnostics::default()))
        }
    }
}

fn is_unexpected_eof(err: &Error) -> bool {
    matches!(err, Error::Io(e) if e.kind() == std::io::ErrorKind::UnexpectedEof)
}

fn laz_declares_point14(path: &Path) -> Result<bool> {
    let las_reader = LasReader::new(BufReader::new(File::open(path)?))?;
    Ok(parse_laszip_vlr(las_reader.vlrs())
        .as_ref()
        .map(|info| info.has_point14_item())
        .unwrap_or(false))
}

/// Write a point cloud to `path` in a specified format.
///
/// # Errors
/// Returns an error if writing or finalization fails.
pub fn write<P: AsRef<Path>>(cloud: &PointCloud, path: P, format: LidarFormat) -> Result<()> {
    let path = path.as_ref();
    match format {
        LidarFormat::Las => write_las(cloud, path),
        LidarFormat::Laz => write_laz(cloud, path),
        LidarFormat::Copc => write_copc(cloud, path),
        LidarFormat::Ply => write_ply(cloud, path),
        LidarFormat::E57 => write_e57(cloud, path),
    }
}

/// Write a point cloud to `path`, inferring output format from extension.
///
/// # Errors
/// Returns an error when extension-based format detection fails or writing fails.
pub fn write_auto<P: AsRef<Path>>(cloud: &PointCloud, path: P) -> Result<()> {
    let path = path.as_ref();
    let format = detect_by_extension(path).ok_or_else(|| Error::InvalidValue {
        field: "format",
        detail: format!(
            "unable to infer output format from extension for path: {}",
            path.display()
        ),
    })?;
    write(cloud, path, format)
}

fn detect_by_extension(path: &Path) -> Option<LidarFormat> {
    let lower = path.to_string_lossy().to_ascii_lowercase();
    if lower.ends_with(".copc.las") || lower.ends_with(".copc.laz") {
        return Some(LidarFormat::Copc);
    }
    if lower.ends_with(".laz") {
        return Some(LidarFormat::Laz);
    }
    if lower.ends_with(".las") {
        return Some(LidarFormat::Las);
    }
    if lower.ends_with(".ply") {
        return Some(LidarFormat::Ply);
    }
    if lower.ends_with(".e57") {
        return Some(LidarFormat::E57);
    }
    None
}

fn write_las(cloud: &PointCloud, path: &Path) -> Result<()> {
    let out = BufWriter::new(File::create(path)?);
    let mut cfg = default_las_config(cloud);
    cfg.crs = cloud.crs.clone();
    let mut writer = LasWriter::new(out, cfg)?;
    writer.write_all_points(&cloud.points)?;
    writer.finish()
}

fn write_laz(cloud: &PointCloud, path: &Path) -> Result<()> {
    let out = BufWriter::new(File::create(path)?);
    let mut cfg = LazWriterConfig::default();
    cfg.las = default_las_config(cloud);
    cfg.las.crs = cloud.crs.clone();
    let mut writer = LazWriter::new(out, cfg)?;
    writer.write_all_points(&cloud.points)?;
    writer.finish()
}

fn write_copc(cloud: &PointCloud, path: &Path) -> Result<()> {
    let out = BufWriter::new(File::create(path)?);
    let mut cfg = default_copc_config(cloud);
    cfg.las.crs = cloud.crs.clone();
    let mut writer = CopcWriter::new(out, cfg);
    writer.write_all_points(&cloud.points)?;
    writer.finish()
}

fn write_ply(cloud: &PointCloud, path: &Path) -> Result<()> {
    let out = BufWriter::new(File::create(path)?);
    let has_color = cloud.points.iter().any(|p| p.color.is_some());
    let has_normals = cloud.points.iter().any(|p| {
        p.normal_x.is_some() || p.normal_y.is_some() || p.normal_z.is_some()
    });
    let mut writer = PlyWriter::new(
        out,
        cloud.points.len() as u64,
        PlyEncoding::BinaryLittleEndian,
        has_color,
        has_normals,
    )?;
    writer.write_all_points(&cloud.points)?;
    writer.finish()
}

fn write_e57(cloud: &PointCloud, path: &Path) -> Result<()> {
    let out = BufWriter::new(File::create(path)?);
    let has_color = cloud.points.iter().any(|p| p.color.is_some());
    let has_intensity = cloud.points.iter().any(|p| p.intensity > 0);
    let cfg = E57WriterConfig {
        has_color,
        has_intensity,
        ..E57WriterConfig::default()
    };
    let mut writer = E57Writer::new(out, cfg);
    writer.write_all_points(&cloud.points)?;
    writer.finish()
}

fn default_las_config(cloud: &PointCloud) -> WriterConfig {
    let mut cfg = WriterConfig::default();
    let has_color = cloud.points.iter().any(|p| p.color.is_some());
    let has_nir = cloud.points.iter().any(|p| p.nir.is_some());
    cfg.point_data_format = if has_nir {
        PointDataFormat::Pdrf8
    } else if has_color {
        PointDataFormat::Pdrf7
    } else {
        PointDataFormat::Pdrf6
    };
    cfg
}

fn default_copc_config(cloud: &PointCloud) -> CopcWriterConfig {
    let mut cfg = CopcWriterConfig::default();
    cfg.las = default_las_config(cloud);

    if cloud.points.is_empty() {
        return cfg;
    }

    // Accumulate bounding box using branchless SIMD min/max.
    // Layout: [x, y, z, unused].
    let inf    = f64::INFINITY;
    let neg_inf = f64::NEG_INFINITY;
    let mut acc_min = f64x4::new([inf,     inf,     inf,     inf]);
    let mut acc_max = f64x4::new([neg_inf, neg_inf, neg_inf, neg_inf]);

    for p in &cloud.points {
        let coords = f64x4::new([p.x, p.y, p.z, 0.0]);
        acc_min = acc_min.min(coords);
        acc_max = acc_max.max(coords);
    }

    let min_arr: [f64; 4] = acc_min.into();
    let max_arr: [f64; 4] = acc_max.into();
    let (min_x, min_y, min_z) = (min_arr[0], min_arr[1], min_arr[2]);
    let (max_x, max_y, max_z) = (max_arr[0], max_arr[1], max_arr[2]);

    cfg.center_x = (min_x + max_x) / 2.0;
    cfg.center_y = (min_y + max_y) / 2.0;
    cfg.center_z = (min_z + max_z) / 2.0;

    let dx = (max_x - min_x).abs();
    let dy = (max_y - min_y).abs();
    let dz = (max_z - min_z).abs();
    let extent = dx.max(dy).max(dz);

    cfg.halfsize = (extent / 2.0).max(1.0) * 1.001;
    cfg.spacing = (cfg.halfsize * 2.0 / 256.0).max(0.001);
    cfg
}

#[cfg(test)]
mod tests {
    use super::PointCloud;
    use crate::crs::Crs;
    use crate::error::Error;
    use crate::point::PointRecord;

    fn sample_cloud_with_wgs84() -> PointCloud {
        PointCloud {
            points: vec![PointRecord {
                x: -2.0,
                y: -0.5,
                ..PointRecord::default()
            }],
            crs: Some(Crs::from_epsg(4326)),
        }
    }

    #[test]
    fn reprojected_to_epsg_returns_updated_copy() {
        let cloud = sample_cloud_with_wgs84();
        let out = cloud.reprojected_to_epsg(3857).unwrap();

        assert_eq!(out.crs.as_ref().and_then(|c| c.epsg), Some(3857));
        assert!(out.points[0].x.abs() > 1000.0);
        assert!(out.points[0].y.abs() > 100.0);

        // Original cloud remains unchanged.
        assert_eq!(cloud.crs.as_ref().and_then(|c| c.epsg), Some(4326));
        assert!((cloud.points[0].x + 2.0).abs() < 1e-9);
        assert!((cloud.points[0].y + 0.5).abs() < 1e-9);
    }

    #[test]
    fn reproject_in_place_updates_points_and_crs() {
        let mut cloud = sample_cloud_with_wgs84();
        cloud.reproject_in_place_to_epsg(3857).unwrap();

        assert_eq!(cloud.crs.as_ref().and_then(|c| c.epsg), Some(3857));
        assert!(cloud.points[0].x.abs() > 1000.0);
        assert!(cloud.points[0].y.abs() > 100.0);
    }

    #[test]
    fn reprojected_to_epsg_requires_cloud_crs() {
        let cloud = PointCloud {
            points: vec![PointRecord::default()],
            crs: None,
        };

        let err = cloud.reprojected_to_epsg(3857).unwrap_err();
        assert!(matches!(err, Error::Projection(_)));
        assert!(err
            .to_string()
            .contains("PointCloud reprojection requires source CRS metadata"));
    }

    #[test]
    fn reproject_in_place_requires_cloud_crs() {
        let mut cloud = PointCloud {
            points: vec![PointRecord::default()],
            crs: None,
        };

        let err = cloud.reproject_in_place_to_epsg(3857).unwrap_err();
        assert!(matches!(err, Error::Projection(_)));
        assert!(err
            .to_string()
            .contains("PointCloud reprojection requires source CRS metadata"));
    }
}