Encoding, indexing and exact primitives
The native binary codec, the candidate filters over polygon parts and ring edges, and the exact ring- and segment-level primitives that the crate’s own constructors and DE-9IM analysis use.
The native codec
geometres::codec is the authoritative definition of a serialized geometres value,
and its format is part of the crate’s public contract. Encoding appends to a
Vec<u8>
and decoding reads a &[u8]; nothing in the module performs I/O. The codec is built on
std and allocates.
The codec makes three guarantees:
- Deterministic. The same value produces byte-identical output on every run, platform and
build. Every
f64is written withf64::to_le_bytesand read withf64::from_le_bytes, never through a decimal representation. - Exact on round trip. Decoding an encoding yields a
PartialEq-equal value,f64bit patterns included. - Validating on decode. Every geometry is rebuilt through its public constructor, and the
constructor’s error is propagated. No type is assembled field by field from bytes, so a malformed or
hostile byte stream produces a
CodecError, never an invalid geometry and never a panic.
A document is a version byte, a tag byte and a body. All integers are little-endian, and every length is an
explicit u32 count, so a decoder never scans for a boundary.
| Element | Encoding |
|---|---|
| document | version:u8 tag:u8 body |
f64 |
8 bytes, to_le_bytes |
| count | u32, 4 bytes little-endian |
Coord2d |
x:f64 y:f64 |
| coordinate sequence | count:u32, then count coordinates |
Polygon |
exterior sequence, holes:u32, then each hole’s sequence |
Envelope |
min_x:f64 min_y:f64 max_x:f64 max_y:f64 |
Geometry |
variant:u8, then that variant’s body; the variant byte reuses the top-level tag
values |
A LinearRing is encoded as its n distinct vertices with closure
implied.
The encoder writes no closing vertex, and the decoder refuses one as
GeometryError::ConsecutiveDuplicateVertices rather than stripping it as
LinearRing::new does. Refusing it keeps every value’s encoding unique: whatever decodes
re-encodes to the bytes read. A GeometryCollection nests at most
GeometryCollection::MAX_NESTING (32) levels deep, and the decoder refuses a deeper header
before
reading inside it.
The result wrappers Unvouched<T> and MaybeVouched<T, U> have no
encoding, and neither does GeometryError. A wrapper describes the outcome of a computation
rather
than a value worth storing; its inner geometry encodes on its own once the caller has unwrapped it.
encode
pub fn encode<T: Encode>(value: &T) -> Vec<u8>
Encodes value as a complete document: version, tag, body. The output is deterministic: the
same value yields the same bytes on every run and platform.
use geometres::codec::{FORMAT_VERSION, decode, encode, tag};
use geometres::types::{Coord2d, CoordSeq, LinearRing, Polygon};
let ring = LinearRing::new(CoordSeq::new(vec![
Coord2d::new(0.0, 0.0), Coord2d::new(1.0, 0.0),
Coord2d::new(1.0, 1.0), Coord2d::new(0.0, 1.0),
])).unwrap();
let square = Polygon::new_simple(ring).unwrap();
let bytes = encode(&square);
assert_eq!(bytes[0], FORMAT_VERSION);
assert_eq!(bytes[1], tag::POLYGON);
// Header 2, vertex count 4, four vertices of 16, hole count 4.
// No closing vertex is written.
assert_eq!(bytes.len(), 2 + 4 + 4 * 16 + 4);
// The round trip is exact, and the same value always encodes the same way.
let back: Polygon = decode(&bytes).unwrap();
assert_eq!(back, square);
assert_eq!(encode(&back), bytes);
encode_into
pub fn encode_into<T: Encode>(value: &T, out: &mut
Vec<u8>)
Appends a complete document for value to an existing buffer. Several documents can share one
allocation, and each remains independently decodable because each carries its own version and tag.
use geometres::codec::{decode, encode_into};
use geometres::types::{Coord2d, Point};
let a = Point::new(Coord2d::new(1.0, 2.0)).unwrap();
let b = Point::new(Coord2d::new(-3.5, 0.25)).unwrap();
let mut buf = Vec::new();
encode_into(&a, &mut buf);
encode_into(&b, &mut buf);
assert_eq!(buf.len(), 2 * 18); // each document: 2 header bytes and 16 coordinate bytes
let (first, second) = buf.split_at(18);
assert_eq!(decode::<Point>(first).unwrap(), a);
assert_eq!(decode::<Point>(second).unwrap(), b);
decode
pub fn decode<T: Decode>(bytes: &[u8]) -> Result<T,
CodecError>
Decodes a complete document into T. It checks the version, checks that the tag is
T’s, decodes the body, and requires the stream to be fully consumed. A document
describes
exactly one value, so trailing bytes are refused rather than partly used.
Every geometry passes its constructor on the way in. A byte stream that describes a NaN
coordinate, a two-vertex ring or a clockwise exterior yields CodecError::Geometry carrying
the
constructor’s own error, never a geometry. Coord2d and CoordSeq are not
geometries, and Coord2d::new does not validate, so their documents decode any bit pattern.
Errors: UnexpectedEnd if the stream ends mid-value;
UnsupportedVersion if the version byte is not FORMAT_VERSION;
UnexpectedTag if the document is not a T; Geometry if the bytes
describe an invalid geometry; TrailingBytes if bytes remain after a complete value. Inside a
body, the variants listed under CodecError can also arise, such as
UnknownVariant for an undefined Geometry variant byte.
use geometres::GeometryError;
use geometres::codec::{CodecError, FORMAT_VERSION, decode, put_count, put_f64, tag};
use geometres::types::{Point, Polygon};
// A unit square written clockwise, byte by byte. The bytes are well formed,
// but Polygon::new requires a counterclockwise exterior.
let mut bytes = vec![FORMAT_VERSION, tag::POLYGON];
put_count(4, &mut bytes);
for (x, y) in [(0.0, 0.0), (0.0, 1.0), (1.0, 1.0), (1.0, 0.0)] {
put_f64(x, &mut bytes);
put_f64(y, &mut bytes);
}
put_count(0, &mut bytes); // no holes
assert_eq!(
decode::<Polygon>(&bytes),
Err(CodecError::Geometry(GeometryError::IncorrectWindingOrder))
);
// A Polygon document is not a Point.
assert_eq!(
decode::<Point>(&bytes),
Err(CodecError::UnexpectedTag { expected: tag::POINT, found: tag::POLYGON })
);
CodecError
#[non_exhaustive]
pub enum CodecError
Why a byte stream could not be decoded. Every variant is a refusal, and none is recoverable into a
partial
value: a decode either yields a fully valid geometry or yields one of these. CodecError
implements Display and Error, with the GeometryError as the source
of
the Geometry variant, and converts from GeometryError by From.
| Variant | Meaning |
|---|---|
UnexpectedEnd { needed, available } |
The stream ended before the value did: the read wanted needed bytes and
available remained.
|
UnsupportedVersion { found } |
The version byte is not FORMAT_VERSION. |
UnexpectedTag { expected, found } |
The tag byte does not identify the type being decoded: an unrecognized tag, or a recognized tag for a different type. |
UnknownVariant { found } |
A Geometry variant byte that this version does not define. Geometry is
#[non_exhaustive], so an unknown variant is refused rather than skipped.
|
InvalidEnumValue { type_name, found } |
An enum payload outside its defined range: a Location byte above 2, or a
Dimension byte outside −1..=2.
|
CountOverflow { count } |
A count that cannot be represented on this platform. Reachable only where usize is
narrower than u32. |
Geometry(GeometryError) |
The bytes decoded, but the value they describe is not a valid geometry. The constructor’s own error, propagated unchanged. |
NestingTooDeep { limit } |
A GeometryCollection header met at the deepest nesting the format allows. Checked
before the nested collection is read. |
TrailingBytes { remaining } |
Bytes remained after a complete value was decoded. |
use geometres::codec::{CodecError, FORMAT_VERSION, decode, encode};
use geometres::types::{Coord2d, Point};
let bytes = encode(&Point::new(Coord2d::new(1.0, 2.0)).unwrap());
// Cut short inside the y coordinate.
assert_eq!(
decode::<Point>(&bytes[..12]),
Err(CodecError::UnexpectedEnd { needed: 8, available: 2 })
);
// One stray byte after the value.
let mut longer = bytes.clone();
longer.push(0);
assert_eq!(decode::<Point>(&longer), Err(CodecError::TrailingBytes { remaining: 1 }));
// A version this build does not read is refused, not guessed.
let mut other = bytes.clone();
other[0] = FORMAT_VERSION + 1;
assert_eq!(
decode::<Point>(&other),
Err(CodecError::UnsupportedVersion { found: FORMAT_VERSION + 1 })
);
FORMAT_VERSION and the tag constants
pub const FORMAT_VERSION: u8 = 1;
FORMAT_VERSION is the version byte written at the start of every document. A decoder rejects
any other value rather than attempting to interpret the remainder.
The codec::tag module holds the type tags. A tag identifies the top-level type of a document
and doubles as the variant discriminant inside a Geometry body, so a value’s tag means
the
same thing wherever it appears. The values are fixed by the format; changing one is a format change and
requires a FORMAT_VERSION bump.
| Tags | Constants |
|---|---|
0x01–0x0D |
COORD2D, COORD_SEQ, POINT, LINE_STRING,
LINEAR_RING, POLYGON, MULTI_POINT,
MULTI_LINE_STRING, MULTI_POLYGON, GEOMETRY,
INTERSECTION_MATRIX, DIMENSION, LOCATION, in that order
|
0x0F |
ENVELOPE |
0x10 |
TESSELLATE_METHOD: reserved, so that no type in this crate can take the value |
0x11 |
GEOMETRY_COLLECTION |
0x20–0x28 |
The 3d types: COORD3D, COORD_SEQ3D, POINT3D,
LINE_STRING3D, LINEAR_RING3D, POLYGON3D,
MULTI_POINT3D, MULTI_LINE_STRING3D, MULTI_POLYGON3D, in that
order
|
0x40–0x7F |
DOWNSTREAM_FIRST to DOWNSTREAM_LAST (inclusive): reserved for crates
built
on this one |
Encoding your own types
pub trait Encode { const TAG: u8; fn encode_body(&self, out: &mut Vec<u8>); } pub trait Decode: Sized + Encode { fn decode_body(r: &mut Reader<'_>) -> Result<Self, CodecError>; }Encode and Decode establish the extension API: a crate built on this one
encodes
its own types in the same format by implementing them. TAG identifies the type in a document
header, and encode_body writes the value without any header, so one type can be nested inside
another. decode_body reads the body after decode has consumed the header; an
implementation must not panic on any input.
A downstream type takes its tag in
tag::DOWNSTREAM_FIRST..=tag::DOWNSTREAM_LAST
(0x40–0x7F). No type in this crate takes a value in that range, so a
downstream encoding can never be read back as a type of this crate. Allocating values inside the range is
the downstream crate’s own business.
A body is built from this crate’s own types and two primitive writers, with Reader as
their inverse:
pub fn put_count(n: usize, out: &mut Vec<u8>)writes au32count, little-endian, whichReader::countreads back. The count is narrowed fromusizeso that a document written on a 64-bit machine is readable on a 32-bit one; a length aboveu32::MAXsaturates.pub fn put_f64(v: f64, out: &mut Vec<u8>)writes anf64by its bit pattern, little-endian, NaN payloads and signed zero included.Reader::f64is its inverse. Whether the value is acceptable is the decoding constructor’s decision.
use geometres::codec::{
CodecError, Decode, Encode, Reader, decode, encode, put_count, tag,
};
use geometres::types::{Coord2d, Point};
/// A labeled point, defined by a crate built on geometres.
#[derive(Debug, PartialEq)]
struct Station {
id: usize,
at: Point,
}
impl Encode for Station {
const TAG: u8 = tag::DOWNSTREAM_FIRST;
fn encode_body(&self, out: &mut Vec<u8>) {
put_count(self.id, out);
self.at.encode_body(out); // nested: Point's body, no header
}
}
impl Decode for Station {
fn decode_body(r: &mut Reader<'_>) -> Result<Self, CodecError> {
let id = r.count()?;
let at = Point::decode_body(r)?; // validated by Point::new
Ok(Station { id, at })
}
}
let s = Station { id: 7, at: Point::new(Coord2d::new(3.0, 4.0)).unwrap() };
let bytes = encode(&s);
assert_eq!(bytes[1], 0x40);
assert_eq!(decode::<Station>(&bytes).unwrap(), s);
// The downstream tag is never read back as one of geometres' types.
assert!(decode::<Point>(&bytes).is_err());
Reader
pub struct Reader<'a>
A bounds-checked cursor over a byte slice. Every read returns Result, and nothing indexes or
slices by a length read from the stream, which is the usual way a hand-written decoder acquires a panic on
hostile input.
| Method | Reads |
|---|---|
new(bytes: &'a [u8]) -> Self |
Starts at the beginning of bytes. |
remaining(&self) -> usize |
Bytes not yet consumed. |
u8(&mut self), i8(&mut self) |
One byte, unsigned or signed. |
count(&mut self) -> Result<usize, CodecError> |
A little-endian u32 count, widened to usize; CountOverflow
where usize is narrower than u32. |
f64(&mut self) -> Result<f64, CodecError> |
A little-endian f64, its bit pattern preserved exactly, NaN payloads included. |
Errors: every read returns CodecError::UnexpectedEnd if too few bytes
remain.
use geometres::codec::{CodecError, Reader, put_count, put_f64};
let mut bytes = Vec::new();
put_count(2, &mut bytes);
put_f64(-0.0, &mut bytes);
let mut r = Reader::new(&bytes);
assert_eq!(r.remaining(), 12);
assert_eq!(r.count(), Ok(2));
let z = r.f64().unwrap();
assert_eq!(z.to_bits(), (-0.0f64).to_bits()); // the sign of zero survives
assert_eq!(r.remaining(), 0);
assert_eq!(r.u8(), Err(CodecError::UnexpectedEnd { needed: 1, available: 0 }));
Candidate filters
geometres::index holds candidate filters over the parts and the edges of a polygonal value. An
index decides nothing geometric: the caller tests each candidate exactly. Its one obligation is
no false negatives: nothing whose box meets the window is left out. It meets that
obligation
exactly, because every entry’s box contains its geometry, every node’s box contains its
children’s by exact union, and the overlap test is the closed-interval comparison of stored values
that
Envelope::intersects makes.
The candidates are not a superset. A leaf entry is reported only after its own box is tested, so
candidates returns precisely the entries whose boxes intersect the window (closed, so touching
counts), each once, in an order that is deterministic but not meaningful. The public API is typed in
Envelope, Polygon and usize.
PartIndex
pub fn new(parts: &[Polygon]) -> Result<Self, GeometryError>
pub fn candidates(&self, window: &Envelope, visit: impl FnMut(usize))
A candidate filter over the parts of a polygonal value, such as a MultiPolygon’s
polygons or any &[Polygon]. Each part’s box is its exterior ring’s envelope,
which contains the holes too. new takes O(n log n), and the part at
position i of parts is reported as candidate i.
candidates calls visit with the index of every part whose box meets
window. len and is_empty give the number of parts indexed, and
bounds returns the envelope of every part, or None if there are none. Every
bound
is one of the parts’ coordinates; nothing is computed.
Errors: GeometryError::TooManyEntries if parts.len() exceeds
u32::MAX; also a LinearRing::envelope error, which is unreachable for a valid
ring
and is propagated rather than unwrapped.
use geometres::index::PartIndex;
use geometres::types::{Coord2d, CoordSeq, Envelope, LinearRing, Polygon};
let square = |x: f64, y: f64| {
let ring = LinearRing::new(CoordSeq::new(vec![
Coord2d::new(x, y), Coord2d::new(x + 1.0, y),
Coord2d::new(x + 1.0, y + 1.0), Coord2d::new(x, y + 1.0),
])).unwrap();
Polygon::new_simple(ring).unwrap()
};
let parts = vec![square(0.0, 0.0), square(5.0, 5.0), square(1.0, 0.0)];
let index = PartIndex::new(&parts).unwrap();
assert_eq!(index.len(), 3);
// A degenerate window: the segment from (1, 0.5) to (1.5, 0.5).
let window = Envelope::new(Coord2d::new(1.0, 0.5), Coord2d::new(1.5, 0.5)).unwrap();
let mut hits = Vec::new();
index.candidates(&window, |part| hits.push(part));
hits.sort_unstable();
assert_eq!(hits, [0, 2]); // part 0 touches the window at x = 1; part 2 contains it
let bounds = index.bounds().unwrap();
assert_eq!((bounds.min(), bounds.max()), (Coord2d::new(0.0, 0.0), Coord2d::new(6.0, 6.0)));
EdgeIndex
pub fn new(parts: &[Polygon]) -> Result<Self, GeometryError>
pub fn candidates(&self, window: &Envelope, visit: impl FnMut(EdgeRef))
A candidate filter over every ring edge of a polygonal value. Each edge’s box is the minimum and
maximum of its two endpoints, both exact selections of stored coordinates. new takes
O(E log E) for E edges.
candidates calls visit with every edge whose box meets window, as
an
EdgeRef. len, is_empty and bounds behave as on
PartIndex, counting edges.
Errors: GeometryError::TooManyEntries if the edge count exceeds
u32::MAX.
use geometres::index::EdgeIndex;
use geometres::types::{Coord2d, CoordSeq, Envelope, LinearRing, Polygon};
let ring = |pts: &[(f64, f64)]| {
LinearRing::new(CoordSeq::new(pts.iter().map(|&(x, y)| Coord2d::new(x, y)).collect()))
.unwrap()
};
// A 4 by 4 square with a clockwise 2 by 2 hole.
let exterior = ring(&[(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (0.0, 4.0)]);
let hole = ring(&[(1.0, 1.0), (1.0, 3.0), (3.0, 3.0), (3.0, 1.0)]);
let poly = Polygon::new(exterior, vec![hole]).unwrap();
let index = EdgeIndex::new(&[poly]).unwrap();
assert_eq!(index.len(), 8);
// Only the hole's edge (3, 3) -> (3, 1) has a box that meets the point (3, 2).
let at = Coord2d::new(3.0, 2.0);
let mut hits = Vec::new();
index.candidates(&Envelope::new(at, at).unwrap(), |e| hits.push((e.part, e.ring, e.edge)));
assert_eq!(hits, [(0, 1, 2)]);
EdgeRef
#[non_exhaustive]
pub struct EdgeRef {
pub part: usize,
pub ring: usize,
pub edge: usize,
}
One ring edge of a polygonal value, by position. part is the position of the part in the
indexed slice. ring 0 is the part’s exterior, and ring k ≥ 1 is
holes()[k − 1]. edge is the position in LinearRing::edges, so
edge i runs from vertex i to vertex i + 1, and the last edge closes the ring.
EdgeRef is Copy, Eq, Ord and Hash, so
candidates can be sorted or collected into a set.
use geometres::index::EdgeIndex;
use geometres::types::{Coord2d, CoordSeq, Envelope, LinearRing, Polygon};
let ring = LinearRing::new(CoordSeq::new(vec![
Coord2d::new(0.0, 0.0), Coord2d::new(4.0, 0.0),
Coord2d::new(4.0, 4.0), Coord2d::new(0.0, 4.0),
])).unwrap();
let square = Polygon::new_simple(ring).unwrap();
let index = EdgeIndex::new(&[square]).unwrap();
// The corner (0, 0) is the end of the closing edge 3 and the start of edge 0.
let corner = Coord2d::new(0.0, 0.0);
let mut hits = Vec::new();
index.candidates(&Envelope::new(corner, corner).unwrap(), |e| hits.push(e));
hits.sort();
let edges: Vec<usize> = hits.iter().map(|e| e.edge).collect();
assert_eq!(edges, [0, 3]);
assert!(hits.iter().all(|e| e.part == 0 && e.ring == 0));
Exact primitives
geometres::exact holds the exact ring- and segment-level primitives, public for crates built
on this one. Every decision is arithmetica::orient2d on stored input coordinates, or a
comparison
of stored input coordinates. Nothing is approximate, no tolerance is involved, and no coordinate is
constructed. These are the same primitives that Polygon::new,
MultiPolygon::new, LinearRing::is_simple and the DE-9IM matrix use, so a caller
that vouches for its own output with them applies exactly the checks the types apply.
Coord2d::new does not validate, so each item either takes only validated types
(place_ring, first_self_contact, rings, Areal::new) or
checks every coordinate it is given and returns GeometryError::NonFiniteCoordinate rather than
an
answer derived from a NaN. In that error, coord_index is the position of the offending
coordinate
among the function’s coordinate arguments, counting from 0, and axis is 0 for x
and 1
for y. Location is geometres::topology::label::Location.
locate
pub fn locate(p: Coord2d, polygon: &Polygon) -> Result<Location,
GeometryError>
The exact location of p relative to polygon: interior, boundary (on an edge of
any ring, vertices included) or exterior. It is the same function the DE-9IM matrix uses for a point
against
a polygon: an exact on-edge test over every ring, then an exact crossing-number test over the exterior and
each hole.
Errors: GeometryError::NonFiniteCoordinate if p has a
non-finite component (position 0).
use geometres::GeometryError;
use geometres::exact::locate;
use geometres::topology::label::Location;
use geometres::types::{Coord2d, CoordSeq, LinearRing, Polygon};
let ring = |pts: &[(f64, f64)]| {
LinearRing::new(CoordSeq::new(pts.iter().map(|&(x, y)| Coord2d::new(x, y)).collect()))
.unwrap()
};
let poly = Polygon::new(
ring(&[(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (0.0, 4.0)]),
vec![ring(&[(1.0, 1.0), (1.0, 3.0), (3.0, 3.0), (3.0, 1.0)])],
).unwrap();
assert_eq!(locate(Coord2d::new(0.5, 2.0), &poly), Ok(Location::Interior));
assert_eq!(locate(Coord2d::new(4.0, 4.0), &poly), Ok(Location::Boundary)); // a vertex
assert_eq!(locate(Coord2d::new(3.0, 2.0), &poly), Ok(Location::Boundary)); // a hole edge
assert_eq!(locate(Coord2d::new(2.0, 2.0), &poly), Ok(Location::Exterior)); // inside the hole
// One ulp left of the hole's edge x = 3 is still interior to the hole.
let just_left = f64::from_bits(3.0f64.to_bits() - 1);
assert_eq!(locate(Coord2d::new(just_left, 2.0), &poly), Ok(Location::Exterior));
assert_eq!(
locate(Coord2d::new(f64::NAN, 0.0), &poly),
Err(GeometryError::NonFiniteCoordinate { coord_index: 0, axis: 0 })
);
Areal
pub struct Areal<'a>
pub fn new<P: Polygonal>(operand: &'a P) -> Self
One polygon, or the parts of a valid multipolygon, as one areal operand. new takes the
sealed
Polygonal trait rather than a slice of parts. Every exact classification over an
Areal relies on its parts meeting at most at finitely many points, and only a
Polygon or a MultiPolygon that passed its constructor guarantees that. An
arbitrary
slice of polygons could overlap, and the classifications would then answer for a region that does not
exist.
use geometres::exact::{Areal, locate_in_areal};
use geometres::topology::label::Location;
use geometres::types::{Coord2d, CoordSeq, LinearRing, MultiPolygon, Polygon};
let ring = LinearRing::new(CoordSeq::new(vec![
Coord2d::new(0.0, 0.0), Coord2d::new(1.0, 0.0),
Coord2d::new(1.0, 1.0), Coord2d::new(0.0, 1.0),
])).unwrap();
let square = Polygon::new_simple(ring).unwrap();
let one_part = MultiPolygon::new(vec![square.clone()]).unwrap();
// A polygon and a one-part multipolygon describe the same region.
let p = Coord2d::new(1.0, 0.5);
assert_eq!(locate_in_areal(p, &Areal::new(&square)), Ok(Location::Boundary));
assert_eq!(locate_in_areal(p, &Areal::new(&one_part)), Ok(Location::Boundary));
locate_in_areal
pub fn locate_in_areal(p: Coord2d, area: &Areal<'_>) ->
Result<Location, GeometryError>
The exact location of p relative to an areal operand: interior, boundary or exterior.
The boundary is topological: a point on the boundary of any part is on the boundary,
including a point where parts touch.
Errors: GeometryError::NonFiniteCoordinate if p has a
non-finite component (position 0).
use geometres::exact::{Areal, locate_in_areal};
use geometres::topology::label::Location;
use geometres::types::{Coord2d, CoordSeq, LinearRing, MultiPolygon, Polygon};
let square = |x: f64, y: f64| {
let ring = LinearRing::new(CoordSeq::new(vec![
Coord2d::new(x, y), Coord2d::new(x + 1.0, y),
Coord2d::new(x + 1.0, y + 1.0), Coord2d::new(x, y + 1.0),
])).unwrap();
Polygon::new_simple(ring).unwrap()
};
// Two unit squares that touch only at the corner (1, 1).
let mp = MultiPolygon::new(vec![square(0.0, 0.0), square(1.0, 1.0)]).unwrap();
let area = Areal::new(&mp);
assert_eq!(locate_in_areal(Coord2d::new(0.5, 0.5), &area), Ok(Location::Interior));
assert_eq!(locate_in_areal(Coord2d::new(1.5, 1.5), &area), Ok(Location::Interior));
// Where the parts touch, the point is on the boundary, not the interior.
assert_eq!(locate_in_areal(Coord2d::new(1.0, 1.0), &area), Ok(Location::Boundary));
assert_eq!(locate_in_areal(Coord2d::new(1.5, 0.5), &area), Ok(Location::Exterior));
on_segment
pub fn on_segment(p: Coord2d, a: Coord2d, b: Coord2d) -> Result<bool,
GeometryError>
Whether p lies on the closed segment [a, b], endpoints included.
The
test is exact: a bounding-box test on stored coordinates, then orient2d(a, b, p) = 0. A
degenerate segment (a == b) contains exactly the point a.
Errors: GeometryError::NonFiniteCoordinate if any of p,
a, b has a non-finite component (positions 0, 1, 2).
use geometres::GeometryError;
use geometres::exact::on_segment;
use geometres::types::Coord2d;
let (a, b) = (Coord2d::new(0.0, 0.0), Coord2d::new(4.0, 0.0));
assert_eq!(on_segment(Coord2d::new(2.0, 0.0), a, b), Ok(true));
assert_eq!(on_segment(Coord2d::new(4.0, 0.0), a, b), Ok(true)); // endpoint
assert_eq!(on_segment(Coord2d::new(5.0, 0.0), a, b), Ok(false)); // collinear, beyond b
// The smallest step off the diagonal y = x is detected exactly.
let (o, d) = (Coord2d::new(0.0, 0.0), Coord2d::new(1.0, 1.0));
let up = f64::from_bits(0.5f64.to_bits() + 1);
assert_eq!(on_segment(Coord2d::new(0.5, 0.5), o, d), Ok(true));
assert_eq!(on_segment(Coord2d::new(0.5, up), o, d), Ok(false));
// A degenerate segment contains exactly its one point.
assert_eq!(on_segment(a, a, a), Ok(true));
assert_eq!(
on_segment(Coord2d::new(2.0, 0.0), a, Coord2d::new(4.0, f64::INFINITY)),
Err(GeometryError::NonFiniteCoordinate { coord_index: 2, axis: 1 })
);
first_self_contact
pub fn first_self_contact(ring: &LinearRing) -> Option<(usize,
usize)>
The first pair of edges of ring that touch anywhere other than at the vertex two consecutive
edges share, by edge index, or None if the ring is simple in the OGC sense. Edge i
runs
from vertex i to vertex i + 1, the last edge closing the ring, and pairs are found in order
of
the first edge.
The absence of proper crossings alone is not simplicity. A crossing, a pinch (the ring
passing through one point twice), a vertex on a non-adjacent edge and a fold-back of consecutive edges are
all contacts. Every test is orient2d on the ring’s stored coordinates or a comparison
of
them, in O(n²) for n vertices. The ring is validated, so its coordinates are
finite
and the answer is always defined.
use geometres::exact::first_self_contact;
use geometres::types::{Coord2d, CoordSeq, LinearRing};
let ring = |pts: &[(f64, f64)]| {
LinearRing::new(CoordSeq::new(pts.iter().map(|&(x, y)| Coord2d::new(x, y)).collect()))
.unwrap()
};
let square = ring(&[(0.0, 0.0), (2.0, 0.0), (2.0, 2.0), (0.0, 2.0)]);
assert_eq!(first_self_contact(&square), None);
// A bowtie: edge 0, (0, 0) -> (2, 2), crosses edge 2, (2, 0) -> (0, 2).
let bowtie = ring(&[(0.0, 0.0), (2.0, 2.0), (2.0, 0.0), (0.0, 2.0)]);
assert_eq!(first_self_contact(&bowtie), Some((0, 2)));
// No two edges cross properly, but vertex 3, (2, 0), lies inside edge 0,
// (0, 0) -> (4, 0). Edge 2, (4, 4) -> (2, 0), ends there: a contact.
let touch = ring(&[(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (2.0, 0.0), (0.0, 4.0)]);
assert_eq!(first_self_contact(&touch), Some((0, 2)));
place_ring
pub fn place_ring(inner: &LinearRing, outer: &LinearRing) ->
RingPlacement
Classifies inner against outer, exactly, for every way two simple rings can
meet.
A proper crossing decides Crossing outright. Otherwise every edge of inner is
cut
at each vertex of outer lying strictly inside it, and each sub-edge is classified on its own
as
inside, outside or along outer’s boundary. The answer is SharedEdge if any
sub-edge lies along the boundary, and otherwise Inside, Outside or
Crossing as the sub-edges are all inside, all outside, or mixed.
One vertex does not decide the placement. inner can pass from one side to
the
other through a vertex, either its own vertex on outer’s boundary or
outer’s vertex on its edge, and neither is a proper crossing. Every decision is
orient2d on stored coordinates or a comparison of them, and no point is constructed. The cost
is O(n·m). The method is given in full on docs.rs.
use geometres::exact::{RingPlacement, place_ring};
use geometres::types::{Coord2d, CoordSeq, LinearRing};
let ring = |pts: &[(f64, f64)]| {
LinearRing::new(CoordSeq::new(pts.iter().map(|&(x, y)| Coord2d::new(x, y)).collect()))
.unwrap()
};
let outer = ring(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)]);
let inside = ring(&[(2.0, 2.0), (4.0, 2.0), (4.0, 4.0), (2.0, 4.0)]);
let overlapping = ring(&[(5.0, 5.0), (15.0, 5.0), (15.0, 15.0), (5.0, 15.0)]);
let surrounding = ring(&[(-5.0, -5.0), (15.0, -5.0), (15.0, 15.0), (-5.0, 15.0)]);
let touching = ring(&[(0.0, 0.0), (3.0, 1.0), (1.0, 3.0)]); // meets outer at (0, 0)
let along = ring(&[(0.0, 2.0), (0.0, 4.0), (3.0, 4.0), (3.0, 2.0)]); // shares part of x = 0
assert_eq!(place_ring(&inside, &outer), RingPlacement::Inside);
assert_eq!(place_ring(&overlapping, &outer), RingPlacement::Crossing);
assert_eq!(place_ring(&surrounding, &outer), RingPlacement::Outside);
assert_eq!(place_ring(&outer, &surrounding), RingPlacement::Inside);
assert_eq!(place_ring(&touching, &outer), RingPlacement::Inside);
assert_eq!(place_ring(&along, &outer), RingPlacement::SharedEdge);
// An L-shaped ring, and a triangle with one vertex inside it and two on the
// notch's edges. No edges cross properly, yet the triangle's third edge runs
// through the notch, outside the L.
let l = ring(&[(0.0, 0.0), (8.0, 0.0), (8.0, 4.0), (4.0, 4.0), (4.0, 8.0), (0.0, 8.0)]);
let tri = ring(&[(3.0, 3.0), (4.0, 6.0), (6.0, 4.0)]);
assert_eq!(place_ring(&tri, &l), RingPlacement::Crossing);
RingPlacement
#[non_exhaustive]
pub enum RingPlacement { Inside, Outside, Crossing, SharedEdge }
Where one simple ring lies relative to another. For two simple closed curves whose boundaries meet in at most finitely many points there are exactly three possibilities; a fourth case is separated out because no valid placement allows it.
| Variant | Meaning |
|---|---|
Inside |
inner’s interior is entirely within the region outer bounds. It
may
touch outer’s boundary at isolated points. |
Outside |
inner’s interior is entirely outside the region outer bounds,
which
includes inner surrounding outer. It may touch at isolated points. |
Crossing |
inner is partly inside and partly outside: an edge properly crosses
outer’s boundary, or inner passes through it at a vertex.
|
SharedEdge |
The boundaries share a stretch of positive length, as two identical rings do. OGC allows rings to touch at points only, so this is never a valid hole placement, hole pair, or pair of disjoint parts. |
segment_events
pub fn segment_events(p: Coord2d, q: Coord2d, area: &Areal<'_>) ->
Result<Vec<SegmentEvent>, GeometryError>
Every event on the segment p → q against area, each with the
location of the open stretch that follows it. The events are the start p, always first; every
vertex of area strictly inside the segment, once each; and every proper crossing of the
segment
with a ring edge, except a crossing that coincides with a listed vertex. The events are distinct points.
A crossing is named by its edge rather than constructed. For the same reason the events
are not ordered along the segment: ordering needs the crossings’ coordinates, which this
crate does not construct. A caller that needs them constructs them exactly. Every location is decided by
orient2d on input coordinates.
Errors: GeometryError::NonFiniteCoordinate if p or
q has a non-finite component (positions 0 and 1).
use geometres::exact::{Areal, EventAt, segment_events};
use geometres::topology::label::Location;
use geometres::types::{Coord2d, CoordSeq, LinearRing, Polygon};
let ring = LinearRing::new(CoordSeq::new(vec![
Coord2d::new(0.0, 0.0), Coord2d::new(4.0, 0.0),
Coord2d::new(4.0, 4.0), Coord2d::new(0.0, 4.0),
])).unwrap();
let square = Polygon::new_simple(ring).unwrap();
let area = Areal::new(&square);
// From inside to outside: the segment crosses the edge (4, 0) -> (4, 4).
let ev = segment_events(Coord2d::new(2.0, 2.0), Coord2d::new(6.0, 2.0), &area).unwrap();
assert_eq!(ev.len(), 2);
assert_eq!(ev[0].at, EventAt::Point(Coord2d::new(2.0, 2.0)));
assert_eq!(ev[0].ahead, Location::Interior);
assert_eq!(ev[1].at, EventAt::Crossing { a: Coord2d::new(4.0, 0.0), b: Coord2d::new(4.0, 4.0) });
assert_eq!(ev[1].ahead, Location::Exterior);
SegmentEvent and EventAt
#[non_exhaustive]
pub struct SegmentEvent { pub at: EventAt, pub ahead: Location }
pub enum EventAt { Point(Coord2d), Crossing { a: Coord2d, b: Coord2d } }
SegmentEvent is one event on a segment and the location of the stretch that follows it.
at is where the event lies, and ahead is the location of the open stretch from
this
event to the next one (or to the segment’s end) in the polygon: interior, boundary or exterior.
EventAt is either a stored input coordinate (Point: the segment’s start,
or
a polygon vertex lying on the segment) or the proper crossing of the segment with the ring edge
a → b (Crossing), with a and b in
ring
order. The two variants are exhaustive, and the enum is deliberately not
#[non_exhaustive]: a point where the location along a segment can change is a stored vertex
or
a proper crossing with one boundary edge. A caller matches both and needs no other arm.
use geometres::exact::{Areal, EventAt, segment_events};
use geometres::topology::label::Location;
use geometres::types::{Coord2d, CoordSeq, LinearRing, Polygon};
let ring = LinearRing::new(CoordSeq::new(vec![
Coord2d::new(0.0, 0.0), Coord2d::new(4.0, 0.0),
Coord2d::new(4.0, 4.0), Coord2d::new(0.0, 4.0),
])).unwrap();
let square = Polygon::new_simple(ring).unwrap();
let area = Areal::new(&square);
// Along the diagonal through two corners: no proper crossing, two vertex events.
let ev = segment_events(Coord2d::new(-1.0, -1.0), Coord2d::new(5.0, 5.0), &area).unwrap();
assert_eq!(ev[0].at, EventAt::Point(Coord2d::new(-1.0, -1.0)));
assert_eq!(ev[0].ahead, Location::Exterior);
let mut vertices = Vec::new();
for e in &ev[1..] {
match e.at {
EventAt::Point(c) => vertices.push((c.x, c.y, e.ahead)),
EventAt::Crossing { .. } => panic!("the diagonal crosses no edge properly"),
}
}
// Not ordered along the segment, so sort before comparing.
vertices.sort_by(|a, b| a.0.total_cmp(&b.0));
assert_eq!(vertices, [(0.0, 0.0, Location::Interior), (4.0, 4.0, Location::Exterior)]);
rings
pub fn rings(poly: &Polygon) -> impl Iterator<Item =
&LinearRing>
Iterates over the exterior ring followed by every hole, in the order that EdgeRef::ring
numbers them.
use geometres::exact::rings;
use geometres::types::{Coord2d, CoordSeq, LinearRing, Polygon};
let ring = |pts: &[(f64, f64)]| {
LinearRing::new(CoordSeq::new(pts.iter().map(|&(x, y)| Coord2d::new(x, y)).collect()))
.unwrap()
};
let poly = Polygon::new(
ring(&[(0.0, 0.0), (4.0, 0.0), (4.0, 4.0), (0.0, 4.0)]),
vec![ring(&[(1.0, 1.0), (1.0, 3.0), (3.0, 3.0), (3.0, 1.0)])],
).unwrap();
let areas: Vec<f64> = rings(&poly).map(|r| r.signed_area()).collect();
assert_eq!(areas, [16.0, -4.0]); // the counterclockwise exterior, then the clockwise hole