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
//! Attributed three-dimensional points.
//!
//! Points are simple structures with public attributes, some optional.
//!
//! ```
//! use las::Point;
//! let point = Point::default();
//! assert_eq!(0., point.x);
//! assert_eq!(None, point.color);
//! ```
//!
//! Point coordinates (x, y, and z) are stored as f64, and are the final coordinates after the
//! scale and offset from the header are applied.

mod classification;
mod format;
mod scan_direction;

pub use self::classification::Classification;
pub use self::format::Format;
pub use self::scan_direction::ScanDirection;

use crate::raw;
use crate::raw::point::Waveform;
use crate::{Color, Result, Transform, Vector};
use thiserror::Error;

/// Point-specific errors
#[derive(Debug, Clone, Copy, Error)]
pub enum Error {
    /// An invalid classification number.
    #[error("invalid classification: {0}")]
    Classification(u8),

    /// This is an invalid format.
    ///
    /// It has a combination of options that can't exist.
    #[error("invalid format: {0}")]
    Format(Format),

    /// This is an invalid format number.
    #[error("invalid format number: {0}")]
    FormatNumber(u8),

    /// Overlap points are handled by an attribute on `las::Point`, not by a classification.
    #[error("overlap points are handled by the `is_overlap` member of `las::Point`, not by classifications")]
    OverlapClassification,

    /// This is not a valid return number.
    #[error("invalid return number {return_number} for version {version:?}")]
    #[allow(missing_docs)]
    ReturnNumber {
        return_number: u8,
        version: Option<crate::Version>,
    },

    /// This is not a valid scanner channel
    #[error("invalid scanner channel: {0}")]
    ScannerChannel(u8),
}

/// A three dimensional point.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Point {
    /// The x coordinate, as a float.
    pub x: f64,

    /// The y coordinate, as a float.
    pub y: f64,

    /// The z coordinate, as a float.
    pub z: f64,

    /// The integer representation of the pulse return magnitude.
    ///
    /// This value is optional and system specific, but should be included when available. Because
    /// there is no way to indicate the "optionalness" of the intensity value and since zero could
    /// be valid intensity, we don't wrap this in an `Option`.
    pub intensity: u16,
    /// The pulse return number for a given output pulse.
    pub return_number: u8,

    /// The total number of returns for a given pulse.
    pub number_of_returns: u8,

    /// The direction at which the scanner mirror was traveling at the time of the output pulse.
    pub scan_direction: ScanDirection,

    /// True if the point is at the end of a scan.
    pub is_edge_of_flight_line: bool,

    /// The ASPRS classification for this point.
    pub classification: Classification,

    /// This point was created by a technique other than LiDAR collection.
    pub is_synthetic: bool,

    /// The point should be considered a model key-point.
    pub is_key_point: bool,

    /// The point should be considered withheld (i.e. it's deleted).
    pub is_withheld: bool,

    /// Is this an overlap point?
    pub is_overlap: bool,

    /// The channel of the scanner, used only in multi-channel systems.
    pub scanner_channel: u8,

    /// The angle of the output of the laser pulse.
    ///
    /// This is supposed to include the roll of the aircraft, if applicable. Zero degrees is nadir,
    /// -90° is to the left.
    pub scan_angle: f32,

    /// Used at the user's discretion.
    pub user_data: u8,

    /// The file from which this point originated.
    ///
    /// This number corresponds to a file source ID.
    pub point_source_id: u16,

    /// The time at which the point was acquired.
    pub gps_time: Option<f64>,

    /// This point's color.
    pub color: Option<Color>,

    /// This point's waveform information.
    pub waveform: Option<Waveform>,

    /// This point's near infrared value.
    pub nir: Option<u16>,

    /// This point's extra bytes.
    ///
    /// These can have structure and meaning, but for now they don't.
    pub extra_bytes: Vec<u8>,
}

impl Point {
    /// Creates a point from a raw point.
    ///
    /// # Examples
    ///
    /// ```
    /// use las::Point;
    /// use las::raw;
    /// let raw_point = raw::Point::default();
    /// let point = Point::new(raw_point, &Default::default());
    /// ```
    pub fn new(mut raw_point: raw::Point, transforms: &Vector<Transform>) -> Point {
        let is_overlap = raw_point.flags.is_overlap();
        raw_point.flags.clear_overlap_class();

        Point {
            x: transforms.x.direct(raw_point.x),
            y: transforms.y.direct(raw_point.y),
            z: transforms.z.direct(raw_point.z),
            intensity: raw_point.intensity,
            return_number: raw_point.flags.return_number(),
            number_of_returns: raw_point.flags.number_of_returns(),
            scan_direction: raw_point.flags.scan_direction(),
            is_edge_of_flight_line: raw_point.flags.is_edge_of_flight_line(),
            classification: raw_point
                .flags
                .to_classification()
                .expect("Overlap classification should have been cleared"),
            is_synthetic: raw_point.flags.is_synthetic(),
            is_key_point: raw_point.flags.is_key_point(),
            is_withheld: raw_point.flags.is_withheld(),
            is_overlap,
            scan_angle: raw_point.scan_angle.into(),
            scanner_channel: raw_point.flags.scanner_channel(),
            user_data: raw_point.user_data,
            point_source_id: raw_point.point_source_id,
            gps_time: raw_point.gps_time,
            color: raw_point.color,
            waveform: raw_point.waveform,
            nir: raw_point.nir,
            extra_bytes: raw_point.extra_bytes,
        }
    }
    /// Creates a raw las point from this point.
    ///
    /// # Examples
    ///
    /// ```
    /// use las::Point;
    /// let point = Point::default();
    /// let raw_point = point.into_raw(&Default::default()).unwrap();
    /// ```
    pub fn into_raw(self, transforms: &Vector<Transform>) -> Result<raw::Point> {
        Ok(raw::Point {
            x: transforms.x.inverse(self.x)?,
            y: transforms.y.inverse(self.y)?,
            z: transforms.z.inverse(self.z)?,
            intensity: self.intensity,
            flags: self.flags()?,
            scan_angle: self.scan_angle.into(),
            user_data: self.user_data,
            point_source_id: self.point_source_id,
            gps_time: self.gps_time,
            color: self.color,
            waveform: self.waveform,
            nir: self.nir,
            extra_bytes: self.extra_bytes,
        })
    }

    /// Creates the flags bytes for use in a raw point.
    ///
    /// # Examples
    ///
    /// ```
    /// use las::Point;
    /// let point = Point { return_number: 1, ..Default::default() };
    /// assert_eq!((1, 0, 0), point.flags().unwrap().into());
    /// ```
    pub fn flags(&self) -> Result<raw::point::Flags> {
        if self.return_number > 15 {
            Err(Error::ReturnNumber {
                return_number: self.return_number,
                version: None,
            }
            .into())
        } else if self.number_of_returns > 15 {
            Err(Error::ReturnNumber {
                return_number: self.number_of_returns,
                version: None,
            }
            .into())
        } else if self.scanner_channel > 3 {
            Err(Error::ScannerChannel(self.scanner_channel).into())
        } else {
            let a = (self.number_of_returns << 4) + self.return_number;
            let mut b = self.scanner_channel << 4;
            if self.is_synthetic {
                b += 1;
            }
            if self.is_key_point {
                b += 2;
            }
            if self.is_withheld {
                b += 4;
            }
            if self.is_overlap {
                b += 8;
            }
            if self.scan_direction == ScanDirection::LeftToRight {
                b += 64;
            }
            if self.is_edge_of_flight_line {
                b += 128;
            }
            Ok(raw::point::Flags::ThreeByte(
                a,
                b,
                self.classification.into(),
            ))
        }
    }

    /// Returns true if this point matches the point format.
    ///
    /// "Matches" means that the set of optional attributes is exactly the same.
    ///
    /// # Examples
    ///
    /// ```
    /// use las::point::Format;
    /// use las::Point;
    ///
    /// let mut format = Format::new(0).unwrap();
    /// let mut point = Point::default();
    /// assert!(point.matches(&format));
    ///
    /// format.has_gps_time = true;
    /// assert!(!point.matches(&format));
    ///
    /// point.gps_time = Some(42.);
    /// assert!(point.matches(&format));
    /// ```
    pub fn matches(&self, format: &Format) -> bool {
        self.gps_time.is_some() == format.has_gps_time
            && self.color.is_some() == format.has_color
            && self.waveform.is_some() == format.has_waveform
            && self.nir.is_some() == format.has_nir
            && self.extra_bytes.len() == format.extra_bytes as usize
    }
}

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

    #[test]
    fn flags_invalid_return_number() {
        assert!(Point {
            return_number: 16,
            ..Default::default()
        }
        .flags()
        .is_err());
    }

    #[test]
    fn flags_invalid_number_of_returns() {
        assert!(Point {
            number_of_returns: 16,
            ..Default::default()
        }
        .flags()
        .is_err());
    }

    #[test]
    fn flags_invalid_scanner_channel() {
        assert!(Point {
            scanner_channel: 4,
            ..Default::default()
        }
        .flags()
        .is_err());
    }

    #[test]
    fn overlap() {
        use crate::raw::point::Flags;

        let raw_point = raw::Point {
            flags: Flags::TwoByte(0, 12),
            ..Default::default()
        };
        let point = Point::new(raw_point, &Default::default());
        assert_eq!(Classification::Unclassified, point.classification);
        assert!(point.is_overlap);
    }
}