brokkr_kitbash.hose: clearance measured between readings, the roll range swept by bins, legs searched with room for their bends (cut kit-hose, h2)
route.measure replaces sampling at half a voxel: a reading answers for its piece less half the piece's length, pieces are halved to 1 mm, so no plate stands unseen between two readings and no measurement depends on step. route.passes measures a range, not a list of rolls: each roll answers for a bin by what a point can move within it (rho x half width), the bend at the pin has one radius through a bin with its dip added to the need, and a bin that falls short is halved down to 0.3 degrees. A leg is searched and pulled with 0.29 of the floor beyond need where a way has it: a line pulled at need grazed what it wrapped and left its corner an accidental room that changed with step. A corner under the floor says what limits it; a refusal names the sagged and the taut attempt; another hose through the same pin is an obstacle where it stands and is not measured across the rolls as if rigid. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
parent
336f94de54
commit
b21e745d2e
4 changed files with 366 additions and 135 deletions
|
|
@ -54,7 +54,8 @@ scene's clearance, pulled taut, sagged a little, filleted, verified, and turned
|
|||
cross) and core.sweep owns every tube, ferrule and clamp. A hose is a bake of the scene at the call: posing or moving a
|
||||
part leaves it stale until hose runs again on its name. It is one object: where it crosses a pin it is meant to be
|
||||
skinned between the bones on either side, and this package writes no weights. kit_hose on it is the request, kept as
|
||||
a record: nothing reads it to decide geometry, and hose is its one writer.
|
||||
a record: hose is its one writer, and the one thing read back from it is which two parts a hose joins, by a later hose
|
||||
that crosses the same pin (it bends with the pin, so it is measured as an obstacle where it stands and not across the rolls).
|
||||
|
||||
Connections are a tree. A loop (a brace from one branch to another) is closed by a closure: three ID properties
|
||||
on the closing part, kit_close_socket, kit_close_to (a pointer to the other part) and kit_close_to_socket. close
|
||||
|
|
@ -96,12 +97,13 @@ LONGERONS_LIMIT = 16 # longerons in one ribs
|
|||
SHELL = "kit_shell" # on a shell: the request its cage is derived from, as JSON; its presence admits a rebuild, and nothing reads it to decide geometry
|
||||
SUBSURF, SOLIDIFY = "Kit Subsurf", "Kit Solidify" # a shell's own modifiers, in that order, before any of its Booleans and the Kit Bevel
|
||||
SHELL_FACES_LIMIT = 262144 # faces of a shell's subdivided surface: cage quads times 4 to the levels
|
||||
HOSE = "kit_hose" # on a hose: the request it was routed from, as JSON; its presence admits a rebuild, and nothing reads it to decide geometry
|
||||
HOSE = "kit_hose" # on a hose: the request it was routed from, as JSON; its presence admits a rebuild, and another hose reads its two ends to know that it crosses the same pin
|
||||
HOSE_CLAMPS = 8 # clamps in one hose: each is one more leg to search
|
||||
HOSE_VOXELS = 2 ** 19 # voxels of one leg's search box: 1.8 s of capped nearest-face queries at 3.4 us each
|
||||
HOSE_MARGIN = 0.25 # metres a leg's search box reaches beyond its two ends: the room a way around an obstacle between them has
|
||||
HOSE_SEGMENTS = 12 # sides of a hose, a ferrule and a clamp's pad
|
||||
ROLL_STEP = 5.0 # degrees between the rolls of a joint's range that hose measures: the step an assembly's clearance is read at
|
||||
ROLL_STEP = 5.0 # degrees between the rolls of a joint's range that hose measures first: the step an assembly's clearance is read at
|
||||
ROLL_FINEST = 0.3 # degrees: the half width under which a bin of rolls that falls short is refused instead of halved (5 degrees halved 4 times)
|
||||
|
||||
|
||||
def kit_work(work):
|
||||
|
|
@ -1484,11 +1486,12 @@ class BROKKR_KITBASH_OT_hose(PolishOperator):
|
|||
raise Refused(f"clamps cross the pin of {child.name!r} {len(changes)} times: list them in order along the hose, those on the start's side of the pin first; nothing changed.")
|
||||
pin = {"origin": axis[:3, 3], "axis": axis[:3, 2], "current": current, "before": changes[0], "child": child, "child_first": sides[0],
|
||||
"point": on["matrix"][:3, 3] + on["matrix"][:3, 2] * joint["standoff"]}
|
||||
rest, moved = self.trees(start["depsgraph"], hose, pin and pin["child"])
|
||||
rest, moved, through = self.trees(start["depsgraph"], hose, pin and pin["child"], kits)
|
||||
reach = need + 2.0 * floor + self.step
|
||||
occupied = self.reader((rest, moved), need + route.REACH * self.step)
|
||||
far, far_rest, far_moved = self.reader((rest, moved), reach), self.reader((rest,), reach), self.reader((moved,), reach)
|
||||
room = lambda a, b: float(far(route.along(a, b, self.step / 2.0)).min()) - need # noqa: E731
|
||||
roomy = route.BEND * floor # room beyond need a leg is searched with: what the arc of a quarter turn at the floor takes
|
||||
occupied = self.reader((rest, moved, through), need + roomy + route.REACH * self.step)
|
||||
far, far_rest, far_moved = self.reader((rest, moved, through), reach), self.reader((rest,), reach), self.reader((moved,), reach)
|
||||
room = lambda a, b: route.room(a, b, far, need) # noqa: E731
|
||||
exempt = max(lead, need) # a bundle wider than its lead stands on its own port's face that far
|
||||
stand = sizes["envelope"] + self.clearance + r # a clamped bundle's centre line above the socket's face: its pad is one radius thick
|
||||
held = 2.0 * 2.0 * r + floor
|
||||
|
|
@ -1502,18 +1505,25 @@ class BROKKR_KITBASH_OT_hose(PolishOperator):
|
|||
into, out = point, point
|
||||
if kind == "clamp":
|
||||
into, out = sorted((point - y * held, point + y * held), key=lambda p: float(np.linalg.norm(p - at)))
|
||||
pulled, voxels = route.leg(at, into, occupied, far, need, self.step, HOSE_MARGIN, HOSE_VOXELS, f"leg {len(legs) + 1} ({came} to {label})")
|
||||
name = f"leg {len(legs) + 1} ({came} to {label})"
|
||||
for pad in (roomy, 0.0): # with room for its bends where a way with that room exists; a clamp stands nearer its seat than that
|
||||
try:
|
||||
pulled, voxels = route.leg(at, into, occupied, far, need, self.step, HOSE_MARGIN, HOSE_VOXELS, name, pad)
|
||||
break
|
||||
except route.RouteError:
|
||||
if pad <= 0.0:
|
||||
raise
|
||||
legs.append((pulled, voxels, kind, out))
|
||||
at, came = out, label
|
||||
shaped, refusal = None, None
|
||||
shaped, refusals = None, []
|
||||
for depth in dict.fromkeys((self.sag * 2.0 * r, 0.0)): # slack yields to clearance: a route the sag breaks is made taut
|
||||
try:
|
||||
shaped = self.shaped(legs, start, end, depth, room, far, far_rest, far_moved, pin, joint, need, floor, lead, exempt, 4.0 * 2.0 * r) # a clamp keeps 2 outside diameters of straight each side of its point
|
||||
break
|
||||
except route.RouteError as error:
|
||||
refusal = refusal or error
|
||||
if shaped is None:
|
||||
raise refusal
|
||||
refusals.append(("sagged" if depth > 0.0 else "taut", str(error)))
|
||||
if shaped is None: # both attempts are named: the taut one is the one sag 0 would make
|
||||
raise route.RouteError(refusals[0][1] if len({text for _, text in refusals}) == 1 else "; ".join(f"{how}: {text}" for how, text in refusals))
|
||||
curve, made, sagged, least, swing = shaped
|
||||
built = self.built(curve, start, clamps, stand, r, sizes["spread"], half_width)
|
||||
except route.RouteError as error:
|
||||
|
|
@ -1616,12 +1626,15 @@ class BROKKR_KITBASH_OT_hose(PolishOperator):
|
|||
pins.append((child, socket[0], stated[2]))
|
||||
return pins
|
||||
|
||||
def trees(self, depsgraph, hose, child):
|
||||
"""(a tree of every mesh the depsgraph evaluates but this hose and the pin's child side, a tree of the child
|
||||
side: the objects whose parent chain passes `child`), in world space; None for a side with no face. Membership
|
||||
of the depsgraph is what makes a mesh an obstacle: no flag or name is read. Only evaluated meshes are read: no
|
||||
datablock is made or freed."""
|
||||
sides = ([], [])
|
||||
def trees(self, depsgraph, hose, child, kits):
|
||||
"""(a tree of every mesh the depsgraph evaluates but this hose, the pin's child side and the hoses through
|
||||
the pin; a tree of the child side: the objects whose parent chain passes `child`; a tree of the other hoses
|
||||
that cross the pin of `child`), in world space; None for a side with no face. Membership of the depsgraph is
|
||||
what makes a mesh an obstacle: no flag or name is read for that. A hose through the same pin bends with it and
|
||||
belongs to neither side: it is an obstacle where it stands (the first two trees and it are what a route keeps
|
||||
clear of), and across the rolls each hose is measured against the parts of the two sides, not against where
|
||||
the other hose stood. Only evaluated meshes are read: no datablock is made or freed."""
|
||||
sides = ([], [], [])
|
||||
for evaluated in depsgraph.objects:
|
||||
source = evaluated.original
|
||||
if evaluated.type != "MESH" or source == hose or not len(evaluated.data.polygons):
|
||||
|
|
@ -1632,7 +1645,7 @@ class BROKKR_KITBASH_OT_hose(PolishOperator):
|
|||
mesh.calc_loop_triangles()
|
||||
corners = np.zeros(3 * len(mesh.loop_triangles), dtype=np.int32)
|
||||
mesh.loop_triangles.foreach_get("vertices", corners)
|
||||
sides[child is not None and child in self.chain(source)].append((points.reshape(-1, 3) @ world[:3, :3].T + world[:3, 3], corners.reshape(-1, 3)))
|
||||
sides[2 if child is not None and self.through(source, child, kits) else int(child is not None and child in self.chain(source))].append((points.reshape(-1, 3) @ world[:3, :3].T + world[:3, 3], corners.reshape(-1, 3)))
|
||||
made = []
|
||||
for side in sides:
|
||||
offsets = np.cumsum([0] + [len(points) for points, _ in side[:-1]])
|
||||
|
|
@ -1640,6 +1653,15 @@ class BROKKR_KITBASH_OT_hose(PolishOperator):
|
|||
if side else None)
|
||||
return made
|
||||
|
||||
def through(self, source, child, kits) -> bool:
|
||||
"""Whether an object is a hose whose two stated ends stand on the two sides of the pin of `child`."""
|
||||
try:
|
||||
stated = json.loads(source.get(HOSE, "null"))
|
||||
ends = [bpy.data.objects.get(text if text in bpy.data.objects else text.rsplit(":", 1)[0]) for text in (stated["start"], stated["end"])]
|
||||
except (ValueError, TypeError, KeyError, AttributeError):
|
||||
return False
|
||||
return None not in ends and any(found[0] == child for found in self.crossed(ends[0], ends[1], kits))
|
||||
|
||||
@staticmethod
|
||||
def reader(trees, cap: float):
|
||||
"""A route distance over trees: how far each point stands from the nearest face, no further than cap (a capped
|
||||
|
|
@ -1658,7 +1680,8 @@ class BROKKR_KITBASH_OT_hose(PolishOperator):
|
|||
def shaped(self, legs, start, end, depth, room, far, far_rest, far_moved, pin, joint, need, floor, lead, exempt, kept):
|
||||
"""(curve, its fillet, the metres each leg sagged, the least distance outside the leads, the joint's passes or
|
||||
None) of the legs joined at one sag depth: one polyline from port to port, one fillet, one verification, and
|
||||
with a pin every roll of its range from the range's low to its high every ROLL_STEP degrees."""
|
||||
with a pin its whole range: the rolls from the range's low to its high every ROLL_STEP degrees, each answering
|
||||
for the rolls about it, and more between them where one falls short (route.passes)."""
|
||||
points, keep, centred, sagged, j, last = [start["matrix"][:3, 3]], [], [], [], None, None
|
||||
for pulled, _, kind, _ in legs:
|
||||
hung, drop = route.sag(pulled, depth, room)
|
||||
|
|
@ -1675,12 +1698,12 @@ class BROKKR_KITBASH_OT_hose(PolishOperator):
|
|||
centred.append(False)
|
||||
points = np.array(points)
|
||||
made = route.fillet(points, room, floor, lead, keep, centred)
|
||||
least = route.verify(made.curve, far, need, exempt, self.step / 2.0)
|
||||
least = route.verify(made.curve, far, need, exempt)
|
||||
swing = None
|
||||
if pin is not None:
|
||||
order = slice(None, None, -1) if pin["child_first"] else slice(None) # passes reads a polyline from the parent's side
|
||||
swing = route.passes(points[order], made.t[order], (len(points) - 1 - j) if pin["child_first"] else j, pin["origin"], pin["axis"],
|
||||
route.rolls_of(joint["range"][0], joint["range"][1], ROLL_STEP), pin["current"], far_rest, far_moved, need, floor, exempt, self.step / 2.0,
|
||||
route.rolls_of(joint["range"][0], joint["range"][1], ROLL_STEP), ROLL_FINEST, pin["current"], far_rest, far_moved, need, floor, exempt,
|
||||
keep=np.array(keep)[order])
|
||||
return made.curve, made, sagged, least, swing
|
||||
|
||||
|
|
|
|||
|
|
@ -784,7 +784,7 @@
|
|||
},
|
||||
{
|
||||
"name": "brokkr_kitbash.hose",
|
||||
"doc": "Route a bundle of hoses between two sockets, around every mesh Blender evaluates in the scene. start and end are 'Object:socket' on a kit part (a hose or flange socket no narrower than the bundle) or 'Object' alone, an empty whose z the hose leaves along. A leg runs between each pair of waypoints (a fitting's lead end, each clamp, the pin point): it is searched on a voxel grid of its ends' box plus 0.25 m (at most 524288 voxels), pulled taut, and the whole polyline is rounded, each corner by the largest arc its measured room allows; the innermost hose's bend radius is at least bend outside diameters, and a fitting keeps a straight of 8 radii (a ferrule, then 1.5 outside diameters). The centre line keeps the bundle's half width plus clearance from every other mesh, other hoses included, outside those leads. sag hangs the middle of each free span by that many outside diameters, never by more than half the room measured along the span; a route the sag breaks is made taut instead (sag in the report reads 0). clamps is a JSON array of up to 8 {\"socket\": \"Object:socket\"}, mount sockets in order along the hose: the bundle runs straight over each, along the socket's y, and gets a pad and a strap. A hose may cross one pin (a pivot connection between its ends' parts): joint is then {\"socket\": \"Object:socket\", \"standoff\": metres, \"range\": [lo, hi]}, a socket on that pin's axis whose z runs along it; the hose passes through the point standoff beyond it, so each side's straights move with their own part and only the bend at that point changes. Every roll from lo to hi in steps of 5 degrees is measured, each side against the other side's parts where the roll puts them, without posing anything. The hose is one mesh object, a child of the start's object, and a bake of the scene at the call: after a part moves or rolls, run hose again on its name to rebuild it in place. Where it crosses a pin it is meant to be skinned between the bones on either side; no weights are written. Refuses before it writes anything, naming the leg, corner, point or roll. Reports object, rebuilt, hoses, length, lengthChange (over the range, of the centre line as each roll rounds it), floor, clearance (least beyond the bundle, outside the leads; readings stop at capped), voxels per leg, sag per leg in metres, rolls, worstRoll, worstClearance, faces, volume, nonManifoldEdges and radii {least, corners}.",
|
||||
"doc": "Route a bundle of hoses between two sockets, around every mesh Blender evaluates in the scene. start and end are 'Object:socket' on a kit part (a hose or flange socket no narrower than the bundle) or 'Object' alone, an empty whose z the hose leaves along. A leg runs between each pair of waypoints (a fitting's lead end, each clamp, the pin point): it is searched on a voxel grid of its ends' box plus 0.25 m (at most 524288 voxels), pulled taut with room for its bends where a way has it, and the whole polyline is rounded, each corner by the largest arc its measured room allows; the innermost hose's bend radius is at least bend outside diameters, and a fitting keeps a straight of 8 radii (a ferrule, then 1.5 outside diameters). The centre line keeps the bundle's half width plus clearance from every other mesh, other hoses included, outside those leads. sag hangs the middle of each free span by that many outside diameters, never by more than half the room measured along the span; a route the sag breaks is made taut instead (sag in the report reads 0). clamps is a JSON array of up to 8 {\"socket\": \"Object:socket\"}, mount sockets in order along the hose: the bundle runs straight over each, along the socket's y, and gets a pad and a strap. A hose may cross one pin (a pivot connection between its ends' parts): joint is then {\"socket\": \"Object:socket\", \"standoff\": metres, \"range\": [lo, hi]}, a socket on that pin's axis whose z runs along it; the hose passes through the point standoff beyond it, so each side's straights move with their own part and only the bend at that point changes. The whole range from lo to hi is measured without posing anything, each side against the other side's parts: a roll every 5 degrees answers for the rolls about it by what a point can move within them, and more are measured between where that falls short; another hose through the same pin is kept clear of where it stands, not across the rolls. Every line is measured so that nothing thinner than a spacing can stand between two readings, whatever the step. The hose is one mesh object, a child of the start's object, and a bake of the scene at the call: after a part moves or rolls, run hose again on its name to rebuild it in place. Where it crosses a pin it is meant to be skinned between the bones on either side; no weights are written. Refuses before it writes anything, naming the leg, corner, point or roll. Reports object, rebuilt, hoses, length, lengthChange (over the range, of the centre line as each roll rounds it), floor, clearance (least beyond the bundle, outside the leads; readings stop at capped), voxels per leg, sag per leg in metres, rolls (how many were measured), worstRoll, worstClearance (least over the range, each reading less what its point can move within its roll's bin), faces, volume, nonManifoldEdges and radii {least, corners}.",
|
||||
"changesScene": true,
|
||||
"editModeSafe": false,
|
||||
"result": "brokkr_mesh_polish_result",
|
||||
|
|
|
|||
|
|
@ -7,10 +7,13 @@ obstacle: the bundle's half width plus its clearance.
|
|||
|
||||
A leg between two waypoints is searched on a voxel grid of the box around them (grid, wavefront), then pulled taut
|
||||
(pull). A voxel is free when it stands need plus half a voxel's diagonal from every obstacle: distance changes by at
|
||||
most the distance moved, so every point of a step between two neighbouring free voxels keeps need. The legs joined are
|
||||
one polyline; fillet rounds its corners, each by the largest arc its measured room allows, and verify measures the
|
||||
curve. sag lowers the middle of a leg by what its room allows. passes turns the part of a polyline beyond a point on
|
||||
a pin's axis through the pin's rolls and measures each. frames gives the rotation-minimising ups the tubes are swept
|
||||
most the distance moved, so every point of a step between two neighbouring free voxels keeps need. The same bound is
|
||||
what every measurement of a line rests on (measure): a reading answers for the piece around it, less half the piece's
|
||||
length, and pieces are halved until that proves need, so nothing thinner than the spacing of some samples can stand
|
||||
unseen between them; no measurement depends on the search's step. The legs joined are one polyline; fillet rounds its
|
||||
corners, each by the largest arc its measured room allows, and verify measures the curve. sag lowers the middle of a leg
|
||||
by what its room allows. passes turns the part of a polyline beyond a point on a pin's axis through the pin's rolls,
|
||||
each roll answering for the rolls about it by what a point can move within them. frames gives the rotation-minimising ups the tubes are swept
|
||||
with (Wang, Juettler, Zheng and Liu, "Computation of rotation minimizing frames", ACM TOG 27(1), 2008: the double
|
||||
reflection method).
|
||||
|
||||
|
|
@ -32,6 +35,8 @@ NEIGHBOURS = [(i, j, k) for i in (-1, 0, 1) for j in (-1, 0, 1) for k in (-1, 0,
|
|||
REACH = math.sqrt(3.0) / 2.0 # of a voxel: how far a point of a step between two neighbouring voxels can stand from the nearer one
|
||||
STRAIGHT = 1e-9 # radians: a corner that turns less is no corner
|
||||
HELD = 1e-9 # metres under need that a reading may stand and hold it
|
||||
FINE = 1e-3 # metres: the shortest piece measure halves to; a line must keep need by half of this to be proven
|
||||
BEND = 1.0 - math.cos(math.pi / 4.0) # of a radius: how far the arc of a quarter turn stands from its tangent segments
|
||||
ARC = 24 # arc segments a radian of turn
|
||||
|
||||
|
||||
|
|
@ -105,43 +110,95 @@ def wavefront(free: np.ndarray, start, goal) -> list:
|
|||
return way
|
||||
|
||||
|
||||
def along(a, b, spacing: float) -> np.ndarray:
|
||||
"""Points from a to b, both included, no further apart than spacing."""
|
||||
a, b = np.asarray(a, dtype=np.float64), np.asarray(b, dtype=np.float64)
|
||||
count = max(2, int(math.ceil(float(np.linalg.norm(b - a)) / spacing)) + 1)
|
||||
return a[None] + (b - a)[None] * np.linspace(0.0, 1.0, count)[:, None]
|
||||
class Measured(NamedTuple):
|
||||
least: float # the least reading taken; of a measure that fell short, the reading that fell short
|
||||
where: np.ndarray # the point it was taken at
|
||||
short: bool # a piece is not proven to keep need
|
||||
|
||||
|
||||
def clear(a, b, distance, need: float, spacing: float) -> bool:
|
||||
return bool((np.asarray(distance(along(a, b, spacing))) >= need - HELD).all())
|
||||
def measure(a, b, distance, need: float, rate: float = 1.0, within: float | None = None) -> Measured:
|
||||
"""The segments a[i]..b[i] measured so that what stands between two readings is bounded, not sampled. A piece's
|
||||
middle reads d, and a reading changes by at most `rate` times the distance moved (1 for a distance to obstacles),
|
||||
so every point of a piece of length L reads at least d - rate x L / 2. A piece whose bound holds need is proven;
|
||||
one whose middle reads under need falls short; any other is halved, down to FINE, where a piece still unproven
|
||||
falls short too: a measure that is not short has proven need of every point, and a line that keeps need by under
|
||||
rate x FINE / 2 is refused with the ones that do not keep it. With `within`, pieces are halved further until each
|
||||
one's bound is within that much of the least reading (or the piece is FINE long): least less `within` then bounds
|
||||
every point from below."""
|
||||
a, b = np.atleast_2d(np.asarray(a, dtype=np.float64)), np.atleast_2d(np.asarray(b, dtype=np.float64))
|
||||
least, where = math.inf, None
|
||||
while len(a):
|
||||
middle, length = (a + b) / 2.0, np.linalg.norm(b - a, axis=1)
|
||||
reads = np.asarray(distance(middle), dtype=np.float64)
|
||||
bound = reads - rate * length / 2.0
|
||||
unproven = bound < need - HELD
|
||||
short = np.flatnonzero(unproven & ((reads < need - HELD) | (length <= FINE)))
|
||||
if len(short):
|
||||
worst = int(short[np.argmin(reads[short])])
|
||||
return Measured(float(reads[worst]), middle[worst], True)
|
||||
if reads.min() < least:
|
||||
least, where = float(reads.min()), middle[int(np.argmin(reads))]
|
||||
again = unproven if within is None else unproven | ((bound < least - within) & (length > FINE))
|
||||
a, b = np.concatenate([a[again], middle[again]]), np.concatenate([middle[again], b[again]])
|
||||
return Measured(least, where, False)
|
||||
|
||||
|
||||
def pull(points, distance, need: float, spacing: float) -> np.ndarray:
|
||||
"""A polyline pulled taut: from each kept point, the farthest later point in clear sight (need kept at samples no
|
||||
further apart than spacing); the next point when none is."""
|
||||
def falls(reading: float, need: float) -> str:
|
||||
"""How a reading that fell short of need reads in a refusal."""
|
||||
return (f"under the {need:.4g} m the bundle needs" if reading < need - HELD else
|
||||
f"too near the {need:.4g} m the bundle needs to prove it of what stands between two readings")
|
||||
|
||||
|
||||
def clear(a, b, distance, need: float, rate: float = 1.0) -> bool:
|
||||
return not measure(a, b, distance, need, rate).short
|
||||
|
||||
|
||||
def room(a, b, distance, need: float) -> float:
|
||||
"""What every point of the segment a..b stands beyond need, less what verify needs to prove an arc that uses it
|
||||
all: the least reading of a measure within FINE, less FINE for its bound and half of FINE more."""
|
||||
return measure(a, b, distance, -math.inf, within=FINE).least - need - 1.5 * FINE
|
||||
|
||||
|
||||
def span(curve, low: float, high: float) -> np.ndarray:
|
||||
"""The part of a polyline between two lengths along it; no point when low is not under high."""
|
||||
curve = np.asarray(curve, dtype=np.float64)
|
||||
s = np.r_[0.0, np.cumsum(np.linalg.norm(np.diff(curve, axis=0), axis=1))]
|
||||
low, high = max(low, 0.0), min(high, float(s[-1]))
|
||||
if not low < high:
|
||||
return curve[:0]
|
||||
ends = np.stack([np.interp((low, high), s, curve[:, axis]) for axis in range(3)], axis=1)
|
||||
return np.vstack([ends[:1], curve[(s > low) & (s < high)], ends[1:]])
|
||||
|
||||
|
||||
def pull(points, distance, need: float, rate: float = 1.0) -> np.ndarray:
|
||||
"""A polyline pulled taut: from each kept point, the farthest later point in clear sight (the line between them
|
||||
swept at need); the next point when none is."""
|
||||
points = np.asarray(points, dtype=np.float64)
|
||||
kept, i = [points[0]], 0
|
||||
while i < len(points) - 1:
|
||||
j = len(points) - 1
|
||||
while j > i + 1 and not clear(points[i], points[j], distance, need, spacing):
|
||||
while j > i + 1 and not clear(points[i], points[j], distance, need, rate):
|
||||
j -= 1
|
||||
kept.append(points[j])
|
||||
i = j
|
||||
return np.array(kept)
|
||||
|
||||
|
||||
def leg(a, b, occupancy, distance, need: float, step: float, margin: float, limit: int, name: str):
|
||||
def leg(a, b, occupancy, distance, need: float, step: float, margin: float, limit: int, name: str, pad: float = 0.0):
|
||||
"""(the pulled polyline from a to b, the voxels searched): a grid over the two ends' box plus margin, free where
|
||||
`occupancy` reads need plus REACH of a voxel, a wavefront between the free voxels beside the ends, pulled at need
|
||||
against `distance`. Refuses, naming the leg: an end nearer an obstacle than need, an end with no free voxel in
|
||||
sight beside it, a box over the limit, and no way through."""
|
||||
`occupancy` reads need plus pad plus REACH of a voxel, a wavefront between the free voxels beside the ends, pulled
|
||||
against `distance`. `pad` is room kept beyond need for the bends the leg's corners will get: a line pulled at
|
||||
need alone grazes what it wraps, and the corner there has no room for an arc. Within twice pad of an end the pull
|
||||
asks for half the distance from that end instead, since an end stands where it is given. Refuses, naming the
|
||||
leg: an end nearer an obstacle than need, an end with no free voxel in sight beside it, a box over the limit, and
|
||||
no way through."""
|
||||
a, b = np.asarray(a, dtype=np.float64), np.asarray(b, dtype=np.float64)
|
||||
for label, point in (("start", a), ("end", b)):
|
||||
reads = float(np.asarray(distance(point[None]))[0])
|
||||
if reads < need - HELD:
|
||||
raise RouteError(f"{name}: its {label} {spot(point)} stands {reads:.4g} m from an obstacle, under the {need:.4g} m the bundle needs")
|
||||
try:
|
||||
cells = grid(np.minimum(a, b) - margin, np.maximum(a, b) + margin, step, occupancy, need + REACH * step, limit)
|
||||
cells = grid(np.minimum(a, b) - margin, np.maximum(a, b) + margin, step, occupancy, need + pad + REACH * step, limit)
|
||||
except RouteError as error:
|
||||
raise RouteError(f"{name}: {error}") from None
|
||||
ends = []
|
||||
|
|
@ -150,15 +207,16 @@ def leg(a, b, occupancy, distance, need: float, step: float, margin: float, limi
|
|||
beside = [tuple(int(v) for v in middle + np.array(d)) for d in [(0, 0, 0)] + NEIGHBOURS]
|
||||
beside = [m for m in beside if all(0 <= m[axis] < cells.free.shape[axis] for axis in range(3)) and cells.free[m]]
|
||||
beside.sort(key=lambda m: float(np.linalg.norm(cells.lo + step * np.array(m) - point)))
|
||||
seen = [m for m in beside if clear(point, cells.lo + step * np.array(m), distance, need, step / 2.0)]
|
||||
seen = [m for m in beside if clear(point, cells.lo + step * np.array(m), distance, need)]
|
||||
if not seen:
|
||||
raise RouteError(f"{name}: no free voxel stands in sight of its {label} {spot(point)}: an obstacle is nearer it than {need + REACH * step:.4g} m on every side")
|
||||
raise RouteError(f"{name}: no free voxel stands in sight of its {label} {spot(point)}: an obstacle is nearer it than {need + pad + REACH * step:.4g} m on every side")
|
||||
ends.append(seen[0])
|
||||
try:
|
||||
way = wavefront(cells.free, ends[0], ends[1])
|
||||
except RouteError as error:
|
||||
raise RouteError(f"{name}: {error}") from None
|
||||
return pull(np.vstack([a[None], cells.lo + step * np.array(way, dtype=np.float64), b[None]]), distance, need, step / 2.0), int(cells.free.size)
|
||||
padded = distance if pad <= 0.0 else lambda p: np.asarray(distance(p)) - np.minimum(pad, 0.5 * np.minimum(np.linalg.norm(p - a, axis=1), np.linalg.norm(p - b, axis=1)))
|
||||
return pull(np.vstack([a[None], cells.lo + step * np.array(way, dtype=np.float64), b[None]]), padded, need, 1.0 if pad <= 0.0 else 1.5), int(cells.free.size)
|
||||
|
||||
|
||||
def sag(points, depth: float, room, down=(0.0, 0.0, -1.0)):
|
||||
|
|
@ -285,37 +343,35 @@ def fillet(polyline, room, floor: float, lead: float, keep=None, centred=None) -
|
|||
under = np.flatnonzero(radii < floor * (1.0 - 1e-9))
|
||||
if len(under):
|
||||
c = int(under[np.argmin(radii[under])])
|
||||
raise RouteError(f"corner {c + 1} at {spot(polyline[c + 1])} turns {math.degrees(turn[c]):.1f} degrees and gets a bend of radius {radii[c]:.4g} m, under the floor {floor:.4g}: "
|
||||
"its segments are too short or an obstacle stands too near it")
|
||||
lengths, unit, _ = _turns(polyline)
|
||||
free = np.maximum(lengths - _kept(len(lengths), lead, keep), 0.0)
|
||||
each = np.where(np.zeros(len(lengths), dtype=bool) if centred is None else np.asarray(centred, dtype=bool), free / 2.0, free)
|
||||
straight, tangent, depth = float(min(each[c], each[c + 1])), floor * math.tan(turn[c] / 2.0), floor * (1.0 - math.cos(turn[c] / 2.0))
|
||||
if straight < tangent:
|
||||
why = (f"the bundle is too stiff for this route: the corner's segments leave {straight:.4g} m of straight for the {tangent:.4g} m its tangent takes at the floor "
|
||||
"(a lower bend, thinner hoses, or ends, clamps and the pin point further apart)")
|
||||
elif room is not None and _radius(polyline[c + 1], unit[c], unit[c + 1], float(turn[c]), straight, room) < floor * (1.0 - 1e-9):
|
||||
stands = min(room(polyline[c + 1] - unit[c] * tangent, polyline[c + 1]), room(polyline[c + 1], polyline[c + 1] + unit[c + 1] * tangent))
|
||||
why = (f"the route passes too near an obstacle to bend here: its segments stand {max(stands, 0.0):.4g} m clear beyond what the bundle needs and the arc at the floor takes {depth:.4g} "
|
||||
"(a lower bend, more room about the obstacle, or a clamp that leads the hose wide of it)")
|
||||
else:
|
||||
why = "it shares a segment with the corner beside it and their tangents do not both fit on it (a lower bend, or the two further apart)"
|
||||
raise RouteError(f"corner {c + 1} at {spot(polyline[c + 1])} turns {math.degrees(turn[c]):.1f} degrees and gets a bend of radius {radii[c]:.4g} m, under the floor {floor:.4g}: {why}")
|
||||
return Filleted(*arcs(polyline, t), t, radii)
|
||||
|
||||
|
||||
def samples(curve, spacing: float):
|
||||
"""(points, arc length at each) along a polyline, its own points included, no further apart than spacing."""
|
||||
curve = np.asarray(curve, dtype=np.float64)
|
||||
lengths = np.linalg.norm(np.diff(curve, axis=0), axis=1)
|
||||
starts = np.r_[0.0, np.cumsum(lengths)]
|
||||
points, s = [curve[:1]], [np.zeros(1)]
|
||||
for i, length in enumerate(lengths):
|
||||
count = max(1, int(math.ceil(length / spacing)))
|
||||
f = np.arange(1, count + 1) / count
|
||||
points.append(curve[i][None] + (curve[i + 1] - curve[i])[None] * f[:, None])
|
||||
s.append(starts[i] + length * f)
|
||||
return np.vstack(points), np.concatenate(s)
|
||||
|
||||
|
||||
def verify(curve, distance, need: float, lead: float, spacing: float, name: str = "the hose") -> float:
|
||||
def verify(curve, distance, need: float, lead: float, name: str = "the hose") -> float:
|
||||
"""The least distance the curve stands from an obstacle outside its two leads (the first and last `lead` of its
|
||||
length, where it leaves its own ports). Refuses a reading under need, naming the point."""
|
||||
points, s = samples(curve, spacing)
|
||||
inside = (s >= lead) & (s <= s[-1] - lead)
|
||||
if not inside.any():
|
||||
length, where it leaves its own ports), within half of FINE (measure). Refuses a curve not proven to keep need at
|
||||
every point, naming the point."""
|
||||
curve = np.asarray(curve, dtype=np.float64)
|
||||
inside = span(curve, lead, float(np.linalg.norm(np.diff(curve, axis=0), axis=1).sum()) - lead)
|
||||
if len(inside) < 2:
|
||||
return math.inf
|
||||
reads = np.asarray(distance(points[inside]))
|
||||
worst = int(np.argmin(reads))
|
||||
if reads[worst] < need - HELD:
|
||||
raise RouteError(f"{name} stands {float(reads[worst]):.4g} m from an obstacle at {spot(points[inside][worst])}, under the {need:.4g} m the bundle needs")
|
||||
return float(reads[worst])
|
||||
swept = measure(inside[:-1], inside[1:], distance, need, within=FINE / 2.0)
|
||||
if swept.short:
|
||||
raise RouteError(f"{name} stands {swept.least:.4g} m from an obstacle at {spot(swept.where)}, {falls(swept.least, need)}")
|
||||
return swept.least
|
||||
|
||||
|
||||
def thinned(curve, gap: float) -> np.ndarray:
|
||||
|
|
@ -371,42 +427,93 @@ def rolls_of(low: float, high: float, step: float) -> list:
|
|||
return [float(v) for v in np.arange(low, high - 1e-9, step)] + [float(high)]
|
||||
|
||||
|
||||
def passes(polyline, t, j: int, origin, axis, rolls, current: float, parent, child, need: float, floor: float, lead: float, spacing: float, keep=None) -> dict:
|
||||
"""A hose through a pin's rolls. `polyline` runs from the parent's side through point j, which stands on the
|
||||
pin's axis (origin, axis), to the child's side; `t` are its tangent lengths at the roll `current`. At each roll
|
||||
the points beyond j are turned about the axis by roll - current, as the child's parts are: the straights on each
|
||||
side move with their own part, and only the corner at j is rounded again, its neighbours' tangents as they were.
|
||||
The parent's side is then measured against the child's obstacles turned (`child` reads the child's parts where
|
||||
they stand at `current`, so the samples are turned back), the child's side against the parent's (`parent`), and the
|
||||
arc at j against both, all outside the leads. Refuses a roll whose bend at the pin is under the floor or whose
|
||||
reading is under need, naming the roll, the side and the reading. {rolls, worstRoll, least, lengthChange, radius}."""
|
||||
def passes(polyline, t, j: int, origin, axis, rolls, finest: float, current: float, parent, child, need: float, floor: float, lead: float, keep=None) -> dict:
|
||||
"""A hose through a pin's rolls, every roll between the first and last of `rolls` and not those alone. `polyline`
|
||||
runs from the parent's side through point j, which stands on the pin's axis (origin, axis), to the child's side;
|
||||
`t` are its tangent lengths at the roll `current`. The points beyond j turn about the axis with the child's parts
|
||||
and the straights and bends on each side move with their own part; only the corner at j is rounded again.
|
||||
|
||||
Each roll of `rolls` answers for a bin: the rolls nearer it than any other. Within a bin of half width w a point
|
||||
that stands rho from the axis moves at most rho x w against the other side's parts, so its reading against them
|
||||
counts for that much less (`parent` and `child` read each side's parts where they stand at `current`; samples are
|
||||
turned back for the child's). The bend at the pin has one radius through a bin, the largest that fits at the bin's
|
||||
sharpest turn: its arc then stands within radius x (1 - cos(turn / 2)) of its two tangent segments, which are swept
|
||||
for need and that much more. Everything else outside the leads is swept for need (measure). A bin that falls short
|
||||
is halved and measured at each half's middle, down to `finest` degrees of half width, where it is refused, naming
|
||||
the roll, the side, the point and the reading; so is a bin whose bend at the pin has no room for the floor.
|
||||
{rolls: how many were measured, worstRoll, least: the least reading, each less what its point moves within its
|
||||
bin, lengthChange, radius}."""
|
||||
polyline, origin = np.asarray(polyline, dtype=np.float64), np.asarray(origin, dtype=np.float64)
|
||||
axis = np.asarray(axis, dtype=np.float64) / np.linalg.norm(axis)
|
||||
c, least, lengths, radius = j - 1, (math.inf, None), [], math.inf
|
||||
kept = _kept(len(polyline) - 1, lead, keep)
|
||||
for roll in rolls:
|
||||
off = float(np.linalg.norm(np.cross(polyline[j] - origin, axis)))
|
||||
if off > 1e-6: # a point counted wrong (a sag's point before it, say) would turn the hose about a point it does not pass
|
||||
raise RouteError(f"point {j} {spot(polyline[j])} of the hose stands {off:.4g} m off the pin's axis: the hose passes the pin at a point on it")
|
||||
kept, sharp = _kept(len(polyline) - 1, lead, keep), np.array(t, dtype=np.float64)
|
||||
sharp[c] = 0.0
|
||||
rolls = [float(v) for v in rolls]
|
||||
edges = [rolls[0]] + [(u + v) / 2.0 for u, v in zip(rolls, rolls[1:])] + [rolls[-1]]
|
||||
bins = [(edges[k + 1], edges[k], roll) for k, roll in reversed(list(enumerate(rolls)))] # a stack: the lowest roll is measured first
|
||||
while bins:
|
||||
high, low, roll = bins.pop()
|
||||
half = max(high - roll, roll - low)
|
||||
width = math.radians(half)
|
||||
posed = np.vstack([polyline[:j + 1], turned(polyline[j + 1:], origin, axis, roll - current)])
|
||||
back = lambda points, roll=roll: turned(points, origin, axis, current - roll) # noqa: E731
|
||||
both = lambda points, back=back: np.minimum(np.asarray(parent(points)), np.asarray(child(back(points)))) # noqa: E731
|
||||
moves = lambda points: np.linalg.norm(np.cross(points - origin, axis), axis=1) * width # noqa: E731
|
||||
sides = {"parent's side": lambda p: np.minimum(np.asarray(parent(p)), np.asarray(child(back(p))) - moves(p)),
|
||||
"child's side": lambda p: np.minimum(np.asarray(child(back(p))), np.asarray(parent(p)) - moves(p))}
|
||||
lengths_, unit, turn = _turns(posed)
|
||||
t_roll = np.array(t, dtype=np.float64)
|
||||
t_roll[c] = 0.0
|
||||
if turn[c] >= STRAIGHT:
|
||||
cap = min(lengths_[c] - kept[c] - (t_roll[c - 1] if c > 0 else 0.0), lengths_[c + 1] - kept[c + 1] - (t_roll[c + 1] if c + 1 < len(t_roll) else 0.0))
|
||||
bend = _radius(posed[j], unit[c], unit[c + 1], float(turn[c]), float(cap), lambda a, b, both=both: float(both(along(a, b, spacing)).min()) - need)
|
||||
if bend < floor * (1.0 - 1e-9):
|
||||
raise RouteError(f"roll {roll:g}: the bend at the pin turns {math.degrees(turn[c]):.1f} degrees and gets radius {bend:.4g} m, under the floor {floor:.4g}")
|
||||
t_roll[c], radius = bend * math.tan(turn[c] / 2.0), min(radius, bend)
|
||||
curve, owner = arcs(posed, t_roll)
|
||||
points, s = samples(curve, spacing)
|
||||
at = np.r_[0.0, np.cumsum(np.linalg.norm(np.diff(curve, axis=0), axis=1))][owner == c]
|
||||
inside = (s >= lead) & (s <= s[-1] - lead)
|
||||
for side, chosen, reads in (("parent's side", inside & (s < at[0]), lambda p, back=back: np.asarray(child(back(p)))),
|
||||
("child's side", inside & (s > at[-1]), parent),
|
||||
("bend at the pin", inside & (s >= at[0]) & (s <= at[-1]), both)):
|
||||
if chosen.any():
|
||||
reading = float(np.asarray(reads(points[chosen])).min())
|
||||
if reading < need - HELD:
|
||||
raise RouteError(f"roll {roll:g}: the hose's {side} stands {reading:.4g} m from the parts on the other side of the pin, under the {need:.4g} m the bundle needs")
|
||||
least = min(least, (reading, float(roll)))
|
||||
lengths.append(float(s[-1]))
|
||||
corner, sharpest = posed[j], min(float(turn[c]) + width, math.pi - 1e-6)
|
||||
cap = min(lengths_[c] - kept[c] - (sharp[c - 1] if c > 0 else 0.0), lengths_[c + 1] - kept[c + 1] - (sharp[c + 1] if c + 1 < len(sharp) else 0.0))
|
||||
|
||||
def fits(bend: float):
|
||||
"""None, or (side, the measure that fell short, the dip) of the bend's two tangent segments at the bin's sharpest turn."""
|
||||
reach, depth = bend * math.tan(sharpest / 2.0), bend * (1.0 - math.cos(sharpest / 2.0))
|
||||
for side, a, b in (("parent's side", corner - unit[c] * reach, corner), ("child's side", corner, corner + unit[c + 1] * reach)):
|
||||
swept = measure(a, b, sides[side], need + depth, 1.0 + width)
|
||||
if swept.short:
|
||||
return side, swept, depth
|
||||
return None
|
||||
|
||||
failed, bend, reach = None, math.inf, 0.0
|
||||
if sharpest >= STRAIGHT:
|
||||
most = max(cap, 0.0) / math.tan(sharpest / 2.0)
|
||||
if most < floor * (1.0 - 1e-9):
|
||||
failed = (f"the bend at the pin turns up to {math.degrees(sharpest):.1f} degrees and its segments leave room for a radius of {most:.4g} m, under the floor {floor:.4g}", None)
|
||||
else:
|
||||
short = fits(floor)
|
||||
if short is not None:
|
||||
failed = (f"the bend at the pin turns up to {math.degrees(sharpest):.1f} degrees and at the floor radius {floor:.4g} its arc can dip {short[2]:.4g} m; "
|
||||
f"the hose's {short[0]} beside it", short[1], need + short[2])
|
||||
else:
|
||||
bend, high_ = floor, most
|
||||
for _ in range(12 if fits(most) is not None else 0):
|
||||
middle = (bend + high_) / 2.0
|
||||
bend, high_ = (middle, high_) if fits(middle) is None else (bend, middle)
|
||||
bend = bend if high_ < most else most
|
||||
reach = bend * math.tan(sharpest / 2.0)
|
||||
curve, owner = arcs(posed, sharp)
|
||||
s = np.r_[0.0, np.cumsum(np.linalg.norm(np.diff(curve, axis=0), axis=1))]
|
||||
at = float(s[np.flatnonzero(owner == c)[0]])
|
||||
for side, part in (("parent's side", span(curve, lead, at - reach)), ("child's side", span(curve, at + reach, float(s[-1]) - lead))):
|
||||
if failed is None and len(part) >= 2:
|
||||
swept = measure(part[:-1], part[1:], sides[side], need, 1.0 + width)
|
||||
if swept.short:
|
||||
failed = (f"the hose's {side}", swept, need)
|
||||
else:
|
||||
least = min(least, (swept.least, float(roll)))
|
||||
if failed is None:
|
||||
radius = min(radius, bend)
|
||||
lengths.append(float(s[-1]) + (0.0 if not math.isfinite(bend) else bend * (float(turn[c]) - 2.0 * math.tan(float(turn[c]) / 2.0))))
|
||||
continue
|
||||
if half > finest and high > low:
|
||||
bins += [(high, (low + high) / 2.0, (low + 3.0 * high) / 4.0), ((low + high) / 2.0, low, (3.0 * low + high) / 4.0)]
|
||||
continue
|
||||
through = f" through the {half:.3g} degrees either side of it" if half > 0.0 else ""
|
||||
if failed[1] is None:
|
||||
raise RouteError(f"roll {roll:.4g}: {failed[0]}{through}")
|
||||
swept, bar = failed[1], failed[2]
|
||||
raise RouteError(f"roll {roll:.4g}: {failed[0]} reads {swept.least:.4g} m from the parts about the pin at {spot(swept.where)}, counting the {float(moves(swept.where[None])[0]):.4g} m it can move against the other side's{through}: "
|
||||
f"{falls(swept.least, bar)}")
|
||||
return {"rolls": len(lengths), "worstRoll": least[1], "least": least[0], "lengthChange": max(lengths) - min(lengths), "radius": radius}
|
||||
|
|
|
|||
|
|
@ -46,8 +46,19 @@ def nothing(points):
|
|||
return np.full(len(points), 10.0)
|
||||
|
||||
|
||||
def room_of(distance, need: float, spacing: float = 0.002):
|
||||
return lambda a, b: float(np.asarray(distance(route.along(a, b, spacing))).min()) - need
|
||||
def room_of(distance, need: float):
|
||||
return lambda a, b: route.room(a, b, distance, need)
|
||||
|
||||
|
||||
def dense(a, b, spacing: float):
|
||||
"""This test's own reading of a segment: points no further apart than spacing."""
|
||||
a, b = np.asarray(a, dtype=np.float64), np.asarray(b, dtype=np.float64)
|
||||
return a[None] + (b - a)[None] * np.linspace(0.0, 1.0, max(2, math.ceil(float(np.linalg.norm(b - a)) / spacing) + 1))[:, None]
|
||||
|
||||
|
||||
def slab(x: float, half: float):
|
||||
"""A plate across x, `half` thick each side of it."""
|
||||
return lambda points: np.maximum(np.abs(np.asarray(points, dtype=np.float64)[:, 0] - x) - half, 0.0)
|
||||
|
||||
|
||||
def length(points) -> float:
|
||||
|
|
@ -63,9 +74,9 @@ class SearchTests(unittest.TestCase):
|
|||
pulled, voxels = route.leg(a, b, distance, distance, NEED, 0.02, 0.3, 2 ** 19, "leg 1")
|
||||
self.assertEqual(voxels, 131 * 31 * 31)
|
||||
self.assertTrue(np.allclose(pulled[0], a) and np.allclose(pulled[-1], b))
|
||||
dense = np.vstack([route.along(p, q, 0.0025) for p, q in zip(pulled[:-1], pulled[1:])]) # a quarter of the spacing pull samples at
|
||||
self.assertGreaterEqual(float(distance(dense).min()), NEED - 1e-9)
|
||||
through = dense[np.abs(dense[:, 0] - 1.0) < 0.02]
|
||||
read = np.vstack([dense(p, q, 0.0025) for p, q in zip(pulled[:-1], pulled[1:])])
|
||||
self.assertGreaterEqual(float(distance(read).min()), NEED - 1e-9)
|
||||
through = read[np.abs(read[:, 0] - 1.0) < 0.02]
|
||||
self.assertTrue(len(through) and (np.hypot(through[:, 1] - 0.2, through[:, 2] - 0.2) < 0.12 - NEED + 1e-9).all())
|
||||
self.assertLess(length(pulled), 2.0 * math.hypot(1.0, 0.2 * math.sqrt(2.0)) + 0.05) # taut: near the two straights through the hole's middle
|
||||
|
||||
|
|
@ -76,10 +87,55 @@ class SearchTests(unittest.TestCase):
|
|||
for reach, holds in ((route.REACH, True), (0.0, False)):
|
||||
cells = route.grid([-0.1, -0.1, 0.0], [0.1, 0.1, 0.0], 0.02, rod, 0.043 + reach * 0.02)
|
||||
free = [np.array(m) for m in zip(*np.nonzero(cells.free))]
|
||||
least = min(float(rod(route.along(cells.lo + 0.02 * p, cells.lo + 0.02 * q, 0.001)).min())
|
||||
least = min(float(rod(dense(cells.lo + 0.02 * p, cells.lo + 0.02 * q, 0.001)).min())
|
||||
for p in free for q in free if 0 < np.abs(p - q).max() <= 1)
|
||||
self.assertEqual(least >= 0.043, holds, least)
|
||||
|
||||
def test_a_measure_proves_what_stands_between_its_readings(self):
|
||||
"""clearance-kept. Mutants M3 and M3b (verify and pull read at a spacing): a plate 1 mm thick stands between
|
||||
two readings 0.1 apart, each of which keeps need, and the line through it is refused by measure, by pull and by
|
||||
verify. The bound is a piece's reading less half its length: with the half length left out the first reading
|
||||
of the whole segment would prove it."""
|
||||
plate, a, b = slab(1.0, 0.0005), np.array([0.05, 0.0, 0.0]), np.array([1.85, 0.0, 0.0])
|
||||
self.assertGreaterEqual(float(plate(dense(a, b, 0.1)).min()), 0.04) # readings 0.1 apart straddle it: the nearest stands 0.0495 off
|
||||
swept = route.measure(a, b, plate, 0.01)
|
||||
self.assertTrue(swept.short and swept.least < 0.01 and abs(float(swept.where[0]) - 1.0) < 0.0105, swept)
|
||||
self.assertFalse(route.clear(a, b, plate, 0.01))
|
||||
self.assertTrue(route.clear(a, [0.98, 0.0, 0.0], plate, 0.01))
|
||||
over = np.array([a, [1.0, 0.0, 5.0], b]) # the plate ends nowhere: a pulled line keeps the point that leads round nothing, and is not shortened through it
|
||||
self.assertEqual(len(route.pull(over, lambda points: np.where(np.asarray(points)[:, 2] > 4.0, 10.0, plate(points)), 0.01)), 3)
|
||||
with self.assertRaisesRegex(route.RouteError, r"^the hose stands 0\.00\d+ m from an obstacle at \[(1|0\.99\d*|1\.00\d*), 0, 0\], under the 0\.01 m the bundle needs"):
|
||||
route.verify(np.array([a, b]), plate, 0.01, 0.0)
|
||||
ground = lambda points: np.asarray(points, dtype=np.float64)[:, 2] # noqa: E731
|
||||
along_ = lambda z: (np.array([0.0, 0.0, z]), np.array([1.0, 0.0, z])) # noqa: E731
|
||||
self.assertFalse(route.measure(*along_(0.01 + route.FINE), ground, 0.01).short) # a line that keeps need by FINE is proven
|
||||
grazing = route.measure(*along_(0.01 + route.FINE / 4.0), ground, 0.01) # one that keeps it by less than half of FINE is not, and is refused as that
|
||||
self.assertTrue(grazing.short and grazing.least >= 0.01)
|
||||
self.assertIn("too near the 0.01 m the bundle needs to prove it", route.falls(grazing.least, 0.01))
|
||||
slope = lambda points: 0.3 + np.abs(np.asarray(points, dtype=np.float64)[:, 0] - 0.7137) # noqa: E731
|
||||
self.assertLess(route.measure([0.0, 0, 0], [1.0, 0, 0], slope, 0.01).least - 0.3, 0.3) # proven at need by a few readings
|
||||
self.assertLess(route.measure([0.0, 0, 0], [1.0, 0, 0], slope, 0.01, within=route.FINE).least - 0.3, route.FINE) # the least itself, within the bound asked
|
||||
self.assertTrue(np.allclose(route.span(np.array([[0.0, 0, 0], [1.0, 0, 0], [1.0, 1.0, 0]]), 0.5, 1.5), [[0.5, 0, 0], [1.0, 0, 0], [1.0, 0.5, 0]]))
|
||||
self.assertEqual(len(route.span(np.array([[0.0, 0, 0], [1.0, 0, 0]]), 0.6, 0.4)), 0)
|
||||
|
||||
def test_a_leg_searched_with_room_keeps_it_where_it_wraps(self):
|
||||
"""A line pulled at need grazes what it wraps, and the corner there has no room for an arc: with pad the
|
||||
pulled line keeps need and pad of every point further than twice pad from its ends, and a corner's room is
|
||||
the pad instead of what the pull happened to leave."""
|
||||
distance, pad = ball([1.0, 0.0, 0.0], 0.3), 0.03
|
||||
a, b = np.array([0.0, 0.0, 0.0]), np.array([2.0, 0.0, 0.0])
|
||||
tight = route.leg(a, b, distance, distance, NEED, 0.02, 0.3, 2 ** 19, "leg 1")[0]
|
||||
roomy = route.leg(a, b, distance, distance, NEED, 0.02, 0.3, 2 ** 19, "leg 1", pad)[0]
|
||||
least = lambda line: float(distance(np.vstack([dense(p, q, 0.002) for p, q in zip(line[:-1], line[1:])])).min()) # noqa: E731
|
||||
self.assertLess(least(tight), NEED + 0.2 * pad)
|
||||
self.assertGreaterEqual(least(tight), NEED)
|
||||
self.assertGreaterEqual(least(roomy), NEED + pad)
|
||||
self.assertGreater(length(roomy), length(tight))
|
||||
near = np.array([0.66, 0.0, 0.0]) # an end that stands need from the ball has no voxel with that room beside it: the caller searches such a leg without
|
||||
with self.assertRaisesRegex(route.RouteError, r"^leg 1: no free voxel stands in sight of its start \[0\.66, 0, 0\]: an obstacle is nearer it than 0\.08732 m on every side"):
|
||||
route.leg(near, [0.0, 0.0, 0.0], distance, distance, NEED, 0.02, 0.3, 2 ** 19, "leg 1", pad)
|
||||
self.assertEqual(len(route.leg(near, [0.0, 0.0, 0.0], distance, distance, NEED, 0.02, 0.3, 2 ** 19, "leg 1")[0]), 2)
|
||||
|
||||
def test_a_closed_way_a_buried_end_and_a_box_too_fine_are_refused_by_name(self):
|
||||
distance = wall(0.03) # a hole narrower than the bundle
|
||||
ends = (np.array([0.0, 0.0, 0.0]), np.array([2.0, 0.0, 0.0]))
|
||||
|
|
@ -155,7 +211,7 @@ class FilletTests(unittest.TestCase):
|
|||
self.assertGreater(radius, 0.03 / depth) # more than the room at the segments' nearest points allows: the room is measured along the tangent segments only
|
||||
self.assertLess(radius, 0.25)
|
||||
arc = made.curve[made.owner == 0]
|
||||
self.assertGreaterEqual(float(distance(np.vstack([route.along(p, q, 0.001) for p, q in zip(arc[:-1], arc[1:])])).min()), 0.05)
|
||||
self.assertGreaterEqual(float(distance(np.vstack([dense(p, q, 0.001) for p, q in zip(arc[:-1], arc[1:])])).min()), 0.05)
|
||||
grown = route.arcs(points, np.array([t * 1.05]))[0] # the largest: 5 percent more breaks the rule
|
||||
t2 = t * 1.05
|
||||
self.assertGreater(t2 / math.tan(math.pi / 4.0) * depth, min(room(points[1] - np.array([1.0, 0.0, 0.0]) * t2, points[1]), room(points[1], points[1] + np.array([0.0, 1.0, 0.0]) * t2)))
|
||||
|
|
@ -163,14 +219,16 @@ class FilletTests(unittest.TestCase):
|
|||
free = route.fillet(points, None, 0.05, 0.0)
|
||||
self.assertAlmostEqual(float(free.radii[0]), 1.0, places=12)
|
||||
self.assertLess(float(distance(free.curve).min()), 0.0)
|
||||
self.assertGreaterEqual(route.verify(made.curve, distance, 0.05, 0.0, 0.002), 0.05)
|
||||
self.assertGreaterEqual(route.verify(made.curve, distance, 0.05, 0.0), 0.05)
|
||||
with self.assertRaisesRegex(route.RouteError, r"^the hose stands -0\.\d+ m from an obstacle at \[-0\.\d+, 0\.\d+, 0\], under the 0\.05 m"):
|
||||
route.verify(free.curve, distance, 0.05, 0.0, 0.002)
|
||||
route.verify(free.curve, distance, 0.05, 0.0)
|
||||
|
||||
def test_a_corner_under_the_floor_is_refused_by_name(self):
|
||||
with self.assertRaisesRegex(route.RouteError, r"^corner 1 at \[1, 0, 0\] turns 90\.0 degrees and gets a bend of radius 0\.15 m, under the floor 0\.5"):
|
||||
with self.assertRaisesRegex(route.RouteError, r"^corner 1 at \[1, 0, 0\] turns 90\.0 degrees and gets a bend of radius 0\.15 m, under the floor 0\.5: the bundle is too stiff for this route: "
|
||||
r"the corner's segments leave 0\.3 m of straight for the 0\.5 m its tangent takes at the floor"):
|
||||
route.fillet(self.ZIGZAG, None, 0.5, 0.2)
|
||||
with self.assertRaisesRegex(route.RouteError, r"^corner 1 at \[0, 0, 0\] turns 90\.0 degrees and gets a bend of radius 0\.00\d+ m, under the floor 0\.05"):
|
||||
with self.assertRaisesRegex(route.RouteError, r"^corner 1 at \[0, 0, 0\] turns 90\.0 degrees and gets a bend of radius 0(\.00\d+)? m, under the floor 0\.05: the route passes too near an obstacle to bend here: "
|
||||
r"its segments stand 0(\.00\d+)? m clear beyond what the bundle needs and the arc at the floor takes 0\.01464 "):
|
||||
route.fillet(np.array([[-1.0, 0.0, 0.0], [0.0, 0.0, 0.0], [0.0, 1.0, 0.0]]), room_of(ball([-0.05, 0.05, 0.0], 0.02), 0.05), 0.05, 0.0) # a ball in the corner
|
||||
|
||||
def test_the_floor_is_the_innermost_hose_s(self):
|
||||
|
|
@ -190,10 +248,10 @@ class FilletTests(unittest.TestCase):
|
|||
ground = lambda points: np.asarray(points, dtype=np.float64)[:, 2] # noqa: E731
|
||||
span = np.array([[0.0, 0.0, 0.1], [1.0, 0.0, 0.1]])
|
||||
hung, drop = route.sag(span, 0.1, room_of(ground, 0.05))
|
||||
self.assertAlmostEqual(drop, 0.025, places=12)
|
||||
self.assertTrue(np.allclose(hung[1], [0.5, 0.0, 0.075]))
|
||||
self.assertAlmostEqual(drop, 0.025 - 0.75 * route.FINE, places=12) # half the room: what the span stands beyond need, less what a measure cannot tell apart
|
||||
self.assertTrue(np.allclose(hung[1], [0.5, 0.0, 0.1 - drop]))
|
||||
made = route.fillet(np.vstack([[[0.0, 0.0, 0.5]], hung, [[1.0, 0.0, 0.5]]]), room_of(ground, 0.05), 0.01, 0.1)
|
||||
self.assertGreaterEqual(route.verify(made.curve, ground, 0.05, 0.1, 0.002), 0.05)
|
||||
self.assertGreaterEqual(route.verify(made.curve, ground, 0.05, 0.1), 0.05)
|
||||
self.assertGreater(float(made.radii[1]), 1.0) # a gentle arc, not a kink
|
||||
high, drop = route.sag(span + [0.0, 0.0, 1.0], 0.1, room_of(ground, 0.05))
|
||||
self.assertEqual((drop, len(high)), (0.1, 3))
|
||||
|
|
@ -256,7 +314,8 @@ class FrameTests(unittest.TestCase):
|
|||
class JointTests(unittest.TestCase):
|
||||
P = np.array([[0.5, 0.0, 1.0], [0.2, 0.0, 0.0], [0.5, 0.0, -1.0]]) # through a point on the x axis
|
||||
AXIS = (np.zeros(3), np.array([1.0, 0.0, 0.0]))
|
||||
SIZES = {"need": 0.05, "floor": 0.05, "lead": 0.1, "spacing": 0.01}
|
||||
SIZES = {"need": 0.05, "floor": 0.05, "lead": 0.1}
|
||||
FINEST = 0.3
|
||||
|
||||
def test_a_polyline_through_the_axis_keeps_its_length_at_every_roll(self):
|
||||
"""joint-passage."""
|
||||
|
|
@ -268,15 +327,24 @@ class JointTests(unittest.TestCase):
|
|||
self.assertAlmostEqual(length(posed), length(self.P), places=12)
|
||||
self.assertTrue(np.allclose(route.turned(np.array([[0.3, 1.0, 0.0]]), *self.AXIS, 90.0), [[0.3, 0.0, 1.0]])) # right-handed about +x
|
||||
t = route.fillet(self.P, None, 0.05, 0.1).t
|
||||
found = route.passes(self.P, t, 1, *self.AXIS, rolls, 0.0, nothing, nothing, **self.SIZES)
|
||||
self.assertEqual((found["rolls"], found["least"]), (27, 10.0))
|
||||
found = route.passes(self.P, t, 1, *self.AXIS, rolls, self.FINEST, 0.0, nothing, nothing, **self.SIZES)
|
||||
self.assertEqual(found["rolls"], 27)
|
||||
self.assertTrue(10.0 - 1.2 * math.radians(2.5) < found["least"] < 10.0, found) # a reading counts for less by what its point moves in half a step of the rolls
|
||||
hung = np.vstack([route.sag(self.P[:2], 0.05, None)[0], route.sag(self.P[1:], 0.05, None)[0][1:]]) # sag-with-joint: each side hangs, and the pin point is still the one turned about
|
||||
self.assertEqual(len(hung), 5)
|
||||
sagged = route.passes(hung, route.fillet(hung, None, 0.05, 0.1).t, 2, *self.AXIS, rolls, self.FINEST, 0.0, nothing, nothing, **self.SIZES)
|
||||
self.assertEqual(sagged["rolls"], 27)
|
||||
self.assertLess(sagged["lengthChange"], found["lengthChange"]) # the hanging spans turn with their sides: only the bend at the pin changes, and its segments are shorter
|
||||
with self.assertRaisesRegex(route.RouteError, r"^point 1 \[\S+, 0, \S+\] of the hose stands 0\.\d+ m off the pin's axis"):
|
||||
route.passes(hung, route.fillet(hung, None, 0.05, 0.1).t, 1, *self.AXIS, rolls, self.FINEST, 0.0, nothing, nothing, **self.SIZES)
|
||||
self.assertGreater(found["lengthChange"], 0.01) # the bend at the pin is what changes: each roll's is the largest arc its segments give
|
||||
self.assertLess(found["lengthChange"], length(self.P) * (1.0 - math.pi / 4.0) * 2.0) # no more than every corner's shortcut
|
||||
|
||||
def test_a_hairpin_roll_is_refused_by_name(self):
|
||||
t = route.fillet(self.P, None, 0.05, 0.1).t
|
||||
with self.assertRaisesRegex(route.RouteError, r"^roll 180: the bend at the pin turns 180\.0 degrees and gets radius \S+e-\d+ m, under the floor 0\.05"):
|
||||
route.passes(self.P, t, 1, *self.AXIS, [0.0, 90.0, 180.0], 0.0, nothing, nothing, **self.SIZES)
|
||||
with self.assertRaisesRegex(route.RouteError, r"^roll 1[67]\d(\.\d+)?: the bend at the pin turns up to 1\d\d\.\d degrees and its segments leave room for a radius of \S+ m, under the floor 0\.05 "
|
||||
r"through the 0\.\d+ degrees either side of it$"):
|
||||
route.passes(self.P, t, 1, *self.AXIS, [0.0, 90.0, 180.0], self.FINEST, 0.0, nothing, nothing, **self.SIZES)
|
||||
|
||||
def test_each_side_is_measured_against_the_other_where_the_roll_puts_it(self):
|
||||
"""Mutants H5 (the child's obstacles not turned with the roll) and H6 (the range checked at its ends only): a
|
||||
|
|
@ -284,19 +352,52 @@ class JointTests(unittest.TestCase):
|
|||
middle = (self.P[0] + self.P[1]) / 2.0
|
||||
child = ball(route.turned(middle[None], *self.AXIS, -45.0)[0], 0.05) # where it stands at roll 0
|
||||
t = route.fillet(self.P, None, 0.05, 0.1).t
|
||||
for ends in ([-90.0, 90.0], [0.0]):
|
||||
self.assertEqual(route.passes(self.P, t, 1, *self.AXIS, ends, 0.0, nothing, child, **self.SIZES)["rolls"], len(ends))
|
||||
with self.assertRaisesRegex(route.RouteError, r"^roll 35: the hose's parent's side stands 0\.0\d+ m from the parts on the other side of the pin, under the 0\.05 m"):
|
||||
route.passes(self.P, t, 1, *self.AXIS, route.rolls_of(-90.0, 90.0, 5.0), 0.0, nothing, child, **self.SIZES)
|
||||
self.assertEqual(route.passes(self.P, t, 1, *self.AXIS, [0.0], self.FINEST, 0.0, nothing, child, **self.SIZES)["rolls"], 1)
|
||||
for rolls in ([-90.0, 90.0], route.rolls_of(-90.0, 90.0, 5.0)): # the rolls given are where measuring starts, not all that is measured: the two ends find it as the 5 degree steps do
|
||||
with self.assertRaisesRegex(route.RouteError, r"^roll 3[34](\.\d+)?: the hose's parent's side reads 0\.0\d+ m from the parts about the pin at \[\S+, \S+, \S+\], counting the 0\.00\d+ m it can move "
|
||||
r"against the other side's through the 0\.\d+ degrees either side of it: "):
|
||||
route.passes(self.P, t, 1, *self.AXIS, rolls, self.FINEST, 0.0, nothing, child, **self.SIZES)
|
||||
seen = []
|
||||
route.passes(self.P, t, 1, *self.AXIS, [30.0], 10.0, nothing, lambda points: seen.append(np.array(points)) or nothing(points), **self.SIZES)
|
||||
route.passes(self.P, t, 1, *self.AXIS, [30.0], self.FINEST, 10.0, nothing, lambda points: seen.append(np.array(points)) or nothing(points), **self.SIZES)
|
||||
line = (self.P[1] - self.P[0]) / np.linalg.norm(self.P[1] - self.P[0])
|
||||
on = [points for points in seen if len(points) > 3 and np.abs(np.cross(route.turned(points, *self.AXIS, 20.0) - self.P[0], line)).max() < 1e-12]
|
||||
on = [points for points in seen if np.abs(np.cross(route.turned(points, *self.AXIS, 20.0) - self.P[0], line)).max() < 1e-12]
|
||||
self.assertTrue(on) # the parent's side was read turned back by roll - current: turned forward again it lies on its own segment
|
||||
self.assertTrue(all(np.abs(np.cross(points - self.P[0], line)).max() > 0.01 for points in on))
|
||||
self.assertTrue(any(np.linalg.norm(np.cross(points - self.P[0], line), axis=1).min() > 0.01 for points in on)) # and as read it lay off it
|
||||
parent = ball(route.turned(((self.P[1] + self.P[2]) / 2.0)[None], *self.AXIS, 45.0)[0], 0.05) # a part of the parent the child's side swings into
|
||||
with self.assertRaisesRegex(route.RouteError, r"^roll 35: the hose's child's side stands"):
|
||||
route.passes(self.P, t, 1, *self.AXIS, route.rolls_of(-90.0, 90.0, 5.0), 0.0, parent, nothing, **self.SIZES)
|
||||
with self.assertRaisesRegex(route.RouteError, r"^roll 3[34](\.\d+)?: the hose's child's side reads"):
|
||||
route.passes(self.P, t, 1, *self.AXIS, route.rolls_of(-90.0, 90.0, 5.0), self.FINEST, 0.0, parent, nothing, **self.SIZES)
|
||||
|
||||
def test_the_bend_at_the_pin_is_no_larger_than_its_room(self):
|
||||
"""A ball inside the bend at the pin that both of the corner's segments clear: the arc there takes the radius
|
||||
whose dip the segments' room allows, not the largest its segments give. Mutant R3 (the bend's tangent segments
|
||||
measured for need alone) rounds the corner under need of the ball."""
|
||||
inside = ball([0.28, 0.0, 0.0], 0.01)
|
||||
t = route.fillet(self.P, None, 0.05, 0.1).t
|
||||
self.assertGreater(float(inside(np.vstack([dense(self.P[0], self.P[1], 0.001), dense(self.P[1], self.P[2], 0.001)])).min()), 0.06)
|
||||
free = route.passes(self.P, t, 1, *self.AXIS, [0.0], self.FINEST, 0.0, nothing, nothing, **self.SIZES)["radius"]
|
||||
found = route.passes(self.P, t, 1, *self.AXIS, [0.0], self.FINEST, 0.0, inside, nothing, **self.SIZES)["radius"]
|
||||
self.assertGreater(free, 2.0)
|
||||
self.assertTrue(0.05 <= found < 0.5, found)
|
||||
turn = float(route._turns(self.P)[2][0])
|
||||
arc = route.arcs(self.P, np.array([found * math.tan(turn / 2.0)]))[0]
|
||||
self.assertGreaterEqual(float(inside(np.vstack([dense(p, q, 0.001) for p, q in zip(arc[:-1], arc[1:])])).min()), 0.05)
|
||||
self.assertLess(float(inside(route.arcs(self.P, np.array([free * math.tan(turn / 2.0)]))[0]).min()), 0.05) # the largest arc its segments give stands under need of the ball
|
||||
|
||||
def test_a_plate_between_two_rolls_is_found(self):
|
||||
"""range-sampled-not-swept. A part of the child 2 mm across that crosses the parent's side of the hose at roll
|
||||
17.5, half way between two rolls 5 degrees apart: at 15 and at 20 the hose reads 0.02 from it and keeps its
|
||||
need of 0.01, and the range is refused at a roll between them. Mutant R1 (a reading not lessened by what its
|
||||
point moves within its bin) accepts the range."""
|
||||
middle = (self.P[0] + self.P[1]) / 2.0
|
||||
child = ball(route.turned(middle[None], *self.AXIS, -17.5)[0], 0.001)
|
||||
t, sizes = route.fillet(self.P, None, 0.05, 0.1).t, {**self.SIZES, "need": 0.01}
|
||||
for roll in (15.0, 20.0):
|
||||
self.assertGreater(float(child(route.turned(dense(self.P[0], self.P[1], 0.0005), *self.AXIS, -roll)).min()), 0.02)
|
||||
self.assertEqual(route.passes(self.P, t, 1, *self.AXIS, [15.0], self.FINEST, 0.0, nothing, child, **sizes)["rolls"], 1) # one roll answers for itself alone
|
||||
with self.assertRaisesRegex(route.RouteError, r"^roll 1[5-9]\.\d+: the hose's parent's side reads"):
|
||||
route.passes(self.P, t, 1, *self.AXIS, route.rolls_of(-20.0, 20.0, 5.0), self.FINEST, 0.0, nothing, child, **sizes)
|
||||
clear_of = route.passes(self.P, t, 1, *self.AXIS, route.rolls_of(-20.0, 10.0, 5.0), self.FINEST, 0.0, nothing, child, **sizes)
|
||||
self.assertGreaterEqual(clear_of["rolls"], 7) # short of the plate the same range passes, with more rolls measured where the 5 degree bins fell short
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
|
|
|||
Loading…
Reference in a new issue