use super::{
Cell, Placement, Position, as_point, compose, linear, repeat_count, transform_element,
};
use crate::geometry::{self, BooleanOp, Ring};
use crate::{
Array, Element, Error, Layer, Layout, PathEnds, Point, ReadOptions, Repetition, Result,
};
use sha1::{Digest, Sha1};
use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
use std::fs::File;
use std::io::{Read, Seek};
use std::path::Path;
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
pub struct Window {
lower: Point,
upper: Point,
}
impl Window {
pub fn new(lower: Point, upper: Point) -> Result<Self> {
if lower.x >= upper.x || lower.y >= upper.y {
return Err(Error::invalid("window needs x0 < x1 and y0 < y1"));
}
Ok(Self { lower, upper })
}
pub fn corners(self) -> (Point, Point) {
(self.lower, self.upper)
}
fn bounds(ring: &Ring) -> Option<Self> {
let first = *ring.first()?;
let mut bounds = Self {
lower: first,
upper: first,
};
for &p in &ring[1..] {
bounds.lower.x = bounds.lower.x.min(p.x);
bounds.lower.y = bounds.lower.y.min(p.y);
bounds.upper.x = bounds.upper.x.max(p.x);
bounds.upper.y = bounds.upper.y.max(p.y);
}
Some(bounds)
}
fn intersection(self, other: Self) -> Option<Self> {
Self::new(
Point {
x: self.lower.x.max(other.lower.x),
y: self.lower.y.max(other.lower.y),
},
Point {
x: self.upper.x.min(other.upper.x),
y: self.upper.y.min(other.upper.y),
},
)
.ok()
}
fn contains(self, other: Self) -> bool {
self.lower.x <= other.lower.x
&& self.lower.y <= other.lower.y
&& self.upper.x >= other.upper.x
&& self.upper.y >= other.upper.y
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Aabb {
min_x: i128,
min_y: i128,
max_x: i128,
max_y: i128,
}
impl Aabb {
fn point(x: i128, y: i128) -> Self {
Self {
min_x: x,
min_y: y,
max_x: x,
max_y: y,
}
}
fn union(self, other: Self) -> Self {
Self {
min_x: self.min_x.min(other.min_x),
min_y: self.min_y.min(other.min_y),
max_x: self.max_x.max(other.max_x),
max_y: self.max_y.max(other.max_y),
}
}
fn include_option(slot: &mut Option<Self>, next: Self) {
*slot = Some(match *slot {
Some(existing) => existing.union(next),
None => next,
});
}
fn pad(self, margin: i128) -> Self {
Self {
min_x: self.min_x - margin,
min_y: self.min_y - margin,
max_x: self.max_x + margin,
max_y: self.max_y + margin,
}
}
fn overlaps_window(self, w: Window) -> bool {
self.min_x < i128::from(w.upper.x)
&& self.max_x > i128::from(w.lower.x)
&& self.min_y < i128::from(w.upper.y)
&& self.max_y > i128::from(w.lower.y)
}
fn overlaps_any(self, windows: &[Window]) -> bool {
windows.iter().any(|&w| self.overlaps_window(w))
}
fn inside_window(self, w: Window) -> bool {
self.min_x >= i128::from(w.lower.x)
&& self.max_x <= i128::from(w.upper.x)
&& self.min_y >= i128::from(w.lower.y)
&& self.max_y <= i128::from(w.upper.y)
}
fn transform(self, placement: Placement) -> Result<Self> {
let mut out = None;
for x in [self.min_x, self.max_x] {
for y in [self.min_y, self.max_y] {
let mapped = placement.map(Position::Grid(x, y))?;
match mapped {
Position::Grid(mx, my) => Self::include_option(&mut out, Self::point(mx, my)),
Position::Real(_, _) => {
let (rx, ry) = mapped.real()?;
let lo = Self::point((rx.floor() as i128) - 1, (ry.floor() as i128) - 1);
let hi = Self::point((rx.ceil() as i128) + 1, (ry.ceil() as i128) + 1);
Self::include_option(&mut out, lo.union(hi));
}
}
}
}
Ok(out.expect("four corners"))
}
fn expand_local_repetition(self, rep: &Repetition) -> Self {
match rep {
Repetition::Regular(a) => {
let dx = i128::from(a.column_step.x) * i128::from(a.columns - 1);
let dy = i128::from(a.column_step.y) * i128::from(a.columns - 1);
let ex = i128::from(a.row_step.x) * i128::from(a.rows - 1);
let ey = i128::from(a.row_step.y) * i128::from(a.rows - 1);
Self {
min_x: self.min_x + dx.min(0) + ex.min(0),
min_y: self.min_y + dy.min(0) + ey.min(0),
max_x: self.max_x + dx.max(0) + ex.max(0),
max_y: self.max_y + dy.max(0) + ey.max(0),
}
}
Repetition::Offsets(offsets) => {
let (mut lx, mut hx, mut ly, mut hy) = (0i128, 0i128, 0i128, 0i128);
for p in offsets {
lx = lx.min(i128::from(p.x));
hx = hx.max(i128::from(p.x));
ly = ly.min(i128::from(p.y));
hy = hy.max(i128::from(p.y));
}
Self {
min_x: self.min_x + lx,
min_y: self.min_y + ly,
max_x: self.max_x + hx,
max_y: self.max_y + hy,
}
}
}
}
}
fn path_pad(width: i64, ends: PathEnds) -> i128 {
let ext = match ends {
PathEnds::Flush => 0,
PathEnds::Round | PathEnds::HalfWidth => (i128::from(width) + 1) / 2,
PathEnds::Explicit { begin, end } => {
i128::from(begin.unsigned_abs().max(end.unsigned_abs()))
}
};
i128::from(width) * 2 + ext + 2
}
fn shape_bounds_and_abs_pad(e: &Element) -> (Option<Aabb>, i128) {
match e.unadorned() {
Element::Polygon { points, .. } => {
let Some(first) = points.first() else {
return (None, 0);
};
let mut bb = Aabb::point(i128::from(first.x), i128::from(first.y));
for p in &points[1..] {
bb = bb.union(Aabb::point(i128::from(p.x), i128::from(p.y)));
}
(Some(bb), 0)
}
Element::Circle { center, radius, .. } => {
if *radius == 0 {
return (None, 0);
}
let (cx, cy, r) = (
i128::from(center.x),
i128::from(center.y),
i128::from(*radius),
);
(
Some(Aabb {
min_x: cx - r,
min_y: cy - r,
max_x: cx + r,
max_y: cy + r,
}),
0,
)
}
Element::Path { points, width, .. } => {
if *width <= 0 || points.len() < 2 {
return (None, 0);
}
let mut bb = Aabb::point(i128::from(points[0].x), i128::from(points[0].y));
for p in &points[1..] {
bb = bb.union(Aabb::point(i128::from(p.x), i128::from(p.y)));
}
(Some(bb.pad(path_pad(*width, PathEnds::Flush))), 0)
}
Element::ExtendedPath {
points,
width,
absolute_width,
ends,
..
} => {
if *width <= 0 || points.len() < 2 {
return (None, 0);
}
let mut bb = Aabb::point(i128::from(points[0].x), i128::from(points[0].y));
for p in &points[1..] {
bb = bb.union(Aabb::point(i128::from(p.x), i128::from(p.y)));
}
let pad = path_pad(*width, *ends);
(Some(bb.pad(pad)), if *absolute_width { pad } else { 0 })
}
Element::Repeated { element, array } => {
let (bb, abs_pad) = shape_bounds_and_abs_pad(element);
(bb.map(|b| b.expand_local_repetition(array)), abs_pad)
}
Element::Text { .. } | Element::Reference { .. } | Element::Attributed { .. } => (None, 0),
}
}
fn material(e: &Element) -> bool {
match e.unadorned() {
Element::Repeated { element, .. } => material(element),
Element::Reference { .. } | Element::Text { .. } => false,
_ => true,
}
}
fn compute_cell_bounds(
graph: &Layout,
local_bounds: &[Option<Aabb>],
local_abs_pad: &[i128],
) -> Result<(Vec<Option<Aabb>>, Vec<i128>)> {
let n = graph.cells.len();
let index: HashMap<_, _> = graph
.cells
.iter()
.enumerate()
.map(|(i, c)| (c.name.as_str(), i))
.collect();
let mut parents = vec![Vec::new(); n];
let mut pending_children = vec![0usize; n];
for (ci, cell) in graph.cells.iter().enumerate() {
for e in &cell.elements {
if let Element::Reference { cell: target, .. } = e.unadorned()
&& let Some(&ti) = index.get(target.as_str())
{
parents[ti].push(ci);
pending_children[ci] += 1;
}
}
}
let mut queue: VecDeque<_> = (0..n).filter(|&i| pending_children[i] == 0).collect();
let mut bounds = local_bounds.to_vec();
let mut abs_pad = local_abs_pad.to_vec();
while let Some(ci) = queue.pop_front() {
let mut cell_bb = bounds[ci];
let mut cell_pad = abs_pad[ci];
for e in &graph.cells[ci].elements {
if let Element::Reference {
cell: target,
origin,
transform,
array,
} = e.unadorned()
&& let Some(&ti) = index.get(target.as_str())
&& let Some(child_bb) = bounds[ti]
{
let mut placed = child_bb.transform(Placement {
origin: Position::point(*origin),
transform: *transform,
})?;
if abs_pad[ti] > 0 && transform.magnification < 1.0 {
placed = placed.pad(abs_pad[ti]);
}
if let Some(rep) = array {
placed = placed.expand_local_repetition(rep);
}
Aabb::include_option(&mut cell_bb, placed);
cell_pad = cell_pad.max(abs_pad[ti]);
}
}
bounds[ci] = cell_bb;
abs_pad[ci] = cell_pad;
for &parent in &parents[ci] {
pending_children[parent] -= 1;
if pending_children[parent] == 0 {
queue.push_back(parent);
}
}
}
Ok((bounds, abs_pad))
}
fn offset_in_root(parent: Placement, origin: Point, dx: i128, dy: i128) -> Result<Position> {
parent.map(Position::Grid(
i128::from(origin.x) + dx,
i128::from(origin.y) + dy,
))
}
#[allow(clippy::too_many_arguments)]
fn regular_block_hull(
zero_bb: Aabb,
origin: Point,
parent: Placement,
array: &Array,
c0: u32,
c1: u32,
r0: u32,
r1: u32,
) -> Result<Aabb> {
let mut out = None;
let cols = if c0 == c1 { [c0, c0] } else { [c0, c1] };
let rows = if r0 == r1 { [r0, r0] } else { [r0, r1] };
let col_slice = if c0 == c1 { &cols[..1] } else { &cols[..] };
let row_slice = if r0 == r1 { &rows[..1] } else { &rows[..] };
for &c in col_slice {
for &r in row_slice {
let dx = i128::from(c) * i128::from(array.column_step.x)
+ i128::from(r) * i128::from(array.row_step.x);
let dy = i128::from(c) * i128::from(array.column_step.y)
+ i128::from(r) * i128::from(array.row_step.y);
let pos = offset_in_root(parent, origin, dx, dy)?;
let shifted = match pos {
Position::Grid(ox, oy) => Aabb {
min_x: zero_bb.min_x + ox,
min_y: zero_bb.min_y + oy,
max_x: zero_bb.max_x + ox,
max_y: zero_bb.max_y + oy,
},
Position::Real(_, _) => {
let (rx, ry) = pos.real()?;
Aabb {
min_x: zero_bb.min_x + (rx.floor() as i128) - 1,
min_y: zero_bb.min_y + (ry.floor() as i128) - 1,
max_x: zero_bb.max_x + (rx.ceil() as i128) + 1,
max_y: zero_bb.max_y + (ry.ceil() as i128) + 1,
}
}
};
Aabb::include_option(&mut out, shifted);
}
}
Ok(out.expect("nonempty block"))
}
fn exact_grid_point(pos: Position) -> Result<Option<Point>> {
match pos {
Position::Grid(x, y) => Ok(Some(as_point(x, y)?)),
Position::Real(_, _) => {
let (rx, ry) = pos.real()?;
if rx.fract() == 0.0 && ry.fract() == 0.0 {
Ok(Some(as_point(rx as i128, ry as i128)?))
} else {
Ok(None)
}
}
}
}
#[allow(clippy::too_many_arguments)]
fn prune_repetition_instances(
zero_bb: Aabb,
origin: Point,
parent: Placement,
rep: Option<&Repetition>,
windows: &[Window],
remaining: &mut usize,
work_remaining: &mut usize,
limit_message: &str,
) -> Result<Vec<Position>> {
let mut found = Vec::new();
let Some(rep) = rep else {
let pos = offset_in_root(parent, origin, 0, 0)?;
let hull = match pos {
Position::Grid(ox, oy) => Aabb {
min_x: zero_bb.min_x + ox,
min_y: zero_bb.min_y + oy,
max_x: zero_bb.max_x + ox,
max_y: zero_bb.max_y + oy,
},
Position::Real(_, _) => {
let (rx, ry) = pos.real()?;
Aabb {
min_x: zero_bb.min_x + (rx.floor() as i128) - 1,
min_y: zero_bb.min_y + (ry.floor() as i128) - 1,
max_x: zero_bb.max_x + (rx.ceil() as i128) + 1,
max_y: zero_bb.max_y + (ry.ceil() as i128) + 1,
}
}
};
if hull.overlaps_any(windows) {
if *remaining == 0 {
return Err(Error::invalid(limit_message));
}
*remaining -= 1;
found.push(pos);
}
return Ok(found);
};
match rep {
Repetition::Offsets(offsets) => {
for i in 0..repeat_count(Some(rep)) {
if *work_remaining == 0 {
return Err(Error::invalid(
"window candidate search exceeded its work limit",
));
}
*work_remaining -= 1;
let (dx, dy) = if i == 0 {
(0, 0)
} else {
let p = offsets[(i - 1) as usize];
(i128::from(p.x), i128::from(p.y))
};
let pos = offset_in_root(parent, origin, dx, dy)?;
let hull = match pos {
Position::Grid(ox, oy) => Aabb {
min_x: zero_bb.min_x + ox,
min_y: zero_bb.min_y + oy,
max_x: zero_bb.max_x + ox,
max_y: zero_bb.max_y + oy,
},
Position::Real(_, _) => {
let (rx, ry) = pos.real()?;
Aabb {
min_x: zero_bb.min_x + (rx.floor() as i128) - 1,
min_y: zero_bb.min_y + (ry.floor() as i128) - 1,
max_x: zero_bb.max_x + (rx.ceil() as i128) + 1,
max_y: zero_bb.max_y + (ry.ceil() as i128) + 1,
}
}
};
if hull.overlaps_any(windows) {
if *remaining == 0 {
return Err(Error::invalid(limit_message));
}
*remaining -= 1;
found.push(pos);
}
}
}
Repetition::Regular(array) => {
let mut stack = vec![(0u32, array.columns - 1, 0u32, array.rows - 1)];
while let Some((c0, c1, r0, r1)) = stack.pop() {
if *work_remaining == 0 {
return Err(Error::invalid(
"window candidate search exceeded its work limit",
));
}
*work_remaining -= 1;
let hull = regular_block_hull(zero_bb, origin, parent, array, c0, c1, r0, r1)?;
if !hull.overlaps_any(windows) {
continue;
}
if c0 == c1 && r0 == r1 {
if *remaining == 0 {
return Err(Error::invalid(limit_message));
}
*remaining -= 1;
let dx = i128::from(c0) * i128::from(array.column_step.x)
+ i128::from(r0) * i128::from(array.row_step.x);
let dy = i128::from(c0) * i128::from(array.column_step.y)
+ i128::from(r0) * i128::from(array.row_step.y);
found.push(offset_in_root(parent, origin, dx, dy)?);
} else {
let dc = c1 - c0;
let dr = r1 - r0;
let col_span = i128::from(dc)
* i128::from(array.column_step.x)
.abs()
.max(i128::from(array.column_step.y).abs());
let row_span = i128::from(dr)
* i128::from(array.row_step.x)
.abs()
.max(i128::from(array.row_step.y).abs());
if dc > 0 && (dr == 0 || col_span >= row_span) {
let mid = c0 + dc / 2;
stack.push((mid + 1, c1, r0, r1));
stack.push((c0, mid, r0, r1));
} else {
let mid = r0 + dr / 2;
stack.push((c0, c1, mid + 1, r1));
stack.push((c0, c1, r0, mid));
}
}
}
}
}
Ok(found)
}
pub struct ClipOptions<'a> {
pub read: ReadOptions<'a>,
pub placement_limit: usize,
pub output_vertex_limit: usize,
pub tolerance_dbu: f64,
pub keep_hierarchy: bool,
}
impl Default for ClipOptions<'_> {
fn default() -> Self {
Self {
read: ReadOptions::default(),
placement_limit: super::DEFAULT_EXPANSION_LIMIT,
output_vertex_limit: 4_000_000,
tolerance_dbu: 0.25,
keep_hierarchy: false,
}
}
}
struct HashedInput<'a> {
file: &'a mut File,
hash: &'a mut Sha1,
}
impl Read for HashedInput<'_> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
let n = self.file.read(buf)?;
self.hash.update(&buf[..n]);
Ok(n)
}
}
fn flat_placements(
graph: &Layout,
top: &str,
local_bounds: &[Option<Aabb>],
cell_bounds: &[Option<Aabb>],
cell_abs_pad: &[i128],
windows: &[Window],
limit: usize,
) -> Result<Vec<Vec<Placement>>> {
let index: HashMap<_, _> = graph
.cells
.iter()
.enumerate()
.map(|(i, c)| (c.name.as_str(), i))
.collect();
let root = *index
.get(top)
.ok_or_else(|| Error::invalid(format!("unknown top cell {top:?}")))?;
let mut result = vec![Vec::new(); graph.cells.len()];
let Some(root_bb) = cell_bounds[root] else {
return Ok(result);
};
if !root_bb.overlaps_any(windows) {
return Ok(result);
}
let mut stack = vec![(root, Placement::identity())];
let mut remaining = limit - 1;
let mut work_remaining = limit.saturating_add(1).saturating_mul(128);
let limit_msg = format!("clip placement expansion exceeds limit {limit}");
while let Some((cell, placement)) = stack.pop() {
if let Some(local_bb) = local_bounds[cell] {
let placed_local = local_bb.transform(placement)?;
if placed_local.overlaps_any(windows) {
result[cell].push(placement);
}
}
for e in &graph.cells[cell].elements {
if let Element::Reference {
cell: target_name,
origin,
transform,
array,
} = e.unadorned()
{
let target = index[target_name.as_str()];
let Some(child_bb) = cell_bounds[target] else {
continue;
};
let composed = compose(placement.transform, *transform)?;
let mut zero_bb = child_bb.transform(Placement {
origin: Position::zero(),
transform: composed,
})?;
if cell_abs_pad[target] > 0 && composed.magnification < 1.0 {
zero_bb = zero_bb.pad(cell_abs_pad[target]);
}
let origins = prune_repetition_instances(
zero_bb,
*origin,
placement,
array.as_ref(),
windows,
&mut remaining,
&mut work_remaining,
&limit_msg,
)?;
for inst_origin in origins {
stack.push((
target,
Placement {
origin: inst_origin,
transform: composed,
},
));
}
}
}
}
Ok(result)
}
type KeptRef = (usize, Point, crate::Transform, Option<Repetition>);
struct HierarchicalPlan {
straddling: Vec<Vec<(Placement, usize)>>,
kept_refs: Vec<Vec<KeptRef>>,
retain_full: Vec<bool>,
}
fn mark_retain_closure(
start: usize,
graph: &Layout,
index: &HashMap<&str, usize>,
retain_full: &mut [bool],
) {
let mut todo = vec![start];
while let Some(ci) = todo.pop() {
if retain_full[ci] {
continue;
}
retain_full[ci] = true;
for e in &graph.cells[ci].elements {
if let Element::Reference { cell, .. } = e.unadorned()
&& let Some(&ti) = index.get(cell.as_str())
&& !retain_full[ti]
{
todo.push(ti);
}
}
}
}
fn hierarchical_plan(
graph: &Layout,
top: &str,
local_bounds: &[Option<Aabb>],
cell_bounds: &[Option<Aabb>],
cell_abs_pad: &[i128],
windows: &[Window],
limit: usize,
) -> Result<HierarchicalPlan> {
let index: HashMap<_, _> = graph
.cells
.iter()
.enumerate()
.map(|(i, c)| (c.name.as_str(), i))
.collect();
let root = *index
.get(top)
.ok_or_else(|| Error::invalid(format!("unknown top cell {top:?}")))?;
let mut straddling = vec![Vec::new(); graph.cells.len()];
let mut kept_refs = vec![Vec::new(); windows.len()];
let mut retain_full = vec![false; graph.cells.len()];
let Some(root_bb) = cell_bounds[root] else {
return Ok(HierarchicalPlan {
straddling,
kept_refs,
retain_full,
});
};
let mut remaining = limit;
let mut work_remaining = limit.saturating_add(1).saturating_mul(128);
let limit_msg = format!("clip placement expansion exceeds limit {limit}");
for (w_idx, &window) in windows.iter().enumerate() {
if !root_bb.overlaps_window(window) {
continue;
}
if remaining == 0 {
return Err(Error::invalid(&limit_msg));
}
remaining -= 1;
let mut stack = vec![(root, Placement::identity())];
while let Some((cell, placement)) = stack.pop() {
if let Some(local_bb) = local_bounds[cell] {
let placed_local = local_bb.transform(placement)?;
if placed_local.overlaps_window(window) {
straddling[cell].push((placement, w_idx));
}
}
for e in &graph.cells[cell].elements {
let Element::Reference {
cell: target_name,
origin,
transform,
array,
} = e.unadorned()
else {
continue;
};
let target = index[target_name.as_str()];
let Some(child_bb) = cell_bounds[target] else {
continue;
};
let composed = compose(placement.transform, *transform)?;
let mut zero_bb = child_bb.transform(Placement {
origin: Position::zero(),
transform: composed,
})?;
if cell_abs_pad[target] > 0 && composed.magnification < 1.0 {
zero_bb = zero_bb.pad(cell_abs_pad[target]);
}
match array {
None => {
let pos = offset_in_root(placement, *origin, 0, 0)?;
let hull = match pos {
Position::Grid(ox, oy) => Aabb {
min_x: zero_bb.min_x + ox,
min_y: zero_bb.min_y + oy,
max_x: zero_bb.max_x + ox,
max_y: zero_bb.max_y + oy,
},
Position::Real(_, _) => {
let (rx, ry) = pos.real()?;
Aabb {
min_x: zero_bb.min_x + (rx.floor() as i128) - 1,
min_y: zero_bb.min_y + (ry.floor() as i128) - 1,
max_x: zero_bb.max_x + (rx.ceil() as i128) + 1,
max_y: zero_bb.max_y + (ry.ceil() as i128) + 1,
}
}
};
if !hull.overlaps_window(window) {
continue;
}
if remaining == 0 {
return Err(Error::invalid(&limit_msg));
}
remaining -= 1;
if hull.inside_window(window)
&& let Some(grid_origin) = exact_grid_point(pos)?
{
mark_retain_closure(target, graph, &index, &mut retain_full);
kept_refs[w_idx].push((target, grid_origin, composed, None));
} else {
stack.push((
target,
Placement {
origin: pos,
transform: composed,
},
));
}
}
Some(Repetition::Offsets(offsets)) => {
for i in 0..repeat_count(array.as_ref()) {
if work_remaining == 0 {
return Err(Error::invalid(
"window candidate search exceeded its work limit",
));
}
work_remaining -= 1;
let (dx, dy) = if i == 0 {
(0, 0)
} else {
let p = offsets[(i - 1) as usize];
(i128::from(p.x), i128::from(p.y))
};
let pos = offset_in_root(placement, *origin, dx, dy)?;
let hull = match pos {
Position::Grid(ox, oy) => Aabb {
min_x: zero_bb.min_x + ox,
min_y: zero_bb.min_y + oy,
max_x: zero_bb.max_x + ox,
max_y: zero_bb.max_y + oy,
},
Position::Real(_, _) => {
let (rx, ry) = pos.real()?;
Aabb {
min_x: zero_bb.min_x + (rx.floor() as i128) - 1,
min_y: zero_bb.min_y + (ry.floor() as i128) - 1,
max_x: zero_bb.max_x + (rx.ceil() as i128) + 1,
max_y: zero_bb.max_y + (ry.ceil() as i128) + 1,
}
}
};
if !hull.overlaps_window(window) {
continue;
}
if remaining == 0 {
return Err(Error::invalid(&limit_msg));
}
remaining -= 1;
if hull.inside_window(window)
&& let Some(grid_origin) = exact_grid_point(pos)?
{
mark_retain_closure(target, graph, &index, &mut retain_full);
kept_refs[w_idx].push((target, grid_origin, composed, None));
} else {
stack.push((
target,
Placement {
origin: pos,
transform: composed,
},
));
}
}
}
Some(Repetition::Regular(a)) => {
let col_root = exact_grid_point(linear(
placement.transform,
Position::point(a.column_step),
)?)?;
let row_root = exact_grid_point(linear(
placement.transform,
Position::point(a.row_step),
)?)?;
let mut blocks = vec![(0u32, a.columns - 1, 0u32, a.rows - 1)];
while let Some((c0, c1, r0, r1)) = blocks.pop() {
if work_remaining == 0 {
return Err(Error::invalid(
"window candidate search exceeded its work limit",
));
}
work_remaining -= 1;
let hull =
regular_block_hull(zero_bb, *origin, placement, a, c0, c1, r0, r1)?;
if !hull.overlaps_window(window) {
continue;
}
let dx = i128::from(c0) * i128::from(a.column_step.x)
+ i128::from(r0) * i128::from(a.row_step.x);
let dy = i128::from(c0) * i128::from(a.column_step.y)
+ i128::from(r0) * i128::from(a.row_step.y);
let pos = offset_in_root(placement, *origin, dx, dy)?;
if hull.inside_window(window)
&& let Some(grid_origin) = exact_grid_point(pos)?
{
let cols = c1 - c0 + 1;
let rows = r1 - r0 + 1;
if cols == 1 && rows == 1 {
if remaining == 0 {
return Err(Error::invalid(&limit_msg));
}
remaining -= 1;
mark_retain_closure(target, graph, &index, &mut retain_full);
kept_refs[w_idx].push((target, grid_origin, composed, None));
continue;
}
if let (Some(cs), Some(rs)) = (col_root, row_root) {
if remaining == 0 {
return Err(Error::invalid(&limit_msg));
}
remaining -= 1;
mark_retain_closure(target, graph, &index, &mut retain_full);
kept_refs[w_idx].push((
target,
grid_origin,
composed,
Some(Repetition::Regular(Array {
columns: cols,
rows,
column_step: cs,
row_step: rs,
})),
));
continue;
}
}
if c0 == c1 && r0 == r1 {
if remaining == 0 {
return Err(Error::invalid(&limit_msg));
}
remaining -= 1;
stack.push((
target,
Placement {
origin: pos,
transform: composed,
},
));
} else {
let dc = c1 - c0;
let dr = r1 - r0;
let col_span = i128::from(dc)
* i128::from(a.column_step.x)
.abs()
.max(i128::from(a.column_step.y).abs());
let row_span = i128::from(dr)
* i128::from(a.row_step.x)
.abs()
.max(i128::from(a.row_step.y).abs());
if dc > 0 && (dr == 0 || col_span >= row_span) {
let mid = c0 + dc / 2;
blocks.push((mid + 1, c1, r0, r1));
blocks.push((c0, mid, r0, r1));
} else {
let mid = r0 + dr / 2;
blocks.push((c0, c1, mid + 1, r1));
blocks.push((c0, c1, r0, mid));
}
}
}
}
}
}
}
}
Ok(HierarchicalPlan {
straddling,
kept_refs,
retain_full,
})
}
fn element_vertex_cost(e: &Element) -> usize {
match e.unadorned() {
Element::Polygon { points, .. }
| Element::Path { points, .. }
| Element::ExtendedPath { points, .. } => points.len(),
Element::Circle { .. } => 1,
Element::Repeated { element, .. } => element_vertex_cost(element),
_ => 0,
}
}
struct Output<'a> {
windows: &'a [Window],
cells: &'a mut [Cell],
remaining: usize,
}
impl Output<'_> {
fn emit_to_window(&mut self, w_idx: usize, layer: Layer, ring: &Ring) -> Result<()> {
if ring.len() < 3 {
return Ok(());
}
let window = self.windows[w_idx];
if let Some((lo, hi)) = geometry::axis_aligned_rect(ring) {
let rect_win = Window {
lower: lo,
upper: hi,
};
let Some(area) = window.intersection(rect_win) else {
return Ok(());
};
let points = geometry::rectangle(area.lower, area.upper)?;
self.remaining = self
.remaining
.checked_sub(points.len())
.ok_or_else(|| Error::invalid("clip output vertex budget exceeded"))?;
self.cells[w_idx]
.elements
.push(Element::Polygon { layer, points });
return Ok(());
}
let bounds = Window::bounds(ring).expect("nonempty ring");
let Some(area) = window.intersection(bounds) else {
return Ok(());
};
let clipped = if window.contains(bounds) {
geometry::fracture(std::slice::from_ref(ring), 8_190)?
} else {
let box_ring = geometry::rectangle(area.lower, area.upper)?;
let clipped = geometry::boolean(
std::slice::from_ref(ring),
&[box_ring],
BooleanOp::Intersection,
)?;
geometry::fracture(&clipped, 8_190)?
};
for points in clipped {
self.remaining = self
.remaining
.checked_sub(points.len())
.ok_or_else(|| Error::invalid("clip output vertex budget exceeded"))?;
self.cells[w_idx]
.elements
.push(Element::Polygon { layer, points });
}
Ok(())
}
fn add_all(&mut self, layer: Layer, ring: Ring) -> Result<()> {
if ring.len() < 3 {
return Ok(());
}
for w_idx in 0..self.windows.len() {
self.emit_to_window(w_idx, layer, &ring)?;
}
Ok(())
}
}
fn clip_element_at_placement(
element: &Element,
placement: Placement,
windows: &[Window],
target_window: Option<usize>,
placement_limit: usize,
tolerance_dbu: f64,
output: &mut Output<'_>,
) -> Result<()> {
let (base, rep) = match element.unadorned() {
Element::Repeated { element, array } => (element.unadorned(), Some(array)),
base => (base, None),
};
let (Some(base_bb), abs_pad) = shape_bounds_and_abs_pad(base) else {
return Ok(());
};
let mut zero_bb = base_bb.transform(Placement {
origin: Position::zero(),
transform: placement.transform,
})?;
if abs_pad > 0 && placement.transform.magnification < 1.0 {
zero_bb = zero_bb.pad(abs_pad);
}
let layer = base.layer().expect("placed shape has a layer");
let slice_win;
let active_windows: &[Window] = match target_window {
Some(idx) => {
slice_win = [windows[idx]];
&slice_win
}
None => windows,
};
if rep.is_none() {
let hull = base_bb.transform(placement)?;
let hull = if abs_pad > 0 && placement.transform.magnification < 1.0 {
hull.pad(abs_pad)
} else {
hull
};
if !hull.overlaps_any(active_windows) {
return Ok(());
}
let mut value = base.clone();
transform_element(&mut value, placement)?;
let ring = super::element_outline(&value, tolerance_dbu)?;
match target_window {
Some(idx) => output.emit_to_window(idx, layer, &ring)?,
None => output.add_all(layer, ring)?,
}
return Ok(());
}
let mut remaining = placement_limit;
let mut work_remaining = placement_limit.saturating_add(1).saturating_mul(128);
let limit_msg = format!("clip record expansion exceeds limit {placement_limit}");
let origins = prune_repetition_instances(
zero_bb,
Point::default(),
placement,
rep,
active_windows,
&mut remaining,
&mut work_remaining,
&limit_msg,
)?;
for inst_origin in origins {
let p = Placement {
origin: inst_origin,
transform: placement.transform,
};
let mut value = base.clone();
transform_element(&mut value, p)?;
let ring = super::element_outline(&value, tolerance_dbu)?;
match target_window {
Some(idx) => output.emit_to_window(idx, layer, &ring)?,
None => output.add_all(layer, ring)?,
}
}
Ok(())
}
pub fn clip_file(
path: impl AsRef<Path>,
top: &str,
windows: &[Window],
options: ClipOptions<'_>,
) -> Result<Layout> {
if windows.is_empty() || options.placement_limit == 0 || options.output_vertex_limit == 0 {
return Err(Error::invalid(
"clip requires windows and positive resource limits",
));
}
if !options.tolerance_dbu.is_finite() || options.tolerance_dbu <= 0.0 {
return Err(Error::invalid("tolerance must be positive and finite"));
}
let mut file = File::open(path)?;
let mut first = Sha1::new();
let mut local_bounds: Vec<Option<Aabb>> = Vec::new();
let mut local_abs_pad: Vec<i128> = Vec::new();
let (graph, _) = options.read.read_filtered(
HashedInput {
file: &mut file,
hash: &mut first,
},
false,
&mut |cell, element| {
if cell >= local_bounds.len() {
local_bounds.resize(cell + 1, None);
local_abs_pad.resize(cell + 1, 0);
}
if material(element) {
let (bb, abs_pad) = shape_bounds_and_abs_pad(element);
if let Some(bb) = bb {
Aabb::include_option(&mut local_bounds[cell], bb);
}
local_abs_pad[cell] = local_abs_pad[cell].max(abs_pad);
}
Ok(matches!(element.unadorned(), Element::Reference { .. }))
},
)?;
local_bounds.resize(graph.cells.len(), None);
local_abs_pad.resize(graph.cells.len(), 0);
let (cell_bounds, cell_abs_pad) = compute_cell_bounds(&graph, &local_bounds, &local_abs_pad)?;
let mut output = Layout::new("CLIPS", graph.dbu_meters)?;
for index in 1..=windows.len() {
output.add_cell(format!("WIN_{index}"))?;
}
if !options.keep_hierarchy {
let placements = flat_placements(
&graph,
top,
&local_bounds,
&cell_bounds,
&cell_abs_pad,
windows,
options.placement_limit,
)?;
let selected_cells: Vec<bool> = placements.iter().map(|v| !v.is_empty()).collect();
let mut target = Output {
windows,
cells: &mut output.cells,
remaining: options.output_vertex_limit,
};
let mut second = Sha1::new();
file.rewind()?;
options.read.read_filtered_cells(
HashedInput {
file: &mut file,
hash: &mut second,
},
true,
Some(&selected_cells),
&mut |cell, element| {
let Some(cell_placements) =
placements.get(cell).filter(|values| !values.is_empty())
else {
return Ok(false);
};
if !material(element) {
return Ok(false);
}
for &p in cell_placements {
clip_element_at_placement(
element,
p,
windows,
None,
options.placement_limit,
options.tolerance_dbu,
&mut target,
)?;
}
Ok(false)
},
)?;
if first.finalize() != second.finalize() {
return Err(Error::invalid("input changed between the two clip scans"));
}
return Ok(output);
}
let plan = hierarchical_plan(
&graph,
top,
&local_bounds,
&cell_bounds,
&cell_abs_pad,
windows,
options.placement_limit,
)?;
let mut reserved: BTreeSet<String> = (1..=windows.len()).map(|i| format!("WIN_{i}")).collect();
for (ci, keep) in plan.retain_full.iter().enumerate() {
if *keep && !reserved.contains(&graph.cells[ci].name) {
reserved.insert(graph.cells[ci].name.clone());
}
}
let mut cell_name_map: BTreeMap<usize, String> = BTreeMap::new();
let mut retained_out_idx: Vec<Option<usize>> = vec![None; graph.cells.len()];
for (ci, keep) in plan.retain_full.iter().enumerate() {
if !*keep {
continue;
}
let orig = &graph.cells[ci].name;
let final_name = if (1..=windows.len()).any(|i| format!("WIN_{i}") == *orig) {
let mut allocated = String::new();
for suffix in 1u64.. {
let candidate = format!("{orig}_{suffix}");
if reserved.insert(candidate.clone()) {
allocated = candidate;
break;
}
}
allocated
} else {
orig.clone()
};
cell_name_map.insert(ci, final_name.clone());
output.add_cell(&final_name)?;
retained_out_idx[ci] = Some(output.cells.len() - 1);
}
let src_index: HashMap<_, _> = graph
.cells
.iter()
.enumerate()
.map(|(i, c)| (c.name.as_str(), i))
.collect();
for (ci, out_idx) in retained_out_idx.iter().enumerate() {
let Some(out_idx) = *out_idx else {
continue;
};
for e in &graph.cells[ci].elements {
if let Element::Reference {
cell: target_name,
origin,
transform,
array,
} = e.unadorned()
{
let ti = src_index[target_name.as_str()];
output.cells[out_idx].elements.push(Element::Reference {
cell: cell_name_map[&ti].clone(),
origin: *origin,
transform: *transform,
array: array.clone(),
});
}
}
}
for (w_idx, refs) in plan.kept_refs.into_iter().enumerate() {
for (ti, origin, transform, array) in refs {
output.cells[w_idx].elements.push(Element::Reference {
cell: cell_name_map[&ti].clone(),
origin,
transform,
array,
});
}
}
let selected_cells: Vec<bool> = (0..graph.cells.len())
.map(|ci| plan.retain_full[ci] || !plan.straddling[ci].is_empty())
.collect();
let mut target = Output {
windows,
cells: &mut output.cells,
remaining: options.output_vertex_limit,
};
let mut second = Sha1::new();
file.rewind()?;
options.read.read_filtered_cells(
HashedInput {
file: &mut file,
hash: &mut second,
},
true,
Some(&selected_cells),
&mut |cell, element| {
if !material(element) {
return Ok(false);
}
if let Some(out_idx) = retained_out_idx.get(cell).copied().flatten() {
let cost = element_vertex_cost(element);
target.remaining = target
.remaining
.checked_sub(cost)
.ok_or_else(|| Error::invalid("clip output vertex budget exceeded"))?;
target.cells[out_idx]
.elements
.push(element.unadorned().clone());
}
if let Some(placements) = plan.straddling.get(cell) {
for &(p, w_idx) in placements {
clip_element_at_placement(
element,
p,
windows,
Some(w_idx),
options.placement_limit,
options.tolerance_dbu,
&mut target,
)?;
}
}
Ok(false)
},
)?;
if first.finalize() != second.finalize() {
return Err(Error::invalid("input changed between the two clip scans"));
}
Ok(output)
}
impl Layout {
pub fn placed_in_windows(
&self,
top: &str,
windows: &[Window],
layers: Option<&BTreeSet<Layer>>,
limit: usize,
) -> Result<Vec<Element>> {
self.validate()?;
if limit == 0 {
return Err(Error::invalid("window expansion limit must be positive"));
}
if windows.is_empty() {
return Ok(Vec::new());
}
let mut local_bounds = vec![None; self.cells.len()];
let mut local_abs_pad = vec![0i128; self.cells.len()];
for (ci, cell) in self.cells.iter().enumerate() {
for e in &cell.elements {
if !material(e) {
continue;
}
if let Some(selected) = layers
&& e.layer().is_none_or(|l| !selected.contains(&l))
{
continue;
}
let (bb, abs_pad) = shape_bounds_and_abs_pad(e);
if let Some(bb) = bb {
Aabb::include_option(&mut local_bounds[ci], bb);
}
local_abs_pad[ci] = local_abs_pad[ci].max(abs_pad);
}
}
let (cell_bounds, cell_abs_pad) = compute_cell_bounds(self, &local_bounds, &local_abs_pad)?;
let placements = flat_placements(
self,
top,
&local_bounds,
&cell_bounds,
&cell_abs_pad,
windows,
limit,
)?;
let mut out = Vec::new();
let mut work_remaining = limit.saturating_add(1).saturating_mul(128);
let limit_msg = format!("window placement expansion exceeds limit {limit}");
for (ci, cell_placements) in placements.iter().enumerate() {
if cell_placements.is_empty() {
continue;
}
for e in &self.cells[ci].elements {
if !material(e) {
continue;
}
if let Some(selected) = layers
&& e.layer().is_none_or(|l| !selected.contains(&l))
{
continue;
}
let (base, rep) = match e.unadorned() {
Element::Repeated { element, array } => (element.unadorned(), Some(array)),
base => (base, None),
};
let (Some(base_bb), abs_pad) = shape_bounds_and_abs_pad(base) else {
continue;
};
for &placement in cell_placements {
let mut zero_bb = base_bb.transform(Placement {
origin: Position::zero(),
transform: placement.transform,
})?;
if abs_pad > 0 && placement.transform.magnification < 1.0 {
zero_bb = zero_bb.pad(abs_pad);
}
let mut remaining = limit.saturating_sub(out.len());
let origins = prune_repetition_instances(
zero_bb,
Point::default(),
placement,
rep,
windows,
&mut remaining,
&mut work_remaining,
&limit_msg,
)?;
for inst_origin in origins {
if out.len() >= limit {
return Err(Error::invalid(&limit_msg));
}
let mut value = base.clone();
transform_element(
&mut value,
Placement {
origin: inst_origin,
transform: placement.transform,
},
)?;
out.push(value);
}
}
}
}
Ok(out)
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Transform;
#[test]
fn clip_file_prunes_huge_compact_arrays_and_preserves_hierarchy() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("huge.oas");
let layer = Layer {
number: 7,
datatype: 0,
};
let mut layout = Layout::new("MASK", 1e-9).unwrap();
layout.add_cell("UNIT").unwrap();
layout
.add_element(
"UNIT",
Element::Polygon {
layer,
points: geometry::rectangle(Point { x: 0, y: 0 }, Point { x: 10, y: 10 })
.unwrap(),
},
)
.unwrap();
layout.add_cell("TOP").unwrap();
layout
.add_element(
"TOP",
Element::Reference {
cell: "UNIT".into(),
origin: Point { x: 0, y: 0 },
transform: Transform::default(),
array: Some(Repetition::Regular(Array {
columns: 100_000,
rows: 100_000,
column_step: Point { x: 20, y: 0 },
row_step: Point { x: 0, y: 20 },
})),
},
)
.unwrap();
crate::write(&layout, &path).unwrap();
let win = Window::new(Point { x: 5, y: 5 }, Point { x: 115, y: 115 }).unwrap();
let flat = clip_file(
&path,
"TOP",
&[win],
ClipOptions {
placement_limit: 500,
keep_hierarchy: false,
..Default::default()
},
)
.unwrap();
let hier = clip_file(
&path,
"TOP",
&[win],
ClipOptions {
placement_limit: 500,
keep_hierarchy: true,
..Default::default()
},
)
.unwrap();
assert!(hier.cells.iter().any(|c| c.name == "UNIT"));
assert!(hier.cells[0].elements.len() < flat.cells[0].elements.len());
let a = crate::file_workflows::placed_rings(&flat, "WIN_1", 10_000, 0.25).unwrap();
let b = crate::file_workflows::placed_rings(&hier, "WIN_1", 10_000, 0.25).unwrap();
let xor = geometry::boolean(&a[&layer], &b[&layer], BooleanOp::Xor).unwrap();
assert!(xor.is_empty());
}
#[test]
fn hierarchical_clip_renames_colliding_win_cell_cleanly() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("collide.oas");
let layer = Layer {
number: 1,
datatype: 0,
};
let mut layout = Layout::new("MASK", 1e-9).unwrap();
layout.add_cell("WIN_1").unwrap();
layout
.add_element(
"WIN_1",
Element::Polygon {
layer,
points: geometry::rectangle(Point { x: 0, y: 0 }, Point { x: 10, y: 10 })
.unwrap(),
},
)
.unwrap();
layout.add_cell("TOP").unwrap();
layout
.add_element(
"TOP",
Element::Reference {
cell: "WIN_1".into(),
origin: Point { x: 20, y: 20 },
transform: Transform::default(),
array: None,
},
)
.unwrap();
crate::write(&layout, &path).unwrap();
let win = Window::new(Point { x: 0, y: 0 }, Point { x: 100, y: 100 }).unwrap();
let hier = clip_file(
&path,
"TOP",
&[win],
ClipOptions {
keep_hierarchy: true,
..Default::default()
},
)
.unwrap();
hier.validate().unwrap();
assert!(hier.cells.iter().any(|c| c.name == "WIN_1_1"));
let rings = crate::file_workflows::placed_rings(&hier, "WIN_1", 100, 0.25).unwrap();
let expected =
vec![geometry::rectangle(Point { x: 20, y: 20 }, Point { x: 30, y: 30 }).unwrap()];
assert!(
geometry::boolean(&rings[&layer], &expected, BooleanOp::Xor)
.unwrap()
.is_empty()
);
}
}