Report coincident terminals and unusable seeds per net, update custom bend handling and verification, and cover the revised behavior with regression tests. Shorten the user and developer guides around reader tasks and keep the illustrated routing walkthrough and reference links easy to find.
706 lines
30 KiB
Python
706 lines
30 KiB
Python
from __future__ import annotations
|
|
|
|
from dataclasses import dataclass, field, replace
|
|
from math import asin, ceil, isfinite, pi, radians, sqrt
|
|
from typing import TYPE_CHECKING, Literal
|
|
|
|
import numpy
|
|
from shapely import get_num_coordinates, transform
|
|
from shapely.affinity import rotate as shapely_rotate
|
|
from shapely.affinity import scale as shapely_scale
|
|
from shapely.affinity import translate as shapely_translate
|
|
from shapely.geometry import Polygon, box
|
|
|
|
from inire.constants import TOLERANCE_ANGULAR, TOLERANCE_LINEAR
|
|
from inire.geometry.sbend import sbend_grid_span, sbend_span
|
|
from inire.seeds import Bend90Seed, PathSegmentSeed, SBendSeed, StraightSeed
|
|
from .primitives import Port, rotate_cardinal, rotation_matrix2
|
|
|
|
if TYPE_CHECKING:
|
|
from collections.abc import Iterable, Sequence
|
|
|
|
from numpy.typing import NDArray
|
|
|
|
|
|
MoveKind = Literal["straight", "bend90", "sbend"]
|
|
BendCollisionModelName = Literal["arc", "bbox", "clipped_bbox"]
|
|
BendCollisionModel = BendCollisionModelName | Polygon
|
|
BendPhysicalGeometry = Literal["arc"] | Polygon
|
|
|
|
|
|
def path_within_board(path: Iterable[ComponentResult], board: Polygon) -> bool:
|
|
"""Check containment of the physical geometry, including boundary contact."""
|
|
return all(board.covers(shape) for component in path for shape in component.physical_geometry)
|
|
|
|
|
|
def _has_port_face(polygon: Polygon, port: Port, *, arrival: bool, width: float) -> bool:
|
|
"""Check a custom outline against one declared port."""
|
|
axis = 0 if port.r % 180 == 0 else 1
|
|
position = (port.x, port.y)
|
|
exterior = polygon.exterior
|
|
coordinates = numpy.asarray(exterior.coords)
|
|
normal = coordinates[:, axis] - position[axis]
|
|
on_plane = numpy.abs(normal) <= TOLERANCE_LINEAR
|
|
lateral = coordinates[:, 1 - axis] - position[1 - axis]
|
|
lower = numpy.minimum(lateral[:-1], lateral[1:])
|
|
upper = numpy.maximum(lateral[:-1], lateral[1:])
|
|
# The interior is left of a counterclockwise exterior edge.
|
|
forward = 1 if port.r < 180 else -1
|
|
inward = forward if not arrival else -forward
|
|
left = (lateral[1:] - lateral[:-1]) * (1 if axis == 1 else -1)
|
|
interior = left if exterior.is_ccw else -left
|
|
edges = numpy.flatnonzero(on_plane[:-1] & on_plane[1:] & (interior * inward > 0))
|
|
spans: list[tuple[float, float]] = []
|
|
for lo, hi in sorted((lower[i], upper[i]) for i in edges):
|
|
if spans and lo <= spans[-1][1]:
|
|
prev_lo, prev_hi = spans[-1]
|
|
spans[-1] = prev_lo, max(prev_hi, hi)
|
|
else:
|
|
spans.append((lo, hi))
|
|
return any(lo < 0 < hi and max(abs(lo + width / 2), abs(hi - width / 2)) <= TOLERANCE_LINEAR for lo, hi in spans)
|
|
|
|
|
|
def bend_fits_width(radius: float, width: float) -> bool:
|
|
return radius >= width / 2
|
|
|
|
|
|
def bend90_uses_circular_geometry(collision_type: BendCollisionModel, physical_geometry_type: BendPhysicalGeometry) -> bool:
|
|
return not (isinstance(collision_type, Polygon) and isinstance(physical_geometry_type, Polygon))
|
|
|
|
|
|
def uses_custom_outline(kind: MoveKind, physical_geometry_type: BendPhysicalGeometry, sbend_outline: Polygon | None) -> bool:
|
|
return (kind == "bend90" and isinstance(physical_geometry_type, Polygon)) or (kind == "sbend" and sbend_outline is not None)
|
|
|
|
|
|
def bend90_grid_span(radius: float) -> int:
|
|
"""Distance from either port face to the corner on the routing grid."""
|
|
return ceil(radius)
|
|
|
|
|
|
def _normalize_length(value: float) -> float:
|
|
return float(value)
|
|
|
|
|
|
class ComponentPreparationError(ValueError):
|
|
"""A move cannot safely be materialized."""
|
|
|
|
|
|
def component_endpoint(start: Port, kind: MoveKind, parameters: tuple) -> Port:
|
|
if kind == "straight":
|
|
forward, lateral, turn = _normalize_length(parameters[0]), 0, 0
|
|
elif kind == "bend90":
|
|
radius, direction = parameters
|
|
sign = 1 if direction == "CCW" else -1
|
|
forward = bend90_grid_span(radius)
|
|
lateral, turn = sign * forward, sign * 90
|
|
else:
|
|
lateral, radius = parameters
|
|
try:
|
|
forward = sbend_grid_span(lateral, radius)
|
|
except (ValueError, OverflowError) as exc:
|
|
raise ComponentPreparationError("has an unrepresentable S-bend span") from exc
|
|
turn = 0
|
|
dx, dy = rotate_cardinal(forward, lateral, int(start.r))
|
|
return start.translate(dx, dy, turn)
|
|
|
|
|
|
def check_component_endpoint(
|
|
start: Port, kind: MoveKind, parameters: tuple, bounds: tuple[float, float, float, float],
|
|
) -> None:
|
|
end = component_endpoint(start, kind, parameters)
|
|
xmin, ymin, xmax, ymax = bounds
|
|
tol = TOLERANCE_LINEAR
|
|
if not (xmin - tol <= end.x <= xmax + tol and ymin - tol <= end.y <= ymax + tol):
|
|
raise ComponentPreparationError("has an endpoint outside the routing board")
|
|
|
|
|
|
def _bend90_length(radius: float) -> float:
|
|
return radius * pi / 2 + 2 * (bend90_grid_span(radius) - radius)
|
|
|
|
|
|
@dataclass(frozen=True, slots=True)
|
|
class ComponentResult:
|
|
start_port: Port
|
|
collision_geometry: Sequence[Polygon]
|
|
end_port: Port
|
|
length: float
|
|
move_type: MoveKind
|
|
move_spec: PathSegmentSeed
|
|
physical_geometry: Sequence[Polygon]
|
|
dilated_collision_geometry: Sequence[Polygon]
|
|
dilated_physical_geometry: Sequence[Polygon]
|
|
width: float | None = None
|
|
standard_faces: bool = False
|
|
_bounds: tuple[tuple[float, float, float, float], ...] = field(init=False, repr=False)
|
|
_total_bounds: tuple[float, float, float, float] = field(init=False, repr=False)
|
|
_dilated_bounds: tuple[tuple[float, float, float, float], ...] = field(init=False, repr=False)
|
|
_total_dilated_bounds: tuple[float, float, float, float] = field(init=False, repr=False)
|
|
_total_physical_bounds: tuple[float, float, float, float] | None = field(init=False, repr=False, compare=False, default=None)
|
|
_physical_geometry_valid: bool | None = field(init=False, repr=False, compare=False, default=None)
|
|
_coordinate_count: int | None = field(init=False, repr=False, compare=False, default=None)
|
|
|
|
def __post_init__(self) -> None:
|
|
collision_geometry = tuple(self.collision_geometry)
|
|
physical_geometry = tuple(self.physical_geometry)
|
|
dilated_collision_geometry = tuple(self.dilated_collision_geometry)
|
|
dilated_physical_geometry = tuple(self.dilated_physical_geometry)
|
|
|
|
object.__setattr__(self, "collision_geometry", collision_geometry)
|
|
object.__setattr__(self, "physical_geometry", physical_geometry)
|
|
object.__setattr__(self, "dilated_collision_geometry", dilated_collision_geometry)
|
|
object.__setattr__(self, "dilated_physical_geometry", dilated_physical_geometry)
|
|
object.__setattr__(self, "length", float(self.length))
|
|
|
|
bounds = tuple(poly.bounds for poly in collision_geometry)
|
|
object.__setattr__(self, "_bounds", bounds)
|
|
object.__setattr__(self, "_total_bounds", _combine_bounds(list(bounds)))
|
|
|
|
dilated_bounds = tuple(poly.bounds for poly in dilated_collision_geometry)
|
|
object.__setattr__(self, "_dilated_bounds", dilated_bounds)
|
|
object.__setattr__(self, "_total_dilated_bounds", _combine_bounds(list(dilated_bounds)))
|
|
|
|
@property
|
|
def bounds(self) -> tuple[tuple[float, float, float, float], ...]:
|
|
return self._bounds
|
|
|
|
@property
|
|
def total_bounds(self) -> tuple[float, float, float, float]:
|
|
return self._total_bounds
|
|
|
|
@property
|
|
def dilated_bounds(self) -> tuple[tuple[float, float, float, float], ...]:
|
|
return self._dilated_bounds
|
|
|
|
@property
|
|
def total_dilated_bounds(self) -> tuple[float, float, float, float]:
|
|
return self._total_dilated_bounds
|
|
|
|
@property
|
|
def total_physical_bounds(self) -> tuple[float, float, float, float]:
|
|
bounds = self._total_physical_bounds
|
|
if bounds is None:
|
|
shapes = self.physical_geometry
|
|
bounds = shapes[0].bounds if len(shapes) == 1 else _combine_bounds([shape.bounds for shape in shapes])
|
|
object.__setattr__(self, "_total_physical_bounds", bounds)
|
|
return bounds
|
|
|
|
@property
|
|
def bend_radius(self) -> float | None:
|
|
return self.move_spec.radius if isinstance(self.move_spec, Bend90Seed) else None
|
|
|
|
@property
|
|
def coordinate_count(self) -> int:
|
|
count = self._coordinate_count
|
|
if count is None:
|
|
polygons = {
|
|
id(polygon): polygon
|
|
for group in (self.physical_geometry, self.collision_geometry, self.dilated_physical_geometry, self.dilated_collision_geometry)
|
|
for polygon in group
|
|
}
|
|
count = sum(int(get_num_coordinates(polygon)) for polygon in polygons.values())
|
|
object.__setattr__(self, "_coordinate_count", count)
|
|
return count
|
|
|
|
@property
|
|
def physical_geometry_valid(self) -> bool:
|
|
valid = self._physical_geometry_valid
|
|
if valid is None:
|
|
shapes = self.physical_geometry
|
|
valid = bool(shapes) and all(not shape.is_empty and shape.is_valid for shape in shapes)
|
|
object.__setattr__(self, "_physical_geometry_valid", valid)
|
|
return valid
|
|
|
|
def translate(self, dx: int | float, dy: int | float) -> ComponentResult:
|
|
# The collision and physical views often reference the same polygons.
|
|
polygons = {
|
|
id(polygon): polygon
|
|
for geometry in (
|
|
self.collision_geometry, self.physical_geometry,
|
|
self.dilated_collision_geometry, self.dilated_physical_geometry,
|
|
)
|
|
for polygon in geometry
|
|
}
|
|
if len(polygons) > 1 and (self.standard_faces or all(not polygon.has_z for polygon in polygons.values())):
|
|
offset = numpy.array((dx, dy))
|
|
shifted = transform(list(polygons.values()), lambda coordinates: coordinates + offset)
|
|
translated = dict(zip(polygons, shifted, strict=True))
|
|
else:
|
|
translated = {key: shapely_translate(polygon, dx, dy) for key, polygon in polygons.items()}
|
|
|
|
def translate_geometry(polygons: Sequence[Polygon]) -> tuple[Polygon, ...]:
|
|
return tuple(translated[id(polygon)] for polygon in polygons)
|
|
|
|
result = ComponentResult(
|
|
start_port=self.start_port.translate(dx, dy),
|
|
collision_geometry=translate_geometry(self.collision_geometry),
|
|
end_port=self.end_port.translate(dx, dy),
|
|
length=self.length,
|
|
move_type=self.move_type,
|
|
move_spec=self.move_spec,
|
|
physical_geometry=translate_geometry(self.physical_geometry),
|
|
dilated_collision_geometry=translate_geometry(self.dilated_collision_geometry),
|
|
dilated_physical_geometry=translate_geometry(self.dilated_physical_geometry),
|
|
width=self.width,
|
|
standard_faces=self.standard_faces,
|
|
)
|
|
object.__setattr__(result, "_coordinate_count", self._coordinate_count)
|
|
return result
|
|
|
|
|
|
def _combine_bounds(bounds_list: list[tuple[float, float, float, float]]) -> tuple[float, float, float, float]:
|
|
if len(bounds_list) == 1:
|
|
return bounds_list[0]
|
|
arr = numpy.asarray(bounds_list, dtype=numpy.float64)
|
|
return (
|
|
float(arr[:, 0].min()),
|
|
float(arr[:, 1].min()),
|
|
float(arr[:, 2].max()),
|
|
float(arr[:, 3].max()),
|
|
)
|
|
|
|
|
|
def _get_num_segments(radius: float, angle_deg: float, sagitta: float = 0.01) -> int:
|
|
if not isfinite(radius) or not isfinite(angle_deg):
|
|
raise ComponentPreparationError("has an unrepresentable circular arc")
|
|
if radius <= 0:
|
|
return 1
|
|
if not numpy.isfinite(sagitta) or sagitta <= 0:
|
|
raise ValueError("Arc sagitta must be finite and positive")
|
|
theta_max = 4 * asin(min(1.0, sqrt(sagitta) / sqrt(radius) / sqrt(2.0)))
|
|
subdivisions = radians(abs(angle_deg)) / theta_max
|
|
if subdivisions > 250_000:
|
|
raise ComponentPreparationError("exceeds 250,000 subdivisions for one circular arc")
|
|
return max(8, ceil(subdivisions))
|
|
|
|
|
|
def _arc_samples(
|
|
radius: float, width: float, angle: float, sagitta: float, dilation: float, *, sample_dilation: bool,
|
|
) -> tuple[int, int | None]:
|
|
if not bend_fits_width(radius, width):
|
|
raise ComponentPreparationError(f"needs radius at least {width / 2:g}, got {radius:g}")
|
|
physical = _get_num_segments(radius + width / 2, angle, sagitta)
|
|
dilated = None
|
|
if sample_dilation and dilation > 0 and bend_fits_width(radius, width + 2 * dilation):
|
|
dilated = _get_num_segments(radius + (width + 2 * dilation) / 2, angle, sagitta)
|
|
return physical, dilated
|
|
|
|
|
|
def _sbend_angle(offset: float, radius: float) -> float:
|
|
return 2 * asin(sqrt(abs(offset) / radius) / 2)
|
|
|
|
|
|
def prepare_component_sampling(
|
|
kind: MoveKind, parameters: tuple, width: float, *,
|
|
collision_type: BendCollisionModel, physical_geometry_type: BendPhysicalGeometry,
|
|
dilation: float, sbend_outline: Polygon | None = None, sagitta: float = 0.01,
|
|
) -> tuple[int, int | None]:
|
|
if kind == "bend90":
|
|
radius = parameters[0]
|
|
if not bend90_uses_circular_geometry(collision_type, physical_geometry_type):
|
|
return 0, None
|
|
sample_dilation = not isinstance(physical_geometry_type, Polygon) or collision_type == "arc"
|
|
return _arc_samples(radius, width, 90, sagitta, dilation, sample_dilation=sample_dilation)
|
|
if kind == "sbend" and sbend_outline is None:
|
|
offset, radius = parameters
|
|
angle = float(numpy.degrees(_sbend_angle(offset, radius)))
|
|
return _arc_samples(radius, width, angle, sagitta, dilation, sample_dilation=True)
|
|
return 0, None
|
|
|
|
|
|
def _get_arc_polygons(
|
|
cxy: tuple[float, float],
|
|
radius: float,
|
|
width: float,
|
|
ts: tuple[float, float],
|
|
num_segments: int,
|
|
dilation: float = 0.0,
|
|
*,
|
|
port_faces: tuple[Port, Port] | None = None,
|
|
) -> list[Polygon]:
|
|
t_start, t_end = numpy.radians(ts[0]), numpy.radians(ts[1])
|
|
cx, cy = cxy
|
|
inner_radius = radius - width / 2.0 - dilation
|
|
outer_radius = radius + width / 2.0 + dilation
|
|
angles = numpy.linspace(t_start, t_end, num_segments + 1)
|
|
|
|
cos_a = numpy.cos(angles)
|
|
sin_a = numpy.sin(angles)
|
|
if port_faces is not None:
|
|
cos_a[[0, -1]] = numpy.rint(cos_a[[0, -1]])
|
|
sin_a[[0, -1]] = numpy.rint(sin_a[[0, -1]])
|
|
|
|
inner_points = numpy.column_stack((cx + inner_radius * cos_a, cy + inner_radius * sin_a))
|
|
outer_points = numpy.column_stack((cx + outer_radius * cos_a[::-1], cy + outer_radius * sin_a[::-1]))
|
|
if port_faces is not None:
|
|
# Extend fractional radii along both tangents to reach exact grid faces.
|
|
centers = numpy.array([(port.x, port.y) for port in port_faces])
|
|
edge = (width / 2 + dilation) * numpy.column_stack((cos_a[[0, -1]], sin_a[[0, -1]]))
|
|
start_inner, end_inner = centers - edge
|
|
start_outer, end_outer = centers + edge
|
|
arc = slice(None) if radius < bend90_grid_span(radius) else slice(1, -1)
|
|
inner_points = numpy.vstack((start_inner, inner_points[arc], end_inner))
|
|
outer_points = numpy.vstack((end_outer, outer_points[arc], start_outer))
|
|
return [Polygon(numpy.concatenate((inner_points, outer_points), axis=0))]
|
|
|
|
|
|
def _clip_bbox_polygonal(
|
|
cxy: tuple[float, float],
|
|
radius: float,
|
|
width: float,
|
|
ts: tuple[float, float],
|
|
tangent_extensions: tuple[float, float],
|
|
) -> Polygon:
|
|
"""Return a conservative polygonal proxy for the arc and its tangents.
|
|
|
|
The polygon uses 4 points along the outer edge and 4 along the inner edge.
|
|
The outer edge is a circumscribed polyline and the inner edge is an
|
|
inscribed polyline, so the result conservatively contains the true arc.
|
|
"""
|
|
cx, cy = cxy
|
|
sample_count = 4
|
|
angle_span = abs(float(ts[1]) - float(ts[0]))
|
|
if angle_span < TOLERANCE_ANGULAR:
|
|
return box(*_get_arc_polygons(cxy, radius, width, ts)[0].bounds)
|
|
|
|
segment_half_angle = numpy.radians(angle_span / (2.0 * (sample_count - 1)))
|
|
cos_half = max(float(numpy.cos(segment_half_angle)), 1e-9)
|
|
|
|
inner_radius = max(0.0, radius - width / 2.0)
|
|
outer_radius = radius + width / 2.0
|
|
tolerance = max(1e-3, radius * 1e-4)
|
|
conservative_inner_radius = max(0.0, inner_radius * cos_half - tolerance)
|
|
conservative_outer_radius = outer_radius / cos_half + tolerance
|
|
|
|
angles = numpy.radians(numpy.linspace(ts[0], ts[1], sample_count))
|
|
cos_a = numpy.cos(angles)
|
|
sin_a = numpy.sin(angles)
|
|
cos_a[numpy.abs(cos_a) < 1e-15] = 0
|
|
sin_a[numpy.abs(sin_a) < 1e-15] = 0
|
|
|
|
outer_points = numpy.column_stack((cx + conservative_outer_radius * cos_a, cy + conservative_outer_radius * sin_a))
|
|
inner_points = numpy.column_stack((cx + conservative_inner_radius * cos_a[::-1], cy + conservative_inner_radius * sin_a[::-1]))
|
|
start_extension, end_extension = tangent_extensions
|
|
sweep_sign = 1 if ts[1] > ts[0] else -1
|
|
# Keep the same conservative radial width along each attached tangent.
|
|
if start_extension > 0:
|
|
shift = numpy.array((sin_a[0], -cos_a[0])) * (sweep_sign * (start_extension + TOLERANCE_LINEAR))
|
|
outer_points = numpy.vstack((outer_points[0] + shift, outer_points))
|
|
inner_points = numpy.vstack((inner_points, inner_points[-1] + shift))
|
|
if end_extension > 0:
|
|
shift = numpy.array((-sin_a[-1], cos_a[-1])) * (sweep_sign * (end_extension + TOLERANCE_LINEAR))
|
|
outer_points = numpy.vstack((outer_points, outer_points[-1] + shift))
|
|
inner_points = numpy.vstack((inner_points[0] + shift, inner_points))
|
|
return Polygon(numpy.concatenate((outer_points, inner_points), axis=0))
|
|
|
|
|
|
def _transform_custom_collision_polygon(
|
|
collision_poly: Polygon,
|
|
cxy: tuple[float, float],
|
|
rotation_deg: float,
|
|
mirror_y: bool,
|
|
) -> Polygon:
|
|
poly = collision_poly
|
|
if mirror_y:
|
|
poly = shapely_scale(poly, xfact=1.0, yfact=-1.0, origin=(0.0, 0.0))
|
|
if rotation_deg % 360:
|
|
poly = shapely_rotate(poly, rotation_deg, origin=(0.0, 0.0), use_radians=False)
|
|
return shapely_translate(poly, cxy[0], cxy[1])
|
|
|
|
|
|
def _apply_collision_model(
|
|
arc_poly: Polygon,
|
|
collision_type: BendCollisionModel,
|
|
radius: float,
|
|
width: float,
|
|
cxy: tuple[float, float],
|
|
ts: tuple[float, float],
|
|
clip_margin: float | None = None,
|
|
rotation_deg: float = 0.0,
|
|
mirror_y: bool = False,
|
|
tangent_extensions: tuple[float, float] = (0.0, 0.0),
|
|
) -> list[Polygon]:
|
|
if isinstance(collision_type, Polygon):
|
|
return [_transform_custom_collision_polygon(collision_type, cxy, rotation_deg, mirror_y)]
|
|
if collision_type == "arc":
|
|
return [arc_poly]
|
|
if collision_type != "clipped_bbox":
|
|
return [box(*arc_poly.bounds)]
|
|
if clip_margin is None:
|
|
return [_clip_bbox_polygonal(cxy, radius, width, ts, tangent_extensions)]
|
|
bbox = box(*arc_poly.bounds)
|
|
shrink = min(clip_margin, max(radius, width))
|
|
clipped = bbox.buffer(-shrink, join_style="mitre") if shrink > 0 else bbox
|
|
return [clipped if not clipped.is_empty else bbox]
|
|
|
|
|
|
def _buffer_geometry(polygons: list[Polygon], dilation: float) -> list[Polygon]:
|
|
return [polygon.buffer(dilation) for polygon in polygons] if dilation > 0 else polygons
|
|
|
|
|
|
class Straight:
|
|
@staticmethod
|
|
def generate(
|
|
start_port: Port,
|
|
length: float,
|
|
width: float,
|
|
dilation: float = 0.0,
|
|
) -> ComponentResult:
|
|
rot2 = rotation_matrix2(start_port.r)
|
|
length_f = _normalize_length(length)
|
|
end_port = component_endpoint(start_port, "straight", (length_f,))
|
|
|
|
half_w = width / 2.0
|
|
pts = numpy.array(((0.0, half_w), (length_f, half_w), (length_f, -half_w), (0.0, -half_w)))
|
|
poly_points = (pts @ rot2.T) + numpy.array((start_port.x, start_port.y))
|
|
geometry = [Polygon(poly_points)]
|
|
|
|
if dilation > 0:
|
|
half_w_d = half_w + dilation
|
|
pts_d = numpy.array(
|
|
(
|
|
(-dilation, half_w_d),
|
|
(length_f + dilation, half_w_d),
|
|
(length_f + dilation, -half_w_d),
|
|
(-dilation, -half_w_d),
|
|
)
|
|
)
|
|
poly_points_d = (pts_d @ rot2.T) + numpy.array((start_port.x, start_port.y))
|
|
dilated_geometry = [Polygon(poly_points_d)]
|
|
else:
|
|
dilated_geometry = geometry
|
|
|
|
return ComponentResult(
|
|
start_port=start_port,
|
|
collision_geometry=geometry,
|
|
end_port=end_port,
|
|
length=abs(length_f),
|
|
move_type="straight",
|
|
move_spec=StraightSeed(length=length_f),
|
|
physical_geometry=geometry,
|
|
dilated_collision_geometry=dilated_geometry,
|
|
dilated_physical_geometry=dilated_geometry,
|
|
width=width,
|
|
standard_faces=length_f > 0 and length_f.is_integer(),
|
|
)
|
|
|
|
|
|
class Bend90:
|
|
@staticmethod
|
|
def generate(
|
|
start_port: Port,
|
|
radius: float,
|
|
width: float,
|
|
direction: Literal["CW", "CCW"],
|
|
sagitta: float = 0.01,
|
|
collision_type: BendCollisionModel = "arc",
|
|
physical_geometry_type: BendPhysicalGeometry = "arc",
|
|
clip_margin: float | None = None,
|
|
dilation: float = 0.0,
|
|
) -> ComponentResult:
|
|
rot2 = rotation_matrix2(start_port.r)
|
|
sign = 1 if direction == "CCW" else -1
|
|
|
|
grid_span = bend90_grid_span(radius)
|
|
tangent_length = grid_span - radius
|
|
center_local = numpy.array((tangent_length, sign * radius))
|
|
center_xy = (rot2 @ center_local) + numpy.array((start_port.x, start_port.y))
|
|
center = (float(center_xy[0]), float(center_xy[1]))
|
|
end_port = component_endpoint(start_port, "bend90", (radius, direction))
|
|
|
|
start_theta = start_port.r - sign * 90
|
|
end_theta = start_port.r
|
|
ts = (float(start_theta), float(end_theta))
|
|
|
|
port_faces = (start_port, end_port)
|
|
custom_physical = isinstance(physical_geometry_type, Polygon)
|
|
segments, dilated_segments = prepare_component_sampling(
|
|
"bend90", (radius, direction), width, collision_type=collision_type,
|
|
physical_geometry_type=physical_geometry_type, dilation=dilation, sagitta=sagitta,
|
|
)
|
|
arc_polys = []
|
|
if segments:
|
|
arc_polys = _get_arc_polygons(center, radius, width, ts, segments, port_faces=port_faces)
|
|
if isinstance(collision_type, Polygon):
|
|
collision_polys = [_transform_custom_collision_polygon(collision_type, center, float(start_port.r), mirror_y=(sign < 0))]
|
|
else:
|
|
collision_polys = _apply_collision_model(
|
|
arc_polys[0], collision_type, radius, width, center, ts, clip_margin=clip_margin,
|
|
rotation_deg=float(start_port.r), mirror_y=(sign < 0), tangent_extensions=(tangent_length, tangent_length),
|
|
)
|
|
|
|
if isinstance(physical_geometry_type, Polygon):
|
|
physical_geometry = [_transform_custom_collision_polygon(
|
|
physical_geometry_type, center, float(start_port.r), mirror_y=(sign < 0),
|
|
)]
|
|
else:
|
|
physical_geometry = arc_polys
|
|
dilated_arcs = arc_polys
|
|
if dilated_segments is not None:
|
|
dilated_arcs = _get_arc_polygons(center, radius, width, ts, dilated_segments, dilation=dilation, port_faces=port_faces)
|
|
elif dilation > 0 and (not custom_physical or collision_type == "arc"):
|
|
dilated_arcs = _buffer_geometry(arc_polys, dilation)
|
|
dilated_physical_geometry = dilated_arcs if physical_geometry is arc_polys else _buffer_geometry(physical_geometry, dilation)
|
|
dilated_collision_geometry = dilated_arcs if collision_type == "arc" else _buffer_geometry(collision_polys, dilation)
|
|
|
|
return ComponentResult(
|
|
start_port=start_port,
|
|
collision_geometry=collision_polys,
|
|
end_port=end_port,
|
|
length=_bend90_length(radius),
|
|
move_type="bend90",
|
|
move_spec=Bend90Seed(radius=radius, direction=direction),
|
|
physical_geometry=physical_geometry,
|
|
dilated_collision_geometry=dilated_collision_geometry,
|
|
dilated_physical_geometry=dilated_physical_geometry,
|
|
width=width,
|
|
standard_faces=physical_geometry is arc_polys,
|
|
)
|
|
|
|
|
|
class SBend:
|
|
@staticmethod
|
|
def _arcs(
|
|
start_port: Port,
|
|
rotation: NDArray[numpy.int32],
|
|
radius: float,
|
|
offset: float,
|
|
theta: float,
|
|
span: float,
|
|
grid_span: int,
|
|
width: float,
|
|
num_segments: int,
|
|
) -> list[Polygon]:
|
|
# Reflect the first arc about the midpoint and reverse it to get the
|
|
# second arc. Reuse the midpoint and its normal for both polygons.
|
|
sign = 1 if offset > 0 else -1
|
|
angles = numpy.linspace(0, theta, num_segments + 1)
|
|
sin, cos = numpy.sin(angles), numpy.cos(angles)
|
|
first = numpy.column_stack((radius * sin, sign * radius * (1 - cos)))
|
|
first[-1] = (span / 2, offset / 2)
|
|
normal = numpy.column_stack((-sign * sin, cos))
|
|
second = numpy.asarray((span, offset)) - first[::-1]
|
|
second[0] = first[-1]
|
|
second_normal = normal[::-1]
|
|
# Keep the radius fixed and extend the final tangent to the grid.
|
|
# An integer-span bend needs no extension.
|
|
if grid_span - span > TOLERANCE_LINEAR:
|
|
second = numpy.vstack((second, (grid_span, offset)))
|
|
second_normal = numpy.vstack((second_normal, (0, 1)))
|
|
else:
|
|
second[-1] = (grid_span, offset)
|
|
|
|
origin = numpy.asarray((start_port.x, start_port.y))
|
|
polygons = []
|
|
for centerline, normals in ((first, normal), (second, second_normal)):
|
|
edge = width / 2 * normals
|
|
points = numpy.concatenate((centerline + edge, (centerline - edge)[::-1]))
|
|
polygons.append(Polygon(points @ rotation.T + origin))
|
|
return polygons
|
|
|
|
@staticmethod
|
|
def generate(
|
|
start_port: Port,
|
|
offset: float,
|
|
radius: float,
|
|
width: float,
|
|
sagitta: float = 0.01,
|
|
collision_type: BendCollisionModelName = "arc",
|
|
outline: Polygon | None = None,
|
|
clip_margin: float | None = None,
|
|
dilation: float = 0.0,
|
|
) -> ComponentResult:
|
|
seed = SBendSeed(offset, radius)
|
|
offset, radius = seed.offset, seed.radius
|
|
sign = 1 if offset >= 0 else -1
|
|
theta = _sbend_angle(offset, radius)
|
|
end_port = component_endpoint(start_port, "sbend", (offset, radius))
|
|
dx = sbend_span(offset, radius)
|
|
grid_span = sbend_grid_span(offset, radius)
|
|
tail = grid_span - dx
|
|
rot2 = rotation_matrix2(start_port.r)
|
|
|
|
if outline is not None:
|
|
physical = _transform_custom_collision_polygon(outline, (start_port.x, start_port.y), start_port.r, mirror_y=False)
|
|
physical_geometry = geometry = [physical]
|
|
dilated_physical_geometry = dilated_collision_geometry = _buffer_geometry(physical_geometry, dilation)
|
|
else:
|
|
theta_deg = float(numpy.degrees(theta))
|
|
segments, dilated_segments = prepare_component_sampling(
|
|
"sbend", (offset, radius), width, collision_type=collision_type,
|
|
physical_geometry_type="arc", dilation=dilation, sagitta=sagitta,
|
|
)
|
|
physical_geometry = SBend._arcs(start_port, rot2, radius, offset, theta, dx, grid_span, width, segments)
|
|
if dilated_segments is not None:
|
|
dilated_physical_geometry = SBend._arcs(
|
|
start_port, rot2, radius, offset, theta, dx, grid_span, width + 2 * dilation, dilated_segments,
|
|
)
|
|
else:
|
|
dilated_physical_geometry = _buffer_geometry(physical_geometry, dilation)
|
|
if collision_type == "arc":
|
|
geometry, dilated_collision_geometry = physical_geometry, dilated_physical_geometry
|
|
else:
|
|
if not isinstance(collision_type, str):
|
|
raise TypeError("Custom S-bend geometry requires a complete outline")
|
|
origin = numpy.array((start_port.x, start_port.y))
|
|
center1 = rot2 @ numpy.array((0.0, sign * radius)) + origin
|
|
center2 = rot2 @ numpy.array((dx, offset - sign * radius)) + origin
|
|
center1_xy = (float(center1[0]), float(center1[1]))
|
|
center2_xy = (float(center2[0]), float(center2[1]))
|
|
ts1 = (float(start_port.r - sign * 90), float(start_port.r - sign * 90 + sign * theta_deg))
|
|
second_base = start_port.r + (90 if sign > 0 else 270)
|
|
ts2 = (float(second_base + sign * theta_deg), float(second_base))
|
|
arc1, arc2 = physical_geometry
|
|
geometry = [
|
|
_apply_collision_model(arc1, collision_type, radius, width, center1_xy, ts1, clip_margin=clip_margin)[0],
|
|
_apply_collision_model(
|
|
arc2, collision_type, radius, width, center2_xy, ts2, clip_margin=clip_margin,
|
|
tangent_extensions=(0, tail if tail > TOLERANCE_LINEAR else 0),
|
|
)[0],
|
|
]
|
|
dilated_collision_geometry = _buffer_geometry(geometry, dilation)
|
|
|
|
return ComponentResult(
|
|
start_port=start_port,
|
|
collision_geometry=geometry,
|
|
end_port=end_port,
|
|
length=2.0 * radius * theta + max(0.0, tail),
|
|
move_type="sbend",
|
|
move_spec=seed,
|
|
physical_geometry=physical_geometry,
|
|
dilated_collision_geometry=dilated_collision_geometry,
|
|
dilated_physical_geometry=dilated_physical_geometry,
|
|
width=width,
|
|
standard_faces=outline is None,
|
|
)
|
|
|
|
|
|
def build_component(
|
|
start: Port,
|
|
width: float,
|
|
kind: MoveKind,
|
|
parameters: tuple,
|
|
*,
|
|
collision_type: BendCollisionModel,
|
|
physical_geometry_type: BendPhysicalGeometry,
|
|
clip_margin: float | None,
|
|
dilation: float,
|
|
sbend_outline: Polygon | None = None,
|
|
physical_length: float | None = None,
|
|
bounds: tuple[float, float, float, float] | None = None,
|
|
) -> ComponentResult:
|
|
if bounds is not None and not uses_custom_outline(kind, physical_geometry_type, sbend_outline):
|
|
check_component_endpoint(start, kind, parameters, bounds)
|
|
if kind == "straight":
|
|
return Straight.generate(start, parameters[0], width, dilation=dilation)
|
|
if kind == "bend90":
|
|
component = Bend90.generate(
|
|
start, parameters[0], width, parameters[1],
|
|
collision_type=collision_type, physical_geometry_type=physical_geometry_type, clip_margin=clip_margin, dilation=dilation,
|
|
)
|
|
else:
|
|
component = SBend.generate(
|
|
start, parameters[0], parameters[1], width,
|
|
collision_type="arc" if isinstance(collision_type, Polygon) else collision_type,
|
|
outline=sbend_outline, clip_margin=clip_margin, dilation=dilation,
|
|
)
|
|
return replace(component, length=physical_length) if physical_length is not None else component
|