brokkr_kitbash.ribs: ribs, holes, posts and longerons derived from an armor cage as it is cut; the shell-cuts Lows (cut kit-ribs) #30

Merged
eureka merged 8 commits from nibu/kit-ribs into main 2026-12-02 10:18:57 +00:00
13 changed files with 2763 additions and 329 deletions

View file

@ -32,14 +32,23 @@ cut cuts a mesh where a ray meets it. The cut is a placed part of the cutters ki
identity parent inverse: its matrix_basis is the recess frame and its params the recess size, so moving or resizing
the cutter object moves the cut and its floor socket together, and nothing else stores either. Machinery attaches
to a floor socket with the ordinary attach. Blender evaluates a changed target after every action, so each cut costs
one Boolean evaluation; cut_many places many cutters for one.
one Boolean evaluation; cut_many places many cutters for one. Every action that evaluates an object (boolean, cut,
cut_many, apply) first refuses one Blender does not evaluate (evaluable). A report's list that would not fit a
receipt is trimmed by fitted, the rows left off counted beside it: the scene keeps what they would have said.
ribs derives the frame under an armor cage from the cage: ribs behind the plate along plane sections, stopped where
the plate is open (core.band), with lightening holes, posts and longerons (core.sweep). What it reads is the cage evaluated
whole (where the plate is) and with its Solidify, Bevel and Booleans off (the surface as designed); it never reads
a cutter. The ribs object is a bake of the cage at that call, and kit_ribs on it is the request, kept as a record:
nothing reads it to decide geometry, and ribs is its one writer. The one Manifold Boolean in the package is the hole
cut inside ribs, on webs it built as closed shells that do not cross; a target's live Booleans stay Exact.
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
solves a loop: a closure never places a part, and a report says how far its two sockets stand apart.
"""
bl_info = {"name": "Brokkr Kitbash", "author": "GameCult", "version": (0, 1, 0), "blender": (4, 2, 0),
bl_info = {"name": "Brokkr Kitbash", "author": "GameCult", "version": (0, 1, 0), "blender": (5, 3, 0),
"category": "Object", "description": "Parametric machine parts from kits, with socket frames; agent-callable through Brokkr."}
import json
@ -68,6 +77,8 @@ CUTTERS = "cutters" # the kit whose parts cut places
OPERATIONS = ("DIFFERENCE", "UNION", "INTERSECT") # a target's Boolean modifiers, "Kit " + operation.title(), in the order they are evaluated
BEVEL_SEGMENTS, BEVEL_ANGLE = 2, math.radians(30.0)
REPORT_LIMIT = 16000 # characters of a result Brokkr copies into a receipt before it truncates
RIBS_LIMIT = 64 # planes in one ribs
LONGERONS_LIMIT = 16 # longerons in one ribs
def kit_work(work):
@ -297,8 +308,7 @@ def closure_report(obj, part, built, held=None, kits=None):
def scene_closures(context, report: dict, ends=()) -> list:
"""Every closure stated in the scene as {part, to, holds}, for a set_params report: a change of params can open
a closure anywhere below the part. The closures `ends` are parts of come first, then those that do not hold,
then the rest, each by name; rows that would take the report past what a receipt carries are left off the end
and counted in closuresOmitted."""
then the rest, each by name, trimmed to a receipt by fitted."""
held, kits, rows = closers(), {}, []
for obj in (o for o in context.scene.objects if o.type == "MESH" and CLOSE in o):
try:
@ -306,14 +316,7 @@ def scene_closures(context, report: dict, ends=()) -> list:
except (Refused, core.KitError): # the closing part itself cannot be read (scaled)
found = {"to": closure(obj)[1].name if closure(obj)[1] else None, "holds": False}
rows.append((obj not in ends and closure(obj)[1] not in ends, found["holds"], obj.name, {"part": obj.name, "to": found["to"], "holds": found["holds"]}))
kept, size = [], len(json.dumps(report, separators=(",", ":"))) + 40
for *_, row in sorted(rows, key=lambda r: r[:3]):
size += len(json.dumps(row, separators=(",", ":"))) + 1
if size > REPORT_LIMIT:
report["closuresOmitted"] = len(rows) - len(kept)
break
kept.append(row)
return kept
return fitted(report, "closures", [row for *_, row in sorted(rows, key=lambda r: r[:3])])
def part_report(obj, part, built) -> dict:
@ -375,6 +378,17 @@ def evaluated_of(context, obj):
return depsgraph, obj.evaluated_get(depsgraph)
def evaluable(context, obj):
"""evaluated_of, for an object Blender evaluates: refuses one the evaluated depsgraph does not hold, which has no
evaluated mesh to cast at, cut or bake. Membership of the depsgraph is the test, whatever keeps the object out
of it. Every action that evaluates calls this before its first write."""
depsgraph, evaluated = evaluated_of(context, obj)
if not evaluated.is_evaluated:
raise Refused(f"Blender does not evaluate {obj.name!r} in this view layer: it is disabled in viewports, or in no collection the "
"view layer shows. Enable it, or link it to the scene; nothing changed.")
return depsgraph, evaluated
def measured(mesh) -> dict:
"""Faces, signed volume (overlapping shells count twice) and edges that do not join exactly two faces."""
bm = bmesh.new()
@ -407,13 +421,27 @@ def bounded(report: dict, advice: str) -> dict:
return report
def place_cutters(context, target, specs, report=None) -> list:
def fitted(report: dict, key: str, rows: list) -> list:
"""The rows of one list of a report that fit what a receipt carries beside the rest of the report, in order; those
left off the end are counted in report[key + 'Omitted']. The one rule that trims a report's rows to a receipt:
the scene keeps what the rows would have said."""
kept, size = [], len(json.dumps(report, separators=(",", ":"))) + 2 * len(key) + 24
for row in rows:
size += len(json.dumps(row, separators=(",", ":"))) + 1
if size > REPORT_LIMIT:
report[key + "Omitted"] = len(rows) - len(kept)
break
kept.append(row)
return kept
def place_cutters(context, target, specs) -> list:
"""Place a cutters part for each spec ({name, part, origin, direction} and optionally params, up, roll, axis; the
vectors in the target's own frame) and add them to the target's difference Boolean; [(cutter, part, built)].
Every refusal comes before any write. The rays are cast in one evaluation of the target with its Kit Booleans
off, the surface as designed and not as already cut: a second cut on the ray of a through bay lands where the
first did, and no Boolean is evaluated here. Blender evaluates the changed target once after the action, however
many cutters it placed. `report`, given the booleans rows to be, may refuse a report too long for a receipt."""
many cutters it placed."""
rigid(target)
kit, made, names = core.load_kit(CUTTERS), [], set()
for spec in specs:
@ -430,7 +458,7 @@ def place_cutters(context, target, specs, report=None) -> list:
try:
for modifier in cuts:
modifier.show_viewport = False
depsgraph, _ = evaluated_of(context, target)
depsgraph, _ = evaluable(context, target)
tree = BVHTree.FromObject(target, depsgraph)
finally:
for modifier in cuts:
@ -447,8 +475,6 @@ def place_cutters(context, target, specs, report=None) -> list:
raise Refused(f"{spec['name']!r}: the axis {tuple(round(v, 6) for v in axis)} points into the surface (its normal there is "
f"{tuple(round(v, 6) for v in normal)}); nothing changed.")
frames.append(core.surface_frame(hit, axis if axis.length > 0.0 else normal, spec.get("up", (0.0, 0.0, 1.0)), spec.get("roll", 0.0)))
if report is not None:
report(booleans(target) + [{"cutter": spec["name"], "operation": "DIFFERENCE"} for spec in specs])
placed = []
for spec, (part, built), frame in zip(specs, made, frames):
mesh = bpy.data.meshes.new(spec["name"])
@ -743,10 +769,12 @@ class BROKKR_KITBASH_OT_boolean(PolishOperator):
report = part_report(obj, *built_part(obj)) if PART in obj else {"object": obj.name}
rigid(obj)
uncut(obj, cutter)
evaluable(context, obj)
operation_collection(obj, self.operation, True).objects.link(cutter)
_, evaluated = evaluated_of(context, obj)
report["booleans"], report["evaluated"] = booleans(obj), measured(evaluated.to_mesh())
report["evaluated"] = measured(evaluated.to_mesh())
evaluated.to_mesh_clear()
report["booleans"] = fitted(report, "booleans", booleans(obj))
return report
@ -782,7 +810,9 @@ class BROKKR_KITBASH_OT_cut(PolishOperator):
"origin": (self.origin_x, self.origin_y, self.origin_z), "direction": (self.direction_x, self.direction_y, self.direction_z),
"up": (self.up_x, self.up_y, self.up_z), "axis": (self.axis_x, self.axis_y, self.axis_z)}
(cutter, part, built), = place_cutters(context, target, [spec])
return {"object": target.name, "cutter": part_report(cutter, part, built), "booleans": booleans(target)}
report = {"object": target.name, "cutter": part_report(cutter, part, built)}
report["booleans"] = fitted(report, "booleans", booleans(target))
return report
CUT_KEYS = {"name": str, "part": str, "params": str, "origin": list, "direction": list, "up": list, "axis": list, "roll": (int, float)}
@ -815,9 +845,9 @@ class BROKKR_KITBASH_OT_cut_many(PolishOperator):
if not isinstance(value, CUT_KEYS[key]) or isinstance(value, bool) or (vector and (len(value) != 3 or not all(core.finite(v) for v in value))) \
or (key == "roll" and not (core.finite(value) and -360.0 <= value <= 360.0)) or (key == "name" and not 1 <= len(value) <= 63):
raise Refused(f"{where}.{key} must be {'three numbers' if vector else 'a number from -360 to 360' if key == 'roll' else 'a string' + (' of 1 to 63 characters' if key == 'name' else '')}; nothing changed.")
placed = place_cutters(context, target, specs, report=lambda rows: bounded({"object": target.name, "cutters": [spec["name"] for spec in specs], "booleans": rows},
"cut fewer at once"))
return {"object": target.name, "cutters": [cutter.name for cutter, _, _ in placed], "booleans": booleans(target)}
report = {"object": target.name, "cutters": [cutter.name for cutter, _, _ in place_cutters(context, target, specs)]}
report["booleans"] = fitted(report, "booleans", booleans(target))
return report
class BROKKR_KITBASH_OT_apply(PolishOperator):
@ -831,6 +861,7 @@ class BROKKR_KITBASH_OT_apply(PolishOperator):
@kit_work
def work(self, context):
obj = mesh_object(self.object_name)
evaluable(context, obj)
part, built = built_part(obj)
own_mesh(obj, "baking")
if not obj.modifiers:
@ -858,6 +889,400 @@ class BROKKR_KITBASH_OT_apply(PolishOperator):
return {**part_report(obj, part, built), **measured(baked), "cutters": cutters}
RIBS = "kit_ribs" # on a ribs object: the request that derived it, as JSON; nothing reads it to decide geometry
SAMPLES_LIMIT = 20000 # section points in one ribs: every chain's length over step, summed
SHELL_MODIFIERS = ("SOLIDIFY", "BEVEL", "BOOLEAN") # what makes a designed surface a cut plate: off, the cage shows the surface
LIFT = 0.01 # metres outside the plate's outer face that the ray asking "is the plate here" starts
NUDGE = 1e-4 # metres along the section that ray is moved off its point: a section's corners lie on the cage's edges, and a ray along an edge can slip between two faces
HOLE_SEGMENTS, POST_SEGMENTS, PAD_SEGMENTS = 16, 8, 12
STANDOFF_CLIP = 1e-6 # of the standoff: a point of the offset surface that stands this much nearer the plate than the standoff is where the surface folded, and is left out
STANDOFF_HELD = 1e-7 # metres inside the standoff that a rib's edge may measure and hold it: what a float32 tree's distances are good to
STANDOFF_ROUNDS = 8 # times a rib's edge is measured against the plate and moved in by what it is short
POST_SUNK = 0.5 # of the plate's thickness: how far under the outer face a post starts
# What a plane's lightening holes removed from its webs, over the holes' faceted area times the rib's thickness, less 1.
# Bound by lodur:ruling:deterministic-bound-margin: shipped worst 2.9e-06 (tests/live/kitbash_ribs.py: thirteen planes
# on a pod, a deck and an egg-crate, float32 meshes); least claimed bad cut 0.0066 (holes of radius 0.018 pitched 0.02,
# which overlap, on the egg-crate); the geometric mean, separation 47 each side.
HOLED = 1.4e-4
def vectors(text: str, what: str, keys, least: int, limit: int) -> list:
"""A JSON array of objects whose every key is three finite numbers, as arrays; anything else is refused."""
try:
rows = json.loads(text)
except ValueError as error:
raise Refused(f"{what} is not JSON ({error}); nothing changed.") from None
if not isinstance(rows, list) or not least <= len(rows) <= limit:
raise Refused(f"{what} must be a JSON array of {least} to {limit} objects; nothing changed.")
for index, row in enumerate(rows):
if not isinstance(row, dict) or set(row) != set(keys) or not all(isinstance(row[k], list) and len(row[k]) == 3 and all(core.finite(v) for v in row[k]) for k in keys):
raise Refused(f"{what}[{index}] must be an object of {' and '.join(keys)}, each three numbers; nothing changed.")
return [{k: np.array(row[k], dtype=np.float64) for k in keys} for row in rows]
def chains_of(edges) -> list:
"""The edges a plane cut, ordered into polylines: [(points (N, 3), closed)], open ones first, each from its
lowest vertex. None when a vertex joins three or more cut edges: no polyline passes it."""
links = {}
for edge in edges:
a, b = edge.verts
links.setdefault(a, []).append(b)
links.setdefault(b, []).append(a)
if any(len(found) > 2 for found in links.values()):
return None
seen, chains = set(), []
for start in sorted((v for v in links if len(links[v]) == 1), key=lambda v: v.index) + sorted(links, key=lambda v: v.index):
if start in seen:
continue
chain, here = [start], start
seen.add(start)
while True:
ahead = [v for v in links[here] if v not in seen]
if not ahead:
break
here = ahead[0]
chain.append(here)
seen.add(here)
chains.append((np.array([v.co for v in chain], dtype=np.float64), len(chain) > 2 and chain[0] in links[chain[-1]]))
return chains
def along(points, closed: bool, pitch: float):
"""Stations on a polyline every `pitch` of its length, half a pitch from an open one's ends (none on one shorter
than a pitch), evenly round a closed one: [(point, segment index, fraction along the segment)]."""
loop = np.vstack([points, points[:1]]) if closed else points
reach = np.concatenate([[0.0], np.cumsum(np.linalg.norm(np.diff(loop, axis=0), axis=1))])
count = int(reach[-1] / pitch + 1e-6) # a length that is a whole number of pitches but for a float32's rounding holds them all
found = []
for at in (reach[-1] * np.arange(count) / max(count, 1) if closed else pitch / 2 + pitch * np.arange(count)):
segment = min(int(np.searchsorted(reach, at, side="right")) - 1, len(loop) - 2)
fraction = (at - reach[segment]) / (reach[segment + 1] - reach[segment])
found.append((loop[segment] + (loop[segment + 1] - loop[segment]) * fraction, segment, fraction))
return found
def shells_of(mesh) -> core.Swept:
"""A mesh datablock's vertices and faces as core.Swept, every face flat."""
V, faces, counts = np.zeros(3 * len(mesh.vertices)), np.zeros(len(mesh.loops), dtype=np.int32), np.zeros(len(mesh.polygons), dtype=np.int32)
mesh.vertices.foreach_get("co", V)
mesh.loops.foreach_get("vertex_index", faces)
mesh.polygons.foreach_get("loop_total", counts)
return core.Swept(V=V.reshape(-1, 3), faces=faces, counts=counts, smooth=np.zeros(len(counts), dtype=bool), sharp=core.NO_SHARP.astype(np.int32))
class BROKKR_KITBASH_OT_ribs(PolishOperator):
"""Derive the frame under an armor cage from the cage itself: a rib behind the plate along each plane's section,
stopped where the plate is open, lightening holes through the ribs, posts that stand the plate off them, and
longerons through the ribs; one mesh object, a child of the cage, baked at this call"""
bl_idname = "brokkr_kitbash.ribs"
bl_label = "Ribs From A Shell"
object_name: bpy.props.StringProperty(name="Object", description="The cage: a mesh whose surface is the plate's designed face, usually subdivided and with one Solidify")
ribs_name: bpy.props.StringProperty(name="Ribs", description="The new ribs object's name")
planes: bpy.props.StringProperty(name="Planes", description="A JSON array of 1 to 64 planes, each {origin, normal} in the cage's own frame: a rib runs where each cuts the surface")
standoff: bpy.props.FloatProperty(name="Standoff", default=0.09, min=0.0, max=2.0, description="Metres between the plate's inner face and the ribs, along the plate's normal")
depth: bpy.props.FloatProperty(name="Depth", default=0.09, min=0.005, max=2.0, description="How far a rib reaches inward from there")
thickness: bpy.props.FloatProperty(name="Thickness", default=0.014, min=0.0005, max=1.0, description="A rib's thickness across its plane")
step: bpy.props.FloatProperty(name="Step", default=0.01, min=0.001, max=1.0, description="Spacing of the points a section is followed by")
holes: bpy.props.FloatProperty(name="Holes", default=0.0, min=0.0, max=10.0, description="Pitch of lightening holes along each rib, radius 0.3 of depth; 0: none")
posts: bpy.props.FloatProperty(name="Posts", default=0.0, min=0.0, max=10.0, description="Pitch of the posts that stand the plate off each rib; 0: none")
post_r: bpy.props.FloatProperty(name="Post Radius", default=0.011, min=0.0005, max=0.5)
bridge: bpy.props.FloatProperty(name="Bridge", default=0.05, min=0.0, max=2.0, description="An opening shorter than this along a section is a panel break: the rib runs behind it")
clearance: bpy.props.FloatProperty(name="Clearance", default=0.02, min=0.0, max=2.0, description="How far a rib stops short of any other opening")
longerons: bpy.props.StringProperty(name="Longerons", default="[]", description="A JSON array of 0 to 16 longerons, each {origin, axis, toward} in the cage's own frame: "
"the half-plane from the line through origin along axis, on toward's side; the longeron runs through each plane's rib where it crosses")
longeron: bpy.props.EnumProperty(name="Longeron", default="T", items=[(name, name, "") for name in core.PROFILES])
longeron_w: bpy.props.FloatProperty(name="Longeron Width", default=0.05, min=0.005, max=2.0)
longeron_h: bpy.props.FloatProperty(name="Longeron Height", default=0.05, min=0.005, max=2.0)
longeron_t: bpy.props.FloatProperty(name="Longeron Wall", default=0.008, min=0.0005, max=1.0)
# the action table states each bound (thickness, step and the walls from 0.001 or 0.002): a float property rounds 0.001 up, so these stand just under
@kit_work
def work(self, context):
cage = mesh_object(self.object_name)
rigid(cage)
depsgraph, _ = evaluable(context, cage)
if not 1 <= len(self.ribs_name) <= 63 or self.ribs_name in bpy.data.objects:
raise Refused(f"ribs_name {self.ribs_name!r} must be 1 to 63 characters and no object's name; nothing changed.")
planes = vectors(self.planes, "planes", ("origin", "normal"), 1, RIBS_LIMIT)
longerons = vectors(self.longerons, "longerons", ("origin", "axis", "toward"), 0, LONGERONS_LIMIT)
for index, plane in enumerate(planes):
if not np.linalg.norm(plane["normal"]) > 0:
raise Refused(f"planes[{index}].normal has no direction; nothing changed.")
plane["normal"] = plane["normal"] / np.linalg.norm(plane["normal"])
if longerons and len(planes) < 2:
raise Refused("A longeron runs through the ribs of two or more planes; this call has one; nothing changed.")
beam = core.profile(self.longeron, self.longeron_w, self.longeron_h, self.longeron_t) if longerons else None
walls = [m for m in cage.modifiers if m.type == "SOLIDIFY" and m.show_viewport]
if len(walls) > 1:
raise Refused(f"{cage.name!r} has {len(walls)} Solidify modifiers ({', '.join(m.name for m in walls)}): its plate has one thickness, read from one; nothing changed.")
# a Solidify of negative thickness grows the other way: the same plate as its size with the offset turned over
plate, offset = (abs(walls[0].thickness), math.copysign(1.0, walls[0].thickness) * walls[0].offset) if walls else (0.0, 0.0)
outer, inner = plate * (1.0 + offset) / 2.0, plate * (1.0 - offset) / 2.0 # the plate's two faces, out of and into the designed surface
whole = BVHTree.FromObject(cage, depsgraph) # the plate as it is cut: where a ray into it finds nothing, it is open
shown = [m for m in cage.modifiers if m.type in SHELL_MODIFIERS and m.show_viewport]
surface, made, drilled, sections, webs, rods, beams, samples, holes = None, [], [], [], [], [], [], 0, 0
try:
for modifier in shown: # this tags the cage, and Blender evaluates it whole again after the call: one evaluation a call, and no cheaper way to the designed surface (docs/kitbash.md, Ribs from a shell)
modifier.show_viewport = False
_, designed = evaluated_of(context, cage)
surface = bmesh.new()
surface.from_mesh(designed.to_mesh())
designed.to_mesh_clear()
nearest = BVHTree.FromBMesh(surface)
at = np.array([v.co for v in surface.verts], dtype=np.float64).reshape(-1, 3)
polygons = [tuple(v.index for v in face.verts) for face in surface.faces]
inner_at = outer_at = at
if walls: # the plate's two faces as its Solidify makes them, whatever its thickness mode: a simple Solidify writes the surface's vertices twice, in the surface's order
walls[0].show_viewport = True
_, walled = evaluated_of(context, cage)
wall = walled.to_mesh()
both = np.zeros(3 * len(wall.vertices))
wall.vertices.foreach_get("co", both)
walled.to_mesh_clear()
walls[0].show_viewport = False
if len(both) == 6 * len(at):
both = both.reshape(2, -1, 3).astype(np.float64)
out_of = [float(np.einsum("ij,ij->", face - at, np.array([v.normal for v in surface.verts]))) for face in both] # the inner face is the one further against the normals
inner_at, outer_at = (both[0], both[1]) if out_of[0] < out_of[1] else (both[1], both[0])
else: # a modifier after the Solidify remade its vertices (a Subsurf), or it is not a simple one: the plate is taken as its thickness behind every face of the surface
behind = core.inset(at, polygons)
inner_at, outer_at = at + inner * behind, at - outer * behind
skin = BVHTree.FromPolygons(inner_at.tolist(), polygons) # the plate's inner face: what the standoff is measured from
hide = BVHTree.FromPolygons(outer_at.tolist(), polygons) if self.posts > 0 else None # its outer face: what no post may stand through
# The inner face offset inward by the standoff, along its own faces' normals: a rib's outer edge is cut from this, so it
# stands the standoff off the plate at any tilt of its plane and any curvature of the wall.
offset = BVHTree.FromPolygons((inner_at + self.standoff * core.inset(inner_at, polygons)).tolist(), polygons)
clip = STANDOFF_CLIP * self.standoff + 1e-7 # and what a float32 tree's distances are good to
def short(points) -> float:
"""How far the nearest of some points comes inside the standoff: over 0, too near the plate."""
return self.standoff - min(skin.find_nearest(Vector(point))[3] for point in points)
for index, plane in enumerate(planes):
where, normal = f"planes[{index}]", plane["normal"]
cut = surface.copy()
edges = [g for g in bmesh.ops.bisect_plane(cut, geom=cut.verts[:] + cut.edges[:] + cut.faces[:], plane_co=Vector(plane["origin"]), plane_no=Vector(normal),
dist=1e-6)["geom_cut"] if isinstance(g, bmesh.types.BMEdge)]
cut.verts.index_update()
chains = chains_of(edges)
cut.free()
if chains is None:
raise Refused(f"{where} cuts {cage.name!r} where three or more of its faces share an edge: no section passes there; nothing changed.")
if not chains:
raise Refused(f"{where} misses {cage.name!r}; nothing changed.")
row = {"plane": index, "chains": len(chains), "pieces": 0, "length": 0.0, "open": 0.0, "ribs": [], "lines": []}
for points, closed in chains:
samples += int(np.linalg.norm(np.diff(points, axis=0), axis=1).sum() / self.step) + 1
if samples > SAMPLES_LIMIT:
raise Refused(f"The sections are over {SAMPLES_LIMIT} points at step {self.step:.6g}: raise step, or give fewer planes; nothing changed.")
P = core.resample(points, closed, self.step)
between = ((P + np.roll(P, -1, axis=0)) / 2.0)[:len(P) if closed else len(P) - 1] # the middle of each segment: a point of one facet, where a corner is a point of two
out, facing = (np.array([nearest.find_nearest(Vector(p))[1] for p in at_points], dtype=np.float64) for at_points in (P, between))
flat = out - normal * (out @ normal)[:, None]
upright = np.sqrt(1.0 - np.minimum((facing @ normal) ** 2, 1.0)) # the cosine of how far the plate's normal leans out of the plane, a segment
if not (np.linalg.norm(flat, axis=1) > 1e-3).all() or not (upright > 1e-3).all():
raise Refused(f"{where} lies along {cage.name!r}'s surface where it meets it: a rib needs a plane that crosses the plate; nothing changed.")
inward = -flat / np.linalg.norm(flat, axis=1)[:, None] # square in from the plate, along the plane
beside = (lambda of: np.maximum(of, np.roll(of, 1))) if closed else (lambda of: np.maximum(np.concatenate([of, of[-1:]]), np.concatenate([of[:1], of]))) # a point's greater of its two segments'
slope = beside(1.0 / upright)
ahead = np.roll(P, -1, axis=0) - np.roll(P, 1, axis=0) if closed else np.gradient(P, axis=0)
turn = np.cross(ahead, inward) @ normal # which side of the section its normals stand on: one sign all the way along
if (turn > 0).any() and (turn < 0).any():
raise Refused(f"{where}: the normals of {cage.name!r} change sides along the section (some of its faces are flipped): "
"recalculate its normals so they all face out of the plate; nothing changed.")
aside = np.roll(P, -1, axis=0) - P if closed else np.vstack([np.diff(P, axis=0), P[-2:-1] - P[-1:]]) # toward the next point; an open chain's last, toward the one before
aside = aside / np.linalg.norm(aside, axis=1)[:, None] * NUDGE
# Where the offset surface stands behind each point of the section, square in along the plane: a point of the rib's
# edge. One that stands nearer the plate than the standoff landed where the offset surface has passed through itself,
# behind a corner of the section or inside a curve tighter than the standoff: it is left out. The rib's edge on
# the side the plate leans over is half a thickness nearer the plate than its middle, which the offset surface was
# cut at: along the plane that is `leaned`, from the lean of the offset face the point landed on.
edge, near, leaned, landed, steep = np.zeros_like(P), np.full(len(P), np.inf), np.zeros(len(P)), np.zeros_like(P), np.ones(len(P))
for k, (p, n) in enumerate(zip(P, inward)):
for start in (p, p + aside[k]): # a ray along the offset surface's own rim can slip past it: an end of the section looks again from just inside
hit = offset.ray_cast(Vector(start - n * 1e-5), Vector(n), (plate + self.standoff) * (2.0 * slope[k] + 2.0) + 1e-3)
if hit[0] is not None:
break
if hit[0] is not None:
tilt = min(abs(float(np.array(hit[1]) @ normal)), 1.0 - 1e-6)
steep[k] = 1.0 / math.sqrt(1.0 - tilt * tilt) # along the plane, over along the normal, where the point landed: the offset surface leans more than the plate where the wall is round
edge[k], near[k], landed[k], leaned[k] = p + n * (hit[3] - 1e-5), short([hit[0]]), hit[1], self.thickness / 2.0 * tilt * steep[k] # the point itself moved along its way: the tree's own point is a float32
def met(a, b):
"""The edge's corner between two of its points that landed on different faces of the offset surface: where
those faces' lines in the plane meet. None where they do not meet between the two points, or meet nearer
the plate than the standoff (faces either side of a fold)."""
ways = np.stack([np.cross(normal, landed[a]), -np.cross(normal, landed[b])], axis=1)
(s, t), _, rank, _ = np.linalg.lstsq(ways, edge[b] - edge[a], rcond=None)
corner, apart = edge[a] + s * ways[:, 0], edge[b] - edge[a]
if (rank == 2 and np.linalg.norm(corner - (edge[b] - t * ways[:, 1])) < 1e-6 and 0.0 < (corner - edge[a]) @ apart < apart @ apart
and np.linalg.norm(corner - edge[a]) < 4.0 * np.linalg.norm(apart) + self.step and short([corner]) <= clip):
return corner
return None
reach = LIFT + 1.25 * plate + 1e-4
opened = [whole.ray_cast(Vector(p + n * (outer + LIFT)), Vector(-n), reach)[0] is None for p, n in zip(P + aside, out)]
lengths = np.linalg.norm(np.diff(np.vstack([P, P[:1]]) if closed else P, axis=0), axis=1)
row["lines"].append((P + inward * ((inner + self.standoff) * slope + self.depth / 2.0)[:, None], closed)) # about where a rib would run: only asked whether a longeron crosses it
for piece in core.spans(opened, lengths, closed, self.bridge, self.clearance):
ring = closed and len(piece) == len(P)
kept = piece[near[piece] <= clip]
if len(kept) < (3 if ring else 2):
raise Refused(f"{where}: the section leaves a rib no room: it turns or closes in tighter than the rib reaches: lower standoff or depth; nothing changed.")
node = lambda k: [edge[k], inward[k], steep[k], leaned[k], False, ahead[k]] # noqa: E731 a point of the edge: where, which way in, its slope, its lean, whether it is a corner, and the section's way there
nodes = []
for k in range(len(kept) if ring else len(kept) - 1):
a, b = kept[k], kept[(k + 1) % len(kept)]
nodes.append(node(a))
corner = met(a, b) if np.abs(landed[a] - landed[b]).max() > 1e-6 else None # the rays only sample the edge: its corners are the offset surface's own
if corner is not None:
nodes.append([corner, (inward[a] + inward[b]) / np.linalg.norm(inward[a] + inward[b]), max(steep[a], steep[b]), max(leaned[a], leaned[b]), True, ahead[a] + ahead[b]])
if not ring:
nodes.append(node(kept[-1]))
run = nodes[:1]
onward = lambda u, v: (v[0] - u[0]) @ v[5] > 1e-5 * np.linalg.norm(v[5]) # noqa: E731 v stands on from u the way the section runs, by more than a hundredth of a millimetre
for here in nodes[1:]: # an edge that steps back against its section has folded there: the point that did it is left out
if onward(run[-1], here):
run.append(here)
while ring and len(run) > 3 and not onward(run[-1], run[0]):
run.pop()
if len(run) < (3 if ring else 2):
raise Refused(f"{where}: the section leaves a rib no room: it turns or closes in tighter than the rib reaches: lower standoff or depth; nothing changed.")
Q, into = (np.array([here[field] for here in run]) for field in (0, 1))
# a segment's half thickness is laid off by its own wall's lean: beside a corner, the lean of its end that is no corner
back = np.array([v[3] if u[4] and not v[4] else u[3] if v[4] and not u[4] else max(u[3], v[3]) for u, v in zip(run, run[1:] + run[:1] if ring else run[1:])])
grade, more, gain, lack = np.array([max(u[2], v[2]) for u, v in zip(run, run[1:] + run[:1] if ring else run[1:])]), 0.0, 1.0, 0.0
for _ in range(STANDOFF_ROUNDS):
# What is left is of the second order (half a thickness laid off along the plane beside a curved or tilted
# wall, a chord across a facet): measured on the rib's own edge, and the edge moved in by what it is short.
try:
rib = core.band(Q, ring, normal, into, back + more * grade, self.depth, self.thickness)
except core.KitError as error:
raise Refused(f"{where}: {error}: lower standoff or depth; nothing changed.") from None
before, lack = lack, short(rib.shell.V[:2 * len(rib.outer)])
if lack <= STANDOFF_HELD:
break
if lack < before: # the last move closed this much of what was short: the next is sized by it (a steep wall gives back less than it is given)
gain = min(gain * before / (before - lack), 8.0)
more += 1.05 * gain * lack + STANDOFF_HELD
else:
raise Refused(f"{where}: a rib there cannot be stood {self.standoff:.6g} off the plate (it comes {lack:.3g} too near where the wall turns): lower standoff or thickness; nothing changed.")
row["ribs"].append({"band": rib, "ring": ring, "inward": into, "edge": Q, "back": back + more * grade, "section": P[piece], "into": inward[piece],
"slope": slope[piece]})
row["pieces"] += 1
row["length"] += float(np.linalg.norm(np.diff(np.vstack([P[piece], P[piece][:1]]) if ring else P[piece], axis=0), axis=1).sum())
webs.append((index, rib.shell))
row["open"] += float(lengths.sum())
row["open"] = round(max(row["open"] - row["length"], 0.0), 6)
sections.append(row)
if not webs:
raise Refused(f"No rib: the plate of {cage.name!r} is open along every section; nothing changed.")
for row in sections: # posts stand on the kept runs only
for rib in row["ribs"] if self.posts > 0 else ():
P, up = rib["section"], planes[row["plane"]]["normal"]
for point, segment, fraction in along(P, rib["ring"], self.posts):
n = rib["into"][segment] + (rib["into"][(segment + 1) % len(P)] - rib["into"][segment]) * fraction
n = n / np.linalg.norm(n)
grade = max(rib["slope"][segment], rib["slope"][(segment + 1) % len(P)])
hit = offset.ray_cast(Vector(point - n * 1e-5), Vector(n), (plate + self.standoff) * (2.0 * grade + 2.0) + 1e-3)[3]
if hit is None:
continue
foot = point + n * (hit - 1e-5 + float(rib["back"].max()) + 0.3 * self.depth)
if short([foot]) > clip or core.away(foot, rib["edge"], rib["ring"], rib["back"])[0] < -1e-9: # inside a turn the rib was clipped at: a post there would end outside it
continue
# A post starts inside the plate, midway between its faces where it stands, and deeper where it leans: its end,
# a disc across its own line, must stay under the outer face.
(face, normal, _, _), under = nearest.find_nearest(Vector(point)), skin.find_nearest(Vector(point))[0]
top = np.array(hide.find_nearest(Vector(point))[0])
normal, thick = np.array(normal), float(np.linalg.norm(top - np.array(under)))
line = foot - (top + np.array(under)) / 2.0
line = line / np.linalg.norm(line)
proud = self.post_r * math.sqrt(max(0.0, 1.0 - float(line @ normal) ** 2)) # how far the end's rim stands out of its middle, toward the outer face
sunk = min(thick, max(thick * POST_SUNK, 1.5 * proud))
if thick > 0.0 and proud >= sunk:
continue # a plate thinner than the post's end leans: no post there
start = top - normal * sunk
across = np.cross(normal, up)
pad = skin.ray_cast(Vector(start), Vector(foot - start), float(np.linalg.norm(foot - start)))[0]
pad = np.array(pad if pad is not None else under)
rods.append(core.sweep([start, foot], core.circle(self.post_r, POST_SEGMENTS), across))
rods.append(core.sweep([pad, pad - normal * self.post_r], core.circle(2.4 * self.post_r, PAD_SEGMENTS), across))
for index, longeron in enumerate(longerons):
where, stations, ups = f"longerons[{index}]", [], []
for row in sections:
try:
hits = [(hit, rib) for rib in row["ribs"] for hit in core.crossings(rib["band"].centre, rib["ring"], longeron["origin"], longeron["axis"], longeron["toward"])]
through = any(core.crossings(line, closed, longeron["origin"], longeron["axis"], longeron["toward"]) for line, closed in row["lines"])
except core.KitError as error:
raise Refused(f"{where}: {error}; nothing changed.") from None
if len(hits) != 1:
raise Refused(f"{where} " + (f"meets the ribs of planes[{row['plane']}] {len(hits)} times: its half-plane must cross them once" if hits else
f"crosses planes[{row['plane']}] where the plate is open and there is no rib" if through else
f"does not meet the ribs of planes[{row['plane']}]") + "; nothing changed.")
((segment, point), rib), = hits
centre, inward = rib["band"].centre, rib["inward"][rib["band"].at]
n = inward[segment] + (inward[(segment + 1) % len(centre)] - inward[segment]) * float(np.linalg.norm(point - centre[segment]) / np.linalg.norm(centre[(segment + 1) % len(centre)] - centre[segment]))
stations.append(point)
ups.append(-n / np.linalg.norm(n)) # up toward the plate
path = [stations[0] + (stations[0] - stations[1]) * 0.12] + stations + [stations[-1] + (stations[-1] - stations[-2]) * 0.12]
try:
beams.append((index, stations, core.sweep(path, beam, ups[:1] + ups + ups[-1:])))
except core.KitError as error:
raise Refused(f"{where}: {error}; nothing changed.") from None
for index in sorted({index for index, _ in webs}) if self.holes > 0 else (): # one Boolean a plane: a plane's webs never cross each other, two planes' do
normal = planes[index]["normal"]
drills = [core.sweep([point - normal * 2.0 * self.thickness, point + normal * 2.0 * self.thickness], core.circle(0.3 * self.depth, HOLE_SEGMENTS), rib["inward"][0])
for rib in sections[index]["ribs"] for point, _, _ in along(rib["band"].centre, rib["ring"], self.holes)] # the centre line stands 0.5 of depth off both edges wherever it runs
if not drills:
continue
pair = []
for name, shells in ((f"{self.ribs_name}.webs.{index}", [rib for at, rib in webs if at == index]), (f"{self.ribs_name}.holes.{index}", drills)):
pair.append(bpy.data.objects.new(name, bpy.data.meshes.new(name)))
made.append(pair[-1])
write_mesh(pair[-1].data, core.joined(shells))
context.scene.collection.objects.link(pair[0])
modifier = pair[0].modifiers.new("Holes", "BOOLEAN") # closed shells that do not cross: what Manifold takes, 26 times sooner than Exact (0.017 s against 0.44 s for the pod's 93 holes)
modifier.object, modifier.operation = pair[1], "DIFFERENCE"
modifier.solver = "MANIFOLD"
drilled.append((index, len(drills), measured(pair[0].data)["volume"], pair[0]))
for index, count, before, target in drilled:
_, holed = evaluated_of(context, target)
cut_mesh = holed.to_mesh()
after, cut_webs = measured(cut_mesh), shells_of(cut_mesh)
holed.to_mesh_clear()
wanted = count * 0.5 * HOLE_SEGMENTS * (0.3 * self.depth) ** 2 * math.sin(2.0 * math.pi / HOLE_SEGMENTS) * self.thickness
if after["nonManifoldEdges"] or not abs((before - after["volume"]) / wanted - 1.0) < HOLED:
raise Refused(f"planes[{index}]: the lightening holes did not cut cleanly (they removed {before - after['volume']:.6g} m3 where {count} holes are {wanted:.6g}, and left "
f"{after['nonManifoldEdges']} open edges): they overlap or leave the rib; raise holes, or lower depth; nothing changed.")
webs = [(at, rib) for at, rib in webs if at != index] + [(index, cut_webs)]
holes += count
finally:
for modifier in shown:
modifier.show_viewport = True
for obj in made: # the webs and drills of the hole cut: gone whether it held or not
mesh = obj.data
bpy.data.objects.remove(obj)
bpy.data.meshes.remove(mesh)
if surface is not None:
surface.free()
mesh = bpy.data.meshes.new(self.ribs_name)
write_mesh(mesh, core.joined([rib for _, rib in sorted(webs, key=lambda found: found[0])] + rods + [beam for _, _, beam in beams]))
ribs = bpy.data.objects.new(self.ribs_name, mesh)
context.scene.collection.objects.link(ribs)
ribs.parent = cage
ribs.matrix_world = cage.matrix_world.copy() # read by a report; no depsgraph update here
seat(ribs, np.eye(4))
ribs[RIBS] = json.dumps({"object_name": cage.name, "planes": json.loads(self.planes), "standoff": self.standoff, "depth": self.depth, "thickness": self.thickness,
"step": self.step, "holes": self.holes, "posts": self.posts, "post_r": self.post_r, "bridge": self.bridge, "clearance": self.clearance,
"longerons": json.loads(self.longerons), "longeron": self.longeron, "longeron_w": self.longeron_w, "longeron_h": self.longeron_h,
"longeron_t": self.longeron_t})
report = {"object": ribs.name, "ribs": sum(row["pieces"] for row in sections), "thickness": round(plate, 6),
"sections": [{"plane": row["plane"], "chains": row["chains"], "pieces": row["pieces"], "length": round(row["length"], 6), "open": row["open"]} for row in sections],
"posts": len(rods) // 2, "holes": holes, **measured(mesh)}
report["longerons"] = fitted(report, "longerons", [{"index": index, "stations": [[round(float(v), 6) for v in station] for station in stations]} for index, stations, _ in beams])
return report
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"""
@ -889,7 +1314,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_close, BROKKR_KITBASH_OT_boolean, BROKKR_KITBASH_OT_cut, BROKKR_KITBASH_OT_cut_many, BROKKR_KITBASH_OT_apply, BROKKR_KITBASH_OT_ribs)
def register():

View file

@ -353,7 +353,7 @@
},
{
"name": "brokkr_kitbash.boolean",
"doc": "Cut a mesh, a kit part or any other, with another mesh object: the cutter joins the collection of the target's one live Boolean modifier for the operation (Exact, self-intersection on; difference, then union, then intersect, above its Bevel). Evaluates the target once, from a few tenths of a second to a few seconds: reports the result's faces, volume and non-manifold edges. The cutter is not changed; hide it with setObjectVisibility.",
"doc": "Cut a mesh, a kit part or any other, with another mesh object: the cutter joins the collection of the target's one live Boolean modifier for the operation (Exact, self-intersection on; difference, then union, then intersect, above its Bevel). Evaluates the target once, from a few tenths of a second to a few seconds: reports the result's faces, volume and non-manifold edges, and booleans, what cuts the target (rows a receipt has no room for are left off the end and counted in booleansOmitted). Refuses a target Blender does not evaluate (disabled in viewports, or in no collection the view layer shows). The cutter is not changed; hide it with setObjectVisibility.",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
@ -388,7 +388,7 @@
},
{
"name": "brokkr_kitbash.cut",
"doc": "Cut a mesh, a kit part or any other, where a ray meets it: places a part of the cutters kit (box, cyl, slot or slab; brokkr_kitbash.describe with kit cutters) on the surface there, parented to the target, and adds it to the target's difference Boolean. The ray is cast at the target without its cuts. The cutter's floor socket (type mount, at the bottom of the recess, facing out) takes a part by brokkr_kitbash.attach; move the cut with setObjectTransform on the cutter, resize it with set_params, hide the cutter with setObjectVisibility. Blender evaluates the changed target after the action: one Boolean evaluation a cut; brokkr_kitbash.cut_many places several cutters for one. Reports the cutter with its sockets, and booleans.",
"doc": "Cut a mesh, a kit part or any other, where a ray meets it: places a part of the cutters kit (box, cyl, slot or slab; brokkr_kitbash.describe with kit cutters) on the surface there, parented to the target, and adds it to the target's difference Boolean. The ray is cast at the target without its cuts. The cutter's floor socket (type mount, at the bottom of the recess, facing out) takes a part by brokkr_kitbash.attach; move the cut with setObjectTransform on the cutter, resize it with set_params, hide the cutter with setObjectVisibility. Blender evaluates the changed target after the action: one Boolean evaluation a cut; brokkr_kitbash.cut_many places several cutters for one. Reports the cutter with its sockets, and booleans (rows a receipt has no room for are counted in booleansOmitted). Refuses a target Blender does not evaluate.",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
@ -528,7 +528,7 @@
},
{
"name": "brokkr_kitbash.cut_many",
"doc": "Cut a mesh at several rays in one action, as brokkr_kitbash.cut does at one: all the cutters are placed or none, every ray is cast at the target without its cuts, and Blender evaluates the target's Boolean once after the action instead of once a cut. Reports object, the cutters' names and booleans; brokkr_kitbash.report gives a cutter's sockets.",
"doc": "Cut a mesh at several rays in one action, as brokkr_kitbash.cut does at one: all the cutters are placed or none, every ray is cast at the target without its cuts, and Blender evaluates the target's Boolean once after the action instead of once a cut. Reports object, the cutters' names and booleans (rows a receipt has no room for are counted in booleansOmitted); brokkr_kitbash.report gives a cutter's sockets.",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
@ -553,7 +553,7 @@
},
{
"name": "brokkr_kitbash.apply",
"doc": "Bake a kit part: its mesh becomes its evaluated mesh, every modifier goes, material slots stay, and it is marked baked (set_params then refuses it). Sockets and connections stay. Refuses a part with no modifiers and a mesh another object shares.",
"doc": "Bake a kit part: its mesh becomes its evaluated mesh, every modifier goes, material slots stay, and it is marked baked (set_params then refuses it). Sockets and connections stay. Refuses a part with no modifiers, a mesh another object shares and a part Blender does not evaluate.",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
@ -566,6 +566,156 @@
"maxLength": 63
}
]
},
{
"name": "brokkr_kitbash.ribs",
"doc": "Derive the frame under an armor cage from the cage itself, so it fits the armor by construction: a rib along each plane's section of the cage's surface, set the standoff behind the plate's inner face (along the plate's normal, at any tilt of the plane and any curvature of the wall: its edge is cut from the inner face offset inward, then measured against the plate) and reaching depth inward, clipped inside a crease tighter than that; lightening holes through the ribs; posts that stand the plate off them; longerons through the ribs. The plate's two faces are read from the cage's one Solidify as it evaluates, whatever its thickness mode. A rib stops where the plate is open (a port cut through it), runs behind an opening shorter than bridge (a panel break) and under a recess: openings are read from the cage as it is cut, so cut first. Inward is the side the cage's normals face away from. Makes one mesh object, a child of the cage, baked at this call: after the cage or its cuts change, delete it and run ribs again (its kit_ribs property keeps the request). Every plane and longeron is checked before anything is written. Reports ribs, thickness, sections [{plane, chains, pieces, length, open}], posts, holes, longerons [{index, stations}], faces, volume and nonManifoldEdges.",
"changesScene": true,
"editModeSafe": false,
"result": "brokkr_mesh_polish_result",
"fields": [
{
"name": "object_name",
"type": "string",
"required": true,
"minLength": 1,
"maxLength": 63,
"doc": "the cage: a mesh whose surface is the plate's designed face, not scaled, its normals facing out of the plate"
},
{
"name": "ribs_name",
"type": "string",
"required": true,
"minLength": 1,
"maxLength": 63,
"doc": "the new ribs object's name"
},
{
"name": "planes",
"type": "string",
"required": true,
"minLength": 2,
"maxLength": 16000,
"doc": "a JSON array of 1 to 64 planes, each {\"origin\": [x, y, z], \"normal\": [x, y, z]} in the cage's own frame; a rib runs where each cuts the surface"
},
{
"name": "standoff",
"type": "number",
"minimum": 0,
"maximum": 2,
"default": 0.09,
"doc": "metres between the plate's inner face and the ribs, along the plate's own normal"
},
{
"name": "depth",
"type": "number",
"minimum": 0.005,
"maximum": 2,
"default": 0.09,
"doc": "how far a rib reaches inward from there"
},
{
"name": "thickness",
"type": "number",
"minimum": 0.001,
"maximum": 1,
"default": 0.014,
"doc": "a rib's thickness across its plane"
},
{
"name": "step",
"type": "number",
"minimum": 0.002,
"maximum": 1,
"default": 0.01,
"doc": "spacing of the points at which a section asks whether the plate is there"
},
{
"name": "holes",
"type": "number",
"minimum": 0,
"maximum": 10,
"default": 0,
"doc": "pitch of the lightening holes along each rib (radius 0.3 of depth); 0: none"
},
{
"name": "posts",
"type": "number",
"minimum": 0,
"maximum": 10,
"default": 0,
"doc": "pitch of the posts that stand the plate off each rib; 0: none"
},
{
"name": "post_r",
"type": "number",
"minimum": 0.001,
"maximum": 0.5,
"default": 0.011,
"doc": "a post's radius; its pad on the plate is 2.4 times as wide"
},
{
"name": "bridge",
"type": "number",
"minimum": 0,
"maximum": 2,
"default": 0.05,
"doc": "an opening shorter than this along a section is a panel break: the rib runs behind it"
},
{
"name": "clearance",
"type": "number",
"minimum": 0,
"maximum": 2,
"default": 0.02,
"doc": "how far a rib stops short of any other opening"
},
{
"name": "longerons",
"type": "string",
"default": "[]",
"minLength": 2,
"maxLength": 8000,
"doc": "a JSON array of 0 to 16 longerons, each {\"origin\": [x, y, z], \"axis\": [x, y, z], \"toward\": [x, y, z]} in the cage's own frame: the half-plane from the line through origin along axis, on toward's side. The longeron runs through the rib of every plane, in the planes' order, where the half-plane crosses the rib's mid-depth line: exactly once a plane, and not in an opening"
},
{
"name": "longeron",
"type": "string",
"enum": [
"I",
"C",
"T",
"L",
"box"
],
"default": "T",
"doc": "the longerons' section; its up faces the plate"
},
{
"name": "longeron_w",
"type": "number",
"minimum": 0.005,
"maximum": 2,
"default": 0.05,
"doc": "the section's width"
},
{
"name": "longeron_h",
"type": "number",
"minimum": 0.005,
"maximum": 2,
"default": 0.05,
"doc": "the section's height"
},
{
"name": "longeron_t",
"type": "number",
"minimum": 0.001,
"maximum": 1,
"default": 0.008,
"doc": "the section's wall"
}
]
}
]
}

View file

@ -17,6 +17,14 @@ both kits declare the socket's type with the same match rule. surface_frame is t
met a surface. closure_residual is how far two sockets stand from meeting as a pin,
whatever the roll: what closes a loop the tree of connections cannot state.
The structure under an armor cage is built, not kit parts: PROFILES are the sections (I, C, T, L, box), sweep takes
an outline along a polyline with mitred joints (a longeron, a post), band is the rib beside a section in its plane,
offset and clipped so that it follows a crease instead of folding in it (away, the distance to a polyline, is what
clips it), inset is the step that offsets a mesh inward by its own faces (the surface a rib's edge is cut from), crossings
finds where a section line meets a half-plane, resample fills a section's points in, and spans
says which runs of a section keep their frame where the plate over them is open. brokkr_kitbash.ribs is the bpy
around them.
A pin's roll is its one degree of freedom, and it is solved in closed form: roll_terms gives how a point or an axis
of the child moves along a world direction as the roll turns (a cosine, a sine and a constant), aim_roll the roll
that points an axis of the child at a direction, reach_roll the roll that brings a point of the child to a plane.
@ -591,6 +599,380 @@ def build(part: dict, params: dict | None = None) -> Built:
shell_count=len(shells), sockets=sockets, bevel=bevel, params=env)
# --- structure: sections swept along paths --------------------------------------------------------------------
PROFILES = { # (w, h, t) -> the outline, counter-clockwise in (x across, y along up): flange width, height, wall
"I": lambda w, h, t: [(-w / 2, -h / 2), (w / 2, -h / 2), (w / 2, -h / 2 + t), (t / 2, -h / 2 + t), (t / 2, h / 2 - t), (w / 2, h / 2 - t),
(w / 2, h / 2), (-w / 2, h / 2), (-w / 2, h / 2 - t), (-t / 2, h / 2 - t), (-t / 2, -h / 2 + t), (-w / 2, -h / 2 + t)],
"C": lambda w, h, t: [(-w / 2, -h / 2), (w / 2, -h / 2), (w / 2, -h / 2 + t), (-w / 2 + t, -h / 2 + t), (-w / 2 + t, h / 2 - t), (w / 2, h / 2 - t),
(w / 2, h / 2), (-w / 2, h / 2)],
"T": lambda w, h, t: [(-t / 2, -h / 2), (t / 2, -h / 2), (t / 2, h / 2 - t), (w / 2, h / 2 - t), (w / 2, h / 2), (-w / 2, h / 2), (-w / 2, h / 2 - t), (-t / 2, h / 2 - t)],
"L": lambda w, h, t: [(-w / 2, -h / 2), (w / 2, -h / 2), (w / 2, -h / 2 + t), (-w / 2 + t, -h / 2 + t), (-w / 2 + t, h / 2), (-w / 2, h / 2)],
"box": lambda w, h, t: [(-w / 2, -h / 2), (w / 2, -h / 2), (w / 2, h / 2), (-w / 2, h / 2)],
}
TURN_LIMIT = 150.0 # degrees a swept path may turn at one point: past it a mitre runs 3.9 times the section's width
def profile(kind: str, w: float, h: float, t: float) -> np.ndarray:
"""PROFILES[kind] at a width, height and wall, as an (M, 2) array. Refuses a kind PROFILES does not have, a size
that is not above 0, and a wall that leaves no section: as wide as the flange, or as thick as the height its
flanges share (two on an I and a C, one on a T and an L). A box has no wall."""
if kind not in PROFILES:
raise KitError(f"profile {kind!r} is not one of {', '.join(PROFILES)}")
limit = min(w, h / 2 if kind in ("I", "C") else h)
if not all(finite(v) and v > 0 for v in (w, h, t)) or (kind != "box" and not t < limit):
raise KitError(f"profile {kind!r} of width {w}, height {h}, wall {t}: every size must be above 0 and the wall under {limit:.6g}")
return np.array(PROFILES[kind](w, h, t), dtype=np.float64)
def circle(r: float, segments: int) -> np.ndarray:
"""A regular polygon of `segments` corners on radius r, counter-clockwise from +x: a rod's or a hole's outline."""
if not (finite(r) and r > 0) or not SEGMENTS[0] <= segments <= SEGMENTS[1]:
raise KitError(f"circle of radius {r} and {segments} segments: the radius must be above 0 and the segments {SEGMENTS[0]} to {SEGMENTS[1]}")
angle = 2.0 * math.pi * np.arange(segments) / segments
return np.stack([r * np.cos(angle), r * np.sin(angle)], axis=1)
class Swept(NamedTuple):
"""Closed shells that are no kit part: the five fields of a Built that a mesh is written from. Every face flat."""
V: np.ndarray
faces: np.ndarray
counts: np.ndarray
smooth: np.ndarray
sharp: np.ndarray
def joined(shells: list) -> Swept:
"""Several Swept as one, in order: shells beside each other, sharing no vertex."""
offsets = np.cumsum([0] + [len(s.V) for s in shells[:-1]])
return Swept(V=np.vstack([s.V for s in shells] or [np.zeros((0, 3))]).astype(np.float64),
faces=np.concatenate([s.faces + o for s, o in zip(shells, offsets)] or [np.zeros(0)]).astype(np.int32),
counts=np.concatenate([s.counts for s in shells] or [np.zeros(0)]).astype(np.int32),
smooth=np.concatenate([s.smooth for s in shells] or [np.zeros(0)]).astype(bool),
sharp=np.concatenate([s.sharp + o for s, o in zip(shells, offsets)] or [NO_SHARP]).astype(np.int32))
def sweep(path, outline, ups, closed: bool = False) -> Swept:
"""A closed 2D outline (counter-clockwise in x across, y up) swept along a polyline: one closed shell, wound
outward. At each path point the outline stands in the plane that bisects the turn: t is the unit bisector
tangent, y the unit projection of that point's up off t, x = y cross t (surface_frame's handedness, with t as its
z). The joint is mitred: the outline's component in the plane of the turn is stretched by 1 / cos(half the
turn), so the section keeps its size on both sides of a corner. Quads join ring to ring; an open path is capped
by the outline as an n-gon at each end. `ups` is one vector or one per point.
Refuses, naming the point's index: fewer than 2 points (3 when closed), a segment shorter than 1e-9, a turn over
TURN_LIMIT, an up along the tangent, and a fold: an outline point whose step from one ring to the next runs
against the path's own segment there (the path turns tighter than the outline is wide on the inside)."""
path, outline, ups = np.asarray(path, dtype=np.float64), np.asarray(outline, dtype=np.float64), np.asarray(ups, dtype=np.float64)
count, m = len(path), len(outline)
if path.ndim != 2 or path.shape[1] != 3 or count < (3 if closed else 2) or not np.isfinite(path).all():
raise KitError(f"a swept path needs {'3 points when closed' if closed else '2 points'} of three finite numbers; it has {count}")
if outline.ndim != 2 or outline.shape[1] != 2 or m < 3 or not np.isfinite(outline).all():
raise KitError("a swept outline is 3 or more points of two finite numbers")
ups = np.broadcast_to(ups, (count, 3)) if ups.shape == (3,) else ups
if ups.shape != (count, 3) or not np.isfinite(ups).all():
raise KitError(f"a sweep takes one up or one for each of its {count} points")
steps = (np.roll(path, -1, axis=0) - path)[:count if closed else count - 1]
lengths = np.linalg.norm(steps, axis=1)
if (lengths < 1e-9).any():
raise KitError(f"path point {int(np.argmax(lengths < 1e-9))}: the segment from it is shorter than 1e-9")
along = steps / lengths[:, None]
before = np.roll(along, 1, axis=0) if closed else np.vstack([along[:1], along]) # the segment into each point
after = along if closed else np.vstack([along, along[-1:]]) # and the one out of it
cosine = np.clip(np.einsum("ij,ij->i", before, after), -1.0, 1.0)
turned = np.degrees(np.arccos(cosine))
if (turned > TURN_LIMIT).any():
index = int(np.argmax(turned > TURN_LIMIT))
raise KitError(f"path point {index}: the path turns {turned[index]:.1f} degrees there, over {TURN_LIMIT:g}")
tangent = before + after
tangent /= np.linalg.norm(tangent, axis=1)[:, None]
y = ups - tangent * np.einsum("ij,ij->i", ups, tangent)[:, None]
flat = np.linalg.norm(y, axis=1)
if not (flat > 1e-6 * np.linalg.norm(ups, axis=1)).all():
index = int(np.argmin(flat > 1e-6 * np.linalg.norm(ups, axis=1)))
raise KitError(f"path point {index}: up {ups[index].tolist()} runs along the path there (or is zero): give an up that crosses it")
y /= flat[:, None]
x = np.cross(y, tangent)
offsets = outline[None, :, 0, None] * x[:, None, :] + outline[None, :, 1, None] * y[:, None, :] # (count, m, 3)
bend = after - before # in the turn's plane, across the bisector tangent
size = np.linalg.norm(bend, axis=1)
bend = np.divide(bend, size[:, None], out=np.zeros_like(bend), where=size[:, None] > 1e-12)
stretch = 1.0 / np.sqrt((1.0 + cosine) / 2.0) - 1.0 # 1 / cos(half the turn) - 1
offsets = offsets + (stretch[:, None] * np.einsum("imk,ik->im", offsets, bend))[:, :, None] * bend[:, None, :]
V = path[:, None, :] + offsets
forward = np.einsum("imk,ik->im", (np.roll(V, -1, axis=0) - V)[:len(steps)], steps)
if (forward <= 0).any():
index = int(np.argmax((forward <= 0).any(axis=1)))
raise KitError(f"path point {index}: the section folds there: the path turns tighter than the outline reaches on the inside of the turn")
ring = np.arange(m)
quads = [np.stack([i * m + ring, i * m + (ring + 1) % m, j * m + (ring + 1) % m, j * m + ring], axis=1) for i, j in
((i, (i + 1) % count) for i in range(len(steps)))]
faces, counts = [np.concatenate(quads).ravel()], [np.full(len(steps) * m, 4)]
if not closed: # the first cap looks back along the path, the last along it
faces += [ring[::-1], (count - 1) * m + ring]
counts += [np.array([m, m])]
counts = np.concatenate(counts).astype(np.int32)
return Swept(V=V.reshape(-1, 3), faces=np.concatenate(faces).astype(np.int32), counts=counts, smooth=np.zeros(len(counts), dtype=bool), sharp=NO_SHARP.astype(np.int32))
def crossings(points, closed: bool, origin, axis, toward) -> list:
"""Where a polyline crosses a half-plane: the half of the plane through `origin` that holds `axis` and `toward`,
on toward's side of the line (origin, axis). [(segment index, point)], ordered along the axis: the points are the
same wherever the chain starts and whichever way it runs. A vertex on the plane counts for one of its two
segments. Refuses an axis of no length and a toward along it."""
points, origin, axis, toward = (np.asarray(v, dtype=np.float64) for v in (points, origin, axis, toward))
if not np.linalg.norm(axis) > 0:
raise KitError(f"axis {axis.tolist()} has no direction")
axis = axis / np.linalg.norm(axis)
side = toward - axis * (toward @ axis)
if not np.linalg.norm(side) > 1e-6 * np.linalg.norm(toward) or not np.linalg.norm(side) > 0:
raise KitError(f"toward {toward.tolist()} runs along the axis {np.round(axis, 6).tolist()} (or is zero): give a toward that crosses it")
side = side / np.linalg.norm(side)
normal = np.cross(axis, side)
height = (points - origin) @ normal
found = []
for i in range(len(points) if closed else len(points) - 1):
j = (i + 1) % len(points)
if (height[i] < 0) != (height[j] < 0):
point = points[i] + (points[j] - points[i]) * (height[i] / (height[i] - height[j]))
if (point - origin) @ side > 0:
found.append((i, point))
return sorted(found, key=lambda hit: (float((hit[1] - origin) @ axis), float((hit[1] - origin) @ side)))
def resample(points, closed: bool, step: float) -> np.ndarray:
"""A polyline's own points with more between them, evenly along each segment, so that none stands over `step`
from the next. A corner stays a corner: points spaced along the arc instead would cut each corner into two, a
step apart, and a band beside the section would be clipped at both. A segment shorter than 1e-7 is dropped with its
first point. An open polyline keeps both ends; a closed one starts at its first point."""
points = np.asarray(points, dtype=np.float64)
if not (finite(step) and step > 0) or len(points) < 2:
raise KitError(f"resample needs 2 or more points and a step above 0; got {len(points)} and {step}")
loop = np.vstack([points, points[:1]]) if closed else points
lengths = np.linalg.norm(np.diff(loop, axis=0), axis=1)
if not lengths.sum() > 0:
raise KitError("resample: the polyline has no length")
made = [loop[i] + (loop[i + 1] - loop[i]) * (k / pieces) for i, length in enumerate(lengths) if length >= 1e-7
for pieces in (max(1, int(math.ceil(length / step - 1e-9))),) for k in range(pieces)]
return np.array(made if closed else made + [loop[-1]])
INSET_RANK = 2.5e-3 # of a vertex's face normals, as eigenvalues of their sum of squares: a direction they span by under 0.05 of the widest is not solved for
def inset(V, faces) -> np.ndarray:
"""For each vertex of a mesh, the step that takes it one unit behind the plane of every face it is a corner of,
against the faces' normals (a face's normal is its winding's, counter-clockwise seen from outside): the mitre of
those planes moved in by 1. `V + d * inset(V, faces)`, with the same faces, is the surface offset inward by d. A
flat or smooth vertex steps along its normal; a crease's or a corner's steps to where its faces' offsets meet,
exactly where they meet in a point or a line. Where no step holds every face's distance (four faces that do not
share a point), the least-squares step is lengthened until the nearest face's plane stands 1 off: further than
asked from the others, never nearer. `faces` is a list of index tuples. A vertex of no face, or of faces that
fold back on each other, steps nowhere."""
V = np.asarray(V, dtype=np.float64).reshape(-1, 3)
corners = np.fromiter((v for face in faces for v in face), dtype=np.int64)
counts = np.fromiter((len(face) for face in faces), dtype=np.int64, count=len(faces))
owner, first = np.repeat(np.arange(len(faces)), counts), np.concatenate([[0], np.cumsum(counts)[:-1]])
ahead = np.arange(len(corners)) + 1
ahead[first + counts - 1] = first # the next corner round each face
normals = np.zeros((len(faces), 3))
np.add.at(normals, owner, np.cross(V[corners], V[corners[ahead]])) # Newell: twice the face's area along its normal
size = np.linalg.norm(normals, axis=1)
normals = normals / np.maximum(size, 1e-300)[:, None]
n = normals[owner] * (size[owner] > 0)[:, None] # a corner's face normal; a face of no area asks nothing
squares, wanted = np.zeros((len(V), 3, 3)), np.zeros((len(V), 3))
np.add.at(squares, corners, n[:, :, None] * n[:, None, :])
np.add.at(wanted, corners, -n)
step = np.einsum("vij,vj->vi", np.linalg.pinv(squares, rcond=INSET_RANK, hermitian=True), wanted)
behind = np.full(len(V), np.inf)
np.minimum.at(behind, corners, np.where(size[owner] > 0, -np.einsum("ij,ij->i", n, step[corners]), np.inf)) # how far behind its nearest face's plane the step ends
held = np.isfinite(behind) & (behind > 1e-6)
return np.where(held[:, None], step / np.where(held, behind, 1.0)[:, None], 0.0)
AWAY_SPAN = 64 # points, and segments, that away takes at a time: a block of points skips the blocks of segments too far off to matter
def away(points, chain, closed: bool, less=0.0, limit: float = math.inf) -> np.ndarray:
"""How far each point stands from a polyline: its least distance to any segment. With `less`, one length for
each segment, the least over the segments of the distance less that segment's length: 0 or more where the point
stands at least each segment's own length off it. A value over `limit` is not looked for and comes back as
`limit`: with one, a long polyline costs each point the segments near it and not all of them (the three edges
of a band on 20000 points: about 60 s without; the whole band 0.7 s with a limit of 0)."""
points, chain = np.asarray(points, dtype=np.float64).reshape(-1, 3), np.asarray(chain, dtype=np.float64)
a, b = (chain, np.roll(chain, -1, axis=0)) if closed else (chain[:-1], chain[1:])
ab = b - a
square, less = np.maximum(np.einsum("ij,ij->i", ab, ab), 1e-300), np.broadcast_to(np.asarray(less, dtype=np.float64), (len(a),))
starts = np.arange(0, len(a), AWAY_SPAN)
low, high = (np.array([side(np.vstack([a[j:j + AWAY_SPAN], b[j:j + AWAY_SPAN]]), axis=0) for j in starts]) for side in (np.min, np.max)) # each block of segments' box
most = np.maximum.reduceat(less, starts)
least = np.full(len(points), float(limit))
for first in range(0, len(points), AWAY_SPAN):
block = points[first:first + AWAY_SPAN]
apart = np.linalg.norm(np.maximum(0.0, np.maximum(low - block.max(axis=0), block.min(axis=0) - high)), axis=1) - most # no segment of a block reads under this
near = np.concatenate([np.arange(j, min(j + AWAY_SPAN, len(a))) for j in starts[apart <= limit]] or [np.zeros(0, dtype=np.int64)])
if len(near):
offset = block[:, None, :] - a[near][None]
offset = offset - np.clip(np.einsum("ksj,sj->ks", offset, ab[near]) / square[near], 0.0, 1.0)[:, :, None] * ab[near][None]
least[first:first + AWAY_SPAN] = np.minimum(least[first:first + AWAY_SPAN], (np.sqrt(np.einsum("ksj,ksj->ks", offset, offset)) - less[near][None]).min(axis=1))
return least
class Band(NamedTuple):
"""A band beside a polyline, as one closed shell, and the lines a frame is hung on it by."""
shell: Swept
outer: np.ndarray # the band's edge next to the polyline
inner: np.ndarray # its far edge
centre: np.ndarray # the line midway between them: the polyline offset by back + depth / 2, clipped as the edges are
at: np.ndarray # for each point of centre, the index of the polyline's point it is offset from
def band(points, closed: bool, normal, inward, back, depth: float, thickness: float) -> Band:
"""The band beside a polyline that lies in a plane: everything in that plane, on the side `inward` points to,
that stands from back to back + depth off the polyline, `thickness` across the plane; one closed shell, wound
outward. `normal` is the plane's unit normal; `inward` (one in-plane vector for each point) only says which
side; `back` is one distance, or one for each segment.
Each edge is the polyline offset and then clipped, as a polygon offset is. A point's offset stands where its two
segments' offset lines meet, a mitre; where their distances differ and the lines meet beside one segment but
past the end of the other (two segments that are nearly one line), it stands the greater distance off both. An
offset point that stands nearer any segment than that segment's own distance is left out, and its neighbours
close the edge there. So inside a turn tighter than the band reaches the far edge cuts the corner, and the band
narrows instead of folding; between two kept points the cut is a chord, which leaves the true corner out by
less than the points' spacing. Points along a straight run with nothing clipped beside them are left out too:
they add no shape.
Refuses, naming the point: fewer than 2 points (3 when closed), a segment shorter than 1e-9, a turn over
TURN_LIMIT; and a polyline that leaves an edge fewer than 2 points (3 when closed): it closes in on itself
nearer than the band reaches, everywhere."""
P, normal, inward, back = (np.asarray(v, dtype=np.float64) for v in (points, normal, inward, back))
count, least = len(P), 3 if closed else 2
if P.ndim != 2 or P.shape[1] != 3 or count < least or inward.shape != P.shape or back.shape not in ((), (count if closed else count - 1,)) or not (
np.isfinite(P).all() and np.isfinite(back).all() and (back >= 0).all() and depth > 0 and thickness > 0):
raise KitError(f"a band needs {least} points of three finite numbers, an inward for each, one distance of 0 or more or one for each segment, and a depth and thickness above 0; it has {count} points")
back = np.broadcast_to(back, (count if closed else count - 1,))
steps = (np.roll(P, -1, axis=0) - P)[:count if closed else count - 1]
lengths = np.linalg.norm(steps, axis=1)
if (lengths < 1e-9).any():
raise KitError(f"path point {int(np.argmax(lengths < 1e-9))}: the segment from it is shorter than 1e-9")
along = steps / lengths[:, None]
aside = np.cross(normal, along) # each segment's in-plane normal
into = lambda of: (np.roll(of, 1, axis=0), of) if closed else (np.concatenate([of[:1], of]), np.concatenate([of, of[-1:]])) # noqa: E731 a point's segment before and after
(before, after), (arriving, leaving) = into(aside), into(along)
cosine = np.clip(np.einsum("ij,ij->i", before, after), -1.0, 1.0)
if (cosine < math.cos(math.radians(TURN_LIMIT))).any():
index = int(np.argmax(cosine < math.cos(math.radians(TURN_LIMIT))))
raise KitError(f"path point {index}: the path turns {math.degrees(math.acos(cosine[index])):.1f} degrees there, over {TURN_LIMIT:g}")
side = 1.0 if np.einsum("ij,ij->", before + after, inward) > 0 else -1.0
square = np.maximum(1.0 - cosine ** 2, 1e-18)
edges, valid, uneven = [], [], np.zeros(count, dtype=bool)
for further in (0.0, depth, depth / 2.0):
first, second = into(back + further)
even = (np.maximum(first, second) / (1.0 + cosine))[:, None] * (before + after) # the greater distance off both segments
met = ((first - cosine * second) / square)[:, None] * before + ((second - cosine * first) / square)[:, None] * after # first off one, second off the other
mitred = (first != second) & (np.einsum("ij,ij->i", met, arriving) * np.einsum("ij,ij->i", met, leaving) <= 0.0) # beside both segments, or past the ends of both
edges.append(P + side * np.where(mitred[:, None], met, even))
valid.append(away(edges[-1], P, closed, back + further, limit=0.0) >= -1e-6 * np.maximum(first, second) - 1e-9)
uneven |= first != second
turns = (cosine < 1.0 - 1e-12) | uneven
if not closed:
turns[[0, -1]] = True
state = valid[0] * 4 + valid[1] * 2 + valid[2]
changes = (state != np.roll(state, 1)) | (state != np.roll(state, -1))
if not closed:
changes[0], changes[-1] = state[0] != state[1], state[-1] != state[-2]
kept = np.flatnonzero((turns | changes) & (valid[0] | valid[1]))
reached = np.concatenate([[0.0], np.cumsum(lengths)])
lines, maps = [], []
for edge, ok in zip(edges, valid): # a clipped point takes the nearest kept one along the polyline
own = kept[ok[kept]]
if len(own) < least:
raise KitError(f"path point {int(np.argmin(valid[1]))}: the section leaves a rib no room: it turns or closes in tighter than the rib reaches")
apart = np.linalg.norm(np.diff(edge[own], axis=0), axis=1) > 1e-9 # a point clipped exactly onto its neighbour is that neighbour
own = own[np.concatenate([[True], apart])]
if closed and np.linalg.norm(edge[own[0]] - edge[own[-1]]) <= 1e-9:
own = own[:-1]
after = np.searchsorted(reached[own], reached[kept]) # the kept point of this edge at or after each kept point, and the one before
pair = np.stack([after - 1, after]) % len(own) if closed else np.clip(np.stack([after - 1, after]), 0, len(own) - 1)
gap = np.abs(reached[own][pair] - reached[kept][None, :])
lines.append((edge[own], own))
maps.append(pair[np.argmin(np.minimum(gap, reached[-1] - gap) if closed else gap, axis=0), np.arange(len(kept))])
((outer, _), (inner, _), (centre, at)), (to_outer, to_inner, _) = lines, maps
half = normal * thickness / 2.0
A, B = len(outer), len(inner) # vertices: outer low, outer high, inner low, inner high
faces = []
for i, j in [(k, k + 1) for k in range(len(kept) - 1)] + ([(len(kept) - 1, 0)] if closed else []):
a0, a1, b0, b1 = to_outer[i], to_outer[j], 2 * A + to_inner[i], 2 * A + to_inner[j]
if a0 != a1:
faces.append((a0, a1, A + a1, A + a0))
if b0 != b1:
faces.append((b0, B + b0, B + b1, b1))
cap = ([a0] if a0 == a1 else [a0, a1]) + ([b1] if b0 == b1 else [b1, b0])
if len(cap) > 2:
faces.append(tuple(A + v if v < 2 * A else B + v for v in cap))
faces.append(tuple(cap[::-1]))
if not closed:
faces.append((to_outer[0], A + to_outer[0], 2 * A + B + to_inner[0], 2 * A + to_inner[0]))
faces.append((to_outer[-1], 2 * A + to_inner[-1], 2 * A + B + to_inner[-1], A + to_outer[-1]))
if side < 0:
faces = [face[::-1] for face in faces]
counts = np.array([len(face) for face in faces], dtype=np.int32)
shell = Swept(V=np.vstack([outer - half, outer + half, inner - half, inner + half]), faces=np.concatenate(faces).astype(np.int32), counts=counts,
smooth=np.zeros(len(counts), dtype=bool), sharp=NO_SHARP.astype(np.int32))
return Band(shell=shell, outer=outer, inner=inner, centre=centre, at=at)
def spans(flags, lengths, closed: bool, bridge: float, clearance: float) -> list:
"""The runs of a chain that keep their frame, as arrays of point indices in chain order. flags[i] says point i is
open (no plate over it); lengths[i] is the segment from point i to the next (N of them when closed, N - 1 when
not). An open run is as long as the chain between the kept points either side of it: one shorter than `bridge`
is closed (a panel break: the frame runs behind it); beside any other, the kept points nearer than `clearance`
are dropped. A run of fewer than 2 points is none. A closed chain's run may cross its start; with nothing open
its one run is every point, and only then is the run itself closed."""
flags, lengths = np.array(flags, dtype=bool), np.asarray(lengths, dtype=np.float64)
count = len(flags)
if len(lengths) != (count if closed else count - 1):
raise KitError(f"spans: {count} points {'closed' if closed else 'open'} have {count if closed else count - 1} segments, not {len(lengths)}")
def runs(wanted):
"""Maximal runs of flags == wanted as (first, length in points), a closed chain's run across its start as one."""
found, i = [], 0
while i < count:
if flags[i] == wanted:
j = i
while j + 1 < count and flags[j + 1] == wanted:
j += 1
found.append([i, j - i + 1])
i = j + 1
else:
i += 1
if closed and len(found) > 1 and found[0][0] == 0 and found[-1][0] + found[-1][1] == count:
found[0] = [found[-1][0], found[-1][1] + found[0][1]]
found.pop()
return found
def arc(first, segments):
return float(sum(lengths[(first + k) % len(lengths)] for k in range(segments)))
if flags.all():
return []
for first, size in runs(True):
inside = closed or (first > 0 and first + size < count) # an open chain's own end is not a break to bridge
if inside and arc((first - 1) % count, size + 1) < bridge:
flags[[(first + k) % count for k in range(size)]] = False
if not flags.any():
return [np.arange(count)]
kept = []
for first, size in runs(False):
indices = [(first + k) % count for k in range(size)]
cut_before, cut_after = closed or first > 0, closed or first + size < count
along = np.concatenate([[0.0], np.cumsum([lengths[i % len(lengths)] for i in indices[:-1]])]) if size > 1 else np.zeros(1)
keep = [k for k in range(size) if (not cut_before or along[k] >= clearance) and (not cut_after or along[-1] - along[k] >= clearance)]
if len(keep) >= 2:
kept.append(np.array([indices[k] for k in keep]))
return kept
# --- reports -------------------------------------------------------------------------------------------------
def rows(matrix) -> list[list[float]]:

View file

@ -43,7 +43,7 @@
},
{
"name": "slot",
"doc": "Round-ended slot, long along x: a visor, a gill, a vent. width must exceed height. Three floor sockets face out of the recess: floor at the frame's centre (between the two middle copies when count is even), floor_l and floor_r a third of the width to each side; each holds one part.",
"doc": "Round-ended slot, long along x: a visor, a gill, a vent. width must exceed height. Three floor sockets face out of the recess: floor at the frame's centre (between the two middle copies when count is even), floor_l and floor_r at the centres of the two round ends; each holds one part and is as large as fits beside the next, min(height, (width-height)/2).",
"params": [
{"name": "width", "type": "number", "min": 0.01, "max": 8, "default": 0.3, "doc": "end to end (x); more than height"},
{"name": "height", "type": "number", "min": 0.005, "max": 4, "default": 0.05, "doc": "across the slot (y); the ends are half-rounds of this diameter"},
@ -58,9 +58,9 @@
{"shape": "repeat", "count": "count", "step": [0, "pitch", 0], "of": {"shape": "tube", "r0": "height/2", "r1": "height/2", "length": "depth+lift", "segments": 32, "at": ["(width-height)/2", "-(count-1)*pitch/2", "-depth"]}}
],
"sockets": [
{"name": "floor", "type": "mount", "size": "height", "at": [0, 0, "-depth"], "z": "+z", "y": "+y"},
{"name": "floor_l", "type": "mount", "size": "height", "at": ["-width/3", 0, "-depth"], "z": "+z", "y": "+y"},
{"name": "floor_r", "type": "mount", "size": "height", "at": ["width/3", 0, "-depth"], "z": "+z", "y": "+y"}
{"name": "floor", "type": "mount", "size": "min(height, (width-height)/2)", "at": [0, 0, "-depth"], "z": "+z", "y": "+y"},
{"name": "floor_l", "type": "mount", "size": "min(height, (width-height)/2)", "at": ["-(width-height)/2", 0, "-depth"], "z": "+z", "y": "+y"},
{"name": "floor_r", "type": "mount", "size": "min(height, (width-height)/2)", "at": ["(width-height)/2", 0, "-depth"], "z": "+z", "y": "+y"}
]
},
{

View file

@ -315,7 +315,7 @@ kit part, where a ray meets it, and what it places is itself a kit part, of the
| --- | --- | --- |
| `box` | `width` (x), `height` (y), `count`, `pitch` | `floor` (mount, size the smaller side) |
| `cyl` | `r`, `count`, `pitch` | `floor` (mount, size `2*r`) |
| `slot` | `width` (x, end to end), `height` (across; less than `width`), `count`, `pitch` | `floor`, `floor_l`, `floor_r` (mount, size `height`) |
| `slot` | `width` (x, end to end), `height` (across; less than `width`), `count`, `pitch` | `floor`, `floor_l`, `floor_r` (mount, size the smaller of `height` and `(width-height)/2`) |
| `slab` | `gap` (x), `length` (y) | none |
A cutter's frame has its origin where the ray met the surface, `z` along the surface normal (turned to face
@ -341,8 +341,9 @@ resizes it, and deleting the cutter removes the cut. `cut` does not hide the cut
and a hidden cutter still cuts.
`box`, `cyl` and `slot` carry a socket, `floor`: on the bottom of the recess at `z = -depth`, at the frame's
centre, facing out of the recess. A `slot` carries two more on the same floor, `floor_l` and `floor_r`, a third
of its width to each side: a visor with three eyes. Machinery attaches there with the ordinary `attach` (a vent's `back`, a
centre, facing out of the recess. A `slot` carries two more on the same floor, `floor_l` and `floor_r`, at the
centres of its two round ends, `(width-height)/2` to each side: a visor with three eyes. The three are sized so
that neighbours never overlap and none passes the slot's ends. Machinery attaches there with the ordinary `attach` (a vent's `back`, a
sensor's `mount`), is a child of the cutter, and so follows the cut when the cutter moves and is seated again
when `set_params` changes its `depth`. With an even `count` and a `pitch` wider than the copies, the centre lies
between the two middle copies: use an odd count, or a cutter of its own, for a recess that carries a part. A
@ -354,11 +355,115 @@ every action, so each `cut` costs one Boolean evaluation of the target: on the s
cutter to eight. `cut_many` takes a JSON array of cutters (`name`, `part`, `origin`, `direction`, and optionally
`params`, `up`, `roll`, `axis`), checks them all and casts every ray before it writes anything, places all of
them or none, and costs one evaluation for the lot. On a pod with a Bevel under the Boolean (6500 faces once
cut; one evaluation 5.2 s), 13 cutters placed by one `cut_many` took 4.9 s, and 15 placed by 15 `cut` actions
took 113 s; the same cuts as one joined cutter, evaluated once and baked, took 4.6 s (Blender 5.3 on Starfire).
Any later action that changes the target or a cutter (hiding the cutters, attaching a part to a floor) costs an
evaluation again while the target is visible. `cut_many` reports `{object, cutters, booleans}` with the cutters
by name.
cut), the same 13 cutters took 6.1 s placed by one `cut_many` and 51.3 s placed by 13 `cut` actions, about 8
times as long (medians of 3, Blender 5.3 on Starfire); hiding each cutter after its `cut` is a second evaluation
each and brought the 13 to 105 s. Any later action that changes the target or a cutter (hiding the cutters,
attaching a part to a floor) costs an evaluation again while the target is visible. `cut_many` reports
`{object, cutters, booleans}` with the cutters by name.
`booleans` in a report of `cut`, `cut_many` or `boolean` is trimmed to what a receipt carries: on a target with
more cutters than fit (about 150 of long names), the rows left off the end are counted in `booleansOmitted`. The
scene keeps every cutter; the target's `Kit` modifier collections list them.
`cut`, `cut_many`, `boolean` and `apply` evaluate their object, and refuse one Blender does not evaluate in the
view layer: an object disabled in viewports that nothing evaluated depends on, or one whose collections no view
layer shows. A disabled object that an evaluated object needs (a parent of one, a cutter of one) is evaluated
all the same, and is cut.
## Ribs from a shell
`ribs` derives the frame under an armor cage from the cage, so the frame fits the armor by construction. It
takes planes in the cage's own frame and makes, as one mesh object under the cage:
- a rib along each plane's section of the cage's surface: `thickness` across the plane, set `standoff` behind
the plate's inner face and reaching `depth` further in along the plane. `standoff` is measured along the
plate's own normal, at any tilt of the plane and any curvature of the wall: the rib's outer edge is cut from
the inner face offset inward by `standoff` (every face moved along its own normal, creases mitred), then set
in by what half the rib's thickness needs on the side the plate leans over, and no part of the rib comes
nearer the inner face than `standoff`;
- lightening holes through each rib every `holes` of its length (radius 0.3 of `depth`; 0 for none);
- posts every `posts` that stand the plate off the rib: a rod from inside the plate into the rib, and a pad flat
on the plate's inner face (0 for none). A post starts midway between the plate's faces where it stands square
to them and deeper where it leans, so its end stays under the outer face; where the plate is thinner than the
lean of the post's end, no post stands;
- longerons through the ribs: each `{origin, axis, toward}` is the half-plane from the line through `origin`
along `axis`, on `toward`'s side. Where it crosses a plane's rib, at the rib's mid-depth, is a station; the
longeron runs through the stations in the planes' order and 0.12 of the end gaps past the end ribs, a section
`longeron` (`I`, `C`, `T`, `L` or `box`; `longeron_w`, `longeron_h`, `longeron_t`) with its up toward the plate.
A rib's outer edge is where its plane cuts the offset surface (`core.inset` makes it: each vertex of the inner
face stepped to where its faces, moved in by `standoff`, meet). Points `step` apart along the section each look
square in from the plate for it, and the edge's corners are put where the offset faces they landed on meet. Where
the offset surface has passed through itself (behind a crease, or inside a curve tighter than `standoff`) its
points measure nearer the plate than `standoff`: they are left out, and the edge closes across them at the corner
the faces either side make. Where nothing is left (a `standoff` greater than the wall's inner radius, a plane
that does not reach the offset surface) the call is refused. The rib is the band beside that edge
(`core.band`): the edge offset in its plane by `depth`, with mitred corners, and clipped as a polygon offset is,
so inside a turn tighter than the rib reaches the inner edge cuts the corner and the rib follows the crease.
The finished outer edge is then measured against the inner face, vertex by vertex, and moved in until none is
nearer than `standoff` (to 1e-7, what a float32 mesh holds). What the measure corrects is the half thickness,
which is laid off along the plane by the lean of the offset face: beside a tilted or curved wall that is right
to first order (it moved a rib 0.0006 on a prism cut at 64 degrees, and 0.005 on a sphere of radius 1 cut 60
degrees off its middle, where the offset surface leans 74 degrees). A rib that 8 moves do not stand off is
refused. The move is one distance for the whole rib, so elsewhere along it the rib stands further off than
`standoff` by up to that much.
Lightening holes stand on the band's centre line, clipped the same way, so a hole (0.3 of `depth`) keeps 0.2 of
`depth` of web on both sides; a post that would end outside the rib inside such a turn is left out. Posts and
longerons are a sweep of an outline along a path with mitred corners (`core.sweep`).
The cage is read twice. Evaluated with its Solidify, Bevel and Boolean modifiers off it is the surface as
designed: each plane cuts that surface into sections, and a section may be several chains (two legs in one cage).
Evaluated whole it is the plate as it is cut: at points `step` apart along a section, a ray from just outside the
plate's outer face asks whether the plate is there, looking 1.25 of the plate's thickness deep: a recess
shallower than the plate is plate, and the far wall of a narrow cage is not. Where it is not, the plate is open. An opening shorter than
`bridge` along the section is a panel break, and the rib runs behind it; at any other the rib stops `clearance`
short, and no post or hole stands there. A recess that does not go through is plate. `ribs` reads no cutter: cut
the cage first, in any way, and the ribs follow what the plate became.
The plate's two faces are read from the cage's one Solidify as Blender evaluates it (a cage with none has a
plate of no thickness; one with two is refused; a negative thickness is the same plate grown to the other side
of the surface). A simple Solidify writes the surface's vertices twice, in the surface's order, and the inner
face is the copy further against the normals: so the standoff is from the face the plate has, whatever the
thickness mode. Blender's default (even thickness off) moves each vertex the thickness along its own normal,
which makes a wall of 0.06 on a box 0.0424 thick beside each right angle; even thickness on a box whose sides
lean 45 and 20 degrees makes it 0.057 and 0.066. The report's `thickness` is the Solidify's own number, not a
measure. Where the Solidify does not write the two faces that way (complex mode, or a modifier after it that
remakes the vertices, such as a Subsurf after the Solidify) the plate is taken instead as the Solidify's
thickness behind every face of the designed surface, and the standoff is off by whatever the plate differs from
that: 0.0176 too far for a wall of 0.06 beside a right angle with even thickness off. Put the Solidify last
before Bevel and Booleans for the plate as it is. Inward is the side the cage's normals face away from, not a guess from
the section's shape: a cage whose normals change sides along a section is refused, and one whose normals all
face inward gets its frame outside. A rib is built at the section's own corners, so its faces lie along the
cage's facets, and it does not depend on which way round the section was followed.
Everything is checked before the ribs object is written, and a refusal names the plane or longeron: a plane that
misses the cage or lies along its surface; a section that leaves a rib no room, closing in on itself nearer than
the rib reaches everywhere (lower `standoff` or `depth`); a rib that cannot be stood `standoff` off the plate; a longeron that meets a plane's ribs twice, not at all, or in an opening;
holes that overlap or leave the rib; a cage that is scaled or that Blender does not evaluate; more than 64 planes or
16 longerons.
The ribs object is a bake of the cage at the call: a child of the cage under identity matrices, with no modifier
and no material. Its `kit_ribs` property is the request as JSON. After the cage or its cuts change, delete the
object and run `ribs` again. The holes are cut with one Manifold Boolean a plane, on that plane's ribs alone
(ribs of one plane never cross; ribs of two planes do), and each cut is checked: closed, and the volume gone is
the holes' own. Manifold is used here and nowhere else because these shells are built closed and apart; a target's
live Booleans stay Exact.
On a pod (2560 faces subdivided, a wall of 0.06, a port, a panel break and a recess; one whole evaluation
1.60 s), five ribs with 91 holes, 51 posts and four longerons took 2.26 s and the five ribs alone
2.02 s, medians of 5 calls in each of 3 processes interleaved with that evaluation (Blender 5.3 on Starfire). The hole cut is the Manifold
Boolean: 0.017 s a call for those holes against 0.44 s with Exact, 26 times.
Each call costs one whole evaluation of the cage, which scales with the cage's Exact Booleans: the action's own
work is the rest, 0.66 s and 0.42 s here: a second, light evaluation for the plate's two faces, three tree
queries for each point of a section, and the measure of each rib's edge against the plate, which builds a rib
again for each move (two to five on the pod). No cheaper route was found in Blender 5.3. The designed surface is read by hiding the cage's
Solidify, Bevel and Boolean modifiers for the call, which tags the cage, and Blender evaluates it whole again
afterwards. Reading the surface from a temporary copy without those modifiers costs 0.001 s to link and
evaluate, but deleting the copy costs the same whole evaluation (1.44 to 1.54 s on the pod against 1.45 to
1.52 s forced): Blender 5.3 evaluates the cage again after any datablock is deleted, a bare unlinked object
included, and the hole cut's temporary objects must be deleted too. So a hull with twenty cutters pays their
evaluation once for every `ribs` call; iterate planes on the cage before it is cut, or with its Booleans off.
## Expressions
@ -388,10 +493,11 @@ vertices overflow.
| `brokkr_kitbash.aim` | `object_name`, `axis` (`+x`, `-x`, `+y`, `-y`, `+z` or `-z`, the part's own), `direction_x`, `direction_y`, `direction_z` (world, any length) | Solves the roll that turns the axis as far toward the direction as the pin lets it, and turns the part to it. Refuses an axis or direction along the pin. Reports the part, `aimed: {roll, dot}` and `closures`. |
| `brokkr_kitbash.reach` | `object_name`, `socket` (one of the part's), `height` (metres, -1000 to 1000), `direction_x`, `direction_y`, `direction_z` (world; default 0, 0, 1) | Solves the roll that brings the socket's origin to `height` along the direction, the nearer of the two, and turns the part to it. Refuses a height out of reach, naming the range. Reports the part, `reached: {roll, residual}` and `closures`. |
| `brokkr_kitbash.close` | `object_name` (the closing part), `socket`, `other_name`, `other_socket` | States that the closing part's socket meets the other part's, closing a loop. Accepted only when they already meet; moves nothing. Reports the closing part. |
| `brokkr_kitbash.boolean` | `object_name` (any mesh), `cutter`, `operation` (`DIFFERENCE`, `UNION` or `INTERSECT`; default `DIFFERENCE`) | Adds the cutter to the collection of the target's one live Exact Boolean for the operation, above the Bevel. Refuses a cutter that is the target, is not a mesh, or already cuts it, and a scaled target. Reports the part (or `object` for a mesh that is not one), `booleans: [{cutter, operation}]` (difference, union, intersect; each in the order added) and `evaluated`. |
| `brokkr_kitbash.cut` | `object_name` (any mesh), `cutter_name`, `part` (`box`, `cyl`, `slot`, `slab`), `params`, `origin_x/y/z`, `direction_x/y/z`, `up_x/y/z` (default 0, 0, 1), `roll` (degrees, default 0), `axis_x/y/z` (default 0, 0, 0: the surface normal) | Places a `cutters` part where the ray meets the target, parented to it, and adds it to the target's difference Boolean. Refuses a ray that misses or has no direction, a name an object has, an `up` along the cutter's axis, an `axis` into the surface and a scaled target. Reports `object`, the `cutter` with its floor sockets, and `booleans`. |
| `brokkr_kitbash.cut_many` | `object_name` (any mesh), `cuts` (a JSON array of 1 to 64 cutters) | `cut` for several cutters in one action: all placed or none, one evaluation of the target afterwards. Reports `object`, `cutters` (names) and `booleans`. |
| `brokkr_kitbash.apply` | `object_name` | Bakes the evaluated mesh into the kit part and clears its modifiers and the collections its Booleans held. Refuses a part with no modifiers and a mesh another object shares. Reports the part, `faces`, `volume`, `nonManifoldEdges` and the `cutters` it no longer refers to. |
| `brokkr_kitbash.boolean` | `object_name` (any mesh), `cutter`, `operation` (`DIFFERENCE`, `UNION` or `INTERSECT`; default `DIFFERENCE`) | Adds the cutter to the collection of the target's one live Exact Boolean for the operation, above the Bevel. Refuses a cutter that is the target, is not a mesh, or already cuts it, and a scaled target. Reports the part (or `object` for a mesh that is not one), `booleans: [{cutter, operation}]` (difference, union, intersect; each in the order added; `booleansOmitted` counts rows a receipt had no room for) and `evaluated`. |
| `brokkr_kitbash.cut` | `object_name` (any mesh), `cutter_name`, `part` (`box`, `cyl`, `slot`, `slab`), `params`, `origin_x/y/z`, `direction_x/y/z`, `up_x/y/z` (default 0, 0, 1), `roll` (degrees, default 0), `axis_x/y/z` (default 0, 0, 0: the surface normal) | Places a `cutters` part where the ray meets the target, parented to it, and adds it to the target's difference Boolean. Refuses a ray that misses or has no direction, a name an object has, an `up` along the cutter's axis, an `axis` into the surface and a scaled target. Reports `object`, the `cutter` with its floor sockets, and `booleans` (with `booleansOmitted`, as `boolean`). |
| `brokkr_kitbash.cut_many` | `object_name` (any mesh), `cuts` (a JSON array of 1 to 64 cutters) | `cut` for several cutters in one action: all placed or none, one evaluation of the target afterwards. Reports `object`, `cutters` (names) and `booleans` (with `booleansOmitted`, as `boolean`). |
| `brokkr_kitbash.apply` | `object_name` | Bakes the evaluated mesh into the kit part and clears its modifiers and the collections its Booleans held. Refuses a part with no modifiers, a mesh another object shares and a part Blender does not evaluate. Reports the part, `faces`, `volume`, `nonManifoldEdges` and the `cutters` it no longer refers to. |
| `brokkr_kitbash.ribs` | `object_name` (the cage), `ribs_name`, `planes` (a JSON array of 1 to 64 `{origin, normal}`, up to 16000 characters), `standoff`, `depth`, `thickness`, `step`, `holes`, `posts`, `post_r`, `bridge`, `clearance`, `longerons` (a JSON array of 0 to 16 `{origin, axis, toward}`, up to 8000 characters), `longeron`, `longeron_w`, `longeron_h`, `longeron_t` | Derives ribs, lightening holes, posts and longerons from the cage as it is cut, as one mesh object under it. Refuses before it writes anything, naming the plane or longeron. Reports `object`, `ribs`, `thickness`, `sections: [{plane, chains, pieces, length, open}]`, `posts`, `holes`, `longerons: [{index, stations}]` (trimmed to a receipt, with `longeronsOmitted`), `faces`, `volume` and `nonManifoldEdges`. |
`params` is `name=value; name=value`; a param left out takes the part's default (`place_part`) or keeps its stored
value (`set_params`). A value outside its bounds is refused with the bounds in the message.

View file

@ -75,7 +75,7 @@ def extent(obj, axis=2):
check("the kitbash rows load as host actions with no errors", not R["hostErrors"]
and [r for r in R["hostRows"] if r.startswith("brokkr_kitbash.")] == [f"brokkr_kitbash.{name}" for name in (
"place_part", "set_params", "describe", "report", "attach", "detach", "roll", "aim", "reach", "close", "boolean", "cut", "cut_many", "apply")], [R["hostErrors"], R["hostRows"]])
"place_part", "set_params", "describe", "report", "attach", "detach", "roll", "aim", "reach", "close", "boolean", "cut", "cut_many", "apply", "ribs")], [R["hostErrors"], R["hostRows"]])
# --- describe ---------------------------------------------------------------------------------------------------------
kit = core.load_kit("mechanical")

View file

@ -419,7 +419,8 @@
"brokkr_kitbash.boolean",
"brokkr_kitbash.cut",
"brokkr_kitbash.cut_many",
"brokkr_kitbash.apply"
"brokkr_kitbash.apply",
"brokkr_kitbash.ribs"
],
"placed": {
"nozzle": {

View file

@ -177,7 +177,7 @@ def evaluated(obj):
rows = [row["name"] for row in target.host_actions()[0] if row["name"].startswith("brokkr_kitbash.")]
check("the kitbash rows load as host actions with no errors", not R["hostErrors"] and rows == [f"brokkr_kitbash.{n}" for n in (
"place_part", "set_params", "describe", "report", "attach", "detach", "roll", "aim", "reach", "close", "boolean", "cut", "cut_many", "apply")], [R["hostErrors"], rows])
"place_part", "set_params", "describe", "report", "attach", "detach", "roll", "aim", "reach", "close", "boolean", "cut", "cut_many", "apply", "ribs")], [R["hostErrors"], rows])
# --- attach -------------------------------------------------------------------------------------------------------------
tank = place("Tank", "tank", location=[1.0, 2.0, 3.0], rotation=[0.3, -0.2, 0.5]) # port size 0.088

View file

@ -0,0 +1,594 @@
"""Live proof, in a background Blender, of brokkr_kitbash.ribs through run_intent: ribs that stand a standoff behind a
cage's plate along the plate's own normal, however it leans, and in their planes, that follow a crease tighter than they
reach, that stop at a port, run behind a panel break and under a recess, that take their side from the cage's normals, longerons through the ribs of a cage a plane cuts twice, lightening holes through crossing
ribs, 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_ribs.py -- <out>
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.
Bounds follow lodur:ruling:deterministic-bound-margin: each sits at the geometric mean of the shipped worst reading
and the least claimed mutant's, both written beside it; the result file carries the readings. 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 bmesh
import bpy
import numpy as np
from mathutils import Matrix, 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-ribs-"))
target.configure_action_dirs("", str(WORK))
target.reload_host_actions()
R = {"blender": bpy.app.version_string, "checks": [], "hostErrors": target.host_actions()[1], "readings": {}}
COUNT, SECTION = [0], ["setup"]
STANDOFF, DEPTH, THICKNESS = 0.04, 0.06, 0.014
SIZES = {"standoff": STANDOFF, "depth": DEPTH, "thickness": THICKNESS}
# Metres between the standoff and how near a rib's outer edge comes to the plate's inner face, at each point of the edge,
# on the pod: a doubly curved wall that leans up to 30 degrees out of a rib's plane. Shipped worst 7.5e-05 (the edge is
# moved in by one distance for the whole rib, what its nearest vertex was short); least claimed mutant 0.00081 (O2, the
# rib's half thickness, which a leaning plate comes nearer, left out of the edge: the measure then moves the whole rib);
# the geometric mean, separation 3.3 each side. U1 reads 0.00017 and M2 0.00013 and die at STOOD and RING; S1 0.025.
FIT = 2.5e-4
# The same on cages of flat facets, where it is exact: cones whose wall leans 0, 30, 45 and 60 degrees out of the plane, a
# cylinder whose Solidify is negative, a hipped box, a crease and a dish. Shipped worst 6.4e-08 (float32 meshes); least
# claimed mutant 0.0003 (O2 at 60 degrees); the geometric mean, separation 68 each side. U1 (every Solidify read as not
# even) reads 0.00051, V1 0.003, S1 (the plate's outer face taken for its inner) 0.032.
STOOD = 4.4e-6
# A cone's rib or a hipped box's, over the ring between the section's two offsets times the thickness, less 1. Shipped worst 2.1e-06;
# least claimed mutant 1.8e-05 (L1, a corner of two distances never mitred); the geometric mean, separation 2.9 each side.
# M2 (the edge's corners left as chords) reads 0.00047, O2 0.0017.
RING = 6.1e-6
# A rib inside a crease, over the true clipped offset's area times the thickness, less 1. Shipped 2.3e-07 (the edge's
# corner is where the offset faces meet); least claimed mutant 0.00051 (M2, a chord across it); the geometric mean,
# separation 47 each side. U2 reads 0.0014, U1 0.031, A2 (an end of the section that finds no offset surface) 0.051, X1
# (nothing left out where the offset surface folded) 0.07. tests/test_kitbash.py CREASED is core.band's own, on the same polyline.
CREASED = 1.1e-5
# Metres between the standoff and how near the rib comes to the plate where a plane tilted 64 degrees cuts a prism of 24
# flat sides. Shipped 2.1e-05 (one move for the whole rib, 0.0006 along the plane); least claimed mutant 5.5e-05 (V1, an
# offset clipped at its own distance); the geometric mean, separation 1.6 each side. U1 reads 0.00014, O2 0.00032, E1
# (the edge never measured against the plate and moved in) 0.00059, G1 0.037. Before cut-kit-ribs.h3 it read 0.007.
TILTED = 3.4e-5
# The same on spheres of radius 1 and 0.6 cut 60 degrees off their middle, standoffs 0.04 and 0.01. Shipped worst 9.7e-08;
# least claimed mutant 5.9e-07 (U2, every Solidify read as even: an icosphere's faces meet at unequal angles); the
# geometric mean, separation 2.5 each side. C1 reads 1.5e-05, U1 5.6e-05, O2 0.00016, E1 0.0014, G1 0.024. Before
# cut-kit-ribs.h3 they read 0.020, and at radius 0.6 and standoff 0.01 the rib stood 0.006 through the inner face.
ROUND = 2.4e-7
# The same on a box whose Solidify is not even (Blender's default). Shipped 8.3e-09; least claimed mutant 0.018 (U2, the
# plate read as its Solidify's thickness behind every face, as before cut-kit-ribs.h3); the geometric mean, separation
# 1500 each side. S1 reads 0.038.
UNEVEN = 1.2e-5
# Metres a rib vertex stands off its plane beyond half the rib's thickness. Shipped worst 1.4e-07 (float32 meshes);
# least claimed mutant 0.007 (KP, a rib twice as thick across its plane); separation 220 each side.
PLANAR = 3.1e-5
# Metres from the port's opening to the nearest vertex of a rib, post or hole, along the section: the least is the
# worst. Shipped 0.031 (the last sample under the plate, the clearance of 0.02 and up to a step); least claimed mutant
# 0.0011 (K6, the clearance ignored); separation 5.3 each side. K4 and K10 put vertices inside the opening: -0.12.
CLEARED = 0.0058
# Metres a longeron's station stands from its half-plane, its plane's height or the rib's mid-depth line. Shipped worst
# 5.2e-07; least claimed mutant 0.0021 (K1, a sweep with no mitre: the rib's mid-depth line stands in from where the
# facets' offsets meet); separation 64 each side. K9 (the station at the chain's first point) reads 1.2.
STATIONED = 3.3e-5
# What lightening holes removed from five crossing ribs, over the holes' faceted area times the thickness, less 1.
# Shipped 2.7e-08; least claimed mutant 22 (K11, each plane's Manifold Boolean taken over all five ribs' webs, which
# cross, with the action's own check of the cut off); separation 28000 each side.
HOLED = 7.7e-4
# Metres under the plate's outer face that the nearest vertex of a frame stands: the least is the worst, and under 0 a post is
# through the plate. Shipped worst 0.0047 (the rim of a post's end on a cone leaning 60 degrees whose wall is 0.02); least
# claimed mutant 0.0015 (P2, every post started a tenth of the plate under its outer face); the geometric mean,
# separation 1.8 each side. P3 (a leaning post not started deeper) reads 0.00013; S1 and G1 put vertices outside: -0.01.
SUNK = 0.0027
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"])[:300], 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)
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.ribs", **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 mesh_object(name, vertices, faces, world=None, wall=None, levels=0):
"""A mesh object from points and faces, normals as the faces are wound, optionally subdivided and given a wall inward."""
made = bpy.data.objects.new(name, bpy.data.meshes.new(name))
made.data.from_pydata(vertices, [], faces)
bpy.context.scene.collection.objects.link(made)
if levels:
made.modifiers.new("Subsurf", "SUBSURF").levels = levels
if wall:
solid = made.modifiers.new("Solidify", "SOLIDIFY")
solid.thickness, solid.offset, solid.use_even_offset = wall, -1.0, True
if world is not None:
made.matrix_world = world
bpy.context.view_layer.update()
return made
def tree(obj, off=()):
"""This script's own BVH of an object evaluated with the modifiers of the named types off, in its own frame."""
hidden = [m for m in obj.modifiers if m.type in off and m.show_viewport]
for m in hidden:
m.show_viewport = False
try:
return BVHTree.FromObject(obj, bpy.context.evaluated_depsgraph_get())
finally:
for m in hidden:
m.show_viewport = True
def points(obj):
V = np.zeros(3 * len(obj.data.vertices))
obj.data.vertices.foreach_get("co", V)
return V.reshape(-1, 3)
def measure(mesh):
bm = bmesh.new()
bm.from_mesh(mesh)
row = {"faces": len(bm.faces), "volume": bm.calc_volume(signed=True), "nonManifoldEdges": sum(1 for e in bm.edges if not e.is_manifold),
"shells": len({min(v.index for v in island) for island in islands(bm)})}
bm.free()
return row
def islands(bm):
seen, found = set(), []
for start in bm.verts:
if start in seen:
continue
island, stack = [], [start]
seen.add(start)
while stack:
v = stack.pop()
island.append(v)
for e in v.link_edges:
other = e.other_vert(v)
if other not in seen:
seen.add(other)
stack.append(other)
found.append(island)
return found
def nearest_by_column(surface, V):
"""The least distance from a BVH to the vertices that share an x and y (to 1e-5), for each such column."""
found = {}
for v in V:
key = (round(float(v[0]), 5), round(float(v[1]), 5))
found[key] = min(found.get(key, 1.0), surface.find_nearest(Vector(v))[3])
return found
def child_of(ribs, cage):
return ribs is not None and ribs.parent == cage and np.array_equal(np.array(ribs.matrix_parent_inverse), np.eye(4)) and np.array_equal(np.array(ribs.matrix_basis), np.eye(4)) \
and np.abs(np.array(ribs.matrix_world) - np.array(cage.matrix_world)).max() < 1e-6 and len(ribs.modifiers) == 0 and len(ribs.data.materials) == 0
def flat(z_planes):
return json.dumps([{"origin": [0.0, 0.0, z], "normal": [0.0, 0.0, 1.0]} for z in z_planes])
try:
# --- a pod: a closed loft of 6 rings of 8, subdivided, with a wall, a port, a panel break and a recess --------------------
section("a pod")
def ring(w, d, z, n=8, p=3.0):
return [(0.5 * w * math.copysign(abs(math.cos(a)) ** (2 / p), math.cos(a)), 0.5 * d * math.copysign(abs(math.sin(a)) ** (2 / p), math.sin(a)), z)
for a in (2 * math.pi * (k + 0.5) / n for k in range(n))]
rings = [ring(w, d, z) for z, w, d in ((0, .6, .5), (.3, 1.0, .8), (.7, 1.2, .95), (1.1, 1.1, .9), (1.4, .8, .6), (1.6, .4, .3))]
pod = mesh_object("Pod", [p for r in rings for p in r], [(i * 8 + j, i * 8 + (j + 1) % 8, (i + 1) * 8 + (j + 1) % 8, (i + 1) * 8 + j) for i in range(5) for j in range(8)],
Matrix.Translation((4.0, -1.0, 2.0)) @ Matrix.Rotation(0.6, 4, "Z") @ Matrix.Rotation(-0.3, 4, "X"), wall=0.06, levels=3)
CUTS = [{"name": "Port", "part": "box", "params": "width=0.25; height=0.2; depth=0.2", "origin": [2, 0, 0.7], "direction": [-1, 0, 0]},
{"name": "Seam", "part": "slab", "params": "gap=0.02; length=0.6; depth=0.2", "origin": [-2, 0, 0.7], "direction": [1, 0, 0]},
{"name": "Recess", "part": "box", "params": "width=0.2; height=0.15; depth=0.03", "origin": [0, 2, 0.7], "direction": [0, -1, 0]}]
receipt, _ = send("brokkr_kitbash.cut_many", object_name="Pod", cuts=json.dumps(CUTS))
check("the pod is cut by a port, a panel break and a recess", receipt["status"] == "accepted", receipt["message"])
HEIGHTS = (0.3, 0.5, 0.7, 0.9, 1.15)
designed = tree(pod, ("SOLIDIFY", "BEVEL", "BOOLEAN")) # the surface as designed
cuts = [m for m in pod.modifiers if m.type == "BOOLEAN"]
for m in cuts:
m.show_viewport = False
wall = pod.evaluated_get(bpy.context.evaluated_depsgraph_get()).to_mesh() # the wall before it is cut; its inner face is the faces that stand off the designed surface
inner = BVHTree.FromPolygons([v.co.copy() for v in wall.vertices], [tuple(p.vertices) for p in wall.polygons if designed.find_nearest(p.center)[3] > 0.045])
for m in cuts:
m.show_viewport = True
bpy.context.view_layer.update()
# --- ribs-fit-the-plate ----------------------------------------------------------------------------------------------------
section("ribs-fit-the-plate")
request = {"object_name": "Pod", "ribs_name": "Fit", "planes": flat(HEIGHTS), **SIZES}
receipt, report = send("brokkr_kitbash.ribs", **request)
fit = bpy.data.objects.get("Fit")
stored = json.loads(fit["kit_ribs"]) if fit is not None and "kit_ribs" in fit else {}
check("ribs makes one mesh object under the cage: a child under identity matrices, no modifier, no material, and kit_ribs the request", receipt["status"] == "accepted"
and child_of(fit, pod) and stored.get("planes") == json.loads(request["planes"]) and stored.get("object_name") == "Pod"
and all(abs(stored[k] - v) < 1e-7 for k, v in SIZES.items()) and sorted(stored) == sorted(
["object_name", "planes", "standoff", "depth", "thickness", "step", "holes", "posts", "post_r", "bridge", "clearance", "longerons", "longeron", "longeron_w", "longeron_h", "longeron_t"]),
[receipt["message"], stored])
shape = measure(fit.data)
check("ribs reports the frame: one rib a plane, the plate's thickness read from the Solidify, the port's plane open along it, closed shells",
report and sorted(report) == ["faces", "holes", "longerons", "nonManifoldEdges", "object", "posts", "ribs", "sections", "thickness", "volume"]
and (report["object"], report["ribs"], report["thickness"], report["posts"], report["holes"], report["longerons"], report["nonManifoldEdges"]) == ("Fit", 5, 0.06, 0, 0, [], 0)
and [(s["plane"], s["chains"], s["pieces"]) for s in report["sections"]] == [(k, 1, 1) for k in range(5)]
and [s["open"] > 0.25 for s in report["sections"]] == [False, False, True, False, False] and all(s["open"] == 0.0 for k, s in enumerate(report["sections"]) if k != 2)
and (shape["faces"], shape["nonManifoldEdges"], shape["shells"]) == (report["faces"], 0, 5) and abs(shape["volume"] - report["volume"]) < 1e-8
and 0.5 < report["volume"] / (sum(s["length"] for s in report["sections"]) * DEPTH * THICKNESS) < 1.0, report) # a rib inside a curve is shorter than the section it follows
behind, V = True, points(fit)
for v in V:
plane = min(HEIGHTS, key=lambda z: abs(v[2] - z))
reading("planar", abs(abs(v[2] - plane) - THICKNESS / 2))
on, normal, _, _ = designed.find_nearest(Vector((v[0], v[1], plane)))
behind = behind and (Vector((v[0], v[1], plane)) - on).dot(normal) < 0
for least in nearest_by_column(inner, V).values(): # a column: the vertices of one point of an edge, half a thickness either side of the plane
if least < STANDOFF + 0.4 * DEPTH: # the outer edge's; the inner edge's stand a depth further in
reading("fit", abs(least - STANDOFF))
check("ribs-fit-the-plate: at every point of a rib's outer edge the nearer vertex stands the standoff behind the plate's inner face, along the plate's normal; every vertex in its plane, on the side the normals face away from",
behind and R["readings"]["fit"] < FIT and R["readings"]["planar"] < PLANAR, R["readings"])
# --- standoff-oblique-sections: cones, a negative Solidify, and a crease ----------------------------------------------------------
section("ribs-on-leaning-plates")
SIDES = 24
def frustum(name, lean, at):
"""A cone's wall from z = 0.3 to 0.7 that leans `lean` degrees from its axis, radius 0.6 at z = 0.5, normals outward, a wall of 0.06 inward."""
rows = [[((0.6 + (z - 0.5) * math.tan(math.radians(lean))) * math.cos(a), (0.6 + (z - 0.5) * math.tan(math.radians(lean))) * math.sin(a), z)
for a in (2 * math.pi * (k + 0.5) / SIDES for k in range(SIDES))] for z in (0.3, 0.7)]
return mesh_object(name, rows[0] + rows[1], [(k, (k + 1) % SIDES, SIDES + (k + 1) % SIDES, SIDES + k) for k in range(SIDES)], Matrix.Translation(at), wall=0.06)
def stood(cage, ribs, standoff=STANDOFF, name="stood"):
"""How near the ribs come to the cage's plate as it is evaluated, less the standoff."""
plate = tree(cage)
return reading(name, abs(min(plate.find_nearest(Vector(v))[3] for v in points(ribs)) - standoff))
def under(cage, ribs):
"""How far under the cage's outer face (its designed surface: every wall here grows inward) the frame's nearest vertex stands: under 0, a vertex is outside the plate."""
outer, worst = tree(cage, ("SOLIDIFY", "BEVEL", "BOOLEAN")), 1.0
for v in points(ribs):
on, normal, _, _ = outer.find_nearest(Vector(v))
worst = min(worst, -(Vector(v) - on).dot(normal))
return reading("sunk", worst, least=True)
leaned = []
for k, lean in enumerate((0, 30, 45, 60)):
cone = frustum(f"Cone{lean}", lean, (3.0 * k, 9.0, 0.0))
receipt, report = send("brokkr_kitbash.ribs", object_name=cone.name, ribs_name=f"ConeRibs{lean}", planes=flat([0.5]), **SIZES)
ribs = bpy.data.objects.get(f"ConeRibs{lean}")
slope = math.tan(math.radians(lean)) * math.cos(math.pi / SIDES) # of a facet: the cone's own lean is its corners'
back = (0.06 + STANDOFF) * math.hypot(1.0, slope) + THICKNESS / 2 * slope # along the plane, to the rib's outer edge
outer = 0.6 * math.cos(math.pi / SIDES) - back # the inradius of the rib's outer edge, a regular polygon
ring = SIDES * math.tan(math.pi / SIDES) * (outer ** 2 - (outer - DEPTH) ** 2) * THICKNESS
readings = (stood(cone, ribs), reading("ring", abs(measure(ribs.data)["volume"] / ring - 1.0))) if ribs is not None else (1.0, 1.0)
leaned.append(receipt["status"] == "accepted" and child_of(ribs, cone) and (report["ribs"], report["thickness"], report["nonManifoldEdges"]) == (1, 0.06, 0)
and readings[0] < STOOD and readings[1] < RING)
check("standoff-oblique-sections: on cones whose wall leans 0, 30, 45 and 60 degrees out of the rib's plane the rib comes the standoff from the plate's inner face and no nearer, and is the ring between the section's offsets",
leaned == [True] * 4, [leaned, R["readings"]])
# A hipped box: walls that lean 45 and 20 degrees meet at its four corners. No Solidify: Blender's even thickness is not even where a
# vertex's faces meet at unequal angles (a wall of 0.06 here is 0.057 and 0.066 thick), and this check is of the rib, against a plate that is exact.
hip = mesh_object("Hip", [(sx * (0.6 + (z - 0.5) * math.tan(math.radians(45))), sy * (0.5 + (z - 0.5) * math.tan(math.radians(20))), z) for z in (0.3, 0.7) for sx, sy in ((1, -1), (1, 1), (-1, 1), (-1, -1))],
[(k, (k + 1) % 4, 4 + (k + 1) % 4, 4 + k) for k in range(4)], Matrix.Translation((15.0, 9.0, 0.0)))
receipt, report = send("brokkr_kitbash.ribs", object_name="Hip", ribs_name="HipRibs", planes=flat([0.5]), **SIZES)
ribs = bpy.data.objects.get("HipRibs")
wide, deep = (0.6 - STANDOFF * math.hypot(1.0, math.tan(math.radians(lean))) - THICKNESS / 2 * math.tan(math.radians(lean)) for lean in (45, 20)) # the rib's outer edge, from the middle
ring = 4.0 * (wide * (deep - 0.1) - (wide - DEPTH) * (deep - 0.1 - DEPTH)) * THICKNESS
check("where walls that lean 45 and 20 degrees meet, the rib stands the standoff off each wall right into the corner: its edges are each wall's own, met in a mitre (mutant V1 runs one wall's edge into the other's standoff)",
receipt["status"] == "accepted" and (report["ribs"], report["thickness"], report["nonManifoldEdges"]) == (1, 0.0, 0) and stood(hip, ribs) < STOOD
and reading("ring", abs(measure(ribs.data)["volume"] / ring - 1.0)) < RING, [receipt["message"], report, R["readings"]])
turned = frustum("Turned", 0, (12.0, 9.0, 0.0))
turned.modifiers["Solidify"].thickness = -0.06 # the plate grows outward of the designed surface
bpy.context.view_layer.update()
grown = max(math.hypot(v.co.x, v.co.y) for v in turned.evaluated_get(bpy.context.evaluated_depsgraph_get()).data.vertices)
receipt, report = send("brokkr_kitbash.ribs", object_name="Turned", ribs_name="TurnedRibs", planes=flat([0.5]), **SIZES)
check("negative-solidify-thickness: a wall of -0.06 grows outward, and the rib stands the standoff inside the designed surface, the plate's inner face",
receipt["status"] == "accepted" and grown > 0.65 and report["thickness"] == 0.06 and stood(turned, bpy.data.objects["TurnedRibs"]) < STOOD, [receipt["message"], report, grown, R["readings"]])
turn, facet, run = math.radians(49.4), 0.062, 0.3 # tests/test_kitbash.py test_a_band_follows_a_crease_tighter_than_it_reaches: the same section, in x and z
profile = [(-facet / 2 - run * math.cos(turn), -run * math.sin(turn)), (-facet / 2, 0.0), (facet / 2, 0.0), (facet / 2 + run * math.cos(turn), -run * math.sin(turn))]
creased = mesh_object("Creased", [(x, y, z) for y in (-0.3, 0.3) for x, z in profile], [(k, k + 1, k + 5, k + 4) for k in range(3)], Matrix.Translation((0.0, 12.0, 0.0)), wall=0.06)
CREASE = {"object_name": "Creased", "planes": json.dumps([{"origin": [0.0, 0.0, 0.0], "normal": [0.0, 1.0, 0.0]}]), "standoff": 0.03, "depth": 0.08, "thickness": THICKNESS}
receipt, report = send("brokkr_kitbash.ribs", ribs_name="CreaseRibs", **CREASE)
ribs = bpy.data.objects.get("CreaseRibs")
near, far, apex = 0.06 + 0.03, 0.06 + 0.03 + 0.08, facet / 2 / math.cos(turn)
area = 2.0 * ((run + apex) * (far - near) - math.tan(turn) * (far ** 2 - near ** 2) / 2.0)
V = points(ribs) if ribs is not None else np.zeros((1, 3))
off = core.away(V * (1.0, 0.0, 1.0), [(x, 0.0, z) for x, z in profile], False)
check("ribs-fold-at-crease: behind a crease of 49.4 degrees either side of a facet of 0.062 a rib of standoff 0.03 and depth 0.08 is made, clipped: one closed shell the area of the true offset, no vertex nearer the section than the rib starts or further than it reaches",
receipt["status"] == "accepted" and child_of(ribs, creased) and (report["ribs"], report["nonManifoldEdges"], report["sections"][0]["pieces"]) == (1, 0, 1)
and reading("creased", abs(measure(ribs.data)["volume"] / THICKNESS / area - 1.0)) < CREASED and stood(creased, ribs, 0.03) < STOOD
and float(off.min()) > near - 1e-6 and float(off.max()) < far + 1e-6, [receipt["message"], report, off.min(), off.max(), R["readings"]])
receipt, report = send("brokkr_kitbash.ribs", ribs_name="CreaseFrame", **CREASE, holes=0.1, posts=0.05)
_, shallow = send("brokkr_kitbash.ribs", ribs_name="CreaseShallow", **{**CREASE, "depth": 0.02}, posts=0.05)
check("a post behind the crease's facet that would end outside a shallow rib, short of where the rib's edges meet, is left out: ten of the thirteen stations (mutant P1 posts eleven)",
shallow is not None and (shallow["posts"], shallow["nonManifoldEdges"]) == (10, 0), shallow)
check("the creased rib takes holes along its clipped centre line, cut clean, and posts", receipt["status"] == "accepted" and (report["holes"], report["posts"], report["nonManifoldEdges"]) == (3, 11, 0),
[receipt["message"], report]) # the centre line is 0.3 + 0.048 - 0.13 tan 49.4 = 0.196 a run: 0.39 holds three holes 0.1 apart; the section, 0.662, thirteen post stations, one each side of the facet clipped
angle = mesh_object("Angle", [(x, y, z) for y in (-0.3, 0.3) for x, z in ((-0.4, 0.0), (0.0, 0.0), (0.0, -0.4))], [(0, 1, 4, 3), (1, 2, 5, 4)], Matrix.Translation((3.0, 12.0, 0.0)), wall=0.05)
receipt, report = send("brokkr_kitbash.ribs", object_name="Angle", ribs_name="AngleRibs", planes=CREASE["planes"], **SIZES, posts=0.05)
check("inside a right angle no post stands nearer the corner than the rib's outer edge is set back, 0.09: twelve of the sixteen stations (mutant P1 posts all sixteen, four through the other wall)",
receipt["status"] == "accepted" and (report["ribs"], report["posts"], report["nonManifoldEdges"]) == (1, 12, 0) and abs(report["sections"][0]["length"] - 0.8) < 1e-6, [receipt["message"], report])
# --- standoff-curved-and-tilted: the standoff where the plate's lean changes across the rib's reach --------------------------------
section("standoff-curved-and-tilted")
prism = mesh_object("Prism", [(0.6 * math.cos(a), 0.6 * math.sin(a), z) for z in (-1.0, 2.0) for a in (2 * math.pi * (k + 0.5) / SIDES for k in range(SIDES))],
[(k, (k + 1) % SIDES, SIDES + (k + 1) % SIDES, SIDES + k) for k in range(SIDES)], Matrix.Translation((18.0, 9.0, 0.0)), wall=0.06)
receipt, report = send("brokkr_kitbash.ribs", object_name="Prism", ribs_name="PrismRibs", planes=json.dumps([{"origin": [0.0, 0.0, 0.5], "normal": [0.0, 0.9, 0.436]}]), **SIZES)
ribs = bpy.data.objects.get("PrismRibs")
check("a plane tilted 64 degrees through a prism of 24 flat sides: every facet leans differently out of the plane, and the rib stands the standoff off each (the finding: 0.007 short)",
receipt["status"] == "accepted" and (report["ribs"], report["nonManifoldEdges"]) == (1, 0) and stood(prism, ribs, STANDOFF, "tilted") < TILTED, [receipt["message"], report, R["readings"]])
def ball(name, radius, at):
made = bmesh.new()
bmesh.ops.create_icosphere(made, subdivisions=5, radius=radius)
vertices, faces = [tuple(v.co) for v in made.verts], [tuple(v.index for v in f.verts) for f in made.faces]
made.free()
return mesh_object(name, vertices, faces, Matrix.Translation(at), wall=0.06)
rounds = []
for k, (radius, standoff, depth) in enumerate(((1.0, 0.04, 0.06), (1.0, 0.01, 0.06), (0.6, 0.01, 0.03))):
sphere = ball(f"Ball{k}", radius, (3.0 * k, 18.0, 0.0))
ROUND_RIB = {"object_name": sphere.name, "planes": flat([radius * math.sin(math.radians(60))]), "standoff": standoff, "depth": depth, "thickness": THICKNESS}
receipt, report = send("brokkr_kitbash.ribs", ribs_name=f"BallRibs{k}", **ROUND_RIB)
_, posted = send("brokkr_kitbash.ribs", ribs_name=f"BallPosts{k}", **ROUND_RIB, posts=0.2)
ribs, frame = bpy.data.objects.get(f"BallRibs{k}"), bpy.data.objects.get(f"BallPosts{k}")
rounds.append(receipt["status"] == "accepted" and (report["ribs"], report["nonManifoldEdges"]) == (1, 0) and stood(sphere, ribs, standoff, "round") < ROUND
and posted is not None and posted["posts"] > 3 and under(sphere, frame) > SUNK)
check("spheres of radius 1 and 0.6 cut 60 degrees off the middle, standoffs 0.04 and 0.01: a wall curved both ways, leaning 60 degrees, and the rib and its posts stand the standoff off it "
"(the finding: 0.020 short, and at radius 0.6 and standoff 0.01 through the inner face)", rounds == [True] * 3, [rounds, R["readings"]])
ball("Ball3", 0.6, (9.0, 18.0, 0.0))
refused("at radius 0.6 a standoff of 0.04 has no rib in that plane: 0.1 inside the wall the sphere is 0.5, and the plane passes 0.52 from its middle",
{"object_name": "Ball3", "ribs_name": "BallRibs3", "planes": flat([0.6 * math.sin(math.radians(60))]), "standoff": 0.04, "depth": 0.03, "thickness": THICKNESS}, "planes[0]: the section leaves a rib no room")
tight = ball("Tight", 0.15, (15.0, 18.0, 0.0))
refused("a standoff greater than the plate's inner radius: the offset surface has passed through itself everywhere", {"object_name": "Tight", "ribs_name": "TightRibs", "planes": flat([0.0]), "standoff": 0.12,
"depth": 0.02, "thickness": THICKNESS}, "planes[0]: the section leaves a rib no room")
plain = mesh_object("Plain", [(sx * 0.5, sy * 0.5, z) for z in (0.3, 0.7) for sx, sy in ((1, -1), (1, 1), (-1, 1), (-1, -1))], [(k, (k + 1) % 4, 4 + (k + 1) % 4, 4 + k) for k in range(4)],
Matrix.Translation((21.0, 9.0, 0.0)), wall=0.06)
plain.modifiers["Solidify"].use_even_offset = False # Blender's default: each vertex 0.06 along its own normal, so the plate is 0.0424 thick beside a right angle
bpy.context.view_layer.update()
receipt, report = send("brokkr_kitbash.ribs", object_name="Plain", ribs_name="PlainRibs", planes=flat([0.5]), **SIZES)
check("solidify-default-unbounded: a box whose Solidify is not even is 0.0424 thick, not its 0.06, and the rib stands the standoff off the inner face it has (read as 0.06: 0.0176 over)",
receipt["status"] == "accepted" and report["thickness"] == 0.06 and stood(plain, bpy.data.objects["PlainRibs"], STANDOFF, "uneven") < UNEVEN, [receipt["message"], report, R["readings"]])
late = frustum("Late", 30, (27.0, 9.0, 0.0))
late.modifiers.new("Subsurf", "SUBSURF").levels = 2 # after the Solidify: the plate is the wall subdivided, and its faces are not the surface's vertices twice
bpy.context.view_layer.update()
receipt, report = send("brokkr_kitbash.ribs", object_name="Late", ribs_name="LateRibs", planes=flat([0.5]), **SIZES)
check("a cage subdivided after its Solidify is taken as that thick behind every face: a rib, clear of the plate",
receipt["status"] == "accepted" and (report["ribs"], report["thickness"], report["nonManifoldEdges"]) == (1, 0.06, 0)
and min(tree(late).find_nearest(Vector(v))[3] for v in points(bpy.data.objects["LateRibs"])) > 0.5 * STANDOFF, [receipt["message"], report])
# --- plate-window-unpinned: how deep the ray that asks "is the plate here" looks ---------------------------------------------------
section("the-plate-window")
sunk = mesh_object("Sunk", [(-0.5, -0.2, 0.0), (0.5, -0.2, 0.0), (0.5, 0.2, 0.0), (-0.5, 0.2, 0.0)], [(0, 1, 2, 3)], Matrix.Translation((0.0, 15.0, 0.0)), wall=0.05)
send("brokkr_kitbash.cut_many", object_name="Sunk", cuts=json.dumps([{"name": "Deep", "part": "box", "params": "width=0.15; height=0.15; depth=0.04", "origin": [0.0, 0.0, 2.0],
"direction": [0.0, 0.0, -1.0], "up": [0.0, 1.0, 0.0]}]))
receipt, report = send("brokkr_kitbash.ribs", object_name="Sunk", ribs_name="SunkRibs", planes=json.dumps([{"origin": [0.0, 0.0, 0.0], "normal": [0.0, 1.0, 0.0]}]), **SIZES)
check("a recess 0.8 of the plate deep is plate: the rib runs on under it (the ray looks 1.25 of the plate deep; mutant N5 looks 0.5)",
receipt["status"] == "accepted" and [(s["pieces"], s["open"]) for s in report["sections"]] == [(1, 0.0)] and abs(report["sections"][0]["length"] - 1.0) < 1e-6, [receipt["message"], report])
tube = [(0.09 * math.cos(a), 0.09 * math.sin(a), z) for z in (0.0, 0.6) for a in (2 * math.pi * (k + 0.5) / 16 for k in range(16))]
narrow = mesh_object("Narrow", tube, [(k, (k + 1) % 16, 16 + (k + 1) % 16, 16 + k) for k in range(16)], Matrix.Translation((3.0, 15.0, 0.0)), wall=0.04)
send("brokkr_kitbash.cut_many", object_name="Narrow", cuts=json.dumps([{"name": "Slot", "part": "box", "params": "width=0.06; height=0.2; depth=0.07", "origin": [2.0, 0.0, 0.3], "direction": [-1.0, 0.0, 0.0]}]))
receipt, report = send("brokkr_kitbash.ribs", object_name="Narrow", ribs_name="NarrowRibs", planes=flat([0.3]), standoff=0.005, depth=0.015, thickness=THICKNESS)
check("a port in a narrow cage is open though the far wall stands 3.5 plates behind it: the rib stops either side (mutant N13 looks 5 plates deep and finds the far wall)",
receipt["status"] == "accepted" and [(s["chains"], s["pieces"]) for s in report["sections"]] == [(1, 1)] and 0.06 < report["sections"][0]["open"] < 0.06 + 4 * 0.02 + 2 * 0.01,
[receipt["message"], report])
# --- ribs-stop-at-ports: a flat deck with a port, a panel break and a recess along one section ----------------------------------
section("ribs-stop-at-ports")
deck = mesh_object("Deck", [(-0.8, -0.5, 0.0), (0.8, -0.5, 0.0), (0.8, 0.5, 0.0), (-0.8, 0.5, 0.0)], [(0, 1, 2, 3)], Matrix.Translation((0.0, 5.0, 0.0)) @ Matrix.Rotation(0.4, 4, "Y"), wall=0.05)
DOWN = {"direction": [0.0, 0.0, -1.0], "up": [0.0, 1.0, 0.0]}
DECK_CUTS = [{**DOWN, "name": "DeckPort", "part": "box", "params": "width=0.25; height=0.2; depth=0.2", "origin": [-0.3, 0.0, 2.0]},
{**DOWN, "name": "DeckSeam", "part": "slab", "params": "gap=0.02; length=0.6; depth=0.2", "origin": [0.3, 0.0, 2.0]},
{**DOWN, "name": "DeckRecess", "part": "box", "params": "width=0.15; height=0.15; depth=0.02", "origin": [0.6, 0.0, 2.0]}]
send("brokkr_kitbash.cut_many", object_name="Deck", cuts=json.dumps(DECK_CUTS))
ALONG = json.dumps([{"origin": [0.0, 0.0, 0.0], "normal": [0.0, 1.0, 0.0]}, {"origin": [0.0, 0.25, 0.0], "normal": [0.0, 1.0, 0.0]}]) # through all three cuts; through the break alone
receipt, report = send("brokkr_kitbash.ribs", object_name="Deck", ribs_name="DeckRibs", planes=ALONG, **SIZES, posts=0.2, holes=0.1)
ribs = bpy.data.objects.get("DeckRibs")
V = points(ribs) if ribs is not None else np.zeros((1, 3))
first = V[np.abs(V[:, 1]) < 0.1] # the section through the port: everything the frame put there, ribs, posts and holes
for x in first[:, 0]:
reading("cleared", abs(x + 0.3) - 0.125, least=True)
lengths = [s["length"] for s in report["sections"]] if report else []
check("ribs-stop-at-ports: no rib, post or hole stands within the clearance of the port; behind the panel break the rib is one piece; under the recess it runs on",
receipt["status"] == "accepted" and child_of(ribs, deck) and [(s["chains"], s["pieces"]) for s in report["sections"]] == [(1, 2), (1, 1)]
and CLEARED < R["readings"]["cleared"] < 0.02 + 2 * 0.01 and 0.25 + 2 * 0.02 < 1.6 - lengths[0] < 0.25 + 4 * 0.02 and abs(lengths[1] - 1.6) < 1e-6
and report["sections"][1]["open"] == 0.0 and abs(report["sections"][0]["open"] - (1.6 - lengths[0])) < 1e-5 and first[:, 0].max() > 0.79 and first[:, 0].min() < -0.79
and (report["posts"], report["holes"], report["nonManifoldEdges"]) == (1 + 4 + 8, 3 + 9 + 16, 0) # runs of 0.34, 0.94 and 1.6: a post every 0.2 and a hole every 0.1, half a pitch from each end
and abs(float(V[:, 2].max()) + 0.025) < 1e-6 and abs(float(V[:, 2].min()) + 0.05 + STANDOFF + DEPTH) < 1e-6, [receipt["message"], report, R["readings"]]) # a post starts mid-plate; the ribs end 0.15 down
seam_free = send("brokkr_kitbash.ribs", object_name="Deck", ribs_name="DeckSplit", planes=ALONG, **SIZES, bridge=0.0)[1]
check("with no bridge the panel break splits both ribs", seam_free and [s["pieces"] for s in seam_free["sections"]] == [3, 2], seam_free)
# --- ribs-from-normals: a dish whose normals face its hollow side ------------------------------------------------------------
section("ribs-from-normals")
ARC = [math.radians(a) for a in range(-40, 41, 10)]
dish_points = [(math.sin(a), y, 1.0 - math.cos(a)) for y in (-0.3, 0.3) for a in ARC] # a trough of radius 1 about the line x = 0, z = 1; its hollow side is up
dish = mesh_object("Dish", dish_points, [(k, k + 1, k + 10, k + 9) for k in range(8)])
up_facing = all(p.normal.z > 0 for p in dish.data.polygons)
receipt, report = send("brokkr_kitbash.ribs", object_name="Dish", ribs_name="DishRibs", planes=json.dumps([{"origin": [0.0, 0.0, 0.0], "normal": [0.0, 1.0, 0.0]}]), **SIZES)
ribs = bpy.data.objects.get("DishRibs")
from_axis = np.hypot(points(ribs)[:, 0], points(ribs)[:, 2] - 1.0) if ribs is not None else np.zeros(1)
check("ribs-from-normals: a dish whose normals face its hollow side gets its rib on the other, the round side, though its section's middle lies in the hollow; a cage with no Solidify has a plate of no thickness",
receipt["status"] == "accepted" and up_facing and report["thickness"] == 0.0 and report["ribs"] == 1 and report["sections"][0]["open"] == 0.0
and stood(dish, ribs) < STOOD and float(from_axis.min()) > 1.0 and float(from_axis.max()) > 1.0 + STANDOFF + DEPTH - 1e-6, [receipt["message"], report, from_axis.min(), from_axis.max(), R["readings"]])
for polygon in list(dish.data.polygons)[:4]:
polygon.flip()
dish.data.update()
bpy.context.view_layer.update()
refused("a cage with a flipped region, naming the plane", {"object_name": "Dish", "ribs_name": "Flipped", "planes": json.dumps([{"origin": [0.0, 0.0, 0.0], "normal": [0.0, 1.0, 0.0]}]), **SIZES},
"planes[0]: the normals of 'Dish' change sides along the section")
# --- longerons-through-ribs: two legs in one cage, so every plane cuts two chains --------------------------------------------
section("longerons-through-ribs")
leg_points = [(side * 0.6 + 0.3 * math.cos(2 * math.pi * k / 16), 0.3 * math.sin(2 * math.pi * k / 16), z) for side in (-1, 1) for z in (0.0, 1.0) for k in range(16)]
legs = mesh_object("Legs", leg_points, [(s * 32 + k, s * 32 + (k + 1) % 16, s * 32 + 16 + (k + 1) % 16, s * 32 + 16 + k) for s in (0, 1) for k in range(16)], wall=0.04)
TOWARD = [math.cos(math.pi / 16), math.sin(math.pi / 16), 0.0] # through the middle of a facet
BEAMS = [{"origin": [0.6, 0.0, 0.0], "axis": [0.0, 0.0, 1.0], "toward": TOWARD}, {"origin": [-0.6, 0.0, 0.0], "axis": [0.0, 0.0, 1.0], "toward": [-TOWARD[0], TOWARD[1], 0.0]}]
LEVELS = (0.2, 0.5, 0.8)
receipt, report = send("brokkr_kitbash.ribs", object_name="Legs", ribs_name="LegRibs", planes=flat(LEVELS), **SIZES, longerons=json.dumps(BEAMS), longeron="T", longeron_w=0.05, longeron_h=0.05, longeron_t=0.008)
ribs = bpy.data.objects.get("LegRibs")
middle = 0.3 * math.cos(math.pi / 16) - (0.04 + STANDOFF + DEPTH / 2) # the rib's mid-depth line where the half-plane crosses it, from the leg's axis
for row in (report or {}).get("longerons", []):
beam = BEAMS[row["index"]]
for station, level in zip(row["stations"], LEVELS):
from_line = np.array(station) - beam["origin"]
across = np.cross([0.0, 0.0, 1.0], beam["toward"])
reading("stationed", max(abs(from_line @ across), abs(station[2] - level), abs(math.hypot(from_line[0], from_line[1]) - middle), 0.0 if from_line @ np.array(beam["toward"]) > 0 else 1.0))
shape = measure(ribs.data) if ribs is not None else {}
check("longerons-through-ribs: a cage every plane cuts into two chains gets a longeron through each leg's ribs: every station on its half-plane, at its plane's height, on the rib's mid-depth line",
receipt["status"] == "accepted" and [s["chains"] for s in report["sections"]] == [2, 2, 2] and report["ribs"] == 6 and [(r["index"], len(r["stations"])) for r in report["longerons"]] == [(0, 3), (1, 3)]
and R["readings"].get("stationed", 1.0) < STATIONED and (shape["shells"], shape["nonManifoldEdges"]) == (8, 0)
and abs(float(points(ribs)[:, 2].max()) - (0.8 + 0.3 * 0.12)) < 1e-6 and abs(float(points(ribs)[:, 2].min()) - (0.2 - 0.3 * 0.12)) < 1e-6, [receipt["message"], report, R["readings"]])
LEG = {"object_name": "Legs", "ribs_name": "Bad", "planes": flat(LEVELS), **SIZES}
refused("a longeron whose half-plane meets no rib", {**LEG, "longerons": json.dumps([{"origin": [0.0, 0.0, 0.0], "axis": [0.0, 0.0, 1.0], "toward": [0.0, 1.0, 0.0]}])},
"longerons[0] does not meet the ribs of planes[0]")
refused("a longeron whose half-plane meets two ribs", {**LEG, "longerons": json.dumps([{"origin": [0.0, 0.0, 0.0], "axis": [0.0, 0.0, 1.0], "toward": [1.0, 0.0, 0.0]}])},
"longerons[0] meets the ribs of planes[0] 2 times")
refused("a longeron with one plane", {**LEG, "planes": flat([0.5]), "longerons": json.dumps(BEAMS[:1])}, "A longeron runs through the ribs of two or more planes")
refused("a longeron whose wall leaves no section", {**LEG, "longerons": json.dumps(BEAMS[:1]), "longeron": "I", "longeron_t": 0.03}, "profile 'I' of width")
refused("a longeron through the pod's port", {"object_name": "Pod", "ribs_name": "Bad", "planes": flat(HEIGHTS), **SIZES,
"longerons": json.dumps([{"origin": [0.0, 0.0, 0.0], "axis": [0.0, 0.0, 1.0], "toward": [1.0, 0.0, 0.0]}])},
"longerons[0] crosses planes[2] where the plate is open and there is no rib")
receipt, report = send("brokkr_kitbash.ribs", object_name="Pod", ribs_name="Frame", planes=flat(HEIGHTS), **SIZES, posts=0.27, holes=0.11,
longerons=json.dumps([{"origin": [0.0, 0.0, 0.0], "axis": [0.0, 0.0, 1.0], "toward": [math.cos(a), math.sin(a), 0.0]} for a in (0.8, 2.4, 3.9, 5.5)]))
check("the pod takes ribs, holes, posts and four longerons clear of its port in one call", receipt["status"] == "accepted" and child_of(bpy.data.objects.get("Frame"), pod)
and (report["ribs"], len(report["longerons"]), report["nonManifoldEdges"]) == (5, 4, 0) and report["posts"] > 40 and report["holes"] > 80
and all(len(r["stations"]) == 5 for r in report["longerons"]), [receipt["message"], report])
# --- posts-under-the-plate ----------------------------------------------------------------------------------------------------------
section("posts-under-the-plate")
receipt, report = send("brokkr_kitbash.ribs", object_name="Cone60", ribs_name="ConePosts", planes=flat([0.5]), **SIZES, posts=0.2)
thin = frustum("Thin", 60, (24.0, 9.0, 0.0))
thin.modifiers["Solidify"].thickness = 0.02 # thinner than a post's end leans out of its middle, twice over
bpy.context.view_layer.update()
_, leaning = send("brokkr_kitbash.ribs", object_name="Thin", ribs_name="ThinPosts", planes=flat([0.5]), **SIZES, posts=0.2)
depths = [under(cage, bpy.data.objects[name]) for cage, name in ((deck, "DeckRibs"), (creased, "CreaseFrame"), (angle, "AngleRibs"), (pod, "Frame"), (bpy.data.objects["Cone60"], "ConePosts"), (thin, "ThinPosts"))]
check("posts-under-the-plate: a post starts inside the plate, half its thickness under the outer face where it stands square and deeper where it leans, and no vertex of a frame stands outside the outer face: "
"a flat deck, a crease, a right angle, the pod, a cone leaning 60 degrees, the same cone with a wall of 0.02 (and the spheres above)", receipt["status"] == "accepted" and report["posts"] > 10 and leaning is not None and leaning["posts"] > 10 and min(depths) > SUNK
and abs(depths[0] - 0.025) < 1e-6, [receipt["message"], depths, R["readings"]])
# --- holes-manifold: an egg-crate of five ribs that cross ---------------------------------------------------------------------
section("holes-manifold")
crate = mesh_object("Crate", [(-0.5, -0.5, 0.0), (0.5, -0.5, 0.0), (0.5, 0.5, 0.0), (-0.5, 0.5, 0.0)], [(0, 1, 2, 3)], Matrix.Translation((0.0, -5.0, 0.0)), wall=0.05)
GRID = json.dumps([{"origin": [x, 0.0, 0.0], "normal": [1.0, 0.0, 0.0]} for x in (-0.3, 0.0, 0.3)] + [{"origin": [0.0, y, 0.0], "normal": [0.0, 1.0, 0.0]} for y in (-0.3, 0.3)])
_, solid = send("brokkr_kitbash.ribs", object_name="Crate", ribs_name="CrateSolid", planes=GRID, **SIZES)
receipt, report = send("brokkr_kitbash.ribs", object_name="Crate", ribs_name="CrateHoled", planes=GRID, **SIZES, holes=0.09)
holed = bpy.data.objects.get("CrateHoled")
one = 0.5 * 16 * (0.3 * DEPTH) ** 2 * math.sin(2 * math.pi / 16) * THICKNESS
removed = (measure(bpy.data.objects["CrateSolid"].data)["volume"] - measure(holed.data)["volume"]) if holed is not None and solid else 0.0
shape = measure(holed.data) if holed is not None else {}
reading("holed", abs(removed / (55 * one) - 1.0))
check("holes-manifold: five ribs that cross each get their eleven holes, cut a plane at a time: closed shells, and the volume gone is the holes' own",
receipt["status"] == "accepted" and (report["ribs"], report["holes"], report["nonManifoldEdges"]) == (5, 55, 0) and (shape["shells"], shape["nonManifoldEdges"]) == (5, 0)
and R["readings"]["holed"] < HOLED and abs(solid["volume"] - 5 * DEPTH * THICKNESS) < 1e-7
and sorted(o.name for o in bpy.data.objects if o.name.startswith("Crate")) == ["Crate", "CrateHoled", "CrateSolid"], [receipt["message"], report, removed, 55 * one])
refused("holes that overlap", {"object_name": "Crate", "ribs_name": "Bad", "planes": GRID, **SIZES, "holes": 0.02}, "planes[0]: the lightening holes did not cut cleanly")
# --- ribs-refusals --------------------------------------------------------------------------------------------------------------
section("ribs-refusals")
POD = {"object_name": "Pod", "ribs_name": "New", "planes": flat(HEIGHTS), **SIZES}
refused("a name an object has", {**POD, "ribs_name": "Fit"}, "ribs_name 'Fit' must be 1 to 63 characters and no object's name")
refused("a plane that misses the cage", {**POD, "planes": flat([0.5, 9.0])}, "planes[1] misses 'Pod'")
refused("65 planes", {**POD, "planes": flat([0.3 + 0.01 * k for k in range(65)])}, "planes must be a JSON array of 1 to 64 objects")
refused("no plane", {**POD, "planes": "[]"}, "planes must be a JSON array of 1 to 64 objects")
refused("planes that are not JSON", {**POD, "planes": "[{"}, "planes is not JSON")
refused("a plane with no normal", {**POD, "planes": json.dumps([{"origin": [0.0, 0.0, 0.5]}])}, "planes[0] must be an object of origin and normal, each three numbers")
refused("a plane whose normal has no length", {**POD, "planes": json.dumps([{"origin": [0.0, 0.0, 0.5], "normal": [0.0, 0.0, 0.0]}])}, "planes[0].normal has no direction")
refused("17 longerons", {**POD, "longerons": json.dumps([BEAMS[0]] * 17)}, "longerons must be a JSON array of 0 to 16 objects")
refused("ribs deeper than the pod is wide", {**POD, "planes": flat([0.5, 1.5]), "standoff": 0.15, "depth": 0.3}, "the section leaves a rib no room: it turns or closes in tighter than the rib reaches: lower standoff or depth")
precise = json.dumps([{"origin": [0.012345678901234567, -0.012345678901234567, 0.3 + 0.012345678901234567 * k], "normal": [1.2345678901234567e-05, -1.2345678901234567e-05, 0.99999999987654321]} for k in range(64)])
receipt, report = send("brokkr_kitbash.ribs", **{**POD, "ribs_name": "Sixtyfour", "planes": precise})
check("planes-string-cap-below-64: 64 planes written at full precision, over 9000 characters, are taken", len(precise) > 9000 and receipt["status"] == "accepted" and len(report["sections"]) == 64,
[len(precise), receipt["message"]])
refused("a cage that is not a mesh", {**POD, "object_name": "Nothing"}, "No mesh object named 'Nothing'")
refused("a section too long for its step", {**POD, "planes": flat([0.3 + 0.01 * k for k in range(64)]), "step": 0.002}, "The sections are over 20000 points at step 0.002")
pod.scale = (1.0, 1.0, 1.01)
bpy.context.view_layer.update()
refused("a scaled cage", POD, "'Pod' is scaled, mirrored or sheared in the world")
pod.scale = (1.0, 1.0, 1.0)
crate.hide_viewport = True # nothing depends on the crate's cage but its ribs, and children do not hold a parent out of the depsgraph... they do: so they go first
for name in ("CrateSolid", "CrateHoled"):
bpy.data.objects[name].parent = None
bpy.context.view_layer.update()
refused("a cage Blender does not evaluate", {"object_name": "Crate", "ribs_name": "New", "planes": GRID, **SIZES}, "Blender does not evaluate 'Crate' in this view layer")
crate.hide_viewport = False
extra = crate.modifiers.new("Second", "SOLIDIFY")
bpy.context.view_layer.update()
refused("a cage with two Solidifies", {"object_name": "Crate", "ribs_name": "New", "planes": GRID, **SIZES}, "'Crate' has 2 Solidify modifiers (Solidify, Second)")
crate.modifiers.remove(extra)
check("every refusal left the cages' modifiers shown", all(m.show_viewport for o in (pod, deck, legs, crate, dish, hip, creased, angle, sunk, narrow) for m in o.modifiers), None)
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())}
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)
sys.exit(0 if R["ok"] else 1)

View file

@ -0,0 +1,266 @@
{
"blender": "5.3.0",
"checks": [
{
"name": "the pod is cut by a port, a panel break and a recess",
"ok": true,
"detail": null
},
{
"name": "ribs makes one mesh object under the cage: a child under identity matrices, no modifier, no material, and kit_ribs the request",
"ok": true,
"detail": null
},
{
"name": "ribs reports the frame: one rib a plane, the plate's thickness read from the Solidify, the port's plane open along it, closed shells",
"ok": true,
"detail": null
},
{
"name": "ribs-fit-the-plate: at every point of a rib's outer edge the nearer vertex stands the standoff behind the plate's inner face, along the plate's normal; every vertex in its plane, on the side the normals face away from",
"ok": true,
"detail": null
},
{
"name": "standoff-oblique-sections: on cones whose wall leans 0, 30, 45 and 60 degrees out of the rib's plane the rib comes the standoff from the plate's inner face and no nearer, and is the ring between the section's offsets",
"ok": true,
"detail": null
},
{
"name": "where walls that lean 45 and 20 degrees meet, the rib stands the standoff off each wall right into the corner: its edges are each wall's own, met in a mitre (mutant V1 runs one wall's edge into the other's standoff)",
"ok": true,
"detail": null
},
{
"name": "negative-solidify-thickness: a wall of -0.06 grows outward, and the rib stands the standoff inside the designed surface, the plate's inner face",
"ok": true,
"detail": null
},
{
"name": "ribs-fold-at-crease: behind a crease of 49.4 degrees either side of a facet of 0.062 a rib of standoff 0.03 and depth 0.08 is made, clipped: one closed shell the area of the true offset, no vertex nearer the section than the rib starts or further than it reaches",
"ok": true,
"detail": null
},
{
"name": "a post behind the crease's facet that would end outside a shallow rib, short of where the rib's edges meet, is left out: ten of the thirteen stations (mutant P1 posts eleven)",
"ok": true,
"detail": null
},
{
"name": "the creased rib takes holes along its clipped centre line, cut clean, and posts",
"ok": true,
"detail": null
},
{
"name": "inside a right angle no post stands nearer the corner than the rib's outer edge is set back, 0.09: twelve of the sixteen stations (mutant P1 posts all sixteen, four through the other wall)",
"ok": true,
"detail": null
},
{
"name": "a plane tilted 64 degrees through a prism of 24 flat sides: every facet leans differently out of the plane, and the rib stands the standoff off each (the finding: 0.007 short)",
"ok": true,
"detail": null
},
{
"name": "spheres of radius 1 and 0.6 cut 60 degrees off the middle, standoffs 0.04 and 0.01: a wall curved both ways, leaning 60 degrees, and the rib and its posts stand the standoff off it (the finding: 0.020 short, and at radius 0.6 and standoff 0.01 through the inner face)",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: at radius 0.6 a standoff of 0.04 has no rib in that plane: 0.1 inside the wall the sphere is 0.5, and the plane passes 0.52 from its middle",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a standoff greater than the plate's inner radius: the offset surface has passed through itself everywhere",
"ok": true,
"detail": null
},
{
"name": "solidify-default-unbounded: a box whose Solidify is not even is 0.0424 thick, not its 0.06, and the rib stands the standoff off the inner face it has (read as 0.06: 0.0176 over)",
"ok": true,
"detail": null
},
{
"name": "a cage subdivided after its Solidify is taken as that thick behind every face: a rib, clear of the plate",
"ok": true,
"detail": null
},
{
"name": "a recess 0.8 of the plate deep is plate: the rib runs on under it (the ray looks 1.25 of the plate deep; mutant N5 looks 0.5)",
"ok": true,
"detail": null
},
{
"name": "a port in a narrow cage is open though the far wall stands 3.5 plates behind it: the rib stops either side (mutant N13 looks 5 plates deep and finds the far wall)",
"ok": true,
"detail": null
},
{
"name": "ribs-stop-at-ports: no rib, post or hole stands within the clearance of the port; behind the panel break the rib is one piece; under the recess it runs on",
"ok": true,
"detail": null
},
{
"name": "with no bridge the panel break splits both ribs",
"ok": true,
"detail": null
},
{
"name": "ribs-from-normals: a dish whose normals face its hollow side gets its rib on the other, the round side, though its section's middle lies in the hollow; a cage with no Solidify has a plate of no thickness",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a cage with a flipped region, naming the plane",
"ok": true,
"detail": null
},
{
"name": "longerons-through-ribs: a cage every plane cuts into two chains gets a longeron through each leg's ribs: every station on its half-plane, at its plane's height, on the rib's mid-depth line",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a longeron whose half-plane meets no rib",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a longeron whose half-plane meets two ribs",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a longeron with one plane",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a longeron whose wall leaves no section",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a longeron through the pod's port",
"ok": true,
"detail": null
},
{
"name": "the pod takes ribs, holes, posts and four longerons clear of its port in one call",
"ok": true,
"detail": null
},
{
"name": "posts-under-the-plate: a post starts inside the plate, half its thickness under the outer face where it stands square and deeper where it leans, and no vertex of a frame stands outside the outer face: a flat deck, a crease, a right angle, the pod, a cone leaning 60 degrees, the same cone with a wall of 0.02 (and the spheres above)",
"ok": true,
"detail": null
},
{
"name": "holes-manifold: five ribs that cross each get their eleven holes, cut a plane at a time: closed shells, and the volume gone is the holes' own",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: holes that overlap",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a name an object has",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a plane that misses the cage",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: 65 planes",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: no plane",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: planes that are not JSON",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a plane with no normal",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a plane whose normal has no length",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: 17 longerons",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: ribs deeper than the pod is wide",
"ok": true,
"detail": null
},
{
"name": "planes-string-cap-below-64: 64 planes written at full precision, over 9000 characters, are taken",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a cage that is not a mesh",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a section too long for its step",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a scaled cage",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a cage Blender does not evaluate",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a cage with two Solidifies",
"ok": true,
"detail": null
},
{
"name": "every refusal left the cages' modifiers shown",
"ok": true,
"detail": null
}
],
"hostErrors": [],
"readings": {
"cleared": 0.031,
"creased": 2.3e-07,
"fit": 7.5e-05,
"holed": 5.5e-08,
"planar": 1.4e-07,
"ring": 2.1e-06,
"round": 9.7e-08,
"stationed": 5.2e-07,
"stood": 6.4e-08,
"sunk": 0.0047,
"tilted": 2.1e-05,
"uneven": 8.3e-09
},
"ok": true
}

View file

@ -1,8 +1,8 @@
"""Live proof, in a background Blender, of brokkr_kitbash shell cuts through run_intent: cut on a mesh that is not a kit
part (a subdivided, solidified cage), the one Boolean modifier per operation and its collection, a cast at the surface
without its cuts, machinery on a cutter's floor socket and what moves when the cutter moves or is resized, boolean on
any mesh, the refusals, cut_many, a cutter's axis, a slot's three floors, an object in no collection, and the order of a set_params report's closures. Not part of the
unittest run: it needs Blender.
any mesh, the refusals, cut_many, a cutter's axis, a slot's three floors, an object in no collection or one Blender does not evaluate, a receipt's rows trimmed
to fit, and the order of a set_params report's closures. Not part of the unittest run: it needs Blender.
blender --background --factory-startup --python-exit-code 1 --python surfaces/blender/tests/live/kitbash_shell.py -- <out>
@ -11,6 +11,9 @@ without them). <out> is an absolute path; writes <out>.result.json and exits 1 w
Bounds follow lodur:ruling:deterministic-bound-margin: each sits at the geometric mean of the shipped worst reading
and the least claimed mutant's, both written beside it; the result file carries the readings.
The checks run inside one try: an uncaught error is a failed check that names the section it happened in, and the
result file is written and the checks printed whatever happened.
"""
import importlib.util
import json
@ -18,6 +21,7 @@ import math
import os
import sys
import tempfile
import traceback
import types
from pathlib import Path
@ -160,123 +164,15 @@ def stack(obj):
return [m.name for m in obj.modifiers]
# --- a cage: not a kit part. A closed loft of 6 rings of 8, subdivided and given a wall ----------------------------------
bm = bmesh.new()
rings = [[bm.verts.new((r * math.cos(math.pi / 8 + k * math.pi / 4), r * math.sin(math.pi / 8 + k * math.pi / 4), z)) for k in range(8)]
for z, r in ((-1.0, 0.5), (-0.6, 0.7), (-0.2, 0.8), (0.2, 0.8), (0.6, 0.7), (1.0, 0.5))]
for low, high in zip(rings, rings[1:]):
for k in range(8):
bm.faces.new((low[k], low[(k + 1) % 8], high[(k + 1) % 8], high[k]))
bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:])
mesh = bpy.data.meshes.new("Cage")
bm.to_mesh(mesh)
bm.free()
cage = bpy.data.objects.new("Cage", mesh)
bpy.context.scene.collection.objects.link(cage)
cage.modifiers.new("Subsurf", "SUBSURF").levels = 2
wall = cage.modifiers.new("Solidify", "SOLIDIFY")
wall.thickness, wall.offset, wall.use_even_offset = 0.05, -1.0, True
cage.matrix_world = Matrix.Translation((4.0, -1.0, 2.0)) @ Matrix.Rotation(0.6, 4, "Z") @ Matrix.Rotation(-0.3, 4, "X")
bpy.context.view_layer.update()
world = np.array(cage.matrix_world, dtype=np.float64)
uncut, _ = evaluated(cage)
check("the cage is a closed wall before it is cut", uncut["nonManifoldEdges"] == 0 and 0.15 < uncut["volume"] < 0.4 and "kit_part" not in cage, uncut)
R["cage"] = {"uncut": uncut}
SECTION = ["setup"]
# --- cut-at-ray: a through bay, a blind round recess, a row of gills and a panel break --------------------------------------
CUTS = [("Bay", "box", (3.0, 0.0, 0.1), (-1.0, 0.0, 0.0), "width=0.3; height=0.3; depth=0.2", {}),
("Recess", "cyl", (-3.0, 0.1, 0.2), (2.0, 0.0, 0.0), "r=0.1; depth=0.02", {}),
("Gills", "slot", (0.1, 3.0, -0.2), (0.0, -1.0, 0.0), "width=0.3; height=0.04; count=4; pitch=0.08; depth=0.02", {}),
("Break", "slab", (0.0, -3.0, 0.3), (0.0, 1.0, 0.0), "length=0.6; depth=0.1", {"roll": 90.0})]
frames, volume, falls, reports = {}, uncut["volume"], [], {}
for name, part, origin, direction, params, more in CUTS:
hit, normal = cast(cage, origin, direction) # before this cutter exists; the cuts made so far are far from this ray
frames[name] = core.surface_frame(hit, normal, (0.0, 0.0, 1.0), more.get("roll", 0.0))
state = sorted(o.name for o in bpy.data.objects)
receipt, report = cut(name, part, origin, direction, params, **more)
reports[name] = report
cutter = bpy.data.objects.get(name)
ok = receipt["status"] == "accepted" and cutter is not None and sorted(o.name for o in bpy.data.objects) == sorted(state + [name])
ok = ok and cutter.parent == cage and np.array_equal(np.array(cutter.matrix_parent_inverse), np.eye(4))
ok = ok and reading("framed", np.abs(np.array(cutter.matrix_basis) - frames[name]).max()) < FRAMED
ok = ok and (cutter["kit_kit"], cutter["kit_part"]) == ("cutters", part) and bpy.context.scene.collection in cutter.users_collection
ok = ok and not cutter.hide_render and not cutter.hide_viewport and len(cutter.modifiers) == 0
check(f"cut places the {part} cutter {name} on the cage where the ray meets it: parented under an identity inverse, its basis the surface frame",
ok, [receipt["message"], cutter and np.array(cutter.matrix_basis).tolist(), frames[name].tolist()])
wanted = world @ frames[name]
check(f"cut reports {name} as a cutters part with its sockets in the world, and what cuts the cage, without evaluating it", report
and report["object"] == "Cage" and report["cutter"]["object"] == name and report["cutter"]["kit"] == "cutters" and "evaluated" not in report
and report["booleans"] == [{"cutter": n, "operation": "DIFFERENCE"} for n in [c[0] for c in CUTS][:len(frames)]]
and [s["name"] for s in report["cutter"]["sockets"]] == {"slab": [], "slot": ["floor", "floor_l", "floor_r"]}.get(part, ["floor"])
and (part == "slab" or np.abs(np.array(report["cutter"]["sockets"][0]["matrix"]) - wanted @ core.build(kits["cutters"]["parts"][part], report["cutter"]["params"]).sockets[0]["matrix"]).max() < 1e-4),
report)
shown, _ = evaluated(cage)
falls.append(shown["volume"] < volume - 1e-4 and shown["nonManifoldEdges"] == 0)
volume = shown["volume"]
R["cage"][name] = shown
modifier = cage.modifiers.get("Kit Difference")
check("four cuts give the cage one Boolean modifier after its own, over one collection of the four cutters in the order they came",
stack(cage) == ["Subsurf", "Solidify", "Kit Difference"] and modifier is not None
and (modifier.type, modifier.solver, modifier.use_self, modifier.operation, modifier.operand_type, modifier.material_mode) == ("BOOLEAN", "EXACT", True, "DIFFERENCE", "COLLECTION", "TRANSFER")
and [o.name for o in modifier.collection.objects] == [c[0] for c in CUTS] and modifier.collection.name == "Cage difference"
and not any(modifier.collection in s.collection.children_recursive for s in bpy.data.scenes), [stack(cage), modifier and modifier.operand_type])
check("the evaluated cage stays a closed wall and loses volume with each cut", all(falls) and len(falls) == 4, R["cage"])
receipt, report = send("brokkr_kitbash.report", object_name="")
check("report lists the cutters as kit parts and not the cage", report and [p["object"] for p in report["parts"]] == sorted(c[0] for c in CUTS)
and all(p["connection"] is None and p["baked"] is False for p in report["parts"]), report and [p["object"] for p in report["parts"]])
# --- cut-casts-the-uncut-surface --------------------------------------------------------------------------------------------
through = cast(cage, CUTS[0][2], CUTS[0][3])[0] # as the cage is evaluated now, with its cuts: through the bay to the far wall
receipt, report = cut("Bay2", "cyl", CUTS[0][2], CUTS[0][3], "r=0.05; depth=0.2")
again = bpy.data.objects.get("Bay2")
check("a second cut on the through bay's ray lands where the first did, on the surface as it was before any cut, though the ray now passes through the bay",
receipt["status"] == "accepted" and again is not None and np.linalg.norm(through - frames["Bay"][:3, 3]) > 1.0
and reading("recast", np.abs(np.array(again.matrix_basis)[:3, 3] - frames["Bay"][:3, 3]).max()) < RECAST
and stack(cage) == ["Subsurf", "Solidify", "Kit Difference"] and all(m.show_viewport for m in cage.modifiers),
[receipt["message"], through.tolist(), frames["Bay"][:3, 3].tolist(), again and list(again.matrix_basis.translation)])
def section(name):
SECTION[0] = name
# --- floor-carries-machinery ------------------------------------------------------------------------------------------------
recess = bpy.data.objects["Recess"]
vent = place("Vent", "vent", "width=0.2; height=0.15") # back size 0.135; the floor's is 0.2
receipt, report = send("brokkr_kitbash.attach", object_name="Vent", socket="back", parent_name="Recess", parent_socket="floor", roll=30.0)
floor = world @ frames["Recess"] @ np.array(Matrix.Translation((0.0, 0.0, -0.02))) # the hit point, depth along the normal
back = frame(vent, "back")
check("a mechanical vent attaches to the round recess's floor: its back on the hit point taken depth down the normal, facing in, and the connection holds",
receipt["status"] == "accepted" and held(report) and vent.parent == recess and report["connection"]["parent"] == "Recess" and report["kit"] == "mechanical"
and reading("floored", max(np.abs(back[:3, 3] - floor[:3, 3]).max(), np.abs(back[:3, 2] + floor[:3, 2]).max())) < FLOORED,
[receipt["message"], back.tolist(), floor.tolist()])
big = place("Big", "vent", "width=0.8; height=0.6")
refused("a vent larger than the recess's floor", "brokkr_kitbash.attach", {"object_name": "Big", "socket": "back", "parent_name": "Recess", "parent_socket": "floor"},
"'Big' on 'Recess': socket 'back' (mount, size 0.54) and parent socket 'floor' (mount, size 0.2) are mount sockets, where the child fits the parent: it is larger")
nozzle = place("Nozzle", "nozzle")
refused("a flange on a floor", "brokkr_kitbash.attach", {"object_name": "Nozzle", "socket": "mount", "parent_name": "Recess", "parent_socket": "floor"}, "are of different types")
refused("a second part on the floor", "brokkr_kitbash.attach", {"object_name": "Nozzle", "socket": "mount", "parent_name": "Recess", "parent_socket": "floor"}, "'Nozzle' on 'Recess'")
refused("a part on a slab, which has no floor", "brokkr_kitbash.attach", {"object_name": "Big", "socket": "back", "parent_name": "Break", "parent_socket": "floor"},
"kit 'cutters' part 'slab' has no socket 'floor'; its sockets: none")
refused("detach of a cutter, which is placed and not attached", "brokkr_kitbash.detach", {"object_name": "Recess"}, "'Recess' is not attached")
before = evaluated(cage)[0]
moved_to = np.array(recess.matrix_basis)[:3, 3] + np.array(recess.matrix_basis)[:3, :3] @ [0.0, 0.25, 0.0] # along the cutter's own y: up the wall
was = frame(vent, "back")
send("setObjectTransform", targetObjectName="Recess", location=moved_to.tolist())
shift = frame(vent, "back")[:3, 3] - was[:3, 3]
after = evaluated(cage)[0]
check("setObjectTransform on the cutter moves the cut and the vent on its floor together: the vent still holds, and the cage is cut elsewhere",
reading("floored", np.abs(shift - world[:3, :3] @ (moved_to - frames["Recess"][:3, 3])).max()) < FLOORED and abs(np.linalg.norm(shift) - 0.25) < 1e-4
and (connection := send("brokkr_kitbash.report", object_name="Vent")[1]["parts"][0]["connection"])["holds"] is True
and after["nonManifoldEdges"] == 0 and after != before, [shift.tolist(), before, after])
was = frame(vent, "back")
receipt, report = send("brokkr_kitbash.set_params", object_name="Recess", params="depth=0.04")
sunk = frame(vent, "back")[:3, 3] - was[:3, 3]
deeper = evaluated(cage)[0]
check("set_params depth=0.04 on the cutter deepens the cut and seats the vent on the new floor, 0.02 further down the normal",
receipt["status"] == "accepted" and report["params"]["depth"] == 0.04 and reading("floored", np.abs(sunk + was[:3, 2] * -0.02).max()) < FLOORED
and send("brokkr_kitbash.report", object_name="Vent")[1]["parts"][0]["connection"]["holds"] is True
and deeper["volume"] < after["volume"] - 1e-5 and deeper["nonManifoldEdges"] == 0 and stack(cage) == ["Subsurf", "Solidify", "Kit Difference"],
[receipt["message"], sunk.tolist(), after, deeper])
R["cage"]["deeper"] = deeper
# --- cut_many: several cutters for one evaluation, all or none; an axis; a slot's three floors -----------------------------------
def uncut_cast(origin, direction):
"""cast at the cage with its Kit Booleans off: the surface as designed."""
shown = [m for m in cage.modifiers if m.name.startswith("Kit ")]
for m in shown:
m.show_viewport = False
@ -287,151 +183,358 @@ def uncut_cast(origin, direction):
m.show_viewport = True
MANY = [{"name": "Visor", "part": "slot", "params": "width=0.6; height=0.14; depth=0.02; lift=0.2", "origin": [0.6, 3.0, 0.5], "direction": [0.0, -1.0, 0.0]},
{"name": "Seam", "part": "slab", "params": "length=0.4; depth=0.1", "origin": [-0.5, -3.0, -0.7], "direction": [0.0, 1.0, 0.0], "up": [1.0, 0.0, 0.0], "axis": [0.0, -1.0, 0.0]},
{"name": "Port", "part": "cyl", "params": "r=0.05", "origin": [-0.6, 3.0, -0.5], "direction": [0.0, -2.0, 0.0], "up": [1.0, 0.0, 0.0], "roll": 45.0}]
wanted = {}
for spec in MANY:
hit, normal = uncut_cast(spec["origin"], spec["direction"])
wanted[spec["name"]] = core.surface_frame(hit, spec.get("axis", normal), spec.get("up", (0.0, 0.0, 1.0)), spec.get("roll", 0.0))
if "axis" in spec:
lean = float(np.degrees(np.arccos(np.clip(normal @ np.array(spec["axis"]), -1.0, 1.0))))
refused("cut_many whose second ray misses places none", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([MANY[0], {**MANY[1], "origin": [0.0, -3.0, 5.0]}])},
"The ray from (0.0, -3.0, 5.0) along (0.0, 1.0, 0.0) misses 'Cage'")
refused("cut_many with a name twice", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([MANY[0], {**MANY[1], "name": "Visor"}])}, "An object named 'Visor' exists in this call")
refused("cut_many with a name an object has", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([MANY[0], {**MANY[1], "name": "Bay"}])}, "An object named 'Bay' exists;")
refused("cut_many whose last cutter has a bad param", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps(MANY[:2] + [{**MANY[2], "params": "r=9"}])}, "param 'r' = 9.0 is outside")
refused("cut_many of text that is not JSON", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": "[{"}, "cuts is not JSON")
refused("cut_many of no cutters", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": "[]"}, "cuts must be a JSON array of 1 to 64 cutters")
refused("cut_many of a cutter with no direction", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{k: v for k, v in MANY[0].items() if k != "direction"}])},
"cuts[0] must be an object with name, part, origin and direction")
refused("cut_many of a cutter with a key cut does not have", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{**MANY[0], "operation": "UNION"}])}, "cuts[0] must be an object")
refused("cut_many of an origin of two numbers", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{**MANY[0], "origin": [0.0, 1.0]}])}, "cuts[0].origin must be three numbers")
refused("cut_many of a roll of 400", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{**MANY[0], "roll": 400}])}, "cuts[0].roll must be a number from -360 to 360")
refused("an axis that points into the surface", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{**MANY[1], "axis": [0.0, 1.0, 0.0]}])}, "'Seam': the axis (0.0, 1.0, 0.0) points into the surface")
addon = sys.modules["brokkr_kitbash"]
limit = addon.REPORT_LIMIT
addon.REPORT_LIMIT = 300
refused("cut_many whose report would not fit a receipt places none", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps(MANY)}, "over the 300 a receipt carries: cut fewer at once")
addon.REPORT_LIMIT = limit
receipt, report = send("brokkr_kitbash.cut_many", object_name="Cage", cuts=json.dumps(MANY))
placed = [bpy.data.objects.get(spec["name"]) for spec in MANY]
check("cut_many places three cutters in one action, each as cut would: parented under an identity inverse, its basis the surface frame at its own ray on the uncut cage, in the difference collection in order",
receipt["status"] == "accepted" and all(placed) and report == {"object": "Cage", "cutters": ["Visor", "Seam", "Port"], "booleans": report["booleans"]}
and [row["cutter"] for row in report["booleans"]] == ["Bay", "Recess", "Gills", "Break", "Bay2", "Visor", "Seam", "Port"]
and all(c.parent == cage and np.array_equal(np.array(c.matrix_parent_inverse), np.eye(4))
and reading("framed", np.abs(np.array(c.matrix_basis) - wanted[c.name]).max()) < FRAMED for c in placed)
and stack(cage) == ["Subsurf", "Solidify", "Kit Difference"] and all(m.show_viewport for m in cage.modifiers) and evaluated(cage)[0]["nonManifoldEdges"] == 0,
[receipt["message"], report])
seam = bpy.data.objects["Seam"]
check("a slab with an axis stands on the axis, not on the wall's normal, which leans from it there", lean > 5.0
and reading("framed", np.abs(np.array(seam.matrix_basis)[:3, 2] - [0.0, -1.0, 0.0]).max()) < FRAMED, [lean, np.array(seam.matrix_basis).tolist()])
receipt, report = send("brokkr_kitbash.cut", object_name="Cage", cutter_name="Seam2", part="slab", params="length=0.3; depth=0.1", origin_x=0.5, origin_y=-3.0, origin_z=-0.7,
direction_x=0.0, direction_y=1.0, direction_z=0.0, up_x=1.0, up_y=0.0, up_z=0.0, axis_x=0.0, axis_y=-1.0, axis_z=0.0)
check("cut takes the same axis", receipt["status"] == "accepted" and reading("framed", np.abs(np.array(bpy.data.objects["Seam2"].matrix_basis)[:3, 2] - [0.0, -1.0, 0.0]).max()) < FRAMED, receipt["message"])
visor = bpy.data.objects["Visor"]
eyes = {}
for socket, x in (("floor", 0.0), ("floor_l", -0.2), ("floor_r", 0.2)):
eye = place(f"Eye_{socket}", "vent", "width=0.2; height=0.15") # back size 0.135; each floor's is 0.14
receipt, report = send("brokkr_kitbash.attach", object_name=eye.name, socket="back", parent_name="Visor", parent_socket=socket)
there = world @ wanted["Visor"] @ np.array(Matrix.Translation((x, 0.0, -0.02)))
eyes[socket] = receipt["status"] == "accepted" and held(report) and eye.parent == visor \
and reading("floored", max(np.abs(frame(eye, "back")[:3, 3] - there[:3, 3]).max(), np.abs(frame(eye, "back")[:3, 2] + there[:3, 2]).max())) < FLOORED
check("a slot's three floors each take a part: at the centre and a third of the width to each side, all on the slot's one floor plane", all(eyes.values()) and len(eyes) == 3, eyes)
refused("a second part on a side floor", "brokkr_kitbash.attach", {"object_name": "Nozzle", "socket": "mount", "parent_name": "Visor", "parent_socket": "floor_l"}, "'Nozzle' on 'Visor'")
refused("a fourth eye on a floor that is taken", "brokkr_kitbash.attach", {"object_name": "Big", "socket": "back", "parent_name": "Visor", "parent_socket": "floor_l"}, "'Big' on 'Visor'")
def quad(name, location):
"""A single square face, 1 m, normal +z: a surface with one side."""
made = bpy.data.objects.new(name, bpy.data.meshes.new(name))
made.data.from_pydata([(-0.5, -0.5, 0.0), (0.5, -0.5, 0.0), (0.5, 0.5, 0.0), (-0.5, 0.5, 0.0)], [], [(0, 1, 2, 3)])
bpy.context.scene.collection.objects.link(made)
made.location = location
bpy.context.view_layer.update()
return made
# --- boolean on any mesh, and the order of the three operations -----------------------------------------------------------------
lump_at = world @ [0.0, 0.0, 1.0, 1.0]
send("createObject", objectType="MESH", name="Lump", location=lump_at[:3].tolist(), size=0.2)
receipt, report = send("brokkr_kitbash.boolean", object_name="Cage", cutter="Lump", operation="UNION")
check("boolean on the cage, which is not a kit part, adds a second modifier after the difference and reports the object, what cuts it and the evaluated mesh",
receipt["status"] == "accepted" and stack(cage) == ["Subsurf", "Solidify", "Kit Difference", "Kit Union"]
and sorted(report) == ["booleans", "evaluated", "object"] and report["object"] == "Cage" and report["evaluated"] == evaluated(cage)[0]
and report["booleans"] == [{"cutter": n, "operation": "DIFFERENCE"} for n in ("Bay", "Recess", "Gills", "Break", "Bay2", "Visor", "Seam", "Port", "Seam2")] + [{"cutter": "Lump", "operation": "UNION"}]
and report["evaluated"]["volume"] > deeper["volume"], [receipt["message"], report])
refused("cut-refusals: a cutter already in the target's union collection", "brokkr_kitbash.boolean", {"object_name": "Cage", "cutter": "Lump"},
"'Lump' already cuts 'Cage' (its Kit Union modifier's collection)")
refused("a cut's own cutter given to boolean again", "brokkr_kitbash.boolean", {"object_name": "Cage", "cutter": "Bay", "operation": "INTERSECT"},
"'Bay' already cuts 'Cage' (its Kit Difference modifier's collection)")
plate = place("Plate", "plate", location=[0.0, -6.0, 0.0])
for name, size, operation in (("Boss", 0.06, "UNION"), ("Keep", 2.0, "INTERSECT"), ("Hole", 0.05, "DIFFERENCE")):
send("createObject", objectType="MESH", name=name, location=[0.0, -6.0, 0.0], size=size)
receipt, report = send("brokkr_kitbash.boolean", object_name="Plate", cutter=name, operation=operation)
check("a part cut by union, then intersect, then difference carries the three modifiers as difference, union, intersect, above its Bevel, and lists its cutters so",
receipt["status"] == "accepted" and stack(plate) == ["Kit Difference", "Kit Union", "Kit Intersect", "Kit Bevel"]
and report["booleans"] == [{"cutter": "Hole", "operation": "DIFFERENCE"}, {"cutter": "Boss", "operation": "UNION"}, {"cutter": "Keep", "operation": "INTERSECT"}]
and report["evaluated"]["nonManifoldEdges"] == 0 and report["kit"] == "mechanical", [stack(plate), report and report["booleans"]])
collections = len(bpy.data.collections)
receipt, baked = send("brokkr_kitbash.apply", object_name="Plate")
check("apply removes the three collections its modifiers held and leaves every cutter in the scene", receipt["status"] == "accepted"
and baked["cutters"] == ["Hole", "Boss", "Keep"] and len(bpy.data.collections) == collections - 3 and len(plate.modifiers) == 0
and all(name in bpy.context.scene.objects for name in ("Hole", "Boss", "Keep")), [receipt["message"], [c.name for c in bpy.data.collections]])
refused("apply on the cage, which is not a kit part", "brokkr_kitbash.apply", {"object_name": "Cage"}, "'Cage' is not a kit part")
# --- cut-refusals -----------------------------------------------------------------------------------------------------------
RAY = {"object_name": "Cage", "cutter_name": "New", "part": "box", "origin_x": 3.0, "origin_y": 0.0, "origin_z": 0.1, "direction_x": -1.0, "direction_y": 0.0, "direction_z": 0.0}
refused("a ray that misses", "brokkr_kitbash.cut", {**RAY, "origin_z": 5.0}, "The ray from (3.0, 0.0, 5.0) along (-1.0, 0.0, 0.0) misses 'Cage'")
refused("a ray of no direction", "brokkr_kitbash.cut", {**RAY, "direction_x": 0.0}, "'New': the ray's direction is zero")
refused("a cutter name an object has", "brokkr_kitbash.cut", {**RAY, "cutter_name": "Bay"}, "An object named 'Bay' exists")
refused("a param the cutter part does not have", "brokkr_kitbash.cut", {**RAY, "params": "radius=0.1"}, "kit 'cutters' part 'box' has no param 'radius'")
refused("a slot wider across than along", "brokkr_kitbash.cut", {**RAY, "part": "slot", "params": "width=0.05; height=0.1"}, "every size must be above 0")
refused("a target that is not a mesh", "brokkr_kitbash.cut", {**RAY, "object_name": "Nothing"}, "No mesh object named 'Nothing'")
block = bpy.data.objects.new("Block", bpy.data.meshes.new("Block"))
bm = bmesh.new()
bmesh.ops.create_cube(bm, size=1.0)
bm.to_mesh(block.data)
bm.free()
bpy.context.scene.collection.objects.link(block)
block.location = (0.0, -9.0, 0.0)
bpy.context.view_layer.update()
DOWN = {**RAY, "object_name": "Block", "origin_x": 0.1, "origin_y": 0.1, "origin_z": 3.0, "direction_x": 0.0, "direction_z": -1.0}
refused("an up along the hit normal", "brokkr_kitbash.cut", DOWN, "up [0.0, 0.0, 1.0] runs along the surface normal [0.0, 0.0, 1.0]")
block.scale = (1.0, 1.0, 1.01)
bpy.context.view_layer.update()
refused("a scaled target", "brokkr_kitbash.cut", {**DOWN, "up_y": 1.0, "up_z": 0.0}, "'Block' is scaled, mirrored or sheared in the world (scale 1, 1, 1.01)")
refused("boolean on a scaled target", "brokkr_kitbash.boolean", {"object_name": "Block", "cutter": "Lump"}, "'Block' is scaled, mirrored or sheared")
block.scale = (1.0, 1.0, 1.0)
bpy.context.view_layer.update()
receipt, report = send("brokkr_kitbash.cut", **{**DOWN, "cutter_name": "Pocket", "up_y": 1.0, "up_z": 0.0, "roll": 90.0})
pocket = bpy.data.objects.get("Pocket")
check("a cut on a plain cube with up +y and roll 90: the cutter's y points along -x, its floor 0.02 under the top face", receipt["status"] == "accepted" and pocket is not None
and np.abs(np.array(pocket.matrix_basis) - [[0, -1, 0, 0.1], [1, 0, 0, 0.1], [0, 0, 1, 0.5], [0, 0, 0, 1]]).max() < 1e-6
and np.abs(np.array(report["cutter"]["sockets"][0]["matrix"])[:3, 3] - [0.1, -8.9, 0.48]).max() < 1e-6 and stack(block) == ["Kit Difference"],
[receipt["message"], pocket and np.array(pocket.matrix_basis).tolist()])
try:
# --- a cage: not a kit part. A closed loft of 6 rings of 8, subdivided and given a wall ----------------------------------
section('a cage: not a kit part. A closed loft of 6 rings of 8, subdivided and given a wall')
bm = bmesh.new()
rings = [[bm.verts.new((r * math.cos(math.pi / 8 + k * math.pi / 4), r * math.sin(math.pi / 8 + k * math.pi / 4), z)) for k in range(8)]
for z, r in ((-1.0, 0.5), (-0.6, 0.7), (-0.2, 0.8), (0.2, 0.8), (0.6, 0.7), (1.0, 0.5))]
for low, high in zip(rings, rings[1:]):
for k in range(8):
bm.faces.new((low[k], low[(k + 1) % 8], high[(k + 1) % 8], high[k]))
bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:])
mesh = bpy.data.meshes.new("Cage")
bm.to_mesh(mesh)
bm.free()
cage = bpy.data.objects.new("Cage", mesh)
bpy.context.scene.collection.objects.link(cage)
cage.modifiers.new("Subsurf", "SUBSURF").levels = 2
wall = cage.modifiers.new("Solidify", "SOLIDIFY")
wall.thickness, wall.offset, wall.use_even_offset = 0.05, -1.0, True
cage.matrix_world = Matrix.Translation((4.0, -1.0, 2.0)) @ Matrix.Rotation(0.6, 4, "Z") @ Matrix.Rotation(-0.3, 4, "X")
bpy.context.view_layer.update()
world = np.array(cage.matrix_world, dtype=np.float64)
uncut, _ = evaluated(cage)
check("the cage is a closed wall before it is cut", uncut["nonManifoldEdges"] == 0 and 0.15 < uncut["volume"] < 0.4 and "kit_part" not in cage, uncut)
R["cage"] = {"uncut": uncut}
# --- cut-orphan and closures-ends-first -----------------------------------------------------------------------------------------
strut = core.build(kits["mechanical"]["parts"]["strut"], {"width": 0.09})
end = {name: next(s for s in strut.sockets if s["name"] == name) for name in ("end_a", "end_b")}
for pair, y in (("Zz", -20.0), ("Aa", -24.0)): # two closures that share no part; the open one is named to sort first
anchor, loose = place(f"{pair}_Anchor", "strut", "width=0.09", location=[0.0, y, 0.0]), place(f"{pair}_Loose", "strut", "width=0.09")
meet = Matrix((np.array(anchor.matrix_world) @ core.mate(end["end_b"], end["end_a"], 40.0)).tolist())
send("setObjectTransform", targetObjectName=f"{pair}_Loose", location=list(meet.translation), rotationEuler=list(meet.to_euler("XYZ")))
send("brokkr_kitbash.close", object_name=f"{pair}_Loose", socket="end_a", other_name=f"{pair}_Anchor", other_socket="end_b")
send("brokkr_kitbash.set_params", object_name="Aa_Anchor", params="length=0.9") # opens Aa's closure
receipt, report = send("brokkr_kitbash.set_params", object_name="Zz_Anchor", params="width=0.09")
check("closures-ends-first: set_params on a part whose own closure holds lists it before another part's closure that is open, though that one sorts first by holds and by name",
receipt["status"] == "accepted" and report["closures"] == [{"part": "Zz_Loose", "to": "Zz_Anchor", "holds": True}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": False}],
report and report.get("closures"))
ghost = bpy.data.objects["Aa_Anchor"]
with bpy.context.temp_override(selected_objects=[ghost], active_object=ghost):
bpy.ops.object.delete() # the ordinary Delete: Aa_Loose's closure still points at it, so it stays in the file, in no collection
tie = place("Tie", "strut", "width=0.09")
check("a part deleted with the Delete operator that a closure points to is still in the file", bpy.data.objects.get("Aa_Anchor") is not None and not ghost.users_collection, list(bpy.data.objects.keys()))
GONE = "'Aa_Anchor' is in no collection (a deleted object something still points to)"
refused("cut-orphan: attach onto a deleted part's name", "brokkr_kitbash.attach", {"object_name": "Tie", "socket": "end_a", "parent_name": "Aa_Anchor", "parent_socket": "end_a"}, GONE)
refused("attach of a deleted part", "brokkr_kitbash.attach", {"object_name": "Aa_Anchor", "socket": "end_a", "parent_name": "Tie", "parent_socket": "end_a"}, GONE)
refused("set_params on a deleted part", "brokkr_kitbash.set_params", {"object_name": "Aa_Anchor", "params": "length=1.0"}, GONE)
refused("report of a deleted part", "brokkr_kitbash.report", {"object_name": "Aa_Anchor"}, GONE)
refused("cut on a deleted part", "brokkr_kitbash.cut", {**RAY, "object_name": "Aa_Anchor"}, GONE)
refused("boolean on a deleted part", "brokkr_kitbash.boolean", {"object_name": "Aa_Anchor", "cutter": "Lump"}, GONE)
refused("boolean with a deleted part as the cutter", "brokkr_kitbash.boolean", {"object_name": "Tie", "cutter": "Aa_Anchor"}, GONE)
refused("close onto a deleted part", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Aa_Anchor", "other_socket": "end_a"}, GONE)
# --- cut-at-ray: a through bay, a blind round recess, a row of gills and a panel break --------------------------------------
section('cut-at-ray: a through bay, a blind round recess, a row of gills and a panel break')
CUTS = [("Bay", "box", (3.0, 0.0, 0.1), (-1.0, 0.0, 0.0), "width=0.3; height=0.3; depth=0.2", {}),
("Recess", "cyl", (-3.0, 0.1, 0.2), (2.0, 0.0, 0.0), "r=0.1; depth=0.02", {}),
("Gills", "slot", (0.1, 3.0, -0.2), (0.0, -1.0, 0.0), "width=0.3; height=0.04; count=4; pitch=0.08; depth=0.02", {}),
("Break", "slab", (0.0, -3.0, 0.3), (0.0, 1.0, 0.0), "length=0.6; depth=0.1", {"roll": 90.0})]
frames, volume, falls, reports = {}, uncut["volume"], [], {}
for name, part, origin, direction, params, more in CUTS:
hit, normal = cast(cage, origin, direction) # before this cutter exists; the cuts made so far are far from this ray
frames[name] = core.surface_frame(hit, normal, (0.0, 0.0, 1.0), more.get("roll", 0.0))
state = sorted(o.name for o in bpy.data.objects)
receipt, report = cut(name, part, origin, direction, params, **more)
reports[name] = report
cutter = bpy.data.objects.get(name)
ok = receipt["status"] == "accepted" and cutter is not None and sorted(o.name for o in bpy.data.objects) == sorted(state + [name])
ok = ok and cutter.parent == cage and np.array_equal(np.array(cutter.matrix_parent_inverse), np.eye(4))
ok = ok and reading("framed", np.abs(np.array(cutter.matrix_basis) - frames[name]).max()) < FRAMED
ok = ok and (cutter["kit_kit"], cutter["kit_part"]) == ("cutters", part) and bpy.context.scene.collection in cutter.users_collection
ok = ok and not cutter.hide_render and not cutter.hide_viewport and len(cutter.modifiers) == 0
check(f"cut places the {part} cutter {name} on the cage where the ray meets it: parented under an identity inverse, its basis the surface frame",
ok, [receipt["message"], cutter and np.array(cutter.matrix_basis).tolist(), frames[name].tolist()])
wanted = world @ frames[name]
check(f"cut reports {name} as a cutters part with its sockets in the world, and what cuts the cage, without evaluating it", report
and report["object"] == "Cage" and report["cutter"]["object"] == name and report["cutter"]["kit"] == "cutters" and "evaluated" not in report
and report["booleans"] == [{"cutter": n, "operation": "DIFFERENCE"} for n in [c[0] for c in CUTS][:len(frames)]]
and [s["name"] for s in report["cutter"]["sockets"]] == {"slab": [], "slot": ["floor", "floor_l", "floor_r"]}.get(part, ["floor"])
and (part == "slab" or np.abs(np.array(report["cutter"]["sockets"][0]["matrix"]) - wanted @ core.build(kits["cutters"]["parts"][part], report["cutter"]["params"]).sockets[0]["matrix"]).max() < 1e-4),
report)
shown, _ = evaluated(cage)
falls.append(shown["volume"] < volume - 1e-4 and shown["nonManifoldEdges"] == 0)
volume = shown["volume"]
R["cage"][name] = shown
modifier = cage.modifiers.get("Kit Difference")
check("four cuts give the cage one Boolean modifier after its own, over one collection of the four cutters in the order they came",
stack(cage) == ["Subsurf", "Solidify", "Kit Difference"] and modifier is not None
and (modifier.type, modifier.solver, modifier.use_self, modifier.operation, modifier.operand_type, modifier.material_mode) == ("BOOLEAN", "EXACT", True, "DIFFERENCE", "COLLECTION", "TRANSFER")
and [o.name for o in modifier.collection.objects] == [c[0] for c in CUTS] and modifier.collection.name == "Cage difference"
and not any(modifier.collection in s.collection.children_recursive for s in bpy.data.scenes), [stack(cage), modifier and modifier.operand_type])
check("the evaluated cage stays a closed wall and loses volume with each cut", all(falls) and len(falls) == 4, R["cage"])
receipt, report = send("brokkr_kitbash.report", object_name="")
check("report lists the cutters as kit parts and not the cage", report and [p["object"] for p in report["parts"]] == sorted(c[0] for c in CUTS)
and all(p["connection"] is None and p["baked"] is False for p in report["parts"]), report and [p["object"] for p in report["parts"]])
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())}
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)
# --- cut-casts-the-uncut-surface --------------------------------------------------------------------------------------------
section('cut-casts-the-uncut-surface')
through = cast(cage, CUTS[0][2], CUTS[0][3])[0] # as the cage is evaluated now, with its cuts: through the bay to the far wall
receipt, report = cut("Bay2", "cyl", CUTS[0][2], CUTS[0][3], "r=0.05; depth=0.2")
again = bpy.data.objects.get("Bay2")
check("a second cut on the through bay's ray lands where the first did, on the surface as it was before any cut, though the ray now passes through the bay",
receipt["status"] == "accepted" and again is not None and np.linalg.norm(through - frames["Bay"][:3, 3]) > 1.0
and reading("recast", np.abs(np.array(again.matrix_basis)[:3, 3] - frames["Bay"][:3, 3]).max()) < RECAST
and stack(cage) == ["Subsurf", "Solidify", "Kit Difference"] and all(m.show_viewport for m in cage.modifiers),
[receipt["message"], through.tolist(), frames["Bay"][:3, 3].tolist(), again and list(again.matrix_basis.translation)])
# --- floor-carries-machinery ------------------------------------------------------------------------------------------------
section('floor-carries-machinery')
recess = bpy.data.objects["Recess"]
vent = place("Vent", "vent", "width=0.2; height=0.15") # back size 0.135; the floor's is 0.2
receipt, report = send("brokkr_kitbash.attach", object_name="Vent", socket="back", parent_name="Recess", parent_socket="floor", roll=30.0)
floor = world @ frames["Recess"] @ np.array(Matrix.Translation((0.0, 0.0, -0.02))) # the hit point, depth along the normal
back = frame(vent, "back")
check("a mechanical vent attaches to the round recess's floor: its back on the hit point taken depth down the normal, facing in, and the connection holds",
receipt["status"] == "accepted" and held(report) and vent.parent == recess and report["connection"]["parent"] == "Recess" and report["kit"] == "mechanical"
and reading("floored", max(np.abs(back[:3, 3] - floor[:3, 3]).max(), np.abs(back[:3, 2] + floor[:3, 2]).max())) < FLOORED,
[receipt["message"], back.tolist(), floor.tolist()])
big = place("Big", "vent", "width=0.8; height=0.6")
refused("a vent larger than the recess's floor", "brokkr_kitbash.attach", {"object_name": "Big", "socket": "back", "parent_name": "Recess", "parent_socket": "floor"},
"'Big' on 'Recess': socket 'back' (mount, size 0.54) and parent socket 'floor' (mount, size 0.2) are mount sockets, where the child fits the parent: it is larger")
nozzle = place("Nozzle", "nozzle")
refused("a flange on a floor", "brokkr_kitbash.attach", {"object_name": "Nozzle", "socket": "mount", "parent_name": "Recess", "parent_socket": "floor"}, "are of different types")
refused("a second part on the floor", "brokkr_kitbash.attach", {"object_name": "Nozzle", "socket": "mount", "parent_name": "Recess", "parent_socket": "floor"}, "'Nozzle' on 'Recess'")
refused("a part on a slab, which has no floor", "brokkr_kitbash.attach", {"object_name": "Big", "socket": "back", "parent_name": "Break", "parent_socket": "floor"},
"kit 'cutters' part 'slab' has no socket 'floor'; its sockets: none")
refused("detach of a cutter, which is placed and not attached", "brokkr_kitbash.detach", {"object_name": "Recess"}, "'Recess' is not attached")
before = evaluated(cage)[0]
moved_to = np.array(recess.matrix_basis)[:3, 3] + np.array(recess.matrix_basis)[:3, :3] @ [0.0, 0.25, 0.0] # along the cutter's own y: up the wall
was = frame(vent, "back")
send("setObjectTransform", targetObjectName="Recess", location=moved_to.tolist())
shift = frame(vent, "back")[:3, 3] - was[:3, 3]
after = evaluated(cage)[0]
check("setObjectTransform on the cutter moves the cut and the vent on its floor together: the vent still holds, and the cage is cut elsewhere",
reading("floored", np.abs(shift - world[:3, :3] @ (moved_to - frames["Recess"][:3, 3])).max()) < FLOORED and abs(np.linalg.norm(shift) - 0.25) < 1e-4
and (connection := send("brokkr_kitbash.report", object_name="Vent")[1]["parts"][0]["connection"])["holds"] is True
and after["nonManifoldEdges"] == 0 and after != before, [shift.tolist(), before, after])
was = frame(vent, "back")
receipt, report = send("brokkr_kitbash.set_params", object_name="Recess", params="depth=0.04")
sunk = frame(vent, "back")[:3, 3] - was[:3, 3]
deeper = evaluated(cage)[0]
check("set_params depth=0.04 on the cutter deepens the cut and seats the vent on the new floor, 0.02 further down the normal",
receipt["status"] == "accepted" and report["params"]["depth"] == 0.04 and reading("floored", np.abs(sunk + was[:3, 2] * -0.02).max()) < FLOORED
and send("brokkr_kitbash.report", object_name="Vent")[1]["parts"][0]["connection"]["holds"] is True
and deeper["volume"] < after["volume"] - 1e-5 and deeper["nonManifoldEdges"] == 0 and stack(cage) == ["Subsurf", "Solidify", "Kit Difference"],
[receipt["message"], sunk.tolist(), after, deeper])
R["cage"]["deeper"] = deeper
# --- cut_many: several cutters for one evaluation, all or none; an axis; a slot's three floors -----------------------------------
section("cut_many: several cutters for one evaluation, all or none; an axis; a slot's three floors")
MANY = [{"name": "Visor", "part": "slot", "params": "width=0.6; height=0.14; depth=0.02; lift=0.2", "origin": [0.6, 3.0, 0.5], "direction": [0.0, -1.0, 0.0]},
{"name": "Seam", "part": "slab", "params": "length=0.4; depth=0.1", "origin": [-0.5, -3.0, -0.7], "direction": [0.0, 1.0, 0.0], "up": [1.0, 0.0, 0.0], "axis": [0.0, -1.0, 0.0]},
{"name": "Port", "part": "cyl", "params": "r=0.05", "origin": [-0.6, 3.0, -0.5], "direction": [0.0, -2.0, 0.0], "up": [1.0, 0.0, 0.0], "roll": 45.0}]
wanted = {}
for spec in MANY:
hit, normal = uncut_cast(spec["origin"], spec["direction"])
wanted[spec["name"]] = core.surface_frame(hit, spec.get("axis", normal), spec.get("up", (0.0, 0.0, 1.0)), spec.get("roll", 0.0))
if "axis" in spec:
lean = float(np.degrees(np.arccos(np.clip(normal @ np.array(spec["axis"]), -1.0, 1.0))))
refused("cut_many whose second ray misses places none", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([MANY[0], {**MANY[1], "origin": [0.0, -3.0, 5.0]}])},
"The ray from (0.0, -3.0, 5.0) along (0.0, 1.0, 0.0) misses 'Cage'")
refused("cut_many with a name twice", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([MANY[0], {**MANY[1], "name": "Visor"}])}, "An object named 'Visor' exists in this call")
refused("cut_many with a name an object has", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([MANY[0], {**MANY[1], "name": "Bay"}])}, "An object named 'Bay' exists;")
refused("cut_many whose last cutter has a bad param", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps(MANY[:2] + [{**MANY[2], "params": "r=9"}])}, "param 'r' = 9.0 is outside")
refused("cut_many of text that is not JSON", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": "[{"}, "cuts is not JSON")
refused("cut_many of no cutters", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": "[]"}, "cuts must be a JSON array of 1 to 64 cutters")
refused("cut_many of a cutter with no direction", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{k: v for k, v in MANY[0].items() if k != "direction"}])},
"cuts[0] must be an object with name, part, origin and direction")
refused("cut_many of a cutter with a key cut does not have", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{**MANY[0], "operation": "UNION"}])}, "cuts[0] must be an object")
refused("cut_many of an origin of two numbers", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{**MANY[0], "origin": [0.0, 1.0]}])}, "cuts[0].origin must be three numbers")
refused("cut_many of a roll of 400", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{**MANY[0], "roll": 400}])}, "cuts[0].roll must be a number from -360 to 360")
refused("an axis that points into the surface", "brokkr_kitbash.cut_many", {"object_name": "Cage", "cuts": json.dumps([{**MANY[1], "axis": [0.0, 1.0, 0.0]}])}, "'Seam': the axis (0.0, 1.0, 0.0) points into the surface")
quad("Many", (0.0, -27.0, 0.0)) # a target of its own, cheap to evaluate should the 65 ever be placed
refused("M7: cut_many of 65 cutters, one over the limit", "brokkr_kitbash.cut_many",
{"object_name": "Many", "cuts": json.dumps([{"name": f"Over{k}", "part": "cyl", "params": "r=0.005", "origin": [0.4 - k * 0.012, 0.0, 3.0], "direction": [0.0, 0.0, -1.0], "up": [0.0, 1.0, 0.0]}
for k in range(65)])}, "cuts must be a JSON array of 1 to 64 cutters")
receipt, report = send("brokkr_kitbash.cut_many", object_name="Cage", cuts=json.dumps(MANY))
placed = [bpy.data.objects.get(spec["name"]) for spec in MANY]
check("cut_many places three cutters in one action, each as cut would: parented under an identity inverse, its basis the surface frame at its own ray on the uncut cage, in the difference collection in order",
receipt["status"] == "accepted" and all(placed) and report == {"object": "Cage", "cutters": ["Visor", "Seam", "Port"], "booleans": report["booleans"]}
and [row["cutter"] for row in report["booleans"]] == ["Bay", "Recess", "Gills", "Break", "Bay2", "Visor", "Seam", "Port"]
and all(c.parent == cage and np.array_equal(np.array(c.matrix_parent_inverse), np.eye(4))
and reading("framed", np.abs(np.array(c.matrix_basis) - wanted[c.name]).max()) < FRAMED for c in placed)
and stack(cage) == ["Subsurf", "Solidify", "Kit Difference"] and all(m.show_viewport for m in cage.modifiers) and evaluated(cage)[0]["nonManifoldEdges"] == 0,
[receipt["message"], report])
seam = bpy.data.objects["Seam"]
check("a slab with an axis stands on the axis, not on the wall's normal, which leans from it there", lean > 5.0
and reading("framed", np.abs(np.array(seam.matrix_basis)[:3, 2] - [0.0, -1.0, 0.0]).max()) < FRAMED, [lean, np.array(seam.matrix_basis).tolist()])
receipt, report = send("brokkr_kitbash.cut", object_name="Cage", cutter_name="Seam2", part="slab", params="length=0.3; depth=0.1", origin_x=0.5, origin_y=-3.0, origin_z=-0.7,
direction_x=0.0, direction_y=1.0, direction_z=0.0, up_x=1.0, up_y=0.0, up_z=0.0, axis_x=0.0, axis_y=-1.0, axis_z=0.0)
check("cut takes the same axis", receipt["status"] == "accepted" and reading("framed", np.abs(np.array(bpy.data.objects["Seam2"].matrix_basis)[:3, 2] - [0.0, -1.0, 0.0]).max()) < FRAMED, receipt["message"])
visor = bpy.data.objects["Visor"]
eyes = {}
for socket, x in (("floor", 0.0), ("floor_l", -0.23), ("floor_r", 0.23)): # the round ends' centres: -+(0.6 - 0.14) / 2
eye = place(f"Eye_{socket}", "vent", "width=0.2; height=0.15") # back size 0.135; each floor's is 0.14
receipt, report = send("brokkr_kitbash.attach", object_name=eye.name, socket="back", parent_name="Visor", parent_socket=socket)
there = world @ wanted["Visor"] @ np.array(Matrix.Translation((x, 0.0, -0.02)))
eyes[socket] = receipt["status"] == "accepted" and held(report) and eye.parent == visor \
and reading("floored", max(np.abs(frame(eye, "back")[:3, 3] - there[:3, 3]).max(), np.abs(frame(eye, "back")[:3, 2] + there[:3, 2]).max())) < FLOORED
check("slot-floors: a slot's three floors each take a part: at the centre and at the round ends, all on the slot's one floor plane", all(eyes.values()) and len(eyes) == 3, eyes)
refused("a second part on a side floor", "brokkr_kitbash.attach", {"object_name": "Nozzle", "socket": "mount", "parent_name": "Visor", "parent_socket": "floor_l"}, "'Nozzle' on 'Visor'")
refused("a fourth eye on a floor that is taken", "brokkr_kitbash.attach", {"object_name": "Big", "socket": "back", "parent_name": "Visor", "parent_socket": "floor_l"}, "'Big' on 'Visor'")
# --- boolean on any mesh, and the order of the three operations -----------------------------------------------------------------
section('boolean on any mesh, and the order of the three operations')
lump_at = world @ [0.0, 0.0, 1.0, 1.0]
send("createObject", objectType="MESH", name="Lump", location=lump_at[:3].tolist(), size=0.2)
receipt, report = send("brokkr_kitbash.boolean", object_name="Cage", cutter="Lump", operation="UNION")
check("boolean on the cage, which is not a kit part, adds a second modifier after the difference and reports the object, what cuts it and the evaluated mesh",
receipt["status"] == "accepted" and stack(cage) == ["Subsurf", "Solidify", "Kit Difference", "Kit Union"]
and sorted(report) == ["booleans", "evaluated", "object"] and report["object"] == "Cage" and report["evaluated"] == evaluated(cage)[0]
and report["booleans"] == [{"cutter": n, "operation": "DIFFERENCE"} for n in ("Bay", "Recess", "Gills", "Break", "Bay2", "Visor", "Seam", "Port", "Seam2")] + [{"cutter": "Lump", "operation": "UNION"}]
and report["evaluated"]["volume"] > deeper["volume"], [receipt["message"], report])
refused("cut-refusals: a cutter already in the target's union collection", "brokkr_kitbash.boolean", {"object_name": "Cage", "cutter": "Lump"},
"'Lump' already cuts 'Cage' (its Kit Union modifier's collection)")
refused("a cut's own cutter given to boolean again", "brokkr_kitbash.boolean", {"object_name": "Cage", "cutter": "Bay", "operation": "INTERSECT"},
"'Bay' already cuts 'Cage' (its Kit Difference modifier's collection)")
blocked = cast(cage, (-0.3, 0.0, 0.95), (1.0, 0.0, 0.0))[0] # as evaluated now: the ray meets Lump, which the union added inside the cage's mouth
hit, normal = uncut_cast((-0.3, 0.0, 0.95), (1.0, 0.0, 0.0))
receipt, report = cut("Past", "cyl", (-0.3, 0.0, 0.95), (1.0, 0.0, 0.0), "r=0.02; depth=0.01")
past = bpy.data.objects.get("Past")
check("M3: a cut whose ray meets what a union added lands on the surface as designed: the cast has the Kit Union off too",
receipt["status"] == "accepted" and past is not None and np.linalg.norm(blocked - hit) > 0.3
and reading("framed", np.abs(np.array(past.matrix_basis) - core.surface_frame(hit, normal, (0.0, 0.0, 1.0))).max()) < FRAMED
and all(m.show_viewport for m in cage.modifiers), [receipt["message"], blocked.tolist(), hit.tolist(), past and list(past.matrix_basis.translation)])
plate = place("Plate", "plate", location=[0.0, -6.0, 0.0])
for name, size, operation in (("Boss", 0.06, "UNION"), ("Keep", 2.0, "INTERSECT"), ("Hole", 0.05, "DIFFERENCE")):
send("createObject", objectType="MESH", name=name, location=[0.0, -6.0, 0.0], size=size)
receipt, report = send("brokkr_kitbash.boolean", object_name="Plate", cutter=name, operation=operation)
check("a part cut by union, then intersect, then difference carries the three modifiers as difference, union, intersect, above its Bevel, and lists its cutters so",
receipt["status"] == "accepted" and stack(plate) == ["Kit Difference", "Kit Union", "Kit Intersect", "Kit Bevel"]
and report["booleans"] == [{"cutter": "Hole", "operation": "DIFFERENCE"}, {"cutter": "Boss", "operation": "UNION"}, {"cutter": "Keep", "operation": "INTERSECT"}]
and report["evaluated"]["nonManifoldEdges"] == 0 and report["kit"] == "mechanical", [stack(plate), report and report["booleans"]])
collections = len(bpy.data.collections)
receipt, baked = send("brokkr_kitbash.apply", object_name="Plate")
check("apply removes the three collections its modifiers held and leaves every cutter in the scene", receipt["status"] == "accepted"
and baked["cutters"] == ["Hole", "Boss", "Keep"] and len(bpy.data.collections) == collections - 3 and len(plate.modifiers) == 0
and all(name in bpy.context.scene.objects for name in ("Hole", "Boss", "Keep")), [receipt["message"], [c.name for c in bpy.data.collections]])
refused("apply on the cage, which is not a kit part", "brokkr_kitbash.apply", {"object_name": "Cage"}, "'Cage' is not a kit part")
twin = place("Twin", "plate", location=[0.0, -15.0, 0.0])
send("createObject", objectType="MESH", name="TwinHole", location=[0.0, -15.0, 0.0], size=0.05)
send("brokkr_kitbash.boolean", object_name="Twin", cutter="TwinHole")
copied = twin.copy() # a copied part: its own mesh, and a Kit Difference modifier that reads the same collection
copied.data = twin.data.copy()
bpy.context.scene.collection.objects.link(copied)
receipt, baked = send("brokkr_kitbash.apply", object_name="Twin")
kept = bpy.data.collections.get("Twin difference")
check("M6: apply keeps a collection a copied part's modifier still reads", receipt["status"] == "accepted" and len(twin.modifiers) == 0 and kept is not None
and copied.modifiers["Kit Difference"].collection == kept and [o.name for o in kept.objects] == ["TwinHole"], [receipt["message"], [c.name for c in bpy.data.collections]])
# --- cut-refusals -----------------------------------------------------------------------------------------------------------
section('cut-refusals')
RAY = {"object_name": "Cage", "cutter_name": "New", "part": "box", "origin_x": 3.0, "origin_y": 0.0, "origin_z": 0.1, "direction_x": -1.0, "direction_y": 0.0, "direction_z": 0.0}
refused("a ray that misses", "brokkr_kitbash.cut", {**RAY, "origin_z": 5.0}, "The ray from (3.0, 0.0, 5.0) along (-1.0, 0.0, 0.0) misses 'Cage'")
refused("a ray of no direction", "brokkr_kitbash.cut", {**RAY, "direction_x": 0.0}, "'New': the ray's direction is zero")
refused("a cutter name an object has", "brokkr_kitbash.cut", {**RAY, "cutter_name": "Bay"}, "An object named 'Bay' exists")
refused("a param the cutter part does not have", "brokkr_kitbash.cut", {**RAY, "params": "radius=0.1"}, "kit 'cutters' part 'box' has no param 'radius'")
refused("a slot wider across than along", "brokkr_kitbash.cut", {**RAY, "part": "slot", "params": "width=0.05; height=0.1"}, "every size must be above 0")
refused("a target that is not a mesh", "brokkr_kitbash.cut", {**RAY, "object_name": "Nothing"}, "No mesh object named 'Nothing'")
block = bpy.data.objects.new("Block", bpy.data.meshes.new("Block"))
bm = bmesh.new()
bmesh.ops.create_cube(bm, size=1.0)
bm.to_mesh(block.data)
bm.free()
bpy.context.scene.collection.objects.link(block)
block.location = (0.0, -9.0, 0.0)
bpy.context.view_layer.update()
DOWN = {**RAY, "object_name": "Block", "origin_x": 0.1, "origin_y": 0.1, "origin_z": 3.0, "direction_x": 0.0, "direction_z": -1.0}
refused("an up along the hit normal", "brokkr_kitbash.cut", DOWN, "up [0.0, 0.0, 1.0] runs along the surface normal [0.0, 0.0, 1.0]")
block.scale = (1.0, 1.0, 1.01)
bpy.context.view_layer.update()
refused("a scaled target", "brokkr_kitbash.cut", {**DOWN, "up_y": 1.0, "up_z": 0.0}, "'Block' is scaled, mirrored or sheared in the world (scale 1, 1, 1.01)")
refused("boolean on a scaled target", "brokkr_kitbash.boolean", {"object_name": "Block", "cutter": "Lump"}, "'Block' is scaled, mirrored or sheared")
block.scale = (1.0, 1.0, 1.0)
bpy.context.view_layer.update()
receipt, report = send("brokkr_kitbash.cut", **{**DOWN, "cutter_name": "Pocket", "up_y": 1.0, "up_z": 0.0, "roll": 90.0})
pocket = bpy.data.objects.get("Pocket")
check("a cut on a plain cube with up +y and roll 90: the cutter's y points along -x, its floor 0.02 under the top face", receipt["status"] == "accepted" and pocket is not None
and np.abs(np.array(pocket.matrix_basis) - [[0, -1, 0, 0.1], [1, 0, 0, 0.1], [0, 0, 1, 0.5], [0, 0, 0, 1]]).max() < 1e-6
and np.abs(np.array(report["cutter"]["sockets"][0]["matrix"])[:3, 3] - [0.1, -8.9, 0.48]).max() < 1e-6 and stack(block) == ["Kit Difference"],
[receipt["message"], pocket and np.array(pocket.matrix_basis).tolist()])
# --- lows-pinned: the surface's side, an axis along it, and an object Blender does not evaluate --------------------------------
section("lows-pinned: the surface's side, an axis along it, and an object Blender does not evaluate")
sheet = quad("Sheet", (0.0, -12.0, 0.0))
UNDER = {"object_name": "Sheet", "cutter_name": "Under", "part": "cyl", "origin_x": 0.1, "origin_y": 0.1, "origin_z": -3.0, "direction_x": 0.0, "direction_y": 0.0, "direction_z": 1.0,
"up_x": 0.0, "up_y": 1.0, "up_z": 0.0}
refused("M1: an axis exactly along the surface, neither out of it nor into it", "brokkr_kitbash.cut", {**UNDER, "cutter_name": "Along", "origin_z": 3.0, "direction_z": -1.0, "axis_x": 1.0},
"'Along': the axis (1.0, 0.0, 0.0) points into the surface")
receipt, report = send("brokkr_kitbash.cut", **UNDER)
under = bpy.data.objects.get("Under")
check("M16: a ray that meets a one-sided face from behind gives a cutter whose z faces the ray, against the face's own normal", receipt["status"] == "accepted" and under is not None
and reading("framed", np.abs(np.array(under.matrix_basis)[:3, 2] - [0.0, 0.0, -1.0]).max()) < FRAMED, [receipt["message"], under and np.array(under.matrix_basis).tolist()])
loose = place("Loose", "plate", location=[0.0, -18.0, 0.0])
apart = bpy.data.collections.new("Apart") # a collection no scene holds: Loose is in a collection, and in no view layer
apart.objects.link(loose)
bpy.context.scene.collection.objects.unlink(loose)
veil = quad("Veil", (0.0, -21.0, 0.0)) # nothing depends on it: a disabled object another evaluated object needs (a parent, a cutter) is still evaluated
veil.hide_viewport = plate.hide_viewport = True
bpy.context.view_layer.update()
for name, why in (("Veil", "disabled in viewports"), ("Loose", "in a collection outside the view layer")):
NOT = f"Blender does not evaluate {name!r} in this view layer"
refused(f"unevaluable-target: cut on a target {why}", "brokkr_kitbash.cut", {**DOWN, "object_name": name, "cutter_name": "Unseen", "up_y": 1.0, "up_z": 0.0}, NOT)
refused(f"cut_many on a target {why}", "brokkr_kitbash.cut_many",
{"object_name": name, "cuts": json.dumps([{"name": "Unseen", "part": "box", "origin": [0.1, 0.1, 3.0], "direction": [0.0, 0.0, -1.0], "up": [0.0, 1.0, 0.0]}])}, NOT)
refused(f"boolean on a target {why}", "brokkr_kitbash.boolean", {"object_name": name, "cutter": "Sheet"}, NOT)
refused("apply on a part disabled in viewports", "brokkr_kitbash.apply", {"object_name": "Plate"}, "Blender does not evaluate 'Plate' in this view layer")
refused("apply on a part in a collection outside the view layer", "brokkr_kitbash.apply", {"object_name": "Loose"}, "Blender does not evaluate 'Loose' in this view layer")
veil.hide_viewport = plate.hide_viewport = False
bpy.context.view_layer.update()
# --- receipt-fitted: rows that would not fit a receipt are left off and counted; the scene keeps the cutters ---------------------
section('receipt-fitted: rows that would not fit a receipt are left off and counted; the scene keeps the cutters')
addon = sys.modules["brokkr_kitbash"]
limit, fits = addon.REPORT_LIMIT, {}
SPOT = {"part": "cyl", "params": "r=0.03", "direction": [0.0, 0.0, -1.0], "up": [0.0, 1.0, 0.0]}
try:
addon.REPORT_LIMIT = 200
fits["cut"] = send("brokkr_kitbash.cut", **{**DOWN, "cutter_name": "Fit1", "part": "cyl", "params": "r=0.03", "origin_x": -0.3, "up_y": 1.0, "up_z": 0.0})
fits["cut_many"] = send("brokkr_kitbash.cut_many", object_name="Block", cuts=json.dumps([{**SPOT, "name": "Fit2", "origin": [-0.3, -0.3, 3.0]}, {**SPOT, "name": "Fit3", "origin": [0.3, -0.3, 3.0]}]))
fits["boolean"] = send("brokkr_kitbash.boolean", object_name="Block", cutter="Lump", operation="UNION")
finally:
addon.REPORT_LIMIT = limit
ROWS = [{"cutter": name, "operation": "DIFFERENCE"} for name in ("Pocket", "Fit1", "Fit2", "Fit3")] + [{"cutter": "Lump", "operation": "UNION"}]
for action, total, keeps in (("cut", 2, 0), ("cut_many", 4, 2), ("boolean", 5, 1)): # rows the scene had after each action, and how many of them 200 characters carry
receipt, report = fits[action]
check(f"receipt-fitted: {action} past what a receipt carries is accepted, its booleans cut short and the rest counted in booleansOmitted", receipt["status"] == "accepted"
and report is not None and report["booleans"] == ROWS[:keeps] and report.get("booleansOmitted") == total - keeps and (keeps == 0 or len(receipt["hostResult"]) <= 200),
[receipt["message"], receipt.get("hostResult")])
check("the scene keeps every cutter a short receipt left off", [o.name for o in block.modifiers["Kit Difference"].collection.objects] == ["Pocket", "Fit1", "Fit2", "Fit3"]
and [o.name for o in block.modifiers["Kit Union"].collection.objects] == ["Lump"], stack(block))
receipt, report = send("brokkr_kitbash.boolean", object_name="Block", cutter="Sheet", operation="INTERSECT")
check("a report that fits carries every row and no count", receipt["status"] == "accepted" and report["booleans"] == ROWS + [{"cutter": "Sheet", "operation": "INTERSECT"}]
and "booleansOmitted" not in report, report)
# --- cut-orphan and closures-ends-first -----------------------------------------------------------------------------------------
section('cut-orphan and closures-ends-first')
strut = core.build(kits["mechanical"]["parts"]["strut"], {"width": 0.09})
end = {name: next(s for s in strut.sockets if s["name"] == name) for name in ("end_a", "end_b")}
for pair, y in (("Zz", -20.0), ("Aa", -24.0)): # two closures that share no part; the open one is named to sort first
anchor, loose = place(f"{pair}_Anchor", "strut", "width=0.09", location=[0.0, y, 0.0]), place(f"{pair}_Loose", "strut", "width=0.09")
meet = Matrix((np.array(anchor.matrix_world) @ core.mate(end["end_b"], end["end_a"], 40.0)).tolist())
send("setObjectTransform", targetObjectName=f"{pair}_Loose", location=list(meet.translation), rotationEuler=list(meet.to_euler("XYZ")))
send("brokkr_kitbash.close", object_name=f"{pair}_Loose", socket="end_a", other_name=f"{pair}_Anchor", other_socket="end_b")
send("brokkr_kitbash.set_params", object_name="Aa_Anchor", params="length=0.9") # opens Aa's closure
receipt, report = send("brokkr_kitbash.set_params", object_name="Zz_Anchor", params="width=0.09")
check("closures-ends-first: set_params on a part whose own closure holds lists it before another part's closure that is open, though that one sorts first by holds and by name",
receipt["status"] == "accepted" and report["closures"] == [{"part": "Zz_Loose", "to": "Zz_Anchor", "holds": True}, {"part": "Aa_Loose", "to": "Aa_Anchor", "holds": False}],
report and report.get("closures"))
ghost = bpy.data.objects["Aa_Anchor"]
with bpy.context.temp_override(selected_objects=[ghost], active_object=ghost):
bpy.ops.object.delete() # the ordinary Delete: Aa_Loose's closure still points at it, so it stays in the file, in no collection
tie = place("Tie", "strut", "width=0.09")
check("a part deleted with the Delete operator that a closure points to is still in the file", bpy.data.objects.get("Aa_Anchor") is not None and not ghost.users_collection, list(bpy.data.objects.keys()))
GONE = "'Aa_Anchor' is in no collection (a deleted object something still points to)"
refused("cut-orphan: attach onto a deleted part's name", "brokkr_kitbash.attach", {"object_name": "Tie", "socket": "end_a", "parent_name": "Aa_Anchor", "parent_socket": "end_a"}, GONE)
refused("attach of a deleted part", "brokkr_kitbash.attach", {"object_name": "Aa_Anchor", "socket": "end_a", "parent_name": "Tie", "parent_socket": "end_a"}, GONE)
refused("set_params on a deleted part", "brokkr_kitbash.set_params", {"object_name": "Aa_Anchor", "params": "length=1.0"}, GONE)
refused("report of a deleted part", "brokkr_kitbash.report", {"object_name": "Aa_Anchor"}, GONE)
refused("cut on a deleted part", "brokkr_kitbash.cut", {**RAY, "object_name": "Aa_Anchor"}, GONE)
refused("boolean on a deleted part", "brokkr_kitbash.boolean", {"object_name": "Aa_Anchor", "cutter": "Lump"}, GONE)
refused("boolean with a deleted part as the cutter", "brokkr_kitbash.boolean", {"object_name": "Tie", "cutter": "Aa_Anchor"}, GONE)
refused("close onto a deleted part", "brokkr_kitbash.close", {"object_name": "Tie", "socket": "end_a", "other_name": "Aa_Anchor", "other_socket": "end_a"}, GONE)
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())}
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)
sys.exit(0 if R["ok"] else 1)

View file

@ -162,7 +162,7 @@
"detail": null
},
{
"name": "refused, scene unchanged: cut_many whose report would not fit a receipt places none",
"name": "refused, scene unchanged: M7: cut_many of 65 cutters, one over the limit",
"ok": true,
"detail": null
},
@ -182,7 +182,7 @@
"detail": null
},
{
"name": "a slot's three floors each take a part: at the centre and a third of the width to each side, all on the slot's one floor plane",
"name": "slot-floors: a slot's three floors each take a part: at the centre and at the round ends, all on the slot's one floor plane",
"ok": true,
"detail": null
},
@ -211,6 +211,11 @@
"ok": true,
"detail": null
},
{
"name": "M3: a cut whose ray meets what a union added lands on the surface as designed: the cast has the Kit Union off too",
"ok": true,
"detail": null
},
{
"name": "a part cut by union, then intersect, then difference carries the three modifiers as difference, union, intersect, above its Bevel, and lists its cutters so",
"ok": true,
@ -226,6 +231,11 @@
"ok": true,
"detail": null
},
{
"name": "M6: apply keeps a collection a copied part's modifier still reads",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: a ray that misses",
"ok": true,
@ -276,6 +286,81 @@
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: M1: an axis exactly along the surface, neither out of it nor into it",
"ok": true,
"detail": null
},
{
"name": "M16: a ray that meets a one-sided face from behind gives a cutter whose z faces the ray, against the face's own normal",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: unevaluable-target: cut on a target disabled in viewports",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: cut_many on a target disabled in viewports",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: boolean on a target disabled in viewports",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: unevaluable-target: cut on a target in a collection outside the view layer",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: cut_many on a target in a collection outside the view layer",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: boolean on a target in a collection outside the view layer",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: apply on a part disabled in viewports",
"ok": true,
"detail": null
},
{
"name": "refused, scene unchanged: apply on a part in a collection outside the view layer",
"ok": true,
"detail": null
},
{
"name": "receipt-fitted: cut past what a receipt carries is accepted, its booleans cut short and the rest counted in booleansOmitted",
"ok": true,
"detail": null
},
{
"name": "receipt-fitted: cut_many past what a receipt carries is accepted, its booleans cut short and the rest counted in booleansOmitted",
"ok": true,
"detail": null
},
{
"name": "receipt-fitted: boolean past what a receipt carries is accepted, its booleans cut short and the rest counted in booleansOmitted",
"ok": true,
"detail": null
},
{
"name": "the scene keeps every cutter a short receipt left off",
"ok": true,
"detail": null
},
{
"name": "a report that fits carries every row and no count",
"ok": true,
"detail": null
},
{
"name": "closures-ends-first: set_params on a part whose own closure holds lists it before another part's closure that is open, though that one sorts first by holds and by name",
"ok": true,
@ -329,7 +414,7 @@
],
"hostErrors": [],
"readings": {
"floored": 2.6e-07,
"floored": 3.3e-07,
"framed": 5.1e-07,
"recast": 0.0
},

View file

@ -595,7 +595,7 @@ class CuttersKitTests(unittest.TestCase):
self.assertAlmostEqual(float(b.V[:, 2].min()), -depth, places=12)
self.assertAlmostEqual(float(b.V[:, 2].max()), lift, places=12)
for socket in b.sockets:
side = {"floor": 0.0, "floor_l": -1.0, "floor_r": 1.0}[socket["name"]] * b.params.get("width", 0.0) / 3
side = {"floor": 0.0, "floor_l": -1.0, "floor_r": 1.0}[socket["name"]] * (b.params.get("width", 0.0) - b.params.get("height", 0.0)) / 2
self.assertEqual(socket["matrix"][:, 3].tolist(), [side, 0.0, -depth, 1.0])
self.assertEqual(socket["matrix"][:3, :3].tolist(), np.eye(3).tolist())
self.assertGreater(socket["size"], 0.0)
@ -619,13 +619,21 @@ class CuttersKitTests(unittest.TestCase):
self.assertTrue(seat < 1e-12 if count % 2 else abs(seat - 0.015) < 1e-12, f"{name} x{count}: {seat}") # even: 0.015 from each middle copy
def test_a_slot_has_three_floors_on_its_bottom(self):
"""A visor carries three eyes: floor_l and floor_r lie a third of the width to each side, on the slot's own
bottom, each the size of the slot's height. Mutant B4 (the two side floors swapped)."""
"""slot-floors. A visor carries three eyes: floor_l and floor_r lie at the centres of the slot's round ends, on
its own bottom; the three never overlap (centres at least a size apart) and none passes the slot's ends, also
where height exceeds a third of the width. Mutants B4 (the two side floors swapped) and F1 (the side floors
back at a third of the width, each the size of the height: at 0.3 by 0.25 they overlap by 0.15 and pass the
ends by 0.075)."""
part = self.kit["parts"]["slot"]
for given in ({"width": 0.66, "height": 0.12, "depth": 0.045}, {"width": 0.3, "height": 0.25}, {"width": 0.3, "height": 0.05, "count": 3, "pitch": 0.2}):
for given in ({"width": 0.66, "height": 0.12, "depth": 0.045}, {"width": 0.3, "height": 0.25}, {"width": 0.3, "height": 0.05, "count": 3, "pitch": 0.2},
{"width": 0.06, "height": 0.05}, {"width": 0.3, "height": 0.1}):
b = core.build(part, given)
self.assertEqual([(s["name"], round(float(s["matrix"][0, 3]), 12), s["size"]) for s in b.sockets],
[("floor", 0.0, given["height"]), ("floor_l", round(-given["width"] / 3, 12), given["height"]), ("floor_r", round(given["width"] / 3, 12), given["height"])])
side, size = (given["width"] - given["height"]) / 2, min(given["height"], (given["width"] - given["height"]) / 2)
self.assertEqual([(s["name"], round(float(s["matrix"][0, 3]), 12), round(s["size"], 12)) for s in b.sockets],
[("floor", 0.0, round(size, 12)), ("floor_l", round(-side, 12), round(size, 12)), ("floor_r", round(side, 12), round(size, 12))])
xs = [float(s["matrix"][0, 3]) for s in b.sockets]
self.assertGreaterEqual(min(xs[0] - xs[1], xs[2] - xs[0]), b.sockets[0]["size"] - 1e-12, given)
self.assertLessEqual(max(abs(x) for x in xs) + b.sockets[0]["size"] / 2, given["width"] / 2 + 1e-12, given)
for socket in b.sockets:
self.assertLess(socket_seat(b, dict(socket, matrix=socket["matrix"] @ core.FLIP)), 1e-12, socket["name"])
@ -1156,9 +1164,284 @@ class PoseTests(unittest.TestCase):
core.reach_roll(world, sp, sc, [rng.uniform(-1, 1) for _ in range(3)], (world @ sp["matrix"])[:3, 2], 0.0, 0.0)
@unittest.skipIf(np is None, "numpy is not installed")
class StructureTests(unittest.TestCase):
"""core's sweep, band, crossings, resample and spans: what brokkr_kitbash.ribs builds a frame from. Every reading is
exact arithmetic, so each assertion is the built value and names the mutant it kills."""
SQUARE = [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 1.0, 0.0), (0.0, 1.0, 0.0)]
BENT = [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 0.7, 0.0), (0.2, 1.4, 0.0)]
@staticmethod
def area(outline) -> float:
x, y = np.asarray(outline, dtype=np.float64).T
return float(0.5 * np.sum(x * np.roll(y, -1) - np.roll(x, -1) * y))
def test_the_profiles_are_counter_clockwise_sections(self):
w, h, t = 0.06, 0.1, 0.012
areas = {"I": 2 * w * t + (h - 2 * t) * t, "C": 2 * w * t + (h - 2 * t) * t, "T": w * t + (h - t) * t, "L": w * t + (h - t) * t, "box": w * h}
self.assertEqual(sorted(core.PROFILES), sorted(areas))
for kind, area in areas.items():
outline = core.profile(kind, w, h, t)
self.assertAlmostEqual(self.area(outline), area, places=15, msg=kind)
self.assertAlmostEqual(float(outline[:, 0].max() - outline[:, 0].min()), w, places=15)
self.assertAlmostEqual(float(outline[:, 1].max() - outline[:, 1].min()), h, places=15)
self.assertAlmostEqual(self.area(core.circle(0.5, 16)), 0.5 * 16 * 0.25 * math.sin(2 * math.pi / 16), places=15)
self.assertEqual(core.circle(0.5, 16)[0].tolist(), [0.5, 0.0])
for bad in (("Z", w, h, t), ("I", w, h, h / 2), ("T", w, h, w), ("L", 0.0, h, t), ("C", w, h, float("nan")), ("box", w, h, 0.0)):
with self.assertRaisesRegex(core.KitError, "profile"):
core.profile(*bad)
for bad in ((0.0, 16), (0.5, 2), (0.5, 129)):
with self.assertRaisesRegex(core.KitError, "circle of radius"):
core.circle(*bad)
def test_a_sweep_is_closed_wound_outward_and_mitred(self):
"""sweep-closed-mitred. A mitred section whose centroid lies on the path in the plane of each turn sweeps its
area times the path's length exactly. Mutants K1 (no mitre: the square loop of a 0.1 by 0.2 box loses
0.0117 of 0.08, and its corner stands 0.0354 from each wall, not 0.05) and K3 (caps wound inward: an open
sweep is no longer oriented)."""
box, tee = core.profile("box", 0.1, 0.2, 0.01), core.profile("T", 0.1, 0.12, 0.02)
for outline in (box, tee):
loop = core.sweep(self.SQUARE, outline, (0.0, 0.0, 1.0), closed=True)
self.assertTrue(closed_and_oriented(loop))
self.assertAlmostEqual(signed_volume(loop), self.area(outline) * 4.0, places=12)
self.assertEqual((len(loop.V), len(loop.counts), int(loop.counts.sum()), bool(loop.smooth.any()), len(loop.sharp)), (4 * len(outline), 4 * len(outline), 16 * len(outline), False, 0))
bent = core.sweep(self.BENT, outline, (0.0, 0.0, 1.0))
self.assertTrue(closed_and_oriented(bent))
self.assertAlmostEqual(signed_volume(bent), self.area(outline) * (1.0 + 0.7 + math.hypot(0.8, 0.7)), places=12)
self.assertEqual(sorted(bent.counts.tolist())[-2:], [len(outline)] * 2) # two n-gon caps
loop = core.sweep(self.SQUARE, box, (0.0, 0.0, 1.0), closed=True)
ring = loop.V[4:8] # at the corner (1, 0, 0), between the walls y = 0 and x = 1
self.assertAlmostEqual(float(np.abs(ring[:, 1]).max()), 0.05, places=12)
self.assertAlmostEqual(float(np.abs(ring[:, 0] - 1.0).max()), 0.05, places=12)
self.assertAlmostEqual(float(np.abs(ring[:, 0] - 1.0).min()), 0.05, places=12)
self.assertEqual(sorted(round(float(z), 12) for z in ring[:, 2]), [-0.1, -0.1, 0.1, 0.1])
again = core.sweep(self.SQUARE, box, (0.0, 0.0, 1.0), closed=True)
self.assertTrue(all(np.array_equal(a, b) for a, b in zip(loop, again)))
def test_a_sweep_stands_as_a_surface_frame_does(self):
"""x = y cross t, as core.surface_frame's x = y cross z: a rod along +z with up +y carries its outline as that frame does."""
rod = core.sweep([(0.0, 0.0, 0.0), (0.0, 0.0, 2.0)], [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0)], (0.0, 1.0, 0.0))
frame = core.surface_frame((0.0, 0.0, 0.0), (0.0, 0.0, 1.0), (0.0, 1.0, 0.0))
self.assertEqual(rod.V[:3].tolist(), [[0.0, 0.0, 0.0], frame[:3, 0].tolist(), frame[:3, 1].tolist()])
self.assertEqual(rod.V[3:, 2].tolist(), [2.0, 2.0, 2.0])
self.assertAlmostEqual(signed_volume(rod), 1.0, places=12)
per_point = core.sweep([(0.0, 0.0, 0.0), (0.0, 0.0, 2.0)], [(0.0, 0.0), (1.0, 0.0), (0.0, 1.0)], [(0.0, 1.0, 0.0), (1.0, 0.0, 0.0)])
self.assertEqual(np.round(per_point.V[3:], 12).tolist(), [[0.0, 0.0, 2.0], [0.0, -1.0, 2.0], [1.0, 0.0, 2.0]]) # the far ring turned with its own up
def test_sweep_refuses_what_makes_no_section(self):
"""sweep-refusals, each naming the path point. Mutant K2 (no fold refusal: the tight arc is swept into a
shell that crosses itself)."""
box = core.profile("box", 0.1, 0.1, 0.01)
with self.assertRaisesRegex(core.KitError, "needs 2 points of three finite numbers; it has 1"):
core.sweep([(0.0, 0.0, 0.0)], box, (0.0, 0.0, 1.0))
with self.assertRaisesRegex(core.KitError, "needs 3 points when closed"):
core.sweep(self.SQUARE[:2], box, (0.0, 0.0, 1.0), closed=True)
with self.assertRaisesRegex(core.KitError, "path point 1: the segment from it is shorter than 1e-9"):
core.sweep([(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 0.0, 0.0), (2.0, 0.0, 0.0)], box, (0.0, 0.0, 1.0))
sharp = [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0 - math.cos(math.radians(10)), math.sin(math.radians(10)), 0.0)]
with self.assertRaisesRegex(core.KitError, r"path point 1: the path turns 170\.0 degrees there, over 150"):
core.sweep(sharp, box, (0.0, 0.0, 1.0))
with self.assertRaisesRegex(core.KitError, r"path point 0: up \[1\.0, 0\.0, 0\.0\] runs along the path there"):
core.sweep(self.BENT, box, (1.0, 0.0, 0.0))
with self.assertRaisesRegex(core.KitError, r"path point 2: up \[0\.0, 0\.0, 0\.0\] runs along the path there"):
core.sweep(self.BENT, box, [(0.0, 0.0, 1.0), (0.0, 0.0, 1.0), (0.0, 0.0, 0.0), (0.0, 0.0, 1.0)])
with self.assertRaisesRegex(core.KitError, "one up or one for each of its 4 points"):
core.sweep(self.BENT, box, [(0.0, 0.0, 1.0)] * 3)
arc = [(0.05 * math.cos(a), 0.05 * math.sin(a), 0.0) for a in np.linspace(0.0, math.pi, 13)] # radius 0.05, turning left about +z
inside = [(0.1, -0.05), (0.3, -0.05), (0.3, 0.05), (0.1, 0.05)] # x = y cross t points into this turn: 0.1 to 0.3 inside a radius of 0.05
with self.assertRaisesRegex(core.KitError, r"path point \d+: the section folds there"):
core.sweep(arc, inside, (0.0, 0.0, 1.0))
outside = [(-x, y) for x, y in inside][::-1]
self.assertTrue(closed_and_oriented(core.sweep(arc, outside, (0.0, 0.0, 1.0))))
self.assertTrue(closed_and_oriented(core.sweep(arc, [(x * 0.1, y) for x, y in inside], (0.0, 0.0, 1.0)))) # 0.01 to 0.03 inside a radius of 0.05
def test_crossings_do_not_depend_on_where_a_chain_starts(self):
"""crossings-start-free. The same closed chain rotated to every start and reversed crosses a half-plane at
the same point; the opposite half-plane finds the opposite point; a chain off the plane finds none. Mutant K9
(a station at a fraction of the section's length: it moves with the start)."""
angle = 2.0 * math.pi * (np.arange(40) + 0.3) / 40
chain = np.stack([0.8 * np.cos(angle), 0.5 * np.sin(angle), np.full(40, 0.7)], axis=1)
origin, axis = (0.1, 0.05, 0.0), (0.0, 0.0, 1.0)
(segment, point), = core.crossings(chain, True, origin, axis, (1.0, 0.3, 0.0))
self.assertTrue(point[0] > 0.1 and abs((point[1] - 0.05) - 0.3 * (point[0] - 0.1)) < 1e-12 and point[2] == 0.7)
self.assertTrue(np.allclose(point, chain[segment] + (chain[(segment + 1) % 40] - chain[segment]) * 0.5, atol=0.1))
for start in range(40):
for turned in (np.roll(chain, -start, axis=0), np.roll(chain, -start, axis=0)[::-1]):
(_, again), = core.crossings(turned, True, origin, axis, (1.0, 0.3, 0.0))
self.assertLess(float(np.abs(again - point).max()), 1e-12)
(_, other), = core.crossings(chain, True, origin, axis, (-1.0, -0.3, 0.0))
self.assertLess(other[0], 0.1)
self.assertEqual(core.crossings(chain + [5.0, 0.0, 0.0], True, origin, axis, (0.0, 1.0, 0.0)), [])
self.assertEqual(len(core.crossings(chain[:20], False, origin, axis, (-1.0, -0.3, 0.0))), 0) # the open half that holds the other point only
self.assertEqual(len(core.crossings(chain[:20], False, origin, axis, (1.0, 0.3, 0.0))), 1)
on_vertex = [(-1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (1.0, 0.0, 0.0)] # its middle vertex lies on the plane x = 0: one crossing, not two
self.assertEqual([(i, p.tolist()) for i, p in core.crossings(on_vertex, False, (0.0, 0.0, 0.0), (0.0, 0.0, 1.0), (0.0, 1.0, 0.0))], [(1, [0.0, 1.0, 0.0])])
two = core.crossings([(-1.0, 1.0, 2.0), (1.0, 1.0, 2.0), (1.0, 1.0, 1.0), (-1.0, 1.0, 1.0)], False, (0.0, 0.0, 0.0), (0.0, 0.0, 1.0), (0.0, 1.0, 0.0))
self.assertEqual([(i, p.tolist()) for i, p in two], [(2, [0.0, 1.0, 1.0]), (0, [0.0, 1.0, 2.0])]) # ordered along the axis
with self.assertRaisesRegex(core.KitError, "has no direction"):
core.crossings(chain, True, origin, (0.0, 0.0, 0.0), (1.0, 0.0, 0.0))
with self.assertRaisesRegex(core.KitError, "runs along the axis"):
core.crossings(chain, True, origin, axis, (0.0, 0.0, 2.0))
def test_inset_steps_each_vertex_behind_every_face_it_is_a_corner_of(self):
"""A flat vertex steps along its normal, a crease's to where its two faces' offsets meet, a corner's to where three do; four faces that share no
point are each held at least 1 off (mutant I1, a step along the mean normal, leaves a crease's faces cos 45 off)."""
cube = [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 1.0, 0.0), (0.0, 1.0, 0.0), (0.0, 0.0, 1.0), (1.0, 0.0, 1.0), (1.0, 1.0, 1.0), (0.0, 1.0, 1.0)]
faces = [(0, 3, 2, 1), (4, 5, 6, 7), (0, 1, 5, 4), (1, 2, 6, 5), (2, 3, 7, 6), (3, 0, 4, 7)] # wound outward
self.assertTrue(np.allclose(core.inset(cube, faces), [[1.0 - 2.0 * v for v in corner] for corner in cube], atol=1e-12)) # every corner toward the middle, 1 behind each of its three faces
self.assertTrue(np.allclose(core.inset(cube, faces[:1]), [[0.0, 0.0, 1.0]] * 4 + [[0.0, 0.0, 0.0]] * 4, atol=1e-12)) # one face: along its normal's back; a vertex of no face, nowhere
self.assertTrue(np.allclose(core.inset(cube, faces[2:4])[[1, 5]], [[-1.0, 1.0, 0.0]] * 2, atol=1e-12)) # a right-angle crease: its mitre, root 2 long
lean = math.tan(math.radians(20.0))
hip = [(sx * (1.0 + z), sy * (1.0 + z * lean), z) for z in (0.0, 1.0) for sx, sy in ((1, -1), (1, 1), (-1, 1), (-1, -1))] # walls that lean 45 and 20 degrees
walls = [(k, (k + 1) % 4, 4 + (k + 1) % 4, 4 + k) for k in range(4)]
step, normals = core.inset(hip, walls), [np.array(n) / np.linalg.norm(n) for n in ((1.0, 0.0, -1.0), (0.0, 1.0, -lean), (-1.0, 0.0, -1.0), (0.0, -1.0, -lean))]
for face, normal in zip(walls, normals):
self.assertTrue(np.allclose(step[list(face)] @ normal, -1.0, atol=1e-12)) # unequal leans: still exactly 1 behind both walls
spire = [(1.0, 0.0, 0.0), (0.0, 1.0, 0.0), (-1.0, 0.0, 0.0), (0.0, -1.0, 0.0), (0.0, 0.0, 0.3), (0.4, 0.0, 0.0)]
sides = [(0, 1, 4), (1, 2, 4), (2, 3, 4), (3, 5, 4), (5, 0, 4)] # five faces round an apex that share no point once moved
behind = [-(core.inset(spire, sides)[4] @ (np.cross(np.subtract(spire[b], spire[a]), np.subtract(spire[c], spire[a])) / np.linalg.norm(np.cross(np.subtract(spire[b], spire[a]), np.subtract(spire[c], spire[a])))))
for a, b, c in sides]
self.assertTrue(1.0 - 1e-9 < min(behind) < 1.0 + 1e-9 and max(behind) < 2.0, behind) # the nearest face 1 off, the others further, never nearer
def test_resample_keeps_every_corner_and_fills_between(self):
"""A corner stays a point of the chain, and no two points stand over the step apart."""
line = core.resample([(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 0.5, 0.0)], False, 0.3)
self.assertEqual((len(line), line[0].tolist(), line[4].tolist(), line[-1].tolist()), (7, [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [1.0, 0.5, 0.0]))
self.assertTrue(np.allclose(np.linalg.norm(np.diff(line, axis=0), axis=1), [0.25] * 6, atol=1e-12))
loop = core.resample(self.SQUARE, True, 0.25)
self.assertEqual((len(loop), loop[0].tolist(), loop[4].tolist(), loop[15].tolist()), (16, [0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 0.25, 0.0]))
self.assertEqual(core.resample(self.SQUARE, True, 100.0).tolist(), [list(p) for p in self.SQUARE])
self.assertEqual(len(core.resample(self.SQUARE[:2], False, 100.0)), 2)
doubled = core.resample([(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 0.0, 1e-9), (1.0, 1.0, 0.0)], False, 100.0)
self.assertEqual(len(doubled), 3) # the doubled point is one
for bad in ((self.SQUARE[:1], False, 0.1), (self.SQUARE, True, 0.0), ([(0.0, 0.0, 0.0)] * 2, False, 0.1)):
with self.assertRaisesRegex(core.KitError, "resample"):
core.resample(*bad)
def test_away_is_the_least_distance_to_a_polyline(self):
el = [(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0, 1.0, 0.0)]
self.assertEqual(core.away([(0.5, 0.25, 0.0), (2.0, 0.0, 0.0), (-3.0, 4.0, 0.0), (0.5, 0.5, 0.0)], el, False).tolist(), [0.25, 1.0, 5.0, 0.5])
self.assertAlmostEqual(float(core.away((0.5, 0.75, 0.0), el, True)[0]), 0.25 / math.sqrt(2.0), places=15) # closed, the segment back to the start is nearest
turns = np.linspace(0.0, 6.0 * math.pi, 400) # a spiral of 399 segments, seven blocks of them, and points all over it: a limit changes no value under it
spiral = np.stack([turns * np.cos(turns), turns * np.sin(turns), np.zeros(400)], axis=1)
spots = np.random.default_rng(7).uniform(-20.0, 20.0, (500, 3)) * (1.0, 1.0, 0.0)
lengths = np.linspace(0.0, 2.0, 399)
for closed, less in ((False, 0.0), (True, 0.0), (False, lengths), (True, np.linspace(0.0, 2.0, 400))):
every = core.away(spots, spiral, closed, less)
for limit in (0.0, 1.5):
self.assertEqual(core.away(spots, spiral, closed, less, limit).tolist(), np.minimum(every, limit).tolist()) # mutant A1 (a block's own segments only) reads the limit where another turn is nearer
self.assertTrue((every < 0.0).any() or less is 0.0)
self.assertTrue((every > 1.5).any())
def test_a_band_stands_beside_a_polyline_on_the_side_it_is_told(self):
"""band on a straight run and on a square: the built values. A straight run is built at its two ends only; the
side comes from `inward`, whichever way the polyline runs; inside a square the far edge is clipped to the
smaller square (the points within a set-back of a corner are left out) and the volume is the ring's."""
line, up = [(0.0, 0.0, 0.0), (0.5, 0.0, 0.0), (1.0, 0.0, 0.0)], (0.0, 0.0, 1.0)
for path in (line, line[::-1]):
for side in (1.0, -1.0):
made = core.band(path, False, up, [(0.0, side, 0.0)] * 3, 0.1, 0.2, 0.05)
self.assertTrue(closed_and_oriented(made.shell))
self.assertAlmostEqual(signed_volume(made.shell), 1.0 * 0.2 * 0.05, places=15)
self.assertEqual((made.at.tolist(), len(made.shell.V), len(made.shell.counts)), ([0, 2], 8, 6))
self.assertEqual(sorted(made.outer[:, 1].tolist() + made.centre[:, 1].tolist() + made.inner[:, 1].tolist()), sorted([0.1 * side, 0.2 * side, side * (0.1 + 0.2)] * 2))
self.assertEqual(sorted(set(np.round(made.shell.V[:, 2], 12).tolist())), [-0.025, 0.025])
square = core.resample(self.SQUARE, True, 0.25)
middle = np.array([0.5, 0.5, 0.0])
for path in (square, square[::-1]):
inside = core.band(path, True, up, middle - path, 0.1, 0.2, 0.05)
self.assertTrue(closed_and_oriented(inside.shell))
self.assertAlmostEqual(signed_volume(inside.shell), (0.8 ** 2 - 0.4 ** 2) * 0.05, places=15)
self.assertEqual((len(inside.outer), len(inside.inner)), (16, 8)) # 0.25 from a corner the far edge, set back 0.3, is clipped; the near one, set back 0.1, is not
outside = core.band(path, True, up, path - middle, 0.1, 0.2, 0.05)
self.assertTrue(closed_and_oriented(outside.shell))
self.assertAlmostEqual(signed_volume(outside.shell), (1.6 ** 2 - 1.2 ** 2) * 0.05, places=14)
self.assertEqual((len(outside.outer), len(outside.inner)), (4, 4))
el = core.resample([(-1.0, 0.0, 0.0), (0.0, 0.0, 0.0), (0.0, -1.0, 0.0)], False, 0.05) # a distance for each segment: 0.1 along x, 0.3 along y, inside the right angle
two = core.band(el, False, up, [(-1.0, -1.0, 0.0)] * len(el), [0.1] * 20 + [0.3] * 20, 0.2, 0.05)
self.assertTrue(closed_and_oriented(two.shell))
self.assertAlmostEqual(signed_volume(two.shell), (0.2 * (0.7 + 0.5) / 2.0 + 0.2 * (0.9 + 0.7) / 2.0) * 0.05, places=15) # each edge's corner stands each leg's own distance off it
self.assertIn([-0.3, -0.1, 0.0], two.outer.round(12).tolist())
self.assertIn([-0.5, -0.3, 0.0], two.inner.round(12).tolist())
for edge, length in ((two.outer, 0.7 + 0.9), (two.centre, 0.6 + 0.8), (two.inner, 0.5 + 0.7)):
# an edge runs once along each leg: mutant L1 (the corner the greater distance off both legs) runs 0.2 past the corner and back, mutant V1
# (clipped at a point's own distance) runs the first leg's edge on to 0.1 from the second; mutant W1 (no weld) has the corner twice
self.assertAlmostEqual(float(np.linalg.norm(np.diff(edge, axis=0), axis=1).sum()), length, places=12)
self.assertGreater(float(np.linalg.norm(np.diff(edge, axis=0), axis=1).min()), 1e-9)
self.assertEqual(core.away([(-0.3, -0.1, 0.0), (-0.3, -0.3, 0.0)], [(-1.0, 0.0, 0.0), (0.0, 0.0, 0.0), (0.0, -1.0, 0.0)], False, [0.1, 0.3]).round(12).tolist(), [0.0, 0.0])
with self.assertRaisesRegex(core.KitError, "path point 0: the section leaves a rib no room"):
core.band(square, True, up, middle - square, 0.1, 0.45, 0.05) # 0.55 in from a square 1 wide: nothing is that far from its sides
with self.assertRaisesRegex(core.KitError, "path point 1: the path turns 160.0 degrees there, over 150"):
core.band([(0.0, 0.0, 0.0), (1.0, 0.0, 0.0), (1.0 - math.cos(math.radians(20.0)), math.sin(math.radians(20.0)), 0.0)], False, up, [(0.0, 1.0, 0.0)] * 3, 0.1, 0.2, 0.05)
with self.assertRaisesRegex(core.KitError, "path point 0: the segment from it is shorter than 1e-9"):
core.band([line[0], line[0], line[2]], False, up, [(0.0, 1.0, 0.0)] * 3, 0.1, 0.2, 0.05)
for bad in ((line[:1], False), (line[:2], True)):
with self.assertRaisesRegex(core.KitError, "a band needs"):
core.band(bad[0], bad[1], up, [(0.0, 1.0, 0.0)] * len(bad[0]), 0.1, 0.2, 0.05)
# What a band inside a crease holds, over the area of the true clipped offset, less 1. Bound by
# lodur:ruling:deterministic-bound-margin: shipped 0.0013 (each clipped corner is cut by a chord between points
# 0.01 apart); least claimed mutant 0.079 (C1, nothing clipped: both edges fold through the crease); separation 7.9.
CREASED = 0.0099
def test_a_band_follows_a_crease_tighter_than_it_reaches(self):
"""ribs-fold-at-crease. Two runs of 0.3 that turn 49.4 degrees at each end of a facet of 0.062, as a creased
shell's section does, and a rib from 0.09 to 0.17 inside the turn: both of the facet's offsets are gone (each
end sets them back 0.041 and 0.078), so each edge is the two runs' offsets, met at one corner. No vertex
stands nearer the section than 0.09 or further than 0.17. Mutant C1 reads 0.079 and stands 0.07 off."""
turn, facet, run, near, far = math.radians(49.4), 0.062, 0.3, 0.09, 0.17
section = [(-facet / 2 - run * math.cos(turn), -run * math.sin(turn), 0.0), (-facet / 2, 0.0, 0.0), (facet / 2, 0.0, 0.0), (facet / 2 + run * math.cos(turn), -run * math.sin(turn), 0.0)]
dense = core.resample(section, False, 0.01)
made = core.band(dense, False, (0.0, 0.0, 1.0), [(0.0, -1.0, 0.0)] * len(dense), near, far - near, 0.014)
self.assertTrue(closed_and_oriented(made.shell))
apex = facet / 2 / math.cos(turn) # from each end of the facet to where the two runs' lines meet
area = 2.0 * ((run + apex) * (far - near) - math.tan(turn) * (far ** 2 - near ** 2) / 2.0)
self.assertLess(abs(signed_volume(made.shell) / 0.014 / area - 1.0), self.CREASED)
off = core.away(made.shell.V * (1.0, 1.0, 0.0), section, False)
self.assertGreaterEqual(float(off.min()), near - 1e-15)
self.assertLessEqual(float(off.max()), far + 1e-15)
self.assertEqual((len(made.outer), len(made.centre), len(made.inner)), (12, 8, 4)) # the far edge: an end, the last point before the corner, the first after, an end; the centre line and the near edge also where the edges further in start and stop being clipped
middle = core.away(made.centre, section, False)
self.assertAlmostEqual(float(middle.min()), (near + far) / 2.0, places=15) # the centre line stands half a depth off both edges, so a hole of radius 0.3 of depth on it stays in the rib
self.assertAlmostEqual(float(middle.max()), (near + far) / 2.0, places=15)
def test_spans_bridge_a_break_and_stand_clear_of_a_port(self):
"""spans. Twenty points 0.25 apart, a bridge of 1.25 and a clearance of 0.5. Mutants K5 (bridge ignored: the two-point break splits the run) and K6
(clearance ignored: the run reaches the port's edge points)."""
def flags(*opened):
return [i in opened for i in range(20)]
closed, unclosed = [0.25] * 20, [0.25] * 19
as_lists = lambda found: [run.tolist() for run in found] # noqa: E731
self.assertEqual(as_lists(core.spans(flags(), closed, True, 1.25, 0.5)), [list(range(20))])
self.assertEqual(as_lists(core.spans(flags(), unclosed, False, 1.25, 0.5)), [list(range(20))])
self.assertEqual(core.spans([True] * 20, closed, True, 1.25, 0.5), [])
# a break of two open points is 0.75 between the kept points either side: under the bridge it closes, and the run is whole
self.assertEqual(as_lists(core.spans(flags(7, 8), closed, True, 1.25, 0.5)), [list(range(20))])
self.assertEqual(as_lists(core.spans(flags(7, 8), closed, True, 0.75, 0.0)), [list(range(9, 20)) + list(range(7))]) # as long as the bridge: not closed; the run wraps the start
# a port of six open points (1.75) stays open, and the kept points within 0.5 of it go: two each side
self.assertEqual(as_lists(core.spans(flags(*range(5, 11)), closed, True, 1.25, 0.5)), [list(range(13, 20)) + list(range(3))])
self.assertEqual(as_lists(core.spans(flags(*range(5, 11)), unclosed, False, 1.25, 0.5)), [list(range(0, 3)), list(range(13, 20))]) # an open chain's own ends stand
self.assertEqual(as_lists(core.spans(flags(*range(5, 11)), unclosed, False, 1.25, 0.0)), [list(range(0, 5)), list(range(11, 20))])
# a port across a closed chain's start is one run; an open chain's first points being open is no break to bridge
self.assertEqual(as_lists(core.spans(flags(18, 19, 0, 1, 2, 3), closed, True, 1.25, 0.5)), [list(range(6, 16))])
self.assertEqual(as_lists(core.spans(flags(0, 1), unclosed, False, 1.25, 0.5)), [list(range(4, 20))])
self.assertEqual(as_lists(core.spans(flags(7, 8, *range(12, 18)), closed, True, 1.25, 0.5)), [list(range(0, 10))])
self.assertEqual(core.spans(flags(*range(2, 18)), closed, True, 1.25, 0.5), []) # four kept points, each within 0.5 of the port
with self.assertRaisesRegex(core.KitError, "20 points closed have 20 segments, not 19"):
core.spans(flags(), unclosed, True, 1.25, 0.5)
def test_joined_shells_stand_beside_each_other(self):
a, b = core.sweep(self.BENT, core.profile("box", 0.1, 0.1, 0.01), (0.0, 0.0, 1.0)), core.sweep(self.SQUARE, core.profile("T", 0.1, 0.12, 0.02), (0.0, 0.0, 1.0), closed=True)
both = core.joined([a, b])
self.assertTrue(closed_and_oriented(both))
self.assertAlmostEqual(signed_volume(both), signed_volume(a) + signed_volume(b), places=12)
self.assertEqual((len(both.V), len(both.counts), both.faces[len(a.faces):].min()), (len(a.V) + len(b.V), len(a.counts) + len(b.counts), len(a.V)))
self.assertEqual((len(core.joined([]).V), len(core.joined([]).counts)), (0, 0))
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.boolean", "brokkr_kitbash.cut", "brokkr_kitbash.cut_many", "brokkr_kitbash.apply", "brokkr_kitbash.ribs"]
class HostFileTests(unittest.TestCase):
@ -1226,6 +1509,20 @@ class HostFileTests(unittest.TestCase):
for row in self.document["actions"][4:]:
self.assertTrue(all(field["type"] in ("string", "number") for field in row["fields"]), row["name"])
def test_the_ribs_row_takes_64_planes_and_16_longerons_at_full_precision(self):
"""planes-string-cap-below-64. A float's longest repr is 24 characters (-1.2345678901234567e-05): 64 planes of
them are 11.3 KB and 16 longerons 4.2 KB, each under its cap; the 65th and 17th are the action's to refuse."""
host = [{**row, "host": "brokkr_kitbash"} for row in self.document["actions"]]
long = [-1.2345678901234567e-05] * 3
planes, longerons = json.dumps([{"origin": long, "normal": long}] * 64), json.dumps([{"origin": long, "axis": long, "toward": long}] * 16)
self.assertEqual((len(planes), len(longerons)), (11264, 4176))
intent = {"schema": "brokkr.blender.command_intent.v0", "commandId": "t-1", "requestedBy": "test/driver", "action": "brokkr_kitbash.ribs", "object_name": "Pod",
"ribs_name": "Ribs", "planes": planes, "longerons": longerons}
self.assertEqual(at.validate(intent, host)["planes"], planes)
for field, cap in (("planes", 16000), ("longerons", 8000)):
with self.assertRaisesRegex(Exception, f"{field} must have at most {cap} characters"):
at.validate({**intent, field: "[" + " " * cap}, host)
def test_the_pose_rows_take_scalars_inside_their_bounds(self):
host = [{**row, "host": "brokkr_kitbash"} for row in self.document["actions"]]
envelope = {"schema": "brokkr.blender.command_intent.v0", "commandId": "t-1", "requestedBy": "test/driver", "object_name": "Strut"}
@ -1262,7 +1559,14 @@ class OwnershipTests(unittest.TestCase):
self.assertEqual(sorted(self.sources()), ["__init__.py", "brokkr_actions.json", "core.py", "cutters.v0.json", "mechanical.v0.json"])
for pattern in self.PACKAGE:
for name, text in self.sources().items():
if pattern is self.PACKAGE[2] and name == "__init__.py":
continue
self.assertIsNone(re.search(pattern, text), f"{pattern} in {name}")
# one Manifold Boolean in the package: the rib hole cut inside ribs, on shells ribs built closed and apart; a target's live Booleans stay Exact with self-intersection
source = self.sources()["__init__.py"]
self.assertEqual(re.findall(self.PACKAGE[2], source), ['solver = "MANIFOLD'])
self.assertIn('modifier.solver = "MANIFOLD"', source.split("class BROKKR_KITBASH_OT_ribs(")[1].split("class BROKKR_KITBASH_OT_")[0])
self.assertIn('"COLLECTION", "EXACT", True', source.split("def operation_collection(")[1].split("\n\n\n")[0])
self.assertIsNone(re.search(self.CORE, self.sources()["core.py"], re.M))
schemas = [p for p in (SURFACE.parents[1] / "schemas").rglob("*") if p.is_file()]
self.assertTrue(schemas)
@ -1275,18 +1579,36 @@ class OwnershipTests(unittest.TestCase):
source = self.sources()["__init__.py"]
self.assertEqual(source.count("evaluated_get("), 1)
self.assertIn("evaluated_get(", source.split("def evaluated_of(")[1].split("\n\n\n")[0])
callers = [body.split("(")[0] for body in source.split("class BROKKR_KITBASH_OT_")[1:] if "evaluated_of(" in body]
self.assertEqual(callers, ["boolean", "apply"])
self.assertEqual(source.count("evaluated_of("), 4)
bodies = {body.split("(")[0]: body.split("\n\n\n")[0] for body in source.split("class BROKKR_KITBASH_OT_")[1:]}
self.assertEqual([name for name, body in bodies.items() if "evaluated_of(" in body], ["boolean", "apply", "ribs"])
self.assertEqual(source.count("evaluated_of("), 7) # its def, evaluable, boolean, apply, and ribs for the designed surface, for the plate's two faces and for its holes
self.assertIn("evaluated_of(", source.split("def evaluable(")[1].split("\n\n\n")[0])
place = source.split("def place_cutters(")[1].split("\n\n\n")[0] # cut and cut_many place through it: one evaluation, with the Booleans off
self.assertEqual(place.count("evaluated_of("), 1)
self.assertLess(place.index("modifier.show_viewport = False"), place.index("evaluated_of("))
self.assertLess(place.index("evaluated_of("), place.index("modifier.show_viewport = True"))
self.assertLess(place.index("report(booleans(target)"), place.index("bpy.data.meshes.new(")) # every refusal before any write
self.assertEqual((place.count("evaluable("), place.count("evaluated_of(")), (1, 0))
self.assertLess(place.index("modifier.show_viewport = False"), place.index("evaluable("))
self.assertLess(place.index("evaluable("), place.index("modifier.show_viewport = True"))
# unevaluable-target: every action that evaluates refuses an object Blender does not evaluate before its first write
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")):
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"])
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"))
self.assertLess(ribs.index("modifier.show_viewport = True"), ribs.index("mesh = bpy.data.meshes.new(self.ribs_name)"))
for body in (place, *(source.split(f"class BROKKR_KITBASH_OT_{name}(")[1].split("class BROKKR_KITBASH_OT_")[0] for name in ("cut", "cut_many"))):
self.assertNotIn("view_layer.update", body) # an update after a cutter joins would evaluate the Boolean
self.assertEqual(body.count("place_cutters("), 0 if body is place else 1)
self.assertEqual(source.count("to_mesh("), 1)
self.assertEqual(source.count("to_mesh("), 4) # boolean's report, and in ribs the designed surface, the plate's two faces and the holed webs
def test_only_ribs_writes_kit_ribs(self):
"""kit_ribs is the request a ribs object was derived from: ribs assigns it once and nothing reads it back to
decide geometry."""
source = self.sources()["__init__.py"]
writes = re.findall(r'[^\n]*\[(?:RIBS|"kit_ribs")\]\s*=(?!=)[^\n]*', source)
self.assertEqual(len(writes), 1)
self.assertIn(writes[0], source.split("class BROKKR_KITBASH_OT_ribs(")[1].split("class BROKKR_KITBASH_OT_")[0])
self.assertEqual(len(re.findall(r'\[RIBS\]|\bRIBS\b(?! =)|"kit_ribs"', source)), 2) # the constant's own line, and that write
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