1mod boolean;
17mod calibration;
18mod contacts;
19mod curves;
20mod editing;
21mod intersections;
22mod nearest;
23mod nurbs;
24mod polygon;
25#[cfg(test)]
26mod scan_equivalence;
27
28pub use boolean::*;
29pub use calibration::*;
30pub use contacts::*;
31pub use curves::*;
32pub use editing::*;
33pub use intersections::*;
34pub use nearest::*;
35pub use nurbs::*;
36pub use polygon::*;
37use serde::{Deserialize, Serialize};
38
39pub type GeometryResult<T> = Result<T, GeometryError>;
41
42#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
43#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
44#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
45#[cfg_attr(feature = "schemars", schemars(transform = crate::unit_enum_schema))]
48pub enum GeometryReason {
49 NonFiniteNumber,
51 NonPositiveValue,
53 InsufficientPoints,
55 BelowTolerance,
57 InvalidParameterRange,
59 UnsupportedDegree,
61 DegenerateAxes,
63 CoincidentControlPoints,
65 InvalidTopology,
67 HoleOutsideBoundary,
69 IntersectingHoles,
71 SingularTransform,
73 SimilarityRequired,
75 AmbiguousNearestPoint,
77 NearestNotSupported,
79 MeasurementNotSupported,
81 IntersectionNotSupported,
83 AmbiguousIntersection,
85 EditingNotSupported,
87 MiterLimitExceeded,
89 OffsetCollapsed,
91 BooleanAmbiguity,
93 BooleanKernelFailure,
95 QuantizationRangeExceeded,
97 ResourceLimit,
99 NotClosed,
101 ApproximationLimit,
103 IntegrationNotConverged,
105 NumericalErrorBudgetExceeded,
107 CollinearControlPoints,
109 ResidualLimitExceeded,
111}
112
113#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
114#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
115#[serde(rename_all = "camelCase", deny_unknown_fields)]
116pub struct GeometryDiagnostic {
119 pub reason: GeometryReason,
121 pub field: String,
123 pub operation: String,
125 pub message: String,
127}
128impl std::fmt::Display for GeometryDiagnostic {
129 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130 formatter.write_str(&self.message)
131 }
132}
133
134#[derive(Debug, Clone, PartialEq, thiserror::Error, Serialize, Deserialize)]
135#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
136#[serde(
137 tag = "code",
138 content = "details",
139 rename_all = "SCREAMING_SNAKE_CASE",
140 deny_unknown_fields
141)]
142pub enum GeometryError {
145 #[error("Invalid geometry: {0}")]
146 Invalid(GeometryDiagnostic),
148 #[error("Unsupported geometry operation: {0}")]
149 Unsupported(GeometryDiagnostic),
152}
153impl GeometryError {
154 pub fn invalid(
156 reason: GeometryReason,
157 field: &str,
158 operation: &str,
159 message: impl Into<String>,
160 ) -> Self {
161 Self::Invalid(GeometryDiagnostic {
162 reason,
163 field: field.into(),
164 operation: operation.into(),
165 message: message.into(),
166 })
167 }
168 pub fn unsupported(
171 reason: GeometryReason,
172 field: &str,
173 operation: &str,
174 message: impl Into<String>,
175 ) -> Self {
176 Self::Unsupported(GeometryDiagnostic {
177 reason,
178 field: field.into(),
179 operation: operation.into(),
180 message: message.into(),
181 })
182 }
183 pub fn diagnostic(&self) -> &GeometryDiagnostic {
185 match self {
186 Self::Invalid(detail) | Self::Unsupported(detail) => detail,
187 }
188 }
189 pub fn at(mut self, field: &str, operation: &str) -> Self {
192 let detail = match &mut self {
193 Self::Invalid(detail) | Self::Unsupported(detail) => detail,
194 };
195 detail.field = field.into();
196 detail.operation = operation.into();
197 self
198 }
199}
200
201#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
202#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
203#[serde(rename_all = "camelCase", deny_unknown_fields)]
204pub struct GeometryTolerance {
207 pub linear: f64,
209 pub angular: f64,
211 pub area: f64,
214}
215
216impl Default for GeometryTolerance {
217 fn default() -> Self {
218 Self {
219 linear: 1e-8,
220 angular: 1e-10,
221 area: 1e-12,
222 }
223 }
224}
225
226impl GeometryTolerance {
227 pub fn validate(self) -> GeometryResult<()> {
230 for (field, value) in [
231 ("linear", self.linear),
232 ("angular", self.angular),
233 ("area", self.area),
234 ] {
235 positive(value, "Tolerance").map_err(|error| error.at(field, "tolerance.validate"))?;
236 }
237 Ok(())
238 }
239}
240
241#[derive(Debug, Default, Clone, Copy, PartialEq, Serialize, Deserialize)]
242#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
243#[serde(deny_unknown_fields)]
244pub struct Point2 {
247 pub x: f64,
249 pub y: f64,
251}
252
253impl Point2 {
254 pub const fn new(x: f64, y: f64) -> Self {
256 Self { x, y }
257 }
258 pub fn validate(self) -> GeometryResult<()> {
261 finite(self.x).map_err(|error| error.at("x", "point.validate"))?;
262 finite(self.y).map_err(|error| error.at("y", "point.validate"))
263 }
264 pub fn distance(self, other: Self) -> f64 {
266 (self.x - other.x).hypot(self.y - other.y)
267 }
268 pub fn lerp(self, other: Self, t: f64) -> Self {
271 Self::new(
272 self.x + (other.x - self.x) * t,
273 self.y + (other.y - self.y) * t,
274 )
275 }
276 pub fn translated(self, delta: Vector2) -> Self {
279 Self::new(self.x + delta.x, self.y + delta.y)
280 }
281 pub fn vector_to(self, other: Self) -> Vector2 {
283 Vector2 {
284 x: other.x - self.x,
285 y: other.y - self.y,
286 }
287 }
288}
289
290#[derive(Debug, Default, Clone, Copy, PartialEq, Serialize, Deserialize)]
291#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
292#[serde(deny_unknown_fields)]
293pub struct Vector2 {
295 pub x: f64,
297 pub y: f64,
299}
300
301impl Vector2 {
302 pub fn length(self) -> f64 {
305 self.x.hypot(self.y)
306 }
307 pub fn dot(self, other: Self) -> f64 {
309 self.x * other.x + self.y * other.y
310 }
311 pub fn cross(self, other: Self) -> f64 {
314 self.x * other.y - self.y * other.x
315 }
316 pub fn scaled(self, scale: f64) -> Self {
318 Self {
319 x: self.x * scale,
320 y: self.y * scale,
321 }
322 }
323}
324
325#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
326#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
327#[serde(deny_unknown_fields)]
328pub struct Bounds2 {
330 pub min: Point2,
332 pub max: Point2,
334}
335
336impl Bounds2 {
337 pub fn from_points(points: &[Point2]) -> GeometryResult<Self> {
340 let first = *points.first().ok_or_else(|| {
341 GeometryError::invalid(
342 GeometryReason::InsufficientPoints,
343 "points",
344 "bounds",
345 "Empty point set",
346 )
347 })?;
348 first.validate()?;
349 let mut bounds = Self {
350 min: first,
351 max: first,
352 };
353 for p in points {
354 p.validate()?;
355 bounds.min.x = bounds.min.x.min(p.x);
356 bounds.min.y = bounds.min.y.min(p.y);
357 bounds.max.x = bounds.max.x.max(p.x);
358 bounds.max.y = bounds.max.y.max(p.y);
359 }
360 Ok(bounds)
361 }
362 pub fn contains(self, p: Point2) -> bool {
364 p.x >= self.min.x && p.x <= self.max.x && p.y >= self.min.y && p.y <= self.max.y
365 }
366 pub fn intersects(self, other: Self) -> bool {
368 self.min.x <= other.max.x
369 && self.max.x >= other.min.x
370 && self.min.y <= other.max.y
371 && self.max.y >= other.min.y
372 }
373}
374
375#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
376#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
377#[serde(deny_unknown_fields)]
378pub struct Transform2 {
381 pub m11: f64,
383 pub m12: f64,
385 pub m21: f64,
387 pub m22: f64,
389 pub tx: f64,
391 pub ty: f64,
393}
394
395impl Default for Transform2 {
396 fn default() -> Self {
397 Self::identity()
398 }
399}
400impl Transform2 {
401 pub const fn identity() -> Self {
404 Self {
405 m11: 1.,
406 m12: 0.,
407 m21: 0.,
408 m22: 1.,
409 tx: 0.,
410 ty: 0.,
411 }
412 }
413 pub fn translation(x: f64, y: f64) -> Self {
415 Self {
416 tx: x,
417 ty: y,
418 ..Self::identity()
419 }
420 }
421 pub fn scale(x: f64, y: f64) -> Self {
424 Self {
425 m11: x,
426 m22: y,
427 ..Self::identity()
428 }
429 }
430 pub fn rotation(angle: f64) -> Self {
433 let (s, c) = angle.sin_cos();
434 Self {
435 m11: c,
436 m12: -s,
437 m21: s,
438 m22: c,
439 ..Self::identity()
440 }
441 }
442 pub fn apply_point(self, p: Point2) -> Point2 {
445 Point2::new(
446 self.m11 * p.x + self.m12 * p.y + self.tx,
447 self.m21 * p.x + self.m22 * p.y + self.ty,
448 )
449 }
450 pub fn apply_vector(self, v: Vector2) -> Vector2 {
453 Vector2 {
454 x: self.m11 * v.x + self.m12 * v.y,
455 y: self.m21 * v.x + self.m22 * v.y,
456 }
457 }
458 pub fn determinant(self) -> f64 {
461 self.m11 * self.m22 - self.m12 * self.m21
462 }
463 pub fn validate(self) -> GeometryResult<()> {
466 for (field, value) in [
467 ("m11", self.m11),
468 ("m12", self.m12),
469 ("m21", self.m21),
470 ("m22", self.m22),
471 ("tx", self.tx),
472 ("ty", self.ty),
473 ] {
474 finite(value).map_err(|error| error.at(field, "transform.validate"))?;
475 }
476 Ok(())
477 }
478 pub fn inverse(self, tolerance: &GeometryTolerance) -> GeometryResult<Self> {
481 self.validate()?;
482 tolerance.validate()?;
483 let d = self.determinant();
484 let scale = self
485 .m11
486 .abs()
487 .max(self.m12.abs())
488 .max(self.m21.abs())
489 .max(self.m22.abs());
490 if scale == 0. || !d.is_finite() || d.abs() <= f64::EPSILON * scale * scale * 16. {
491 return Err(GeometryError::invalid(
492 GeometryReason::SingularTransform,
493 "transform",
494 "inverse",
495 "Singular or unstable transform",
496 ));
497 }
498 let mut inv = Self {
499 m11: self.m22 / d,
500 m12: -self.m12 / d,
501 m21: -self.m21 / d,
502 m22: self.m11 / d,
503 tx: 0.,
504 ty: 0.,
505 };
506 inv.tx = -(inv.m11 * self.tx + inv.m12 * self.ty);
507 inv.ty = -(inv.m21 * self.tx + inv.m22 * self.ty);
508 inv.validate()?;
509 Ok(inv)
510 }
511 pub fn then(self, next: Self) -> Self {
513 Self {
514 m11: next.m11 * self.m11 + next.m12 * self.m21,
515 m12: next.m11 * self.m12 + next.m12 * self.m22,
516 m21: next.m21 * self.m11 + next.m22 * self.m21,
517 m22: next.m21 * self.m12 + next.m22 * self.m22,
518 tx: next.m11 * self.tx + next.m12 * self.ty + next.tx,
519 ty: next.m21 * self.tx + next.m22 * self.ty + next.ty,
520 }
521 }
522 pub fn similarity_scale(self, t: &GeometryTolerance) -> GeometryResult<f64> {
525 self.validate()?;
526 t.validate()?;
527 let a = Vector2 {
528 x: self.m11,
529 y: self.m21,
530 };
531 let b = Vector2 {
532 x: self.m12,
533 y: self.m22,
534 };
535 let la = a.length();
536 let lb = b.length();
537 positive(la, "Scale")?;
538 positive(lb, "Scale")?;
539 if (la - lb).abs() > t.angular * la.max(lb)
540 || a.scaled(1. / la).dot(b.scaled(1. / lb)).abs() > t.angular
541 {
542 return Err(GeometryError::unsupported(
543 GeometryReason::SimilarityRequired,
544 "transform",
545 "similarity_scale",
546 "This curve requires a similarity transform",
547 ));
548 }
549 Ok(la)
550 }
551}
552
553pub fn finite(value: f64) -> GeometryResult<()> {
555 if value.is_finite() {
556 Ok(())
557 } else {
558 Err(GeometryError::invalid(
559 GeometryReason::NonFiniteNumber,
560 "value",
561 "finite",
562 "Number must be finite",
563 ))
564 }
565}
566pub fn positive(value: f64, label: &str) -> GeometryResult<()> {
569 finite(value)?;
570 if value > 0. {
571 Ok(())
572 } else {
573 Err(GeometryError::invalid(
574 GeometryReason::NonPositiveValue,
575 "value",
576 "positive",
577 format!("{label} must be positive"),
578 ))
579 }
580}
581
582fn missing_geometry() -> GeometryError {
585 GeometryError::invalid(
586 GeometryReason::InvalidTopology,
587 "structure",
588 "geometry.access",
589 "Geometry structure is missing a required element",
590 )
591}
592fn at<T, I: std::slice::SliceIndex<[T]>>(values: &[T], index: I) -> GeometryResult<&I::Output> {
593 values.get(index).ok_or_else(missing_geometry)
594}
595fn at_mut<T, I: std::slice::SliceIndex<[T]>>(
596 values: &mut [T],
597 index: I,
598) -> GeometryResult<&mut I::Output> {
599 values.get_mut(index).ok_or_else(missing_geometry)
600}
601fn last<T>(values: &[T]) -> GeometryResult<&T> {
602 values.last().ok_or_else(missing_geometry)
603}
604
605#[cfg(feature = "schemars")]
609fn unit_enum_schema(schema: &mut schemars::Schema) {
610 let values = schema
611 .get("oneOf")
612 .and_then(|value| value.as_array())
613 .and_then(|variants| {
614 variants
615 .iter()
616 .map(|variant| variant.get("const").cloned())
617 .collect::<Option<Vec<_>>>()
618 });
619 if let Some(values) = values {
620 schema.remove("oneOf");
621 schema.insert("type".into(), "string".into());
622 schema.insert("enum".into(), values.into());
623 }
624}
625
626#[cfg(test)]
627mod checked_access_tests {
628 use super::*;
629
630 #[test]
631 fn missing_internal_elements_return_typed_errors() {
632 let mut values = [1_u8, 2];
633 for error in [
634 at(&values, 2).unwrap_err(),
635 at(&values, 1..3).unwrap_err(),
636 at_mut(&mut values, 2).unwrap_err(),
637 last::<u8>(&[]).unwrap_err(),
638 ] {
639 assert_eq!(error.diagnostic().reason, GeometryReason::InvalidTopology);
640 assert_eq!(error.diagnostic().operation, "geometry.access");
641 }
642 }
643}