-
Notifications
You must be signed in to change notification settings - Fork 91
/
srs.rs
520 lines (469 loc) · 16.1 KB
/
srs.rs
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
use crate::utils::{_last_cpl_err, _last_null_pointer_err, _string};
use gdal_sys::{self, CPLErr, OGRCoordinateTransformationH, OGRErr, OGRSpatialReferenceH};
use libc::{c_char, c_int};
use std::ffi::{CStr, CString};
use std::ptr::{self, null_mut};
use std::str::FromStr;
use crate::errors::*;
pub struct CoordTransform {
inner: OGRCoordinateTransformationH,
from: String,
to: String,
}
impl Drop for CoordTransform {
fn drop(&mut self) {
unsafe { gdal_sys::OCTDestroyCoordinateTransformation(self.inner) };
self.inner = ptr::null_mut();
}
}
impl CoordTransform {
pub fn new(sp_ref1: &SpatialRef, sp_ref2: &SpatialRef) -> Result<CoordTransform> {
let c_obj = unsafe { gdal_sys::OCTNewCoordinateTransformation(sp_ref1.0, sp_ref2.0) };
if c_obj.is_null() {
return Err(_last_null_pointer_err("OCTNewCoordinateTransformation"));
}
Ok(CoordTransform {
inner: c_obj,
from: sp_ref1.authority().or_else(|_| sp_ref1.to_proj4())?,
to: sp_ref2.authority().or_else(|_| sp_ref2.to_proj4())?,
})
}
/// Transform coordinates in place.
///
/// # Arguments
/// * x - slice of x coordinates
/// * y - slice of y coordinates (must match x in length)
/// * z - slice of z coordinates, or an empty slice to ignore
pub fn transform_coords(&self, x: &mut [f64], y: &mut [f64], z: &mut [f64]) -> Result<()> {
let nb_coords = x.len();
assert_eq!(
nb_coords,
y.len(),
"transform coordinate slices have different lengths: {} != {}",
nb_coords,
y.len()
);
let ret_val = unsafe {
gdal_sys::OCTTransform(
self.inner,
nb_coords as c_int,
x.as_mut_ptr(),
y.as_mut_ptr(),
if z.is_empty() {
null_mut()
} else {
assert_eq!(
nb_coords,
z.len(),
"transform coordinate slices have different lengths: {} != {}",
nb_coords,
z.len()
);
z.as_mut_ptr()
},
) == 1
};
if ret_val {
Ok(())
} else {
let err = _last_cpl_err(CPLErr::CE_Failure);
let msg = if let GdalError::CplError { msg, .. } = err {
if msg.trim().is_empty() {
None
} else {
Some(msg)
}
} else {
return Err(err);
};
Err(GdalError::InvalidCoordinateRange {
from: self.from.clone(),
to: self.to.clone(),
msg,
})
}
}
#[deprecated(since = "0.3.1", note = "use `transform_coords` instead")]
pub fn transform_coord(&self, x: &mut [f64], y: &mut [f64], z: &mut [f64]) {
self.transform_coords(x, y, z)
.expect("Coordinate transform failed")
}
pub fn to_c_hct(&self) -> OGRCoordinateTransformationH {
self.inner
}
}
#[derive(Debug, Clone)]
pub struct AreaOfUse {
pub west_lon_degree: f64,
pub south_lat_degree: f64,
pub east_lon_degree: f64,
pub north_lat_degree: f64,
pub name: String,
}
pub type AxisOrientationType = gdal_sys::OGRAxisOrientation::Type;
#[derive(Debug)]
pub struct SpatialRef(OGRSpatialReferenceH);
impl Drop for SpatialRef {
fn drop(&mut self) {
unsafe { gdal_sys::OSRRelease(self.0) };
self.0 = ptr::null_mut();
}
}
impl Clone for SpatialRef {
fn clone(&self) -> SpatialRef {
let n_obj = unsafe { gdal_sys::OSRClone(self.0) };
SpatialRef(n_obj)
}
}
impl PartialEq for SpatialRef {
fn eq(&self, other: &SpatialRef) -> bool {
unsafe { gdal_sys::OSRIsSame(self.0, other.0) == 1 }
}
}
impl SpatialRef {
pub fn new() -> Result<SpatialRef> {
let c_obj = unsafe { gdal_sys::OSRNewSpatialReference(ptr::null()) };
if c_obj.is_null() {
return Err(_last_null_pointer_err("OSRNewSpatialReference"));
}
Ok(SpatialRef(c_obj))
}
pub fn from_definition(definition: &str) -> Result<SpatialRef> {
let c_obj = unsafe { gdal_sys::OSRNewSpatialReference(ptr::null()) };
if c_obj.is_null() {
return Err(_last_null_pointer_err("OSRNewSpatialReference"));
}
let rv =
unsafe { gdal_sys::OSRSetFromUserInput(c_obj, CString::new(definition)?.as_ptr()) };
if rv != OGRErr::OGRERR_NONE {
return Err(GdalError::OgrError {
err: rv,
method_name: "OSRSetFromUserInput",
});
}
Ok(SpatialRef(c_obj))
}
pub fn from_wkt(wkt: &str) -> Result<SpatialRef> {
let c_str = CString::new(wkt)?;
let c_obj = unsafe { gdal_sys::OSRNewSpatialReference(c_str.as_ptr()) };
if c_obj.is_null() {
return Err(_last_null_pointer_err("OSRNewSpatialReference"));
}
Ok(SpatialRef(c_obj))
}
pub fn from_epsg(epsg_code: u32) -> Result<SpatialRef> {
let null_ptr = ptr::null_mut();
let c_obj = unsafe { gdal_sys::OSRNewSpatialReference(null_ptr) };
let rv = unsafe { gdal_sys::OSRImportFromEPSG(c_obj, epsg_code as c_int) };
if rv != OGRErr::OGRERR_NONE {
Err(GdalError::OgrError {
err: rv,
method_name: "OSRImportFromEPSG",
})
} else {
Ok(SpatialRef(c_obj))
}
}
pub fn from_proj4(proj4_string: &str) -> Result<SpatialRef> {
let c_str = CString::new(proj4_string)?;
let null_ptr = ptr::null_mut();
let c_obj = unsafe { gdal_sys::OSRNewSpatialReference(null_ptr) };
let rv = unsafe { gdal_sys::OSRImportFromProj4(c_obj, c_str.as_ptr()) };
if rv != OGRErr::OGRERR_NONE {
Err(GdalError::OgrError {
err: rv,
method_name: "OSRImportFromProj4",
})
} else {
Ok(SpatialRef(c_obj))
}
}
pub fn from_esri(esri_wkt: &str) -> Result<SpatialRef> {
let c_str = CString::new(esri_wkt)?;
let mut ptrs = vec![c_str.as_ptr() as *mut c_char, ptr::null_mut()];
let null_ptr = ptr::null_mut();
let c_obj = unsafe { gdal_sys::OSRNewSpatialReference(null_ptr) };
let rv = unsafe { gdal_sys::OSRImportFromESRI(c_obj, ptrs.as_mut_ptr()) };
if rv != OGRErr::OGRERR_NONE {
Err(GdalError::OgrError {
err: rv,
method_name: "OSRImportFromESRI",
})
} else {
Ok(SpatialRef(c_obj))
}
}
/// Returns a wrapped `SpatialRef` from a raw C API handle.
///
/// # Safety
/// The handle passed to this function must be valid.
pub unsafe fn from_c_obj(c_obj: OGRSpatialReferenceH) -> Result<SpatialRef> {
let mut_c_obj = gdal_sys::OSRClone(c_obj);
if mut_c_obj.is_null() {
Err(_last_null_pointer_err("OSRClone"))
} else {
Ok(SpatialRef(mut_c_obj))
}
}
pub fn to_wkt(&self) -> Result<String> {
let mut c_wkt = ptr::null_mut();
let rv = unsafe { gdal_sys::OSRExportToWkt(self.0, &mut c_wkt) };
let res = if rv != OGRErr::OGRERR_NONE {
Err(GdalError::OgrError {
err: rv,
method_name: "OSRExportToWkt",
})
} else {
Ok(_string(c_wkt))
};
unsafe { gdal_sys::VSIFree(c_wkt.cast::<std::ffi::c_void>()) };
res
}
pub fn morph_to_esri(&self) -> Result<()> {
let rv = unsafe { gdal_sys::OSRMorphToESRI(self.0) };
if rv != OGRErr::OGRERR_NONE {
return Err(GdalError::OgrError {
err: rv,
method_name: "OSRMorphToESRI",
});
}
Ok(())
}
pub fn to_pretty_wkt(&self) -> Result<String> {
let mut c_wkt = ptr::null_mut();
let rv = unsafe { gdal_sys::OSRExportToPrettyWkt(self.0, &mut c_wkt, false as c_int) };
let res = if rv != OGRErr::OGRERR_NONE {
Err(GdalError::OgrError {
err: rv,
method_name: "OSRExportToPrettyWkt",
})
} else {
Ok(_string(c_wkt))
};
unsafe { gdal_sys::VSIFree(c_wkt.cast::<std::ffi::c_void>()) };
res
}
pub fn to_xml(&self) -> Result<String> {
let mut c_raw_xml = ptr::null_mut();
let rv = unsafe { gdal_sys::OSRExportToXML(self.0, &mut c_raw_xml, ptr::null()) };
let res = if rv != OGRErr::OGRERR_NONE {
Err(GdalError::OgrError {
err: rv,
method_name: "OSRExportToXML",
})
} else {
Ok(_string(c_raw_xml))
};
unsafe { gdal_sys::VSIFree(c_raw_xml.cast::<std::ffi::c_void>()) };
res
}
pub fn to_proj4(&self) -> Result<String> {
let mut c_proj4str = ptr::null_mut();
let rv = unsafe { gdal_sys::OSRExportToProj4(self.0, &mut c_proj4str) };
let res = if rv != OGRErr::OGRERR_NONE {
Err(GdalError::OgrError {
err: rv,
method_name: "OSRExportToProj4",
})
} else {
Ok(_string(c_proj4str))
};
unsafe { gdal_sys::VSIFree(c_proj4str.cast::<std::ffi::c_void>()) };
res
}
pub fn auth_name(&self) -> Result<String> {
let c_ptr = unsafe { gdal_sys::OSRGetAuthorityName(self.0, ptr::null()) };
if c_ptr.is_null() {
Err(_last_null_pointer_err("SRGetAuthorityName"))
} else {
Ok(_string(c_ptr))
}
}
pub fn auth_code(&self) -> Result<i32> {
let c_ptr = unsafe { gdal_sys::OSRGetAuthorityCode(self.0, ptr::null()) };
if c_ptr.is_null() {
return Err(_last_null_pointer_err("OSRGetAuthorityCode"));
}
let c_str = unsafe { CStr::from_ptr(c_ptr) };
let epsg = i32::from_str(c_str.to_str()?);
match epsg {
Ok(n) => Ok(n),
Err(_) => Err(GdalError::OgrError {
err: OGRErr::OGRERR_UNSUPPORTED_SRS,
method_name: "OSRGetAuthorityCode",
}),
}
}
pub fn authority(&self) -> Result<String> {
let c_ptr = unsafe { gdal_sys::OSRGetAuthorityName(self.0, ptr::null()) };
if c_ptr.is_null() {
return Err(_last_null_pointer_err("SRGetAuthorityName"));
}
let name = unsafe { CStr::from_ptr(c_ptr) }.to_str()?;
let c_ptr = unsafe { gdal_sys::OSRGetAuthorityCode(self.0, ptr::null()) };
if c_ptr.is_null() {
return Err(_last_null_pointer_err("OSRGetAuthorityCode"));
}
let code = unsafe { CStr::from_ptr(c_ptr) }.to_str()?;
Ok(format!("{}:{}", name, code))
}
pub fn auto_identify_epsg(&mut self) -> Result<()> {
let rv = unsafe { gdal_sys::OSRAutoIdentifyEPSG(self.0) };
if rv != OGRErr::OGRERR_NONE {
Err(GdalError::OgrError {
err: rv,
method_name: "OSRAutoIdentifyEPSG",
})
} else {
Ok(())
}
}
#[cfg(major_ge_3)]
pub fn name(&self) -> Result<String> {
let c_ptr = unsafe { gdal_sys::OSRGetName(self.0) };
if c_ptr.is_null() {
return Err(_last_null_pointer_err("OSRGetName"));
}
Ok(_string(c_ptr))
}
pub fn angular_units_name(&self) -> Result<String> {
let mut c_ptr = ptr::null_mut();
unsafe { gdal_sys::OSRGetAngularUnits(self.0, &mut c_ptr) };
if c_ptr.is_null() {
return Err(_last_null_pointer_err("OSRGetAngularUnits"));
}
Ok(_string(c_ptr))
}
pub fn angular_units(&self) -> f64 {
unsafe { gdal_sys::OSRGetAngularUnits(self.0, ptr::null_mut()) }
}
pub fn linear_units_name(&self) -> Result<String> {
let mut c_ptr = ptr::null_mut();
unsafe { gdal_sys::OSRGetLinearUnits(self.0, &mut c_ptr) };
if c_ptr.is_null() {
return Err(_last_null_pointer_err("OSRGetLinearUnits"));
}
Ok(_string(c_ptr))
}
pub fn linear_units(&self) -> f64 {
unsafe { gdal_sys::OSRGetLinearUnits(self.0, ptr::null_mut()) }
}
#[inline]
pub fn is_geographic(&self) -> bool {
unsafe { gdal_sys::OSRIsGeographic(self.0) == 1 }
}
#[inline]
#[cfg(all(major_ge_3, minor_ge_1))]
pub fn is_derived_geographic(&self) -> bool {
unsafe { gdal_sys::OSRIsDerivedGeographic(self.0) == 1 }
}
#[inline]
pub fn is_local(&self) -> bool {
unsafe { gdal_sys::OSRIsLocal(self.0) == 1 }
}
#[inline]
pub fn is_projected(&self) -> bool {
unsafe { gdal_sys::OSRIsProjected(self.0) == 1 }
}
#[inline]
pub fn is_compound(&self) -> bool {
unsafe { gdal_sys::OSRIsCompound(self.0) == 1 }
}
#[inline]
pub fn is_geocentric(&self) -> bool {
unsafe { gdal_sys::OSRIsGeocentric(self.0) == 1 }
}
#[inline]
pub fn is_vertical(&self) -> bool {
unsafe { gdal_sys::OSRIsVertical(self.0) == 1 }
}
pub fn axis_orientation(&self, target_key: &str, axis: i32) -> Result<AxisOrientationType> {
let mut orientation = gdal_sys::OGRAxisOrientation::OAO_Other;
let c_ptr = unsafe {
gdal_sys::OSRGetAxis(
self.0,
CString::new(target_key)?.as_ptr(),
axis as c_int,
&mut orientation,
)
};
// null ptr indicate a failure (but no CPLError) see Gdal documentation.
if c_ptr.is_null() {
Err(GdalError::AxisNotFoundError {
key: target_key.into(),
method_name: "OSRGetAxis",
})
} else {
Ok(orientation)
}
}
pub fn axis_name(&self, target_key: &str, axis: i32) -> Result<String> {
// See get_axis_orientation
let c_ptr = unsafe {
gdal_sys::OSRGetAxis(
self.0,
CString::new(target_key)?.as_ptr(),
axis as c_int,
ptr::null_mut(),
)
};
if c_ptr.is_null() {
Err(GdalError::AxisNotFoundError {
key: target_key.into(),
method_name: "OSRGetAxis",
})
} else {
Ok(_string(c_ptr))
}
}
#[cfg(all(major_ge_3, minor_ge_1))]
pub fn axes_count(&self) -> i32 {
unsafe { gdal_sys::OSRGetAxesCount(self.0) }
}
#[cfg(major_ge_3)]
pub fn set_axis_mapping_strategy(&self, strategy: gdal_sys::OSRAxisMappingStrategy::Type) {
unsafe {
gdal_sys::OSRSetAxisMappingStrategy(self.0, strategy);
}
}
#[cfg(major_ge_3)]
#[deprecated(note = "use `axis_mapping_strategy` instead")]
pub fn get_axis_mapping_strategy(&self) -> gdal_sys::OSRAxisMappingStrategy::Type {
self.axis_mapping_strategy()
}
#[cfg(major_ge_3)]
pub fn axis_mapping_strategy(&self) -> gdal_sys::OSRAxisMappingStrategy::Type {
unsafe { gdal_sys::OSRGetAxisMappingStrategy(self.0) }
}
#[cfg(major_ge_3)]
pub fn area_of_use(&self) -> Option<AreaOfUse> {
let mut c_area_name: *const libc::c_char = ptr::null_mut();
let (mut w_long, mut s_lat, mut e_long, mut n_lat): (f64, f64, f64, f64) =
(0.0, 0.0, 0.0, 0.0);
let ret_val = unsafe {
gdal_sys::OSRGetAreaOfUse(
self.0,
&mut w_long,
&mut s_lat,
&mut e_long,
&mut n_lat,
&mut c_area_name,
) == 1
};
if ret_val {
Some(AreaOfUse {
west_lon_degree: w_long,
south_lat_degree: s_lat,
east_lon_degree: e_long,
north_lat_degree: n_lat,
name: _string(c_area_name),
})
} else {
None
}
}
// TODO: should this take self instead of &self?
pub fn to_c_hsrs(&self) -> OGRSpatialReferenceH {
self.0
}
}