layouttk 0.5.0

GDSII and OASIS layout toolkit for layer extraction, verification, and window clipping
Documentation
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
//! Polygon operations on integer database coordinates. A region is a list of
//! implicitly closed contours, filled by the nonzero winding rule. Results have
//! counterclockwise outer boundaries and clockwise holes. Use [`fracture`] to
//! obtain independent filled polygons suitable for [`crate::Layout::add_element`].
//!
//! Clipping and sizing translate coordinates to a local frame with 256 working
//! units per DBU. The combined input extent may span up to 2^41 DBU along each
//! axis anywhere within the i64 domain. Intersections are snapped to integer
//! DBU, with exact half-grid ties going toward positive infinity. Sub-grid
//! slivers may collapse. Curve construction tolerances apply to chord error
//! before rounding vertices to the grid.
mod construction;

use crate::{Error, Point, Result};
use clipper2_rust as cl;
pub use construction::{
    Sampling, ellipse, elliptic_sector, fillet, fillet_radii, mirror_points, rectangle,
    regular_polygon, scale_points, transform_points,
};
use num_bigint::BigInt;
use num_traits::Signed;

pub type Ring = Vec<Point>;
pub type Region = Vec<Ring>;

/// A finer working grid protects one-DBU features from Clipper's tiny triangle
/// removal and improves rounding of intersections. Final points remain in DBU.
const SCALE: i64 = 256;
// Clipper documents decreasing intersection accuracy beyond 10^15. Recenter
// each operation so a tiny shape can still live at any signed 64-bit origin.
const WORK_LIMIT: i64 = 1 << 49;

#[derive(Debug, Copy, Clone)]
pub enum BooleanOp {
    Union,
    Intersection,
    Difference,
    Xor,
}

impl std::str::FromStr for BooleanOp {
    type Err = Error;
    fn from_str(s: &str) -> Result<Self> {
        match s {
            "union" | "or" => Ok(Self::Union),
            "intersection" | "and" => Ok(Self::Intersection),
            "difference" | "not" => Ok(Self::Difference),
            "xor" => Ok(Self::Xor),
            _ => Err(Error::invalid(
                "operation must be union, intersection, difference or xor",
            )),
        }
    }
}

impl From<BooleanOp> for cl::ClipType {
    fn from(value: BooleanOp) -> Self {
        match value {
            BooleanOp::Union => Self::Union,
            BooleanOp::Intersection => Self::Intersection,
            BooleanOp::Difference => Self::Difference,
            BooleanOp::Xor => Self::Xor,
        }
    }
}

#[derive(Debug, Copy, Clone)]
pub enum Join {
    Miter,
    Bevel,
    Square,
    Round,
}

#[derive(Debug, Copy, Clone)]
pub enum Axis {
    X,
    Y,
}

#[derive(Clone, Copy)]
struct Frame {
    center: Point,
    min: Point,
    max: Point,
}

impl Frame {
    fn new<'a>(points: impl Iterator<Item = &'a Point>) -> Result<Self> {
        let mut min = Point {
            x: i64::MAX,
            y: i64::MAX,
        };
        let mut max = Point {
            x: i64::MIN,
            y: i64::MIN,
        };
        for p in points {
            min.x = min.x.min(p.x);
            min.y = min.y.min(p.y);
            max.x = max.x.max(p.x);
            max.y = max.y.max(p.y);
        }
        if min.x > max.x {
            min = Point::default();
            max = min;
        }
        let span = |lo: i64, hi: i64| i128::from(hi) - i128::from(lo);
        if span(min.x, max.x).max(span(min.y, max.y)) > i128::from(WORK_LIMIT / SCALE) {
            return Err(Error::invalid(
                "geometry span exceeds the clipping kernel range (2^41 DBU)",
            ));
        }
        Ok(Self {
            center: Point {
                x: min.x.midpoint(max.x),
                y: min.y.midpoint(max.y),
            },
            min,
            max,
        })
    }

    fn local(self, p: Point) -> cl::Point64 {
        cl::Point64::new((p.x - self.center.x) * SCALE, (p.y - self.center.y) * SCALE)
    }

    fn paths(self, polygons: &[Ring]) -> Result<cl::Paths64> {
        polygons
            .iter()
            .map(|ring| {
                let mut path: cl::Path64 = ring.iter().map(|p| self.local(*p)).collect();
                path.dedup();
                if path.len() > 1 && path.first() == path.last() {
                    path.pop();
                }
                if path.len() < 3 {
                    return Err(Error::invalid(
                        "a contour needs at least three distinct vertices",
                    ));
                }
                Ok(path)
            })
            .collect()
    }

    fn decode(self, paths: cl::Paths64) -> Result<Region> {
        let mut rings = Vec::with_capacity(paths.len());
        for path in paths {
            let mut ring = Vec::with_capacity(path.len());
            for p in path {
                let coordinate = |value: i64, origin: i64| {
                    origin
                        .checked_add((value + SCALE / 2).div_euclid(SCALE))
                        .ok_or_else(|| Error::invalid("geometry result exceeds i64 DBU"))
                };
                ring.push(Point {
                    x: coordinate(p.x, self.center.x)?,
                    y: coordinate(p.y, self.center.y)?,
                });
            }
            ring.dedup();
            if ring.len() > 1 && ring.first() == ring.last() {
                ring.pop();
            }
            if ring.len() >= 3 && signed_twice_area(&ring) != 0 {
                rings.push(ring);
            }
        }
        Ok(rings)
    }
}

