brokkr_kitbash.hose: a hose bundle routed between two sockets, clamped, through a pin's axis across its roll range (cut kit-hose)
The action is the bpy around route.py: ends and clamps from kit sockets, the crossed pin from the parent chain, obstacles from every evaluated mesh as two trees split at the pin, one mesh object swept by core.sweep. Each free span sags a little, bounded by its measured room, and a hose stays one object across a pin (ruling hose-slack-and-skinned). Row in brokkr_actions.json; tests/live/kitbash_hose.py and its result. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
parent
9352dd7736
commit
8150ad656a
7 changed files with 1191 additions and 5 deletions
|
|
@ -49,6 +49,13 @@ shell is the one writer of the mesh, its crease attributes and those two modifie
|
|||
object rewrites the mesh in place, leaving the object, its cutters, ribs, Booleans and material slots. shell
|
||||
evaluates nothing: Blender's own update after the action evaluates the plate once.
|
||||
|
||||
hose routes a bundle of hoses between two sockets. route.py owns the path (legs searched on a voxel grid of the
|
||||
scene's clearance, pulled taut, sagged a little, filleted, verified, and turned through the rolls of the one pin it may
|
||||
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.
|
||||
|
||||
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
|
||||
writes them, only when the two sockets already meet, and writes nothing else; detach clears them. Nothing here
|
||||
|
|
@ -73,7 +80,7 @@ try:
|
|||
except ImportError as error: # register() says so; the classes below only need something to subclass
|
||||
RESULT, PolishOperator, Refused, mesh_object, MISSING = "brokkr_mesh_polish_result", bpy.types.Operator, RuntimeError, None, error
|
||||
|
||||
from . import core
|
||||
from . import core, route
|
||||
|
||||
KIT, PART, PARAMS = "kit_kit", "kit_part", "kit_params"
|
||||
SOCKET, PARENT_SOCKET, ROLL, BAKED = "kit_socket", "kit_parent_socket", "kit_roll", "kit_baked"
|
||||
|
|
@ -89,6 +96,12 @@ 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_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
|
||||
|
||||
|
||||
def kit_work(work):
|
||||
|
|
@ -1405,6 +1418,308 @@ class BROKKR_KITBASH_OT_shell(PolishOperator):
|
|||
evaluated.to_mesh_clear()
|
||||
|
||||
|
||||
class BROKKR_KITBASH_OT_hose(PolishOperator):
|
||||
"""Route a bundle of hoses between two sockets around every mesh in the scene, through clamps on mount sockets and
|
||||
through a point on a pin's axis across the pin's roll range; on an object that is already a hose, rebuild it in
|
||||
place"""
|
||||
bl_idname = "brokkr_kitbash.hose"
|
||||
bl_label = "Route A Hose"
|
||||
object_name: bpy.props.StringProperty(name="Object", description="The hose's name: a new object, or a hose to rebuild")
|
||||
start: bpy.props.StringProperty(name="Start", description="'Object:socket', a hose or flange socket of a kit part; or 'Object', an empty whose z the hose leaves along")
|
||||
end: bpy.props.StringProperty(name="End", description="As start")
|
||||
count: bpy.props.IntProperty(name="Count", default=1, min=1, max=8, description="Hoses in the bundle, side by side")
|
||||
radius: bpy.props.FloatProperty(name="Radius", default=0.01, min=0.0029, max=0.1, description="A hose's outside radius")
|
||||
spread: bpy.props.FloatProperty(name="Spread", default=0.0, min=0.0, max=0.5, description="Centre to centre between hoses; 0: 2.6 radii")
|
||||
clearance: bpy.props.FloatProperty(name="Clearance", default=0.01, min=0.0, max=0.5, description="Free space kept between the bundle and every other mesh")
|
||||
bend: bpy.props.FloatProperty(name="Bend", default=4.0, min=1.0, max=20.0, description="Least bend radius of the innermost hose, in outside diameters")
|
||||
step: bpy.props.FloatProperty(name="Step", default=0.02, min=0.0049, max=0.2, description="Voxel size of the search")
|
||||
sag: bpy.props.FloatProperty(name="Sag", default=1.0, min=0.0, max=8.0, description="How far the middle of each free span hangs, in outside diameters; 0: taut")
|
||||
clamps: bpy.props.StringProperty(name="Clamps", default="[]", description="A JSON array of up to 8 {socket: 'Object:socket'}, mount sockets, in order along the hose")
|
||||
joint: bpy.props.StringProperty(name="Joint", default="", description="Empty, or a JSON object {socket, standoff, range: [lo, hi]}: the pin the hose crosses")
|
||||
|
||||
# the action table states radius from 0.003 and step from 0.005: a float property rounds those up, so its bounds stand just under
|
||||
@kit_work
|
||||
def work(self, context):
|
||||
if not 1 <= len(self.object_name) <= 63:
|
||||
raise Refused(f"object_name {self.object_name!r} must be 1 to 63 characters; nothing changed.")
|
||||
hose = bpy.data.objects.get(self.object_name)
|
||||
if hose is not None:
|
||||
if hose.type != "MESH" or HOSE not in hose:
|
||||
raise Refused(f"An object named {hose.name!r} exists and is no hose (it carries no {HOSE}): hose rebuilds only what hose made; nothing changed.")
|
||||
own_mesh(hose, "rebuilding")
|
||||
sizes = route.bundle(self.count, self.radius, self.spread, self.clearance, self.bend)
|
||||
r, need, floor, lead, half_width = self.radius, sizes["need"], sizes["floor"], sizes["lead"], sizes["envelope"] - self.radius
|
||||
kits = {}
|
||||
start, end = (self.frame(context, text, what, ("hose", "flange"), kits, True) for text, what in ((self.start, "start"), (self.end, "end")))
|
||||
for what, port in (("start", start), ("end", end)):
|
||||
if port["size"] is not None and sizes["width"] > port["size"] * (1.0 + core.SLACK):
|
||||
raise Refused(f"{what}: a bundle of {self.count} hoses is {sizes['width']:.6g} m wide, over socket {port['name']!r} ({port['type']}, size {port['size']:.6g}): "
|
||||
"use fewer or thinner hoses, a smaller spread, or a larger port; nothing changed.")
|
||||
clamp_rows, joint = self.rows()
|
||||
clamps = [self.frame(context, row, f"clamps[{index}]", ("mount",), kits) for index, row in enumerate(clamp_rows)]
|
||||
pins, pin = self.crossed(start["object"], end["object"], kits), None
|
||||
if joint is None and pins:
|
||||
raise Refused(f"The hose crosses the pin of {pins[0][0].name!r} on {pins[0][0].parent.name!r} (socket {pins[0][1]['name']!r}): give joint, a socket on that pin's axis, "
|
||||
"a standoff and the roll range; nothing changed.")
|
||||
if joint is not None and len(pins) != 1:
|
||||
raise Refused(("joint is given and the hose crosses no pin: its ends are on parts no pivot connection stands between" if not pins else
|
||||
f"The hose crosses {len(pins)} pins ({', '.join(repr(child.name) + ' on ' + repr(child.parent.name) for child, _, _ in pins)}): a hose crosses one; "
|
||||
"end it on a part between them and route the next from there") + "; nothing changed.")
|
||||
if pins:
|
||||
child, socket, current = pins[0]
|
||||
if current is None:
|
||||
raise Refused(f"{child.name!r} on {child.parent.name!r}: its {ROLL} is not a number: detach it and attach it again; nothing changed.")
|
||||
on = self.frame(context, joint["socket"], "joint.socket", None, kits)
|
||||
axis = np.array(child.parent.matrix_world) @ socket["matrix"]
|
||||
off = float(np.linalg.norm(np.cross(on["matrix"][:3, 3] - axis[:3, 3], axis[:3, 2])))
|
||||
lean = float(np.linalg.norm(np.cross(on["matrix"][:3, 2], axis[:3, 2])))
|
||||
if off > 1e-6 or lean > 1e-6:
|
||||
raise Refused(f"joint.socket {on['name']!r} is not on the axis of the pin the hose crosses ({child.name!r} on {child.parent.name!r}, socket {socket['name']!r}): "
|
||||
f"its origin stands {off:.6g} m off the axis and its z leans {math.degrees(math.asin(min(1.0, lean))):.6g} degrees from it; nothing changed.")
|
||||
if not joint["range"][0] - 1e-9 <= current <= joint["range"][1] + 1e-9:
|
||||
raise Refused(f"{child.name!r} stands at roll {current:.6g}, outside joint.range {joint['range']}: the range holds the pose the hose is routed at; nothing changed.")
|
||||
sides = [child in self.chain(stop["object"]) for stop in (start, *clamps, end)]
|
||||
changes = [index for index in range(len(sides) - 1) if sides[index] != sides[index + 1]]
|
||||
if len(changes) != 1:
|
||||
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"])
|
||||
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
|
||||
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
|
||||
try:
|
||||
ends = [port["matrix"][:3, 3] + port["matrix"][:3, 2] * (lead + floor) for port in (start, end)] # a leg starts where the first bend has its floor's length of straight behind it
|
||||
stops = [("clamp", f"clamps[{index}]", clamp["matrix"][:3, 3] + clamp["matrix"][:3, 2] * stand, clamp["matrix"][:3, 1]) for index, clamp in enumerate(clamps)]
|
||||
if pin is not None:
|
||||
stops.insert(pin["before"], ("pin", "the pin", pin["point"], None))
|
||||
legs, at, came = [], ends[0], "start"
|
||||
for kind, label, point, y in stops + [("end", "end", ends[1], None)]:
|
||||
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})")
|
||||
legs.append((pulled, voxels, kind, out))
|
||||
at, came = out, label
|
||||
shaped, refusal = None, 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
|
||||
curve, made, sagged, least, swing = shaped
|
||||
built = self.built(curve, start, clamps, stand, r, sizes["spread"], half_width)
|
||||
except route.RouteError as error:
|
||||
raise Refused(f"{error}; nothing changed.") from None
|
||||
world = np.array(start["object"].matrix_world)
|
||||
built = built._replace(V=(built.V - world[:3, 3]) @ world[:3, :3]) # into the start's object's frame: the hose is its child
|
||||
rebuilt = hose is not None
|
||||
if rebuilt:
|
||||
mesh = hose.data
|
||||
mesh.clear_geometry()
|
||||
else:
|
||||
mesh = bpy.data.meshes.new(self.object_name)
|
||||
write_mesh(mesh, built)
|
||||
if not rebuilt:
|
||||
hose = bpy.data.objects.new(self.object_name, mesh)
|
||||
context.scene.collection.objects.link(hose)
|
||||
hose.parent = start["object"]
|
||||
hose.matrix_world = start["object"].matrix_world.copy() # read by a report; no depsgraph update here
|
||||
seat(hose, np.eye(4))
|
||||
hose[HOSE] = json.dumps({"object_name": self.object_name, "start": self.start, "end": self.end, "count": self.count, "radius": self.radius, "spread": self.spread,
|
||||
"clearance": self.clearance, "bend": self.bend, "step": self.step, "sag": self.sag, "clamps": json.loads(self.clamps),
|
||||
"joint": json.loads(self.joint) if self.joint else None})
|
||||
radii = made.radii[np.isfinite(made.radii)]
|
||||
report = {"object": hose.name, "rebuilt": rebuilt, "hoses": self.count, "length": round(float(np.linalg.norm(np.diff(curve, axis=0), axis=1).sum()), 6),
|
||||
"lengthChange": None if swing is None else round(swing["lengthChange"], 6), "floor": round(floor, 6),
|
||||
"clearance": None if not math.isfinite(least) else round(least - sizes["envelope"], 6), "capped": round(reach - sizes["envelope"], 6),
|
||||
"voxels": [voxels for _, voxels, _, _ in legs], "sag": [round(drop, 6) for drop in sagged],
|
||||
"rolls": None if swing is None else swing["rolls"], "worstRoll": None if swing is None else swing["worstRoll"],
|
||||
"worstClearance": None if swing is None or not math.isfinite(swing["least"]) else round(swing["least"] - sizes["envelope"], 6), **measured(mesh)}
|
||||
report["radii"] = {"least": round(float(radii.min()), 6) if len(radii) else None}
|
||||
report["radii"]["corners"] = fitted(report, "corners", [round(float(v), 6) for v in radii])
|
||||
return report
|
||||
|
||||
@staticmethod
|
||||
def chain(obj) -> list:
|
||||
"""An object and its parents, nearest first."""
|
||||
found = []
|
||||
while obj is not None:
|
||||
found.append(obj)
|
||||
obj = obj.parent
|
||||
return found
|
||||
|
||||
@staticmethod
|
||||
def frame(context, text: str, what: str, kinds, kits, loose: bool = False) -> dict:
|
||||
"""What a hose reads at 'Object:socket': {object, matrix (the socket's world frame), size, type, name, depsgraph}.
|
||||
The socket is a kit part's, of one of `kinds` (any when None); with `loose`, 'Object' alone names an empty and
|
||||
its own frame. Refuses a name with no object, a part that is scaled (rigid), a socket the part does not have or
|
||||
of another type, and an object Blender does not evaluate."""
|
||||
name, socket = (text, "") if text in bpy.data.objects or ":" not in text else text.rsplit(":", 1)
|
||||
obj = bpy.data.objects.get(name)
|
||||
if obj is None:
|
||||
raise Refused(f"{what}: no object named {name!r}; nothing changed.")
|
||||
if not socket:
|
||||
if not loose or obj.type != "EMPTY":
|
||||
raise Refused(f"{what} {text!r} names no socket: give 'Object:socket'" + (", or an empty whose z the hose leaves along" if loose else "") + "; nothing changed.")
|
||||
rigid(obj)
|
||||
return {"object": obj, "matrix": np.array(obj.matrix_world), "size": None, "type": "empty", "name": text, "depsgraph": evaluable(context, obj)[0]}
|
||||
part, built = built_part(obj, kits)
|
||||
found = [s for s in built.sockets if s["name"] == socket]
|
||||
if not found:
|
||||
raise Refused(f"{what}: {obj.name!r} (a {part['name']}) has no socket {socket!r}; its sockets: {', '.join(s['name'] for s in built.sockets) or 'none'}; nothing changed.")
|
||||
if kinds is not None and found[0]["type"] not in kinds:
|
||||
raise Refused(f"{what}: socket {socket!r} of {obj.name!r} is a {found[0]['type']} socket; this takes a {' or '.join(kinds)} socket; nothing changed.")
|
||||
return {"object": obj, "matrix": np.array(obj.matrix_world) @ found[0]["matrix"], "size": found[0]["size"], "type": found[0]["type"], "name": text,
|
||||
"depsgraph": evaluable(context, obj)[0]}
|
||||
|
||||
def rows(self):
|
||||
"""(the clamps' 'Object:socket' texts, the joint as {socket, standoff, range} or None), each refused by shape."""
|
||||
try:
|
||||
clamps, joint = json.loads(self.clamps or "[]"), json.loads(self.joint) if self.joint else None
|
||||
except ValueError as error:
|
||||
raise Refused(f"clamps and joint must be JSON ({error}); nothing changed.") from None
|
||||
if not isinstance(clamps, list) or len(clamps) > HOSE_CLAMPS:
|
||||
raise Refused(f"clamps must be a JSON array of 0 to {HOSE_CLAMPS} objects; nothing changed.")
|
||||
for index, row in enumerate(clamps):
|
||||
if not isinstance(row, dict) or set(row) != {"socket"} or not isinstance(row["socket"], str):
|
||||
raise Refused(f"clamps[{index}] must be an object of socket, an 'Object:socket' text; nothing changed.")
|
||||
if joint is not None:
|
||||
span = joint.get("range") if isinstance(joint, dict) else None
|
||||
if (not isinstance(joint, dict) or set(joint) != {"socket", "standoff", "range"} or not isinstance(joint["socket"], str)
|
||||
or not (core.finite(joint["standoff"]) and 0.0 <= joint["standoff"] <= 10.0)
|
||||
or not (isinstance(span, list) and len(span) == 2 and all(core.finite(v) and -360.0 <= v <= 360.0 for v in span) and 0.0 <= span[1] - span[0] <= 360.0)):
|
||||
raise Refused("joint must be an object of socket (an 'Object:socket' text), standoff (0 to 10) and range ([lo, hi] in degrees, lo to hi at most 360, each within 360 of 0); nothing changed.")
|
||||
return [row["socket"] for row in clamps], joint
|
||||
|
||||
def crossed(self, start, end, kits) -> list:
|
||||
"""The pins between two objects, [(child, the parent's pivot socket, roll)]: a connection is a child's parent
|
||||
pointer and its kit_parent_socket (link), and it is a pin when that socket is a pivot. Read along both parent
|
||||
chains up to the first object they share; with none shared, along both whole chains."""
|
||||
up, down = self.chain(start), self.chain(end)
|
||||
shared = [obj for obj in up if obj in down]
|
||||
between = up[:up.index(shared[0])] + down[:down.index(shared[0])] if shared else up + down
|
||||
pins = []
|
||||
for child in between:
|
||||
stated = link(child)
|
||||
if stated is None or child.parent is None or PART not in child.parent:
|
||||
continue
|
||||
socket = [s for s in built_part(child.parent, kits)[1].sockets if s["name"] == stated[1] and s["type"] == "pivot"]
|
||||
if socket:
|
||||
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 = ([], [])
|
||||
for evaluated in depsgraph.objects:
|
||||
source = evaluated.original
|
||||
if evaluated.type != "MESH" or source == hose or not len(evaluated.data.polygons):
|
||||
continue
|
||||
mesh, world = evaluated.data, np.array(evaluated.matrix_world)
|
||||
points = np.zeros(3 * len(mesh.vertices))
|
||||
mesh.vertices.foreach_get("co", points)
|
||||
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)))
|
||||
made = []
|
||||
for side in sides:
|
||||
offsets = np.cumsum([0] + [len(points) for points, _ in side[:-1]])
|
||||
made.append(BVHTree.FromPolygons(np.vstack([points for points, _ in side]).tolist(), np.vstack([corners + offset for (_, corners), offset in zip(side, offsets)]).tolist())
|
||||
if side else None)
|
||||
return made
|
||||
|
||||
@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
|
||||
find_nearest costs 3.4 us on 82,000 faces where an uncapped one costs 100)."""
|
||||
def distance(points):
|
||||
out = np.full(len(points), cap)
|
||||
for tree in trees:
|
||||
if tree is not None:
|
||||
for index, point in enumerate(np.asarray(points, dtype=np.float64).tolist()):
|
||||
found = tree.find_nearest(point, cap)[3]
|
||||
if found is not None and found < out[index]:
|
||||
out[index] = found
|
||||
return out
|
||||
return distance
|
||||
|
||||
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."""
|
||||
points, keep, centred, sagged, j, last = [start["matrix"][:3, 3]], [], [], [], None, None
|
||||
for pulled, _, kind, _ in legs:
|
||||
hung, drop = route.sag(pulled, depth, room)
|
||||
sagged.append(drop)
|
||||
hung = hung[1:] if last == "pin" else hung # a leg from the pin point starts on the point the last one ended on
|
||||
points += list(hung)
|
||||
keep += [kept if last == "clamp" else 0.0] + [0.0] * (len(hung) - 1) # a leg from a clamp starts at the far end of the clamp's straight
|
||||
centred += [last == "clamp"] + [False] * (len(hung) - 1)
|
||||
if kind == "pin":
|
||||
j = len(points) - 1
|
||||
last = kind
|
||||
points.append(end["matrix"][:3, 3])
|
||||
keep.append(0.0)
|
||||
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)
|
||||
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,
|
||||
keep=np.array(keep)[order])
|
||||
return made.curve, made, sagged, least, swing
|
||||
|
||||
def built(self, curve, start, clamps, stand, r, spread, half_width):
|
||||
"""The mesh, in world space: each hose swept along the curve offset across the bundle, two ferrule collars at
|
||||
each of its ends, and at each clamp a pad on the socket's face and a strap around the bundle. The ups are
|
||||
route.frames', turned so the bundle lies flat on the first clamp."""
|
||||
curve = route.thinned(curve, 0.05 * r) # an arc's chord is at least a twelfth of a radius at the least bend
|
||||
steps = np.diff(curve, axis=0)
|
||||
steps /= np.linalg.norm(steps, axis=1)[:, None]
|
||||
tangent = np.vstack([steps[:1], steps[:-1] + steps[1:], steps[-1:]])
|
||||
tangent /= np.linalg.norm(tangent, axis=1)[:, None]
|
||||
ups = route.frames(curve, start["matrix"][:3, 1])
|
||||
seats = [int(np.argmin(np.linalg.norm(curve - (clamp["matrix"][:3, 3] + clamp["matrix"][:3, 2] * stand), axis=1))) for clamp in clamps]
|
||||
if clamps: # rotation-minimising ups keep their angle to each other: turning the first turns every one as much
|
||||
k, z = seats[0], clamps[0]["matrix"][:3, 2]
|
||||
turn = math.atan2(float(tangent[k] @ np.cross(ups[k], z)), float(ups[k] @ z))
|
||||
ups = route.frames(curve, ups[0] * math.cos(turn) + np.cross(tangent[0], ups[0]) * math.sin(turn))
|
||||
side = np.cross(ups, tangent)
|
||||
shells, section = [], core.circle(r, HOSE_SEGMENTS)
|
||||
for index in range(self.count):
|
||||
path = curve + side * ((index - (self.count - 1) / 2.0) * spread)
|
||||
shells.append(core.sweep(path, section, ups))
|
||||
for at, along_, up in ((path[0], tangent[0], ups[0]), (path[-1], -tangent[-1], ups[-1])):
|
||||
shells.append(core.sweep([at, at + along_ * 4.5 * r], core.circle(1.45 * r, HOSE_SEGMENTS), up))
|
||||
shells.append(core.sweep([at + along_ * 4.5 * r, at + along_ * 6.0 * r], core.circle(1.2 * r, HOSE_SEGMENTS), up))
|
||||
band, reach = 0.5 * r, 1.25 * r + 1e-4 # a strap's thickness, and its mid-line's distance from a hose's centre
|
||||
for clamp, k in zip(clamps, seats):
|
||||
centre, across, up = curve[k], side[k], ups[k]
|
||||
turns = np.radians(np.arange(-90.0, 90.0 + 1e-9, 30.0))
|
||||
loop = ([centre + across * (half_width + reach * math.cos(a)) + up * (reach * math.sin(a)) for a in turns]
|
||||
+ [centre - across * (half_width + reach * math.cos(a)) - up * (reach * math.sin(a)) for a in turns])
|
||||
loop = np.array(loop if half_width > 1e-9 else loop[:6] + loop[7:13])
|
||||
shells.append(core.sweep(loop, core.profile("box", band, 2.0 * r, band), tangent[k], closed=True))
|
||||
face, out = clamp["matrix"][:3, 3], clamp["matrix"][:3, 2]
|
||||
shells.append(core.sweep([face, face + out * (float(((loop - face) @ out).min()) + 0.25 * band)], core.circle(1.5 * r + 0.5 * half_width, HOSE_SEGMENTS), clamp["matrix"][:3, 1]))
|
||||
return core.joined(shells)
|
||||
|
||||
|
||||
class BROKKR_KITBASH_OT_describe(PolishOperator):
|
||||
"""List a kit's parts, or one part: params with type, bounds, default and doc, and sockets in the part's frame
|
||||
at default params"""
|
||||
|
|
@ -1437,7 +1752,7 @@ class BROKKR_KITBASH_OT_report(PolishOperator):
|
|||
classes = (BROKKR_KITBASH_OT_place_part, BROKKR_KITBASH_OT_set_params, BROKKR_KITBASH_OT_describe, BROKKR_KITBASH_OT_report,
|
||||
BROKKR_KITBASH_OT_attach, BROKKR_KITBASH_OT_detach, BROKKR_KITBASH_OT_roll, BROKKR_KITBASH_OT_aim, BROKKR_KITBASH_OT_reach,
|
||||
BROKKR_KITBASH_OT_close, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_cut, BROKKR_KITBASH_OT_cut_many, BROKKR_KITBASH_OT_apply, BROKKR_KITBASH_OT_ribs,
|
||||
BROKKR_KITBASH_OT_shell)
|
||||
BROKKR_KITBASH_OT_shell, BROKKR_KITBASH_OT_hose)
|
||||
|
||||
|
||||
def register():
|
||||
|
|
|
|||
|
|
@ -779,6 +779,111 @@
|
|||
"doc": "evaluate the wall (Kit Subsurf and Kit Solidify alone) and report folded, the number of its inner faces that fold over"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"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}.",
|
||||
"changesScene": true,
|
||||
"editModeSafe": false,
|
||||
"result": "brokkr_mesh_polish_result",
|
||||
"fields": [
|
||||
{
|
||||
"name": "object_name",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"minLength": 1,
|
||||
"maxLength": 63,
|
||||
"doc": "the hose's name: no object's name, or a hose's, which is then rebuilt"
|
||||
},
|
||||
{
|
||||
"name": "start",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"minLength": 1,
|
||||
"maxLength": 96,
|
||||
"doc": "'Object:socket' (a hose or flange socket of a kit part), or 'Object' (an empty: the hose leaves along its z)"
|
||||
},
|
||||
{
|
||||
"name": "end",
|
||||
"type": "string",
|
||||
"required": true,
|
||||
"minLength": 1,
|
||||
"maxLength": 96,
|
||||
"doc": "as start"
|
||||
},
|
||||
{
|
||||
"name": "count",
|
||||
"type": "integer",
|
||||
"minimum": 1,
|
||||
"maximum": 8,
|
||||
"default": 1,
|
||||
"doc": "hoses in the bundle, side by side"
|
||||
},
|
||||
{
|
||||
"name": "radius",
|
||||
"type": "number",
|
||||
"minimum": 0.003,
|
||||
"maximum": 0.1,
|
||||
"default": 0.01,
|
||||
"doc": "a hose's outside radius"
|
||||
},
|
||||
{
|
||||
"name": "spread",
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 0.5,
|
||||
"default": 0,
|
||||
"doc": "centre to centre between hoses; 0: 2.6 radii"
|
||||
},
|
||||
{
|
||||
"name": "clearance",
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 0.5,
|
||||
"default": 0.01,
|
||||
"doc": "free space kept between the bundle and every other mesh"
|
||||
},
|
||||
{
|
||||
"name": "bend",
|
||||
"type": "number",
|
||||
"minimum": 1,
|
||||
"maximum": 20,
|
||||
"default": 4,
|
||||
"doc": "least bend radius of the innermost hose, in outside diameters"
|
||||
},
|
||||
{
|
||||
"name": "step",
|
||||
"type": "number",
|
||||
"minimum": 0.005,
|
||||
"maximum": 0.2,
|
||||
"default": 0.02,
|
||||
"doc": "voxel size of the search; a way narrower than the bundle plus two voxels is not found"
|
||||
},
|
||||
{
|
||||
"name": "sag",
|
||||
"type": "number",
|
||||
"minimum": 0,
|
||||
"maximum": 8,
|
||||
"default": 1,
|
||||
"doc": "how far the middle of each free span hangs, in outside diameters; 0: taut"
|
||||
},
|
||||
{
|
||||
"name": "clamps",
|
||||
"type": "string",
|
||||
"minLength": 2,
|
||||
"maxLength": 4000,
|
||||
"doc": "a JSON array of 0 to 8 {\"socket\": \"Object:socket\"}, mount sockets in order along the hose",
|
||||
"default": "[]"
|
||||
},
|
||||
{
|
||||
"name": "joint",
|
||||
"type": "string",
|
||||
"minLength": 0,
|
||||
"maxLength": 4000,
|
||||
"doc": "empty, or a JSON object {\"socket\": \"Object:socket\", \"standoff\": 0 to 10, \"range\": [lo, hi]}: the pin the hose crosses",
|
||||
"default": ""
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
|
|
|||
|
|
@ -318,6 +318,20 @@ def verify(curve, distance, need: float, lead: float, spacing: float, name: str
|
|||
return float(reads[worst])
|
||||
|
||||
|
||||
def thinned(curve, gap: float) -> np.ndarray:
|
||||
"""A curve without the points that stand within `gap` of the point kept before them; its two ends stay. Where two
|
||||
arcs meet tangent to tangent they can leave a straight far shorter than a tube is wide between them, and a
|
||||
section swept over it would fold; with the short straight gone the two arcs meet at one point."""
|
||||
curve = np.asarray(curve, dtype=np.float64)
|
||||
kept = [0]
|
||||
for index in range(1, len(curve)):
|
||||
if np.linalg.norm(curve[index] - curve[kept[-1]]) > gap:
|
||||
kept.append(index)
|
||||
if kept[-1] != len(curve) - 1:
|
||||
kept[-1 if len(kept) > 1 else len(kept):] = [len(curve) - 1]
|
||||
return curve[kept]
|
||||
|
||||
|
||||
def frames(curve, up0) -> np.ndarray:
|
||||
"""An up for each point of a curve, rotation minimising: the first is up0 projected off the tangent, each next the
|
||||
last reflected twice (Wang et al. 2008), so the ups do not twist about the curve. Tangents are the unit bisectors
|
||||
|
|
|
|||
364
surfaces/blender/tests/live/kitbash_hose.py
Normal file
364
surfaces/blender/tests/live/kitbash_hose.py
Normal file
|
|
@ -0,0 +1,364 @@
|
|||
"""Live proof, in a background Blender, of brokkr_kitbash.hose through run_intent: a bundle of three hoses from an actuator
|
||||
on one strut to an actuator on the next, around an armour plate and through a point on the knee pin's axis; the pin's
|
||||
roll range measured without posing anything, and a range that swings the hose into the plate refused by roll; a second
|
||||
hose that keeps clear of the first; a rebuild in place; a hose from a tank's flange over two clamps to an actuator's
|
||||
port; and the refusals. Not part of the unittest run: it needs Blender.
|
||||
|
||||
blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_hose.py -- <out> [<blend>]
|
||||
|
||||
Run it with private BLENDER_USER_CONFIG, BLENDER_USER_EXTENSIONS and BLENDER_USER_SCRIPTS directories (it refuses
|
||||
without them). <out> is an absolute path; writes <out>.result.json and exits 1 when a check failed. With <blend>, an
|
||||
absolute path, the scene is saved there at the end.
|
||||
|
||||
Bounds follow lodur:ruling:deterministic-bound-margin; each is written beside its constant with the shipped reading
|
||||
and the least claimed mutant's (cut kit-hose's H list). The checks run inside one try: an uncaught error is a failed
|
||||
check that names its section, and the result file is always written.
|
||||
"""
|
||||
import importlib.util
|
||||
import json
|
||||
import math
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import traceback
|
||||
import types
|
||||
from pathlib import Path
|
||||
|
||||
import bpy
|
||||
import numpy as np
|
||||
from mathutils import Vector
|
||||
from mathutils.bvhtree import BVHTree
|
||||
|
||||
SURFACE = Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0, str(SURFACE / "tools"))
|
||||
import private_dirs # noqa: E402
|
||||
|
||||
_refused = private_dirs.refusal(os.environ, os.path.expanduser("~"), lambda kind: bpy.utils.user_resource(kind))
|
||||
if _refused:
|
||||
raise SystemExit(_refused)
|
||||
OUT = sys.argv[sys.argv.index("--") + 1]
|
||||
if not Path(OUT).is_absolute():
|
||||
raise SystemExit(f"{OUT!r} is not an absolute path")
|
||||
package = types.ModuleType("brokkr_bridge")
|
||||
package.__path__ = [str(SURFACE / "brokkr_bridge")]
|
||||
sys.modules["brokkr_bridge"] = package
|
||||
from brokkr_bridge import blender_target as bt # noqa: E402
|
||||
|
||||
import addon_utils # noqa: E402
|
||||
|
||||
spec = importlib.util.spec_from_file_location("brokkr_kitbash_core_reference", SURFACE / "brokkr_kitbash" / "core.py")
|
||||
core = importlib.util.module_from_spec(spec) # core as the unit tests load it
|
||||
spec.loader.exec_module(core)
|
||||
|
||||
sys.path.append(str(SURFACE))
|
||||
bpy.ops.wm.read_factory_settings(use_empty=True)
|
||||
for module in ("brokkr_mesh_polish", "brokkr_kitbash"):
|
||||
addon_utils.enable(module, default_set=True)
|
||||
target = bt.BrokkrBlenderTarget(bpy)
|
||||
WORK = Path(tempfile.mkdtemp(prefix="brokkr-kitbash-hose-"))
|
||||
target.configure_action_dirs("", str(WORK))
|
||||
target.reload_host_actions()
|
||||
R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1], "readings": {}, "reports": {}, "seconds": {}}
|
||||
COUNT, SECTION = [0], ["setup"]
|
||||
kit = core.load_kit("mechanical")
|
||||
RADIUS, CLEARANCE, COUNT_HOSES = 0.006, 0.005, 3
|
||||
SPREAD = 2.6 * RADIUS
|
||||
ENVELOPE = SPREAD + RADIUS # half the bundle's width
|
||||
LEAD = 8.0 * RADIUS
|
||||
FLOOR = 4.0 * 2.0 * RADIUS + SPREAD # of the centre line: the innermost hose keeps 4 outside diameters
|
||||
BUNDLE = {"count": COUNT_HOSES, "radius": RADIUS, "clearance": CLEARANCE}
|
||||
# Metres between a hose's surface and the nearest other mesh, read on the hose's own vertices further than the lead
|
||||
# from both its ports (the least is the worst). The action promises the clearance asked for, 0.005, beyond the
|
||||
# bundle's envelope, and a vertex of a 12-sided tube swept over chords of a 24th of a radian stands inside its circle
|
||||
# by under 0.0002: the bound is that promise less the faceting. Shipped worst 0.030 (the second hose beside the
|
||||
# first). No mutant of the cut's list lowers this reading: H10 (other hoses no obstacles) dies where a third hose is
|
||||
# refused at a port a hose already holds, H4 (no verification) at tests/test_kitbash.py's count of route.verify, and
|
||||
# H3 and H12 at tests/test_route.py; the reading is claimed by none of them and stands as the action's own promise.
|
||||
CLEAR = 0.0048
|
||||
# Metres a clamped hose's ring vertices stand off the radius about its own line over a clamp (the line through the
|
||||
# clamp point along the socket's y, offset across the bundle), over the 24 nearest; 1 when a hose has no 24 vertices
|
||||
# there. Shipped worst 4.6e-08 (float32 meshes); least claimed mutant 1 (C2, the straight laid along the socket's x:
|
||||
# the route is refused, or no ring stands on the line); the geometric mean, separation 4700 each side. C1 (no
|
||||
# straight kept at a clamp) reads 0.013 on `kept`, the least distance along the line from a clamp point to a ring,
|
||||
# where shipped reads 0.028 and the promise is 0.024, two outside diameters.
|
||||
CLAMPED = 2.1e-4
|
||||
|
||||
def check(name, ok, detail=None):
|
||||
R["checks"].append({"name": name, "ok": bool(ok), "detail": None if ok else detail})
|
||||
|
||||
|
||||
def reading(name, value, least=False):
|
||||
"""The worst of a metric: the largest, or with `least` the smallest."""
|
||||
R["readings"][name] = (min if least else max)(R["readings"].get(name, float(value)), float(value))
|
||||
return float(value)
|
||||
|
||||
|
||||
def section(name):
|
||||
SECTION[0] = name
|
||||
|
||||
|
||||
def send(action, **fields):
|
||||
COUNT[0] += 1
|
||||
receipt = target.run_intent(bpy.context, {"commandId": f"live-{COUNT[0]}", "requestedBy": "test/driver", "action": action, **fields})
|
||||
result = None
|
||||
if receipt.get("hostResult"):
|
||||
try:
|
||||
result = json.loads(receipt["hostResult"])
|
||||
except ValueError:
|
||||
result = None
|
||||
print("SEND", action, receipt["status"], str(receipt["message"])[:400], flush=True)
|
||||
return receipt, result
|
||||
|
||||
|
||||
def scene_state():
|
||||
return {o.name: (o.parent and o.parent.name, np.round(np.array(o.matrix_basis), 6).tolist(), {k: repr(o[k]) for k in sorted(o.keys()) if k.startswith("kit_")},
|
||||
[(m.name, m.type, m.show_viewport) for m in o.modifiers], o.data.name if o.type == "MESH" else None, len(o.data.polygons) if o.type == "MESH" else None,
|
||||
np.round(np.array([v.co for v in o.data.vertices[:8]]), 6).tolist() if o.type == "MESH" else None)
|
||||
for o in bpy.data.objects}, sorted(m.name for m in bpy.data.meshes), sorted(c.name for c in bpy.data.collections)
|
||||
|
||||
|
||||
def refused(label, fields, expected):
|
||||
state = scene_state()
|
||||
receipt, _ = send("brokkr_kitbash.hose", **fields)
|
||||
check(f"refused, scene unchanged: {label}", receipt["status"] != "accepted" and expected in str(receipt["message"]) and scene_state() == state,
|
||||
[receipt["status"], receipt["message"]])
|
||||
|
||||
|
||||
def place(name, part, params="", location=None, rotation=None, parent=None):
|
||||
send("brokkr_kitbash.place_part", part=part, object_name=name, params=params)
|
||||
if location is not None:
|
||||
send("setObjectTransform", targetObjectName=name, location=location, rotationEuler=rotation or [0.0, 0.0, 0.0])
|
||||
made = bpy.data.objects[name]
|
||||
if parent is not None: # carried rigidly: a plain parent, which states no connection
|
||||
bpy.context.view_layer.update()
|
||||
made.parent = parent
|
||||
made.matrix_parent_inverse = parent.matrix_world.inverted()
|
||||
return made
|
||||
|
||||
|
||||
def box(name, low, high, parent=None):
|
||||
(x0, y0, z0), (x1, y1, z1) = low, high
|
||||
made = bpy.data.objects.new(name, bpy.data.meshes.new(name))
|
||||
made.data.from_pydata([(x0, y0, z0), (x1, y0, z0), (x1, y1, z0), (x0, y1, z0), (x0, y0, z1), (x1, y0, z1), (x1, y1, z1), (x0, y1, z1)], [],
|
||||
[(0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4), (1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7)])
|
||||
bpy.context.scene.collection.objects.link(made)
|
||||
if parent is not None:
|
||||
bpy.context.view_layer.update()
|
||||
made.parent = parent
|
||||
made.matrix_parent_inverse = parent.matrix_world.inverted()
|
||||
return made
|
||||
|
||||
|
||||
def frame(obj, name):
|
||||
"""A socket's world frame, from the object's matrix_world and core's build of its stored params."""
|
||||
built = core.build(core.part(kit, obj["kit_part"]), json.loads(obj["kit_params"]))
|
||||
return np.array(obj.matrix_world, dtype=np.float64) @ next(s for s in built.sockets if s["name"] == name)["matrix"]
|
||||
|
||||
|
||||
def world_points(obj):
|
||||
points = np.zeros(3 * len(obj.data.vertices))
|
||||
obj.data.vertices.foreach_get("co", points)
|
||||
world = np.array(obj.matrix_world)
|
||||
return points.reshape(-1, 3) @ world[:3, :3].T + world[:3, 3]
|
||||
|
||||
|
||||
def others(hose):
|
||||
"""A tree of every other mesh object's evaluated mesh in the world: this test's own reading of the obstacles."""
|
||||
depsgraph, points, faces = bpy.context.evaluated_depsgraph_get(), [], []
|
||||
for obj in bpy.context.scene.objects:
|
||||
if obj.type != "MESH" or obj == hose:
|
||||
continue
|
||||
evaluated = obj.evaluated_get(depsgraph)
|
||||
mesh, start = evaluated.to_mesh(), sum(len(p) for p in points)
|
||||
points.append(np.array([evaluated.matrix_world @ v.co for v in mesh.vertices]).reshape(-1, 3))
|
||||
faces += [[start + i for i in polygon.vertices] for polygon in mesh.polygons]
|
||||
evaluated.to_mesh_clear()
|
||||
return BVHTree.FromPolygons(np.vstack(points).tolist(), faces)
|
||||
|
||||
|
||||
def surface_clearance(hose, ports):
|
||||
"""The least distance from the hose's vertices to any other mesh, over the vertices further than the lead and the
|
||||
bundle's half width from both ports."""
|
||||
bpy.context.view_layer.update()
|
||||
tree, points = others(hose), world_points(hose)
|
||||
far = np.all([np.linalg.norm(points - port, axis=1) > LEAD + ENVELOPE + CLEARANCE for port in ports], axis=0)
|
||||
return min(tree.find_nearest(Vector(p))[3] for p in points[far])
|
||||
|
||||
|
||||
def shells(obj):
|
||||
"""(closed shells, edges that do not join two faces) of a mesh object."""
|
||||
edges = {}
|
||||
for polygon in obj.data.polygons:
|
||||
for a, b in polygon.edge_keys:
|
||||
edges[(a, b)] = edges.get((a, b), 0) + 1
|
||||
root = list(range(len(obj.data.vertices)))
|
||||
|
||||
def find(i):
|
||||
while root[i] != i:
|
||||
root[i] = root[root[i]]
|
||||
i = root[i]
|
||||
return i
|
||||
for a, b in edges:
|
||||
root[find(a)] = find(b)
|
||||
return len({find(i) for i in range(len(root))}), sum(1 for n in edges.values() if n != 2)
|
||||
|
||||
|
||||
def timed(fields):
|
||||
"""Median wall seconds of three rebuilds of a hose, each after one report action."""
|
||||
import time
|
||||
taken = []
|
||||
for _ in range(3):
|
||||
send("brokkr_kitbash.report", object_name="Thigh")
|
||||
started = time.perf_counter()
|
||||
send("brokkr_kitbash.hose", **fields)
|
||||
taken.append(time.perf_counter() - started)
|
||||
return sorted(taken)[1]
|
||||
|
||||
|
||||
try:
|
||||
section("knee")
|
||||
STRUT = "length=0.8;width=0.08;thickness=0.05"
|
||||
RAM = "body_r=0.12;body_len=0.2;extension=0"
|
||||
thigh = place("Thigh", "strut", STRUT)
|
||||
place("Shin", "strut", STRUT)
|
||||
send("brokkr_kitbash.attach", object_name="Shin", socket="end_a", parent_name="Thigh", parent_socket="end_b_back", roll=0.0)
|
||||
shin = bpy.data.objects["Shin"]
|
||||
upper = place("ActT", "actuator", RAM, [-0.674, -0.2, -0.2], parent=thigh)
|
||||
lower = place("ActS", "actuator", RAM, [-0.674, -0.2, 0.89], parent=shin)
|
||||
plate = box("Armour", (-0.21, -0.45, 0.15), (-0.19, 0.05, 0.7), parent=thigh)
|
||||
bpy.context.view_layer.update()
|
||||
ports = [frame(upper, "port_cap")[:3, 3], frame(lower, "port_cap")[:3, 3]]
|
||||
check("the actuator's ports sit on its boss faces, facing out", np.allclose(ports[0], [-0.5, -0.2, 0.01], atol=1e-6) and np.allclose(frame(upper, "port_cap")[:3, 2], [1, 0, 0], atol=1e-6)
|
||||
and others(None).find_nearest(Vector(ports[0]))[3] < 1e-6 and np.allclose(frame(upper, "port_rod")[:3, 3], [-0.5, -0.2, 0.27], atol=1e-6), ports[0].tolist())
|
||||
JOINT = {"socket": "Shin:end_a_back", "standoff": 0.08, "range": [-20, 20]}
|
||||
FEED = {"object_name": "Feed", "start": "ActT:port_cap", "end": "ActS:port_cap", **BUNDLE, "joint": json.dumps(JOINT)}
|
||||
state = scene_state()
|
||||
receipt, report = send("brokkr_kitbash.hose", **FEED)
|
||||
R["reports"]["feed"] = report
|
||||
check("hose-behind-armour: three hoses route from the thigh's ram to the shin's, round the plate and through the pin point",
|
||||
receipt["status"] == "accepted" and report["hoses"] == 3 and not report["rebuilt"] and report["nonManifoldEdges"] == 0 and report["rolls"] == 9
|
||||
and report["clearance"] >= CLEARANCE and report["worstClearance"] >= CLEARANCE and report["radii"]["least"] >= FLOOR * (1 - 1e-6) and len(report["voxels"]) == 2,
|
||||
[receipt["status"], receipt["message"], report])
|
||||
feed = bpy.data.objects["Feed"]
|
||||
check("the hose is one object, the start's child under an identity parent inverse, and carries its request",
|
||||
feed.parent == upper and np.allclose(np.array(feed.matrix_parent_inverse), np.eye(4)) and np.allclose(np.array(feed.matrix_basis), np.eye(4))
|
||||
and json.loads(feed["kit_hose"])["joint"] == JOINT and len(feed.data.materials) == 0 and len(feed.vertex_groups) == 0, feed.get("kit_hose"))
|
||||
check("every hose and collar is a closed shell", shells(feed) == (3 + 3 * 4, 0), shells(feed))
|
||||
points = world_points(feed)
|
||||
check("each hose starts on the port's face, side by side across it",
|
||||
min(np.linalg.norm(points - ports[0], axis=1)) < RADIUS * 1.5 and abs(float(((points - ports[0]) @ [1.0, 0, 0]).min())) < 1e-5, None)
|
||||
line_blocked = others(feed).ray_cast(Vector(ports[0] + [0.12, 0, 0]), Vector((np.array([0, -0.2075, 0.764]) - ports[0] - [0.12, 0, 0])))[0] is not None
|
||||
check("the straight way from the port to the pin point is through the plate", line_blocked, None)
|
||||
check("hose-behind-armour: the hose's surface keeps the clearance from every other mesh outside its leads",
|
||||
reading("clear", surface_clearance(feed, ports), least=True) >= CLEAR, R["readings"])
|
||||
check("the hose passes the pin's axis: its vertices come within the bundle of the point 0.08 beyond the shin's pin face",
|
||||
float(np.linalg.norm(points - [0.0, -0.2075, 0.764], axis=1).min()) < 0.08, float(np.linalg.norm(points - [0.0, -0.2075, 0.764], axis=1).min()))
|
||||
check("the report states sag for both legs, no more than the sag asked for", len(report["sag"]) == 2 and all(0.0 <= s <= 2 * RADIUS + 1e-9 for s in report["sag"]) and any(s > 0 for s in report["sag"]), report["sag"])
|
||||
_, taut = send("brokkr_kitbash.hose", **{**FEED, "sag": 0.0})
|
||||
check("sag 0 routes taut and no longer than the sagged hose", taut["sag"] == [0.0, 0.0] and taut["rebuilt"] and taut["length"] < report["length"], [taut["length"], report["length"]])
|
||||
reading("slack", report["length"] - taut["length"])
|
||||
section("range")
|
||||
_, again = send("brokkr_kitbash.hose", **FEED)
|
||||
check("a rebuild at the same pose reports what the first call did", {**again, "rebuilt": False} == report and len(bpy.data.meshes) == len(state[1]) + 1, again)
|
||||
check("hose-through-range: the range passes and reports the length's change", report["lengthChange"] is not None and report["lengthChange"] >= 0 and report["worstRoll"] is not None, report)
|
||||
refused("a range that swings the shin's hose into the thigh's parts", {**FEED, "joint": json.dumps({**JOINT, "range": [-20, 90]})},
|
||||
"roll 50: the hose's child's side stands 0.02384 m from the parts on the other side of the pin, under the 0.0266 m the bundle needs")
|
||||
send("brokkr_kitbash.roll", object_name="Shin", roll=10.0)
|
||||
bpy.context.view_layer.update()
|
||||
receipt, rolled = send("brokkr_kitbash.hose", **FEED)
|
||||
check("after a roll the hose rebuilds in place on its name", receipt["status"] == "accepted" and rolled["rebuilt"] and bpy.data.objects["Feed"] == feed and rolled["rolls"] == 9, receipt["message"])
|
||||
check("the rebuilt hose keeps the clearance at the new pose", reading("clear", surface_clearance(feed, [frame(upper, "port_cap")[:3, 3], frame(lower, "port_cap")[:3, 3]]), least=True) >= CLEAR, R["readings"])
|
||||
mesh = feed.data
|
||||
bpy.data.objects.remove(feed)
|
||||
bpy.data.meshes.remove(mesh)
|
||||
bpy.context.view_layer.update()
|
||||
receipt, fresh = send("brokkr_kitbash.hose", **FEED)
|
||||
feed = bpy.data.objects["Feed"]
|
||||
check("hose-through-range: roll then rebuild gives the same report as a fresh hose", receipt["status"] == "accepted" and {**rolled, "rebuilt": False} == fresh, [rolled, fresh])
|
||||
R["seconds"]["hose on the knee, median of 3"] = round(timed(FEED), 3)
|
||||
section("second hose")
|
||||
RETURN = {"object_name": "Return", "start": "ActT:port_rod", "end": "ActS:port_rod", **BUNDLE, "step": 0.03, "joint": json.dumps({**JOINT, "standoff": 0.24})} # round the plate's edge a voxel of 0.02 leaves a bend under the floor
|
||||
receipt, back = send("brokkr_kitbash.hose", **RETURN)
|
||||
R["reports"]["return"] = back
|
||||
check("a second hose routes through the same knee", receipt["status"] == "accepted" and back["nonManifoldEdges"] == 0, [receipt["status"], receipt["message"]])
|
||||
rod_ports = [frame(upper, "port_rod")[:3, 3], frame(lower, "port_rod")[:3, 3]]
|
||||
check("hose-behind-armour: the second hose keeps the clearance from the first", reading("clear", surface_clearance(bpy.data.objects["Return"], rod_ports), least=True) >= CLEAR, R["readings"])
|
||||
refused("a pin point another hose already passes", {**RETURN, "object_name": "Third"}, "from an obstacle")
|
||||
section("clamps")
|
||||
tank = place("Tank", "tank", "radius=0.22;length=0.9", [3.0, 0.0, 0.0])
|
||||
seats = [place(name, "plate", "width=0.1;height=0.1", [x, 0.0, 1.25], [0.0, 0.0, math.pi / 2]) for name, x in (("SeatA", 3.45), ("SeatB", 4.05))]
|
||||
ram = place("Ram", "actuator", RAM, [5.074, 0.0, 1.07], [0.0, 0.0, math.pi])
|
||||
bpy.context.view_layer.update()
|
||||
LINE = {"object_name": "Line", "start": "Tank:port_b", "end": "Ram:port_cap", **BUNDLE, "clamps": json.dumps([{"socket": "SeatA:front"}, {"socket": "SeatB:front"}])}
|
||||
receipt, line = send("brokkr_kitbash.hose", **LINE)
|
||||
R["reports"]["line"] = line
|
||||
check("hose-clamps-ports: a hose runs from the tank's flange over two clamps to the ram's port", receipt["status"] == "accepted" and line["nonManifoldEdges"] == 0 and len(line["voxels"]) == 3
|
||||
and line["rolls"] is None and line["lengthChange"] is None, [receipt["status"], receipt["message"]])
|
||||
hose = bpy.data.objects["Line"]
|
||||
check("three hoses with four collars each, two straps and two pads", shells(hose) == (3 + 12 + 4, 0), shells(hose))
|
||||
points = world_points(hose)
|
||||
stand, held = ENVELOPE + CLEARANCE + RADIUS, 4.0 * RADIUS + FLOOR
|
||||
for seat in seats:
|
||||
at = frame(seat, "front")
|
||||
centre, y, x = at[:3, 3] + at[:3, 2] * stand, at[:3, 1], at[:3, 0]
|
||||
for k in range(COUNT_HOSES):
|
||||
origin = centre + x * (k - 1) * SPREAD
|
||||
rel = points - origin
|
||||
along = rel @ y
|
||||
off = np.abs(np.linalg.norm(rel - np.outer(along, y), axis=1) - RADIUS)
|
||||
near = np.sort(off[np.abs(along) <= held + 1e-6])[:24] # the two rings where the kept straight ends, twelve vertices each
|
||||
reading("clamped", near.max() if len(near) == 24 else 1.0)
|
||||
reading("kept", np.abs(along[off < 1e-5]).min() if (off < 1e-5).any() else 0.0, least=True)
|
||||
check("hose-clamps-ports: each hose passes each clamp point straight along the socket's y", R["readings"]["clamped"] <= CLAMPED, R["readings"])
|
||||
check("the bundle runs straight for two outside diameters each side of a clamp point: no ring of a bend stands nearer", R["readings"]["kept"] >= 4.0 * RADIUS * (1 - 1e-6), R["readings"])
|
||||
check("the clamped hose reports the clearance it keeps (its pads stand on their seats)", line["clearance"] >= CLEARANCE and surface_clearance(hose, [frame(tank, "port_b")[:3, 3], frame(ram, "port_cap")[:3, 3]]) < 1e-6,
|
||||
line["clearance"])
|
||||
refused("a bundle wider than the port", {**LINE, "object_name": "Wide", "count": 5}, "a bundle of 5 hoses is 0.0744 m wide, over socket 'Ram:port_cap' (hose, size 0.048)")
|
||||
tip = bpy.data.objects.new("Tip", None)
|
||||
bpy.context.scene.collection.objects.link(tip)
|
||||
tip.location, tip.rotation_euler = (3.5, 0.0, -1.3), (0.0, -math.pi / 6, 0.0) # under the tank's lower port, its z up toward it
|
||||
bpy.context.view_layer.update()
|
||||
receipt, loose = send("brokkr_kitbash.hose", object_name="Loose", start="Tank:port_a", end="Tip", radius=0.02)
|
||||
check("a hose runs from a flange to an empty", receipt["status"] == "accepted" and loose["hoses"] == 1 and shells(bpy.data.objects["Loose"]) == (5, 0), [receipt["status"], receipt["message"]])
|
||||
section("refusals")
|
||||
refused("a name taken by a mesh that is no hose", {**FEED, "object_name": "Thigh"}, "An object named 'Thigh' exists and is no hose")
|
||||
refused("a socket the part does not have", {**FEED, "start": "ActT:nope"}, "start: 'ActT' (a actuator) has no socket 'nope'; its sockets: base, base_back, rod_end, rod_end_back, port_cap, port_rod")
|
||||
refused("an object that does not exist", {**FEED, "end": "Nobody:port_cap"}, "end: no object named 'Nobody'")
|
||||
refused("a pivot as an end", {**FEED, "start": "Thigh:end_a"}, "start: socket 'end_a' of 'Thigh' is a pivot socket; this takes a hose or flange socket")
|
||||
refused("a mesh that is no empty as an end", {**FEED, "end": "Armour"}, "end 'Armour' names no socket")
|
||||
refused("a clamp on a pivot", {**FEED, "clamps": json.dumps([{"socket": "Thigh:end_a"}])}, "clamps[0]: socket 'end_a' of 'Thigh' is a pivot socket; this takes a mount socket")
|
||||
refused("clamps that are not rows of socket", {**FEED, "clamps": json.dumps([{"at": [0, 0, 0]}])}, "clamps[0] must be an object of socket")
|
||||
refused("nine clamps", {**FEED, "clamps": json.dumps([{"socket": "SeatA:front"}] * 9)}, "clamps must be a JSON array of 0 to 8 objects")
|
||||
refused("a pin crossed with no joint", {k: v for k, v in FEED.items() if k != "joint"}, "The hose crosses the pin of 'Shin' on 'Thigh' (socket 'end_b_back'): give joint")
|
||||
refused("a joint where no pin is crossed", {**LINE, "object_name": "New", "joint": json.dumps(JOINT)}, "joint is given and the hose crosses no pin")
|
||||
place("Jack", "actuator", "body_r=0.0534;body_len=0.2;extension=0")
|
||||
send("brokkr_kitbash.attach", object_name="Jack", socket="base", parent_name="Shin", parent_socket="end_b", roll=90.0)
|
||||
bpy.context.view_layer.update()
|
||||
refused("two pins crossed", {**FEED, "object_name": "New", "end": "Jack:port_cap", "count": 1, "radius": 0.004}, "The hose crosses 2 pins ('Jack' on 'Shin', 'Shin' on 'Thigh'): a hose crosses one")
|
||||
refused("a joint socket off the crossed pin's axis", {**FEED, "joint": json.dumps({**JOINT, "socket": "Shin:end_b_back"})}, "joint.socket 'Shin:end_b_back' is not on the axis of the pin the hose crosses ('Shin' on 'Thigh', socket 'end_b_back')")
|
||||
refused("the current roll outside the range", {**FEED, "joint": json.dumps({**JOINT, "range": [30, 60]})}, "'Shin' stands at roll 10, outside joint.range [30, 60]")
|
||||
refused("a range over a full turn", {**FEED, "joint": json.dumps({**JOINT, "range": [-200, 200]})}, "joint must be an object of socket")
|
||||
refused("a grid past the voxel limit", {**FEED, "step": 0.005}, "voxels at step 0.005, over 524288: a step of ")
|
||||
lower.scale = (1.0, 1.0, 1.01)
|
||||
bpy.context.view_layer.update()
|
||||
refused("a scaled part", FEED, "'ActS' is scaled, mirrored or sheared in the world")
|
||||
lower.scale = (1.0, 1.0, 1.0)
|
||||
tip.hide_viewport = True
|
||||
bpy.context.view_layer.update()
|
||||
refused("a hidden end", {"object_name": "Loose", "start": "Tank:port_a", "end": "Tip", "radius": 0.02}, "Blender does not evaluate 'Tip' in this view layer")
|
||||
tip.hide_viewport = False
|
||||
bpy.context.view_layer.update()
|
||||
if len(sys.argv) > sys.argv.index("--") + 2:
|
||||
bpy.ops.wm.save_as_mainfile(filepath=sys.argv[sys.argv.index("--") + 2])
|
||||
except Exception: # noqa: BLE001 whatever it was, it is a failed check with a name, not a missing result file
|
||||
check(f"no uncaught error in section: {SECTION[0]}", False, traceback.format_exc().splitlines()[-6:])
|
||||
finally:
|
||||
R["ok"] = all(c["ok"] for c in R["checks"])
|
||||
R["readings"] = {name: float(f"{value:.2g}") for name, value in sorted(R["readings"].items())}
|
||||
seconds = R.pop("seconds") # wall time is this machine's: printed, and kept out of the result file
|
||||
Path(OUT + ".result.json").write_text(json.dumps(R, indent=1, default=str), encoding="utf-8")
|
||||
for c in R["checks"]:
|
||||
print("CHECK", "ok " if c["ok"] else "FAIL", c["name"], "" if c["ok"] else c["detail"], flush=True)
|
||||
print("READINGS", R["readings"], flush=True)
|
||||
print("SECONDS", seconds, flush=True)
|
||||
sys.exit(0 if R["ok"] else 1)
|
||||
340
surfaces/blender/tests/live/kitbash_hose.result.json
Normal file
340
surfaces/blender/tests/live/kitbash_hose.result.json
Normal file
|
|
@ -0,0 +1,340 @@
|
|||
{
|
||||
"blender": "5.3.0",
|
||||
"checks": [
|
||||
{
|
||||
"name": "the actuator's ports sit on its boss faces, facing out",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "hose-behind-armour: three hoses route from the thigh's ram to the shin's, round the plate and through the pin point",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "the hose is one object, the start's child under an identity parent inverse, and carries its request",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "every hose and collar is a closed shell",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "each hose starts on the port's face, side by side across it",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "the straight way from the port to the pin point is through the plate",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "hose-behind-armour: the hose's surface keeps the clearance from every other mesh outside its leads",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "the hose passes the pin's axis: its vertices come within the bundle of the point 0.08 beyond the shin's pin face",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "the report states sag for both legs, no more than the sag asked for",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "sag 0 routes taut and no longer than the sagged hose",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "a rebuild at the same pose reports what the first call did",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "hose-through-range: the range passes and reports the length's change",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: a range that swings the shin's hose into the thigh's parts",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "after a roll the hose rebuilds in place on its name",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "the rebuilt hose keeps the clearance at the new pose",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "hose-through-range: roll then rebuild gives the same report as a fresh hose",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "a second hose routes through the same knee",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "hose-behind-armour: the second hose keeps the clearance from the first",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: a pin point another hose already passes",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "hose-clamps-ports: a hose runs from the tank's flange over two clamps to the ram's port",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "three hoses with four collars each, two straps and two pads",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "hose-clamps-ports: each hose passes each clamp point straight along the socket's y",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "the bundle runs straight for two outside diameters each side of a clamp point: no ring of a bend stands nearer",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "the clamped hose reports the clearance it keeps (its pads stand on their seats)",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: a bundle wider than the port",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "a hose runs from a flange to an empty",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: a name taken by a mesh that is no hose",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: a socket the part does not have",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: an object that does not exist",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: a pivot as an end",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: a mesh that is no empty as an end",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: a clamp on a pivot",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: clamps that are not rows of socket",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: nine clamps",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: a pin crossed with no joint",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: a joint where no pin is crossed",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: two pins crossed",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: a joint socket off the crossed pin's axis",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: the current roll outside the range",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: a range over a full turn",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: a grid past the voxel limit",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: a scaled part",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
},
|
||||
{
|
||||
"name": "refused, scene unchanged: a hidden end",
|
||||
"ok": true,
|
||||
"detail": null
|
||||
}
|
||||
],
|
||||
"hostErrors": [],
|
||||
"readings": {
|
||||
"clamped": 4.6e-08,
|
||||
"clear": 0.03,
|
||||
"kept": 0.028,
|
||||
"slack": 0.021
|
||||
},
|
||||
"reports": {
|
||||
"feed": {
|
||||
"object": "Feed",
|
||||
"rebuilt": false,
|
||||
"hoses": 3,
|
||||
"length": 1.64165,
|
||||
"lengthChange": 0.030219,
|
||||
"floor": 0.0636,
|
||||
"clearance": 0.005763,
|
||||
"capped": 0.1522,
|
||||
"voxels": [
|
||||
79488,
|
||||
53406
|
||||
],
|
||||
"sag": [
|
||||
0.001609,
|
||||
0.009076
|
||||
],
|
||||
"rolls": 9,
|
||||
"worstRoll": -20.0,
|
||||
"worstClearance": 0.057408,
|
||||
"faces": 3378,
|
||||
"volume": 0.000577078,
|
||||
"nonManifoldEdges": 0,
|
||||
"radii": {
|
||||
"least": 0.123768,
|
||||
"corners": [
|
||||
0.248224,
|
||||
0.123768,
|
||||
30.12343,
|
||||
0.218148,
|
||||
3.812707,
|
||||
0.129781
|
||||
]
|
||||
}
|
||||
},
|
||||
"return": {
|
||||
"object": "Return",
|
||||
"rebuilt": false,
|
||||
"hoses": 3,
|
||||
"length": 1.678891,
|
||||
"lengthChange": 0.034002,
|
||||
"floor": 0.0636,
|
||||
"clearance": 0.021671,
|
||||
"capped": 0.1622,
|
||||
"voxels": [
|
||||
26040,
|
||||
28560
|
||||
],
|
||||
"sag": [
|
||||
0.006276,
|
||||
0.00844
|
||||
],
|
||||
"rolls": 9,
|
||||
"worstRoll": 20.0,
|
||||
"worstClearance": 0.034016,
|
||||
"faces": 4926,
|
||||
"volume": 0.000589144,
|
||||
"nonManifoldEdges": 0,
|
||||
"radii": {
|
||||
"least": 0.071383,
|
||||
"corners": [
|
||||
0.073199,
|
||||
7.398753,
|
||||
0.071383,
|
||||
0.118904,
|
||||
10.830696,
|
||||
0.095513
|
||||
]
|
||||
}
|
||||
},
|
||||
"line": {
|
||||
"object": "Line",
|
||||
"rebuilt": false,
|
||||
"hoses": 3,
|
||||
"length": 2.10108,
|
||||
"lengthChange": null,
|
||||
"floor": 0.0636,
|
||||
"clearance": 0.011,
|
||||
"capped": 0.1522,
|
||||
"voxels": [
|
||||
49815,
|
||||
34992,
|
||||
43011
|
||||
],
|
||||
"sag": [
|
||||
0.00942,
|
||||
0.012,
|
||||
0.011996
|
||||
],
|
||||
"rolls": null,
|
||||
"worstRoll": null,
|
||||
"worstClearance": null,
|
||||
"faces": 2510,
|
||||
"volume": 0.000777433,
|
||||
"nonManifoldEdges": 0,
|
||||
"radii": {
|
||||
"least": 0.09689,
|
||||
"corners": [
|
||||
0.097757,
|
||||
4.439012,
|
||||
0.09689,
|
||||
1.734649,
|
||||
2.898844,
|
||||
1.734649,
|
||||
1.665625,
|
||||
7.39548,
|
||||
10.86245
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"ok": true
|
||||
}
|
||||
|
|
@ -1562,7 +1562,7 @@ class SheetTests(unittest.TestCase):
|
|||
ROWS = ["brokkr_kitbash.place_part", "brokkr_kitbash.set_params", "brokkr_kitbash.describe", "brokkr_kitbash.report",
|
||||
"brokkr_kitbash.attach", "brokkr_kitbash.detach", "brokkr_kitbash.roll", "brokkr_kitbash.aim", "brokkr_kitbash.reach", "brokkr_kitbash.close",
|
||||
"brokkr_kitbash.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", "brokkr_kitbash.apply", "brokkr_kitbash.ribs",
|
||||
"brokkr_kitbash.shell"]
|
||||
"brokkr_kitbash.shell", "brokkr_kitbash.hose"]
|
||||
|
||||
|
||||
class HostFileTests(unittest.TestCase):
|
||||
|
|
@ -1632,7 +1632,7 @@ class HostFileTests(unittest.TestCase):
|
|||
self.assertEqual([(row["name"], field["name"], field["default"]) for row in self.document["actions"] for field in row["fields"] if field["type"] == "boolean"],
|
||||
[("brokkr_kitbash.shell", "count_folds", False)]) # the one evaluation shell makes is asked for, never the default
|
||||
self.assertEqual([(row["name"], field["name"]) for row in self.document["actions"] for field in row["fields"] if field["type"] == "integer"],
|
||||
[("brokkr_kitbash.shell", "levels")])
|
||||
[("brokkr_kitbash.shell", "levels"), ("brokkr_kitbash.hose", "count")])
|
||||
sheet = json.dumps({"rings": [[[0, 0, 0], [1, 0, 0]], [[0, 0, 1], [1, 0, 1]]]})
|
||||
shell = {**envelope, "action": "brokkr_kitbash.shell", "object_name": "Plate", "sheet": sheet}
|
||||
self.assertEqual([at.validate(shell, host)[k] for k in ("thickness", "offset", "levels", "bevel", "count_folds")], [0.05, -1, 3, 0, False])
|
||||
|
|
@ -1725,7 +1725,7 @@ class OwnershipTests(unittest.TestCase):
|
|||
for body, first_write in ((place, "bpy.data.meshes.new("), (bodies["boolean"], ".objects.link("), (bodies["apply"], "bpy.data.meshes.new_from_object("),
|
||||
(bodies["ribs"], "show_viewport = False"), (bodies["shell"], "clear_geometry()")):
|
||||
self.assertLess(body.index("evaluable("), body.index(first_write))
|
||||
self.assertEqual([name for name, body in bodies.items() if "evaluable(" in body], ["boolean", "apply", "ribs", "shell"])
|
||||
self.assertEqual([name for name, body in bodies.items() if "evaluable(" in body], ["boolean", "apply", "ribs", "shell", "hose"])
|
||||
ribs = bodies["ribs"] # every refusal before the ribs object is written, and the cage's modifiers shown again whatever happened
|
||||
self.assertLess(ribs.rindex("raise Refused("), ribs.index("mesh = bpy.data.meshes.new(self.ribs_name)"))
|
||||
self.assertLess(ribs.index("finally:"), ribs.index("modifier.show_viewport = True"))
|
||||
|
|
@ -1773,6 +1773,47 @@ class OwnershipTests(unittest.TestCase):
|
|||
self.assertEqual(len(re.findall(rf"(?<!['\"])\b{name}\b(?!['\"])" if name[0] != '"' else name, source.replace(body, ""))), 0 if name[0] == '"' else 1, name)
|
||||
self.assertIn(name, body)
|
||||
|
||||
def test_only_hose_writes_kit_hose(self):
|
||||
"""kit_hose is the request a hose was routed from: hose assigns it once, after its last refusal, and outside
|
||||
hose it is named only by its constant's line. The path is route.py's, which needs no Blender; every tube is
|
||||
core.sweep's: no curve object, no hide flag and no deleted object stand in for either (mutant H11: a write
|
||||
before the range's refusal)."""
|
||||
source = self.sources()["__init__.py"]
|
||||
body = source.split("class BROKKR_KITBASH_OT_hose(")[1].split("class BROKKR_KITBASH_OT_")[0]
|
||||
writes = re.findall(r'[^\n]*\[(?:HOSE|"kit_hose")\]\s*=(?!=)[^\n]*', source)
|
||||
self.assertEqual(len(writes), 1)
|
||||
self.assertIn(writes[0], body)
|
||||
self.assertEqual(len(re.findall(r'\bHOSE\b|"kit_hose"', source.replace(body, ""))), 2) # outside hose: the constant's own line, its name and its value
|
||||
self.assertEqual(re.findall(r"\[HOSE\]|HOSE not in hose|HOSE in \w+", body), ["HOSE not in hose", "[HOSE]"])
|
||||
work = body.split(" @staticmethod")[0]
|
||||
first = min(work.index(write) for write in ("clear_geometry()", "bpy.data.meshes.new(", "write_mesh(", ".parent =", "[HOSE] ="))
|
||||
self.assertLess(work.rindex("raise Refused("), first) # every refusal before any write
|
||||
for call in ("route.leg(", "self.shaped(", "self.built(", "self.trees(", "self.crossed(", "self.rows()", "self.frame("):
|
||||
self.assertLess(work.rindex(call), first, call)
|
||||
shaped = body.split(" def shaped(")[1].split(" def built(")[0]
|
||||
self.assertLess(shaped.index("route.fillet("), shaped.index("route.verify("))
|
||||
self.assertLess(shaped.index("route.verify("), shaped.index("route.passes("))
|
||||
self.assertEqual((body.count("route.fillet("), body.count("route.verify("), body.count("route.passes("), body.count("route.leg(")), (1, 1, 1, 1)) # every leg and both sags through one path
|
||||
for pattern in (r"bevel_depth|curves\.new|\"CURVE\"", r"objects\.remove|meshes\.remove|to_mesh\(", r"scene\.frame_set|view_layer\.update|write_connection\(|\[ROLL\]"):
|
||||
self.assertIsNone(re.search(pattern, body), pattern) # no curve object, nothing deleted or baked, and no part posed to measure a roll
|
||||
self.assertIsNone(re.search(r"bevel_depth|curves\.new|\"CURVE\"", source))
|
||||
self.assertIsNone(re.search(r"^import bpy|^from bpy|^import bmesh|mathutils", self.sources()["route.py"], re.M))
|
||||
self.assertEqual(len(re.findall(r"core\.sweep\(", body)), 5) # a hose, two collars, a strap and a pad
|
||||
self.assertIsNone(re.search(r"def sweep|sweep\(", self.sources()["route.py"])) # route.py sweeps nothing
|
||||
|
||||
def test_the_hose_row_takes_its_bounds(self):
|
||||
host = [{**row, "host": "brokkr_kitbash"} for row in json.loads((SURFACE / "brokkr_kitbash" / "brokkr_actions.json").read_text(encoding="utf-8"))["actions"]]
|
||||
hose = {"schema": "brokkr.blender.command_intent.v0", "commandId": "t-1", "requestedBy": "test/driver", "action": "brokkr_kitbash.hose", "object_name": "Hose",
|
||||
"start": "Ram:port_cap", "end": "Feed"}
|
||||
admitted = at.validate(hose, host)
|
||||
self.assertEqual([admitted[k] for k in ("count", "radius", "spread", "clearance", "bend", "step", "sag", "clamps", "joint")], [1, 0.01, 0, 0.01, 4, 0.02, 1, "[]", ""])
|
||||
at.validate({**hose, "count": 8, "radius": 0.003, "step": 0.005, "sag": 0, "joint": '{"socket": "Shin:end_a_back", "standoff": 0.05, "range": [-120, 10]}'}, host)
|
||||
for bad in ({**hose, "count": 9}, {**hose, "count": 1.5}, {**hose, "radius": 0.002}, {**hose, "step": 0.004}, {**hose, "bend": 0.5}, {**hose, "sag": 9}, {**hose, "clamps": ""},
|
||||
{**hose, "clamps": "[" + " " * 4000}, {**hose, "joint": "{" + " " * 4000}, {k: v for k, v in hose.items() if k != "end"}, {**hose, "start": ""}, {**hose, "object_name": "x" * 64},
|
||||
{**hose, "range": [0, 1]}):
|
||||
with self.assertRaises(at.IntentInvalid, msg=str(bad)[:200]):
|
||||
at.validate(bad, host)
|
||||
|
||||
def test_only_write_connection_writes_the_roll(self):
|
||||
"""one-writer. kit_roll is the one statement of a connection's roll, and write_connection its one writer: attach
|
||||
and pose (roll, aim and reach) call it; set_params and the reports read the roll and never write it back.
|
||||
|
|
|
|||
|
|
@ -245,6 +245,13 @@ class FrameTests(unittest.TestCase):
|
|||
route.frames(planar, planar[1] - planar[0])
|
||||
|
||||
|
||||
def test_a_short_straight_between_two_arcs_is_dropped(self):
|
||||
curve = np.array([[0.0, 0, 0], [1.0, 0, 0], [1.0 + 1e-6, 0, 0], [2.0, 1, 0], [2.0, 1 + 1e-6, 0]])
|
||||
self.assertEqual(route.thinned(curve, 1e-3).tolist(), curve[[0, 1, 4]].tolist()) # the ends stay, the last in place of a point beside it
|
||||
self.assertEqual(route.thinned(curve, 1e-9).tolist(), curve.tolist())
|
||||
self.assertEqual(route.thinned(curve[:2], 10.0).tolist(), curve[:2].tolist())
|
||||
|
||||
|
||||
@unittest.skipIf(np is None, "numpy is not installed")
|
||||
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
|
||||
|
|
|
|||
Loading…
Reference in a new issue