layouttk 0.5.0

GDSII and OASIS layout toolkit for layer extraction, verification, and window clipping
Documentation
use crate::geometry::{self as geom, Axis, BooleanOp, Join, Region, Ring};
use crate::{Error, Point, Transform};
use pyo3::prelude::*;

type XY = (i64, i64);
type PyRing = Vec<XY>;
type PyRegion = Vec<PyRing>;

fn point((x, y): XY) -> Point {
    Point { x, y }
}
fn ring(points: PyRing) -> Ring {
    points.into_iter().map(point).collect()
}
fn region(rings: PyRegion) -> Region {
    rings.into_iter().map(ring).collect()
}
fn py_ring(ring: Ring) -> PyRing {
    ring.into_iter().map(|p| (p.x, p.y)).collect()
}
fn py_region(region: Region) -> PyRegion {
    region.into_iter().map(py_ring).collect()
}

/// Apply union/or, intersection/and, difference/not or xor to two sets of
/// contours using nonzero winding. Results contain CCW outlines and CW holes.
#[pyfunction]
fn boolean(
    py: Python<'_>,
    subject: PyRegion,
    clip: PyRegion,
    operation: &str,
) -> PyResult<PyRegion> {
    let op = operation.parse::<BooleanOp>()?;
    Ok(py.detach(|| geom::boolean(&region(subject), &region(clip), op).map(py_region))?)
}

/// Grow or shrink a filled region. Distance and round-join tolerance are in DBU.
#[pyfunction(signature=(polygons, distance, *, join="miter", miter_limit=2.0, tolerance=0.25))]
fn offset(
    py: Python<'_>,
    polygons: PyRegion,
    distance: f64,
    join: &str,
    miter_limit: f64,
    tolerance: f64,
) -> PyResult<PyRegion> {
    let join = match join {
        "miter" => Join::Miter,
        "round" => Join::Round,
        "bevel" => Join::Bevel,
        "square" => Join::Square,
        _ => return Err(Error::invalid("join must be miter, round, bevel or square").into()),
    };
    Ok(py.detach(|| {
        geom::offset(&region(polygons), distance, join, miter_limit, tolerance).map(py_region)
    })?)
}

/// Split along sorted cut positions. Returns one region for each strip, including empty strips.
#[pyfunction(signature=(polygons, positions, axis="x"))]
fn slice(
    py: Python<'_>,
    polygons: PyRegion,
    positions: Vec<i64>,
    axis: &str,
) -> PyResult<Vec<PyRegion>> {
    let axis = match axis {
        "x" => Axis::X,
        "y" => Axis::Y,
        _ => return Err(Error::invalid("axis must be x or y").into()),
    };
    Ok(py.detach(|| {
        geom::slice(&region(polygons), &positions, axis)
            .map(|bins| bins.into_iter().map(py_region).collect())
    })?)
}

/// Test points against a region. Both outer and hole boundaries follow include_boundary.
#[pyfunction(signature=(points, polygons, *, include_boundary=true))]
fn inside(
    py: Python<'_>,
    points: PyRing,
    polygons: PyRegion,
    include_boundary: bool,
) -> PyResult<Vec<bool>> {
    Ok(py.detach(|| geom::inside(&ring(points), &region(polygons), include_boundary))?)
}

/// Return hole-free polygons bounded by max_points. Each can be passed to Layout.add_polygon.
#[pyfunction(signature=(polygons, max_points=199))]
fn fracture(py: Python<'_>, polygons: PyRegion, max_points: usize) -> PyResult<PyRegion> {
    Ok(py.detach(|| geom::fracture(&region(polygons), max_points).map(py_region))?)
}

/// Reflect, magnify and rotate around origin, then translate. Rotation is counterclockwise in degrees.
#[pyfunction(signature=(points, *, origin=(0,0), translation=(0,0), angle_deg=0.0, magnification=1.0, reflect_x=false))]
fn transform_points(
    py: Python<'_>,
    points: PyRing,
    origin: XY,
    translation: XY,
    angle_deg: f64,
    magnification: f64,
    reflect_x: bool,
) -> PyResult<PyRing> {
    let transform = Transform {
        angle_deg,
        magnification,
        reflect_x,
    };
    Ok(py.detach(|| {
        geom::transform_points(&ring(points), point(origin), point(translation), transform)
            .map(py_ring)
    })?)
}