// Subtract an origin before multiplying, so large absolute positions do not
// cause loss of precision. Callers use a frame-bounded ring.
fn signed_twice_area(ring: &[Point]) -> i128 {
    let o = ring[0];
    ring[1..]
        .windows(2)
        .map(|p| {
            let delta = |q: Point| {
                (
                    i128::from(q.x) - i128::from(o.x),
                    i128::from(q.y) - i128::from(o.y),
                )
            };
            let (ax, ay) = delta(p[0]);
            let (bx, by) = delta(p[1]);
            ax * by - ay * bx
        })
        .sum()
}

fn engine(subject: &cl::Paths64, clip: &cl::Paths64) -> cl::Clipper64 {
    let mut c = cl::Clipper64::new();
    c.set_preserve_collinear(false);
    c.add_subject(subject);
    c.add_clip(clip);
    c
}

fn clip_paths(subject: &cl::Paths64, clip: &cl::Paths64, op: BooleanOp) -> Result<cl::Paths64> {
    let mut out = Vec::new();
    if !engine(subject, clip).execute(op.into(), cl::FillRule::NonZero, &mut out, None) {
        return Err(Error::invalid("polygon clipping failed"));
    }
    Ok(out)
}

/// Detect a non-degenerate axis-aligned rectangle without invoking the clipping kernel.
pub fn axis_aligned_rect(ring: &[Point]) -> Option<(Point, Point)> {
    let [a, b, c, d] = ring else {
        return None;
    };
    let ortho = (a.x == b.x && b.y == c.y && c.x == d.x && d.y == a.y)
        || (a.y == b.y && b.x == c.x && c.y == d.y && d.x == a.x);
    if !ortho {
        return None;
    }
    let lo = Point {
        x: a.x.min(c.x),
        y: a.y.min(c.y),
    };
    let hi = Point {
        x: a.x.max(c.x),
        y: a.y.max(c.y),
    };
    (lo.x < hi.x && lo.y < hi.y).then_some((lo, hi))
}

/// Normalize a single stored polygon contour to counterclockwise filled rings.
/// Simple rectangles and triangles avoid the clipping kernel entirely.
pub fn normalize_ring(mut ring: Ring) -> Result<Region> {
    if let Some((lo, hi)) = axis_aligned_rect(&ring) {
        return Ok(vec![rectangle(lo, hi)?]);
    }
    if ring.len() == 3 {
        let area2 = signed_twice_area(&ring);
        if area2 == 0 {
            return Ok(Vec::new());
        }
        if area2 < 0 {
            ring.reverse();
        }
        return Ok(vec![ring]);
    }
    boolean(&[ring], &[], BooleanOp::Union)
}

fn cross_sign(dx: i128, dy: i128, rx: i128, ry: i128) -> i8 {
    if let Some(left) = dx.checked_mul(ry)
        && let Some(right) = dy.checked_mul(rx)
        && let Some(diff) = left.checked_sub(right)
    {
        return diff.signum() as i8;
    }
    let diff = BigInt::from(dx) * ry - BigInt::from(dy) * rx;
    if diff.is_positive() {
        1
    } else if diff.is_negative() {
        -1
    } else {
        0
    }
}

/// Exact positive-area intersection test between a contour and an open rectangle.
/// Boundary-only contacts return false; sub-grid positive overlaps return true.
pub fn hits_open_box(ring: &[Point], lower: Point, upper: Point) -> bool {
    if ring.len() < 3 || lower.x >= upper.x || lower.y >= upper.y {
        return false;
    }
    let (mut min_x, mut min_y, mut max_x, mut max_y) = (ring[0].x, ring[0].y, ring[0].x, ring[0].y);
    for p in &ring[1..] {
        min_x = min_x.min(p.x);
        min_y = min_y.min(p.y);
        max_x = max_x.max(p.x);
        max_y = max_y.max(p.y);
    }
    if max_x <= lower.x || min_x >= upper.x || max_y <= lower.y || min_y >= upper.y {
        return false;
    }
    if axis_aligned_rect(ring).is_some() {
        return true;
    }
    let (x0, y0, x1, y1) = (
        i128::from(lower.x),
        i128::from(lower.y),
        i128::from(upper.x),
        i128::from(upper.y),
    );
    let cx2 = x0 + x1;
    let cy2 = y0 + y1;
    let mut winding: i64 = 0;
    let mut prev = ring[ring.len() - 1];
    for &curr in ring {
        let (ax, ay) = (i128::from(prev.x), i128::from(prev.y));
        let (bx, by) = (i128::from(curr.x), i128::from(curr.y));
        let dx = bx - ax;
        let dy = by - ay;
        if ax.max(bx) > x0 && ax.min(bx) < x1 && ay.max(by) > y0 && ay.min(by) < y1 {
            let mut has_neg = false;
            let mut has_pos = false;
            for x in [x0, x1] {
                for y in [y0, y1] {
                    match cross_sign(dx, dy, x - ax, y - ay) {
                        -1 => has_neg = true,
                        1 => has_pos = true,
                        _ => {}
                    }
                }
            }
            if has_neg && has_pos {
                return true;
            }
        }
        let ay2 = 2 * ay;
        let by2 = 2 * by;
        if ay2 <= cy2 && cy2 < by2 {
            if cross_sign(dx, dy, cx2 - 2 * ax, cy2 - ay2) > 0 {
                winding += 1;
            }
        } else if by2 <= cy2 && cy2 < ay2 && cross_sign(dx, dy, cx2 - 2 * ax, cy2 - ay2) < 0 {
            winding -= 1;
        }
        prev = curr;
    }
    winding != 0
}

/// Apply a nonzero-winding set operation and snap intersections to the DBU grid.
pub fn boolean(subject: &[Ring], clip: &[Ring], op: BooleanOp) -> Result<Region> {
    let frame = Frame::new(subject.iter().chain(clip).flatten())?;
    frame.decode(clip_paths(&frame.paths(subject)?, &frame.paths(clip)?, op)?)
}

/// Grow (positive) or shrink (negative) a filled region. Distance and circular
/// join chord tolerance are in DBU. The miter limit is a ratio to the distance.
pub fn offset(
    polygons: &[Ring],
    distance: f64,
    join: Join,
    miter_limit: f64,
    tolerance: f64,
) -> Result<Region> {
    if !distance.is_finite() || !miter_limit.is_finite() || miter_limit < 1.0 {
        return Err(Error::invalid(
            "offset needs a finite distance and finite miter limit >= 1",
        ));
    }
    construction::validate_tolerance(tolerance)?;
    if distance.abs() * miter_limit.max(2.0) * SCALE as f64 > WORK_LIMIT as f64 {
        return Err(Error::invalid("offset exceeds the clipping kernel range"));
    }
    if matches!(join, Join::Round) && distance != 0.0 {
        construction::arc_steps(distance.abs(), std::f64::consts::TAU, tolerance)?;
    }
    let frame = Frame::new(polygons.iter().flatten())?;
    let normalized = clip_paths(&frame.paths(polygons)?, &Vec::new(), BooleanOp::Union)?;
    let jt = match join {
        Join::Miter => cl::JoinType::Miter,
        Join::Round => cl::JoinType::Round,
        Join::Square => cl::JoinType::Square,
        Join::Bevel => cl::JoinType::Bevel,
    };
    frame.decode(cl::inflate_paths_64(
        &normalized,
        distance * SCALE as f64,
        jt,
        cl::EndType::Polygon,
        miter_limit,
        tolerance.min(distance.abs()) * SCALE as f64,
    ))
}

/// Split a region into strips along X or Y. Sorted cut positions may repeat.
/// The result has exactly one more entry than the number of cuts.
pub fn slice(polygons: &[Ring], positions: &[i64], axis: Axis) -> Result<Vec<Region>> {
    if !positions.is_sorted() {
        return Err(Error::invalid("slice positions must be sorted"));
    }
    let frame = Frame::new(polygons.iter().flatten())?;
    let subject = frame.paths(polygons)?;
    let (min, max) = match axis {
        Axis::X => (frame.min.x, frame.max.x),
        Axis::Y => (frame.min.y, frame.max.y),
    };
    let mut low = min;
    let mut bins = Vec::with_capacity(positions.len() + 1);
    for high in positions
        .iter()
        .copied()
        .chain(std::iter::once(max))
        .map(|v| v.clamp(min, max))
    {
        if low == high || frame.min.x == frame.max.x || frame.min.y == frame.max.y {
            bins.push(Vec::new());
        } else {
            let (a, b) = match axis {
                Axis::X => (
                    Point {
                        x: low,
                        y: frame.min.y,
                    },
                    Point {
                        x: high,
                        y: frame.max.y,
                    },
                ),
                Axis::Y => (
                    Point {
                        x: frame.min.x,
                        y: low,
                    },
                    Point {
                        x: frame.max.x,
                        y: high,
                    },
                ),
            };
            let clip = frame.paths(&[rectangle(a, b)?])?;
            bins.push(frame.decode(clip_paths(&subject, &clip, BooleanOp::Intersection)?)?);
        }
        low = high;
    }
    Ok(bins)
}

/// Query a batch of points against the union. Boundary policy applies to both
/// exterior boundaries and hole boundaries.
pub fn inside(points: &[Point], polygons: &[Ring], include_boundary: bool) -> Result<Vec<bool>> {
    let frame = Frame::new(polygons.iter().flatten())?;
    let paths = clip_paths(&frame.paths(polygons)?, &Vec::new(), BooleanOp::Union)?;
    Ok(points
        .iter()
        .map(|p| {
            if p.x < frame.min.x || p.x > frame.max.x || p.y < frame.min.y || p.y > frame.max.y {
                return false;
            }
            let q = frame.local(*p);
            let mut filled = false;
            for path in &paths {
                match cl::point_in_polygon(q, path) {
                    cl::PointInPolygonResult::IsOn => return include_boundary,
                    cl::PointInPolygonResult::IsInside => filled = !filled,
                    cl::PointInPolygonResult::IsOutside => {}
                }
            }
            filled
        })
        .collect())
}

/// Preserve small simple boundaries and triangulate faces with holes or too
/// many vertices. The result consists of independent hole-free filled polygons.
pub fn fracture(polygons: &[Ring], max_points: usize) -> Result<Region> {
    if max_points < 3 {
        return Err(Error::invalid("max_points must be at least 3"));
    }
    let frame = Frame::new(polygons.iter().flatten())?;
    let paths = frame.paths(polygons)?;
    let mut tree = cl::PolyTree64::new();
    if !engine(&paths, &Vec::new()).execute_tree(
        cl::ClipType::Union,
        cl::FillRule::NonZero,
        &mut tree,
        &mut Vec::new(),
    ) {
        return Err(Error::invalid(
            "could not identify polygon faces for fracture",
        ));
    }
    let mut pieces = Vec::new();
    for face in cl::poly_tree_to_faces64(&tree) {
        if face.outer.len() <= max_points && face.holes.is_empty() {
            pieces.push(face.outer);
        } else {
            let mut paths = face.holes;
            paths.insert(0, face.outer);
            let mut triangles = Vec::new();
            let status = cl::triangulate_64(&paths, &mut triangles, false);
            if status != cl::TriangulateResult::Success {
                return Err(Error::invalid(format!(
                    "polygon triangulation failed ({status:?})"
                )));
            }
            pieces.extend(triangles);
        }
    }
    frame.decode(pieces)
}