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
use std::convert::TryFrom;
use std::ptr;

use gdal_sys::{self, CPLErr};
use libc::c_void;

use crate::cpl::CslStringList;
use crate::dataset::Dataset;
use crate::errors::*;
use crate::utils::_last_cpl_err;
use crate::vector::Geometry;

#[derive(Copy, Clone, Debug)]
pub enum BurnSource {
    /// Use whatever `burn_values` argument is supplied to
    /// `rasterize`.
    UserSupplied,

    /// Add the geometry's Z value to whatever `burn_values` argument
    /// is supplied to `rasterize`.
    Z,
    // `M` is defined but seemingly not allowed for rasterization
}

#[derive(Copy, Clone, Debug)]
pub enum MergeAlgorithm {
    Replace,
    Add,
}

#[derive(Copy, Clone, Debug)]
pub enum OptimizeMode {
    Automatic,
    Raster,
    Vector,
}

/// Options that specify how to rasterize geometries.
#[derive(Copy, Clone, Debug)]
pub struct RasterizeOptions {
    /// Set to `true` to set all pixels touched by the line or
    /// polygons, not just those whose center is within the polygon or
    /// that are selected by brezenhams line algorithm. Defaults to
    /// `false`.
    pub all_touched: bool,

    /// May be set to `BurnSource::Z` to use the Z values of the
    /// geometries. `burn_value` is added to this before
    /// burning. Defaults to `BurnSource::UserSupplied` in which case
    /// just the `burn_value` is burned. This is implemented only for
    /// points and lines for now. `BurnValue::M` may be supported in
    /// the future.
    pub source: BurnSource,

    /// May be `MergeAlgorithm::Replace` (the default) or
    /// `MergeAlgorithm::Add`. `Replace` results in overwriting of
    /// value, while `Add` adds the new value to the existing raster,
    /// suitable for heatmaps for instance.
    pub merge_algorithm: MergeAlgorithm,

    /// The height in lines of the chunk to operate on. The larger the
    /// chunk size the less times we need to make a pass through all
    /// the shapes. If it is not set or set to zero the default chunk
    /// size will be used. Default size will be estimated based on the
    /// GDAL cache buffer size using formula: `cache_size_bytes /
    /// scanline_size_bytes`, so the chunk will not exceed the
    /// cache. Not used in `OPTIM=RASTER` mode.
    pub chunk_y_size: usize,

    pub optimize: OptimizeMode,
}

impl Default for RasterizeOptions {
    fn default() -> Self {
        RasterizeOptions {
            all_touched: false,
            source: BurnSource::UserSupplied,
            merge_algorithm: MergeAlgorithm::Replace,
            chunk_y_size: 0,
            optimize: OptimizeMode::Automatic,
        }
    }
}

impl TryFrom<RasterizeOptions> for CslStringList {
    type Error = GdalError;

    fn try_from(value: RasterizeOptions) -> Result<CslStringList> {
        let mut options = CslStringList::new();

        options.set_name_value(
            "ALL_TOUCHED",
            if value.all_touched { "TRUE" } else { "FALSE" },
        )?;
        options.set_name_value(
            "MERGE_ALG",
            match value.merge_algorithm {
                MergeAlgorithm::Replace => "REPLACE",
                MergeAlgorithm::Add => "ADD",
            },
        )?;
        options.set_name_value("CHUNKYSIZE", &value.chunk_y_size.to_string())?;
        options.set_name_value(
            "OPTIM",
            match value.optimize {
                OptimizeMode::Automatic => "AUTO",
                OptimizeMode::Raster => "RASTER",
                OptimizeMode::Vector => "VECTOR",
            },
        )?;
        if let BurnSource::Z = value.source {
            options.set_name_value("BURN_VALUE_FROM", "Z")?;
        }

        Ok(options)
    }
}

#[cfg(test)]
mod tests {
    use std::convert::TryFrom;

    use crate::cpl::CslStringList;

    use super::RasterizeOptions;

    #[test]
    fn test_rasterizeoptions_as_ptr() {
        let c_options = CslStringList::try_from(RasterizeOptions::default()).unwrap();
        assert_eq!(
            c_options.fetch_name_value("ALL_TOUCHED").unwrap(),
            Some("FALSE".to_string())
        );
        assert_eq!(c_options.fetch_name_value("BURN_VALUE_FROM").unwrap(), None);
        assert_eq!(
            c_options.fetch_name_value("MERGE_ALG").unwrap(),
            Some("REPLACE".to_string())
        );
        assert_eq!(
            c_options.fetch_name_value("CHUNKYSIZE").unwrap(),
            Some("0".to_string())
        );
        assert_eq!(
            c_options.fetch_name_value("OPTIM").unwrap(),
            Some("AUTO".to_string())
        );
    }
}

/// Burn geometries into raster.
///
/// Rasterize a sequence of `gdal::vector::Geometry` onto some
/// `dataset` bands. Those geometries must have coordinates
/// georegerenced to `dataset`.
///
/// Bands are selected using indices supplied in `bands`.
///
/// Options are specified with `options`.
///
/// There must be one burn value for every geometry. The output raster
/// may be of any GDAL supported datatype.
pub fn rasterize(
    dataset: &mut Dataset,
    bands: &[isize],
    geometries: &[Geometry],
    burn_values: &[f64],
    options: Option<RasterizeOptions>,
) -> Result<()> {
    if bands.is_empty() {
        return Err(GdalError::BadArgument(
            "`bands` must not be empty".to_string(),
        ));
    }
    if burn_values.len() != geometries.len() {
        return Err(GdalError::BadArgument(format!(
            "Burn values length ({}) must match geometries length ({})",
            burn_values.len(),
            geometries.len()
        )));
    }
    for band in bands {
        let is_good = *band > 0 && *band <= dataset.raster_count();
        if !is_good {
            return Err(GdalError::BadArgument(format!(
                "Band index {} is out of bounds",
                *band
            )));
        }
    }

    let bands: Vec<i32> = bands.iter().map(|&band| band as i32).collect();
    let options = options.unwrap_or_default();

    let geometries: Vec<_> = geometries
        .iter()
        .map(|geo| unsafe { geo.c_geometry() })
        .collect();
    let burn_values: Vec<f64> = burn_values
        .iter()
        .flat_map(|burn| std::iter::repeat(burn).take(bands.len()))
        .copied()
        .collect();

    let c_options = CslStringList::try_from(options).unwrap();
    unsafe {
        // The C function takes `bands`, `geometries`, `burn_values`
        // and `options` without mention of `const`, and this is
        // propagated to the gdal_sys wrapper. The lack of `const`
        // seems like a mistake in the GDAL API, so we just do a casts
        // here.

        let error = gdal_sys::GDALRasterizeGeometries(
            dataset.c_dataset(),
            bands.len() as i32,
            bands.as_ptr() as *mut i32,
            geometries.len() as i32,
            geometries.as_ptr() as *mut *mut c_void,
            None,
            ptr::null_mut(),
            burn_values.as_ptr() as *mut f64,
            c_options.as_ptr(),
            None,
            ptr::null_mut(),
        );
        if error != CPLErr::CE_None {
            return Err(_last_cpl_err(error));
        }
    }
    Ok(())
}