/// Round one contour's corners with tangent circular arcs. All lengths are in DBU.
#[pyfunction(signature=(points, radius, *, tolerance=0.25))]
fn fillet(
    py: Python<'_>,
    points: PyRing,
    radius: &Bound<'_, PyAny>,
    tolerance: f64,
) -> PyResult<PyRing> {
    let radii = if let Ok(scalar) = radius.extract::<f64>() {
        vec![scalar]
    } else {
        radius.extract::<Vec<f64>>()?
    };
    Ok(py.detach(|| geom::fillet_radii(&ring(points), &radii, tolerance).map(py_ring))?)
}

#[pyfunction(signature=(points,sx,sy=None,*,origin=(0,0)))]
fn scale_points(points: PyRing, sx: f64, sy: Option<f64>, origin: XY) -> PyResult<PyRing> {
    Ok(py_ring(geom::scale_points(
        &ring(points),
        point(origin),
        sx,
        sy.unwrap_or(sx),
    )?))
}

#[pyfunction]
fn mirror_points(points: PyRing, a: XY, b: XY) -> PyResult<PyRing> {
    Ok(py_ring(geom::mirror_points(
        &ring(points),
        point(a),
        point(b),
    )?))
}

#[pyfunction(signature=(center,outer,*,inner=None,start_deg=0.0,sweep_deg=360.0,tolerance=None,vertices=None))]
fn elliptic_sector(
    center: XY,
    outer: (f64, f64),
    inner: Option<(f64, f64)>,
    start_deg: f64,
    sweep_deg: f64,
    tolerance: Option<f64>,
    vertices: Option<usize>,
) -> PyResult<PyRegion> {
    let sampling = match (tolerance, vertices) {
        (Some(_), Some(_)) => return Err(Error::invalid("choose vertices or tolerance").into()),
        (_, Some(n)) => geom::Sampling::Vertices(n),
        (tol, None) => geom::Sampling::Tolerance(tol.unwrap_or(0.25)),
    };
    Ok(py_region(geom::elliptic_sector(
        point(center),
        outer,
        inner,
        start_deg,
        sweep_deg,
        sampling,
    )?))
}

/// Construct a counterclockwise rectangle from opposite corners in DBU.
#[pyfunction]
fn rectangle(corner1: XY, corner2: XY) -> PyResult<PyRing> {
    Ok(py_ring(geom::rectangle(point(corner1), point(corner2))?))
}

/// Approximate an ellipse in DBU. Tolerance bounds the chord error before DBU snapping.
#[pyfunction(signature=(center, radius_x, radius_y, *, tolerance=0.25))]
fn ellipse(
    py: Python<'_>,
    center: XY,
    radius_x: f64,
    radius_y: f64,
    tolerance: f64,
) -> PyResult<PyRing> {
    Ok(py.detach(|| geom::ellipse(point(center), radius_x, radius_y, tolerance).map(py_ring))?)
}

/// Construct a regular polygon with the given circumradius and first-vertex angle.
#[pyfunction(signature=(center, radius, sides, *, angle_deg=0.0))]
fn regular_polygon(
    py: Python<'_>,
    center: XY,
    radius: f64,
    sides: usize,
    angle_deg: f64,
) -> PyResult<PyRing> {
    Ok(py.detach(|| geom::regular_polygon(point(center), radius, sides, angle_deg).map(py_ring))?)
}

pub(crate) fn register(m: &Bound<'_, PyModule>) -> PyResult<()> {
    m.add_function(wrap_pyfunction!(boolean, m)?)?;
    m.add_function(wrap_pyfunction!(scale_points, m)?)?;
    m.add_function(wrap_pyfunction!(mirror_points, m)?)?;
    m.add_function(wrap_pyfunction!(elliptic_sector, m)?)?;
    m.add_function(wrap_pyfunction!(offset, m)?)?;
    m.add_function(wrap_pyfunction!(slice, m)?)?;
    m.add_function(wrap_pyfunction!(inside, m)?)?;
    m.add_function(wrap_pyfunction!(fracture, m)?)?;
    m.add_function(wrap_pyfunction!(transform_points, m)?)?;
    m.add_function(wrap_pyfunction!(fillet, m)?)?;
    m.add_function(wrap_pyfunction!(rectangle, m)?)?;
    m.add_function(wrap_pyfunction!(ellipse, m)?)?;
    m.add_function(wrap_pyfunction!(regular_polygon, m)?)?;
    Ok(())
}