diff --git a/surfaces/blender/experiments/mechs/massing.py b/surfaces/blender/experiments/mechs/massing.py index dd436df..6410922 100644 --- a/surfaces/blender/experiments/mechs/massing.py +++ b/surfaces/blender/experiments/mechs/massing.py @@ -8,6 +8,10 @@ a wall, so plates conform to the mass by construction and step from their neighb Tools here (seraph_body uses each more than once): solid(name, points, faces, frame, ...) a closed cage, subdivided: the mass. Its mesh is in its own frame. + cage(name, sheet, frame, ...) the same from a free-cage sheet as brokkr_kitbash.shell takes one (verts, + faces, creases, mirror): a closed, creased, minimal cage made a mass. + cage_sheet(sheet) is that sheet wound and with its poles declared, and + cage_report(sheet) what the shell action reports of it. ellipsoid / slab cutters (hidden objects) in a mass's frame carve(obj, cutters) wells: an exact Boolean difference, applied plate(name, mass, keep, ...) the mass's surface lifted `proud`, kept inside the half-spaces `keep` @@ -16,6 +20,23 @@ Tools here (seraph_body uses each more than once): Curtain(cam, line, frame) a line traced on the concept as a cut: the solved camera's sight lines along it, so the plate's edge is drawn exactly on the line half(axis, sign, at) a half-space by axis: half("x", -1, 0.3) keeps x >= 0.3 + +Hard plates (a plate whose silhouette the concept draws faceted: mech-lessons-2026-12-03; bastion_body uses each): + + plane(point, normal) / through(a, b, c, out) a face as a half-space (n, d): kept where n.p <= d + corners(planes) the corners of the convex solid a set of faces bounds: every three + faces' meeting point that lies inside all the others. Authoring a + plate by its faces is what keeps every facet flat. + slab_points(at, normal, outline, thick) a hard plate as a thick slab: an outline drawn on its outer face (the + plane through `at` facing `normal`), the face's rim chamfered by `taper` + section_points(sections) a housing's corners from chamfered sections down a limb + hard(name, points, host, ...) a faceted solid on those corners (or any points): flat faces, every + edge chamfered by a bevel; obj["plate_kind"] = "hard" + panel(geo, polygon, ...) a raised inner panel on a flat polygon: inset, lifted, chamfered + clad(obj, geo, ...) detail plating after the main split: every large facet of a hard solid + gets its own raised panel, split in two at varied depths + Face(obj) a flat facet standing in for a surface.Skin, so surface.py's numerals, + emblems, bolt rows and handles land on a hard plate """ import math @@ -62,6 +83,142 @@ def solid(name, points, faces, frame, mat="khaki", levels=1, flat=True): return obj +def _cage_bmesh(sheet): + """(bmesh, crease layer) of a free-cage sheet, mirrored about x where it says so, its faces wound outward.""" + V = [Vector(p) for p in sheet["verts"]] + faces = [list(f) for f in sheet["faces"]] + creases = [tuple(c) for c in sheet.get("creases", ())] + if sheet.get("mirror"): + tol = 0.005 * max(abs(p.x) for p in V) + twin = {} + for i, p in enumerate(list(V)): + if abs(p.x) <= tol: + V[i] = Vector((0.0, p.y, p.z)) + twin[i] = i + else: + twin[i] = len(V) + V.append(Vector((-p.x, p.y, p.z))) + faces += [[twin[i] for i in reversed(f)] for f in faces] + creases += [(twin[a], twin[b], w) for a, b, w in creases if (twin[a], twin[b]) != (a, b)] + bm = bmesh.new() + verts = [bm.verts.new(p) for p in V] + for f in faces: + bm.faces.new([verts[i] for i in f]) + bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:]) + layer = bm.edges.layers.float.new("crease_edge") + bm.verts.ensure_lookup_table() + for a, b, w in creases: + e = bm.edges.get((bm.verts[a], bm.verts[b])) + if e is None: + raise ValueError(f"cage: a crease on no edge ({a}, {b})") + e[layer] = w + return bm, layer + + +def cage_sheet(sheet, inside=None): + """The sheet as brokkr_kitbash.shell takes it: every authored face wound counter-clockwise seen from outside (read + off the cage's recalculated normals; an open cage says where `inside` is, a point its faces look away from) and + its poles declared (the authored vertices whose valence is not 4 off the boundary, not 2 or 3 on it).""" + bm, _ = _cage_bmesh(sheet) + n = len(sheet["verts"]) + out = dict(sheet) + if inside is not None and sum(f.normal.dot(f.calc_center_median() - Vector(inside)) * f.calc_area() for f in bm.faces) < 0: + bmesh.ops.reverse_faces(bm, faces=bm.faces[:]) + out["faces"] = [[v.index for v in f.verts] for f in bm.faces[:len(sheet["faces"])]] + bm.verts.ensure_lookup_table() + out["poles"] = [i for i in range(n) if len(bm.verts[i].link_edges) not in ((2, 3) if bm.verts[i].is_boundary else (4,))] + bm.free() + return out + + +def cage_stats(sheet): + """{"verts" (authored), "all_verts" (mirrored), "edges", "creased", "crease_share", "poles" {valence: count}, + "triangles"} of the cage as built.""" + bm, layer = _cage_bmesh(sheet) + poles = {} + for v in bm.verts: + if len(v.link_edges) != 4: + poles[len(v.link_edges)] = poles.get(len(v.link_edges), 0) + 1 + out = {"verts": len(sheet["verts"]), "all_verts": len(bm.verts), "faces": len(bm.faces), "edges": len(bm.edges), "creased": sum(1 for e in bm.edges if e[layer] > 0), + "poles": poles, "triangles": sum(1 for f in bm.faces if len(f.verts) == 3), "closed": all(e.is_manifold for e in bm.edges)} + out["crease_share"] = out["creased"] / out["edges"] + bm.free() + return out + + +def cage(name, sheet, frame, mat="khaki", levels=3, flat=True): + """A free cage made a mass: Catmull-Clark `levels` times with its creases, applied. Closed where the cage is.""" + bm, _ = _cage_bmesh(sheet) + obj = _object(name, bm, mat, frame) + mod = obj.modifiers.new("Subdivision", "SUBSURF") + mod.levels = mod.render_levels = levels + mod.use_creases = True + M.bake(obj) + for p in obj.data.polygons: + p.use_smooth = not flat + return obj + + +def cage_through(sheet, levels=3, rounds=5): + """The sheet with its vertices moved until the subdivided surface passes through the points it was authored at: + a Catmull-Clark surface lies inside its cage, by a tenth of its size on a cage this coarse, so a cage authored + on the concept's outline builds a mass a tenth too small. Each round moves every vertex by what its surface + point misses (a subdivided mesh keeps the cage's vertices first, in order).""" + want = [Vector(p) for p in sheet["verts"]] + out = dict(sheet, verts=[list(p) for p in sheet["verts"]]) + for _ in range(rounds): + obj = cage("Cage.through", out, Matrix.Identity(4), levels=levels) + got = [obj.data.vertices[i].co.copy() for i in range(len(want))] + bpy.data.objects.remove(obj, do_unlink=True) + out["verts"] = [list(Vector(p) + (w - g)) for p, w, g in zip(out["verts"], want, got)] + if sheet.get("mirror"): + out["verts"] = [[0.0 if abs(w.x) < 1e-6 else p[0], p[1], p[2]] for p, w in zip(out["verts"], want)] + return out + + +def cage_shell(name, sheet, host=None, to_host=None, mat="khaki", thickness=0.1, levels=2, bevel=0.02, inside=(0, 0, 0)): + """A sculpted plate as a minimal free cage, by brokkr_kitbash.shell: the sheet in its own frame, the object + parented to `host` at `to_host`. Prints the cage's count (CAGE). Returns the object.""" + import json + result = bpy.ops.brokkr_kitbash.shell(object_name=name, sheet=json.dumps(cage_sheet(sheet, inside)), thickness=thickness, levels=levels, bevel=bevel, count_folds=True) + if "FINISHED" not in result: + raise SystemExit(f"cage_shell {name}: {result}") + report = json.loads(getattr(bpy.context.window_manager, M.KB.RESULT)) + stats = cage_stats_open(sheet) + print("CAGE", name, json.dumps({"authored": len(sheet["verts"]), "cageVerts": report["cageVerts"], "cageFaces": report["cageFaces"], "creases": report["creases"], "crease_share": round(stats, 3), + "poles": report["poles"], "folded": report["folded"]}), flush=True) + obj = bpy.data.objects[name] + if host is not None: + obj.parent = host + obj.matrix_parent_inverse = Matrix.Identity(4) + obj.matrix_local = Matrix(to_host) if to_host is not None else Matrix.Identity(4) + M.assign(obj, mat) + for p in obj.data.polygons: + p.use_smooth = False + return obj + + +def cage_stats_open(sheet): + """The share of the cage's edges that carry a crease (the rim's own weight not counted).""" + bm, layer = _cage_bmesh(sheet) + share = sum(1 for e in bm.edges if e[layer] > 0) / max(len(bm.edges), 1) + bm.free() + return share + + +def cage_report(sheet, thickness=0.05, levels=2): + """What brokkr_kitbash.shell reports of the cage (it refuses an unsound one, naming the fault): the action's own + count of vertices, faces, creases and poles. The shell it makes is removed.""" + import json + name = "Cage.report" + result = bpy.ops.brokkr_kitbash.shell(object_name=name, sheet=json.dumps(cage_sheet(sheet)), thickness=thickness, levels=levels) + if "FINISHED" not in result: + raise SystemExit(f"cage_report: {result}") + report = json.loads(getattr(bpy.context.window_manager, M.KB.RESULT)) + bpy.data.objects.remove(bpy.data.objects[name], do_unlink=True) + return {key: report.get(key) for key in ("cageVerts", "cageFaces", "triangles", "creases", "poles", "closed", "subdividedFaces")} + + def _cutter(name, bm, frame): obj = _object(name, bm, "frame", frame) obj.hide_render = obj.hide_viewport = True @@ -212,3 +369,200 @@ def plate(name, mass, keep, proud=0.06, wall=0.08, mat="khaki", cutters=(), beve lo, hi = (min(v.co[k] for v in obj.data.vertices) for k in range(3)), (max(v.co[k] for v in obj.data.vertices) for k in range(3)) print(f"PLATE {name}: {len(obj.data.polygons)} faces, " + " ".join(f"{a:.2f}..{b:.2f}" for a, b in zip(lo, hi)), flush=True) return obj + + +# --- hard plates --------------------------------------------------------------------------------------------------------- +def plane(point, normal): + """A face through `point` whose outward normal is `normal`: (n, d), kept where n.p <= d.""" + n = Vector(normal).normalized() + return (n, n.dot(Vector(point))) + + +def through(a, b, c, out): + """The face through three points, its outward side the one `out` points to.""" + a, b, c = Vector(a), Vector(b), Vector(c) + n = (b - a).cross(c - a).normalized() + if n.dot(Vector(out)) < 0: + n = -n + return (n, n.dot(a)) + + +def moved(face, by): + """A face moved `by` metres along its outward normal (negative: inward).""" + return (face[0], face[1] + by) + + +def corners(planes, tol=1e-6): + """The corners of the convex solid bounded by `planes` [(n, d)]: each three faces' meeting point that is inside + every other face. An unbounded or empty set of faces is an error, not a guess.""" + out = [] + P = [(Vector(n), float(d)) for n, d in planes] + for i in range(len(P)): + for j in range(i + 1, len(P)): + for k in range(j + 1, len(P)): + m = Matrix((P[i][0], P[j][0], P[k][0])) + if abs(m.determinant()) < 1e-7: + continue + p = m.inverted() @ Vector((P[i][1], P[j][1], P[k][1])) + if p.length < 1e3 and all(n.dot(p) <= d + tol for n, d in P) and not any((p - q).length < 1e-5 for q in out): + out.append(p) + if len(out) < 4: + raise ValueError(f"massing.corners: {len(planes)} faces bound no solid ({len(out)} corners)") + return out + + +def plane_basis(normal, up=(0, 0, 1), right=None): + """(a, b, n): unit axes of the plane facing `normal`: b the in-plane part of `up`, a across it, turned to the + side `right` points to where one is given (so an outline's +a is a named direction on either side of a mech).""" + n = Vector(normal).normalized() + b = Vector(up) - n * n.dot(Vector(up)) + if b.length < 1e-6: + raise ValueError("massing.plane_basis: up lies along the normal") + b.normalize() + a = b.cross(n) + if right is not None and a.dot(Vector(right)) < 0: + a = -a + return a, b, n + + +def slab_points(at, normal, outline, thick, taper=0.04, up=(0, 0, 1), right=None, back=1.0): + """The corners of a hard plate authored as a slab: `outline` [(a, b)] is its outer face, drawn on the plane + through `at` facing `normal` (plane_basis); the face's rim is chamfered `taper` wide and deep; the back face + stands `thick` behind, its outline scaled by `back` about the middle (under 1: a plate undercut to its seat).""" + a, b, n = plane_basis(normal, up, right) + at = Vector(at) + flat = [Vector((x, y)) for x, y in outline] + area = 0.5 * sum(flat[i].x * flat[(i + 1) % len(flat)].y - flat[(i + 1) % len(flat)].x * flat[i].y for i in range(len(flat))) + ring = flat if area > 0 else flat[::-1] + inner = M._inset(ring, taper) if taper else ring + out = [at + a * p.x + b * p.y for p in inner] + if taper: + out += [at + a * p.x + b * p.y - n * taper for p in ring] + out += [at + a * p.x * back + b * p.y * back - n * thick for p in ring] + return out + + +def ring8(w, y0, y1, c): + """A chamfered rectangle's eight corners: w across x, from y0 to y1.""" + return [(-w / 2 + c, y0), (w / 2 - c, y0), (w / 2, y0 + c), (w / 2, y1 - c), (w / 2 - c, y1), (-w / 2 + c, y1), (-w / 2, y1 - c), (-w / 2, y0 + c)] + + +def section_points(sections): + """A housing's corners from its sections down a limb: [(z, width, y0, y1, chamfer)].""" + return [(x, y, z) for z, w, y0, y1, c in sections for x, y in ring8(w, y0, y1, c)] + + +def hard(name, points, host=None, mat="olive", mirror=False, bevel=0.03, sx=1): + """A hard plate or block: the faceted convex solid on `points` (massing.corners of its faces, or corners given + outright), every facet flat, every edge chamfered `bevel` wide. `sx` -1 builds its mirror across x; `mirror` + one solid across the centre line from its right half.""" + g = M.Geo() + g.hull([(sx * Vector(p).x, Vector(p).y, Vector(p).z) for p in points], mirror=mirror) + bmesh.ops.dissolve_limit(g.bm, angle_limit=math.radians(0.5), verts=g.bm.verts[:], edges=g.bm.edges[:]) + obj = g.to_object(name, mat, host, 1.0) + if bevel: + mod = obj.modifiers.new("Bevel", "BEVEL") + mod.width, mod.segments, mod.limit_method, mod.angle_limit = bevel, 1, "ANGLE", math.radians(12) + for p in obj.data.polygons: + p.use_smooth = False + obj["plate_kind"] = "hard" + return obj + + +def _clip(poly, point, normal): + """A convex polygon (3D points in one plane) kept on the side of a line the normal points away from.""" + out = [] + for i, a in enumerate(poly): + b = poly[(i + 1) % len(poly)] + da, db = (a - point).dot(normal), (b - point).dot(normal) + if da <= 0: + out.append(a) + if (da < 0) != (db < 0) and abs(da - db) > 1e-9: + out.append(a + (b - a) * (da / (da - db))) + return out + + +def panel(geo, polygon, lift=0.05, inset=0.1, chamfer=0.02, out=None, sink=0.02, bolts=None, bolt_r=0.028): + """A raised inner panel on a flat convex polygon (3D points, either winding): the polygon moved in `inset` on + every edge, standing `lift` proud, its outer rim chamfered. `bolts` is a Geo that takes a hex head inside each + of the panel's corners. Returns its frame (z the outward normal), or None for a polygon too small to take one.""" + P = [Vector(p) for p in polygon] + c = sum(P, Vector()) / len(P) + n = sum(((P[i] - c).cross(P[(i + 1) % len(P)] - c) for i in range(len(P))), Vector()) + if n.length < 1e-9: + return None + n.normalize() + if out is not None and n.dot(Vector(out)) < 0: + P.reverse() + n = -n + frame = M.frame_at(c, n) + inv = frame.inverted() + flat = [(inv @ p).to_2d() for p in P] + inner = M._inset(flat, inset) + area = lambda q: 0.5 * sum(q[i].x * q[(i + 1) % len(q)].y - q[(i + 1) % len(q)].x * q[i].y for i in range(len(q))) # noqa: E731 + if area(inner) < 0.25 * area(flat) or area(inner) < 0.02: + return None + geo.prism(frame @ Matrix.Translation((0, 0, -sink)), inner, lift + sink, chamfer) + if bolts is not None: + for q in M._inset(inner, 3.2 * bolt_r): + bolts.cylinder(frame @ Matrix.Translation((q.x, q.y, lift + 0.3 * bolt_r)), bolt_r, 0.6 * bolt_r, 6) + return frame + + +def facets(obj, min_area=0.6): + """The flat facets of a hard solid's own mesh, in its frame: [(points, normal, area)], largest first.""" + out = [] + for p in obj.data.polygons: + if p.area >= min_area: + out.append(([obj.data.vertices[i].co.copy() for i in p.vertices], p.normal.copy(), p.area)) + return sorted(out, key=lambda f: -f[2]) + + +def clad(obj, geo, keep=None, min_area=0.9, lifts=(0.045, 0.075), inset=0.11, gap=0.05, split=2.2, seed=0, bolts=None): + """Detail plating on a hard solid, after the main split: each facet of at least `min_area` (and passing + `keep(normal, centre)`) takes a raised panel; a facet over `split` square metres is cut in two across its + longest side at an uneven share, the two panels at different lifts. Geometry goes into `geo`, in the solid's + frame; `bolts` is a Geo for the panels' corner bolts. Returns the number of panels made.""" + import random + rnd = random.Random(seed) + made = 0 + for pts, n, area in facets(obj, min_area): + c = sum(pts, Vector()) / len(pts) + if keep and not keep(n, c): + continue + if area > split: + k = max(range(len(pts)), key=lambda i: (pts[(i + 1) % len(pts)] - pts[i]).length) + a, b = pts[k], pts[(k + 1) % len(pts)] + way = (b - a).normalized() + at = a + (b - a) * rnd.uniform(0.36, 0.64) + parts = [_clip(pts, at - way * gap / 2, way), _clip(pts, at + way * gap / 2, -way)] + else: + parts = [pts] + order = list(lifts) if rnd.random() < 0.5 else list(reversed(lifts)) + for i, part in enumerate(parts): + if len(part) >= 3 and panel(geo, part, lift=order[i % len(order)], inset=inset, out=n, bolts=bolts) is not None: + made += 1 + return made + + +class Face: + """A hard plate's flat facet standing in for a surface.Skin: surface.py's numeral, emblem, bolt_row, rivet_row, + grab_handle and lifting_eye take it. Frames are in the plate object's own frame; done() makes the geometry.""" + + def __init__(self, obj, mat="olive"): + self.obj, self.name, self.mat = obj, obj.name, mat + self.geos, self.decals, self.count = {}, [], 0 + + def frame(self, point, normal, up=(0, 0, 1)): + return M.frame_at(point, normal, up) + + def sub(self, frame, x, y, roll=0.0, z=0.0): + return frame @ Matrix.Translation((x, y, z)) @ Matrix.Rotation(math.radians(roll), 4, "Z") + + def geo(self, mat=None): + return self.geos.setdefault(mat or self.mat, M.Geo()) + + def done(self, smooth=32.0): + made = [g.to_object(f"{self.name}.fit.{mat}", mat, self.obj, smooth) for mat, g in self.geos.items() if len(g.bm.verts)] + self.geos = {} + return made + self.decals diff --git a/surfaces/blender/experiments/mechs/mechlib.py b/surfaces/blender/experiments/mechs/mechlib.py index abb3006..4b3a327 100644 --- a/surfaces/blender/experiments/mechs/mechlib.py +++ b/surfaces/blender/experiments/mechs/mechlib.py @@ -723,8 +723,9 @@ def _turn_and_stretch(name, to_host): def shell_action(name, sheet, build, mat, thickness=0.05, offset=-1.0, levels=3, bevel=0.0): - """A faceted, hollow plate by brokkr_kitbash.shell on a Build's host: `sheet` is its document ({rings, closed, - mirror, creases, rim, flip}) in the component's frame. The shell is parented to build.host and stands where + """A faceted, hollow plate by brokkr_kitbash.shell on a Build's host: `sheet` is its document, a loft ({rings, + closed, mirror, creases, rim, flip}) or a free cage ({verts, faces, creases, corners, poles, mirror, rim, flip}), + in the component's frame. The shell is parented to build.host and stands where Build.done puts a Geo: the turn and move of build.to_host are the object's matrix, and its sizes and mirror are written into the ring points, since the kitbash actions cut and rib only an unscaled object. A mirror reverses `flip`, so the wall stays on the plate's inside; on a sheet that is itself mirrored about x it changes nothing. A @@ -736,16 +737,20 @@ def shell_action(name, sheet, build, mat, thickness=0.05, offset=-1.0, levels=3, turn, stretch = _turn_and_stretch(name, Matrix.Identity(4) if build.to_host is None else Matrix(build.to_host)) sx, sy, sz = (stretch[k][k] for k in range(3)) sheet = dict(sheet) - if sheet.get("mirror"): - sheet["rings"] = [[[abs(sx) * p[0], sy * p[1], sz * p[2]] for p in ring] for ring in sheet["rings"]] # the cage is its own mirror image about x + mx = abs(sx) if sheet.get("mirror") else sx # a mirrored cage is its own mirror image about x + if "verts" in sheet: + sheet["verts"] = [[mx * p[0], sy * p[1], sz * p[2]] for p in sheet["verts"]] else: - sheet["rings"] = [[[sx * p[0], sy * p[1], sz * p[2]] for p in ring] for ring in sheet["rings"]] - if sx < 0: - sheet["flip"] = not sheet.get("flip", False) + sheet["rings"] = [[[mx * p[0], sy * p[1], sz * p[2]] for p in ring] for ring in sheet["rings"]] + if mx < 0: + sheet["flip"] = not sheet.get("flip", False) result = bpy.ops.brokkr_kitbash.shell(object_name=name, sheet=json.dumps(sheet), thickness=thickness, offset=offset, levels=levels, bevel=bevel, count_folds=True) if "FINISHED" not in result: raise SystemExit(f"shell {name}: {result}") - FOLDED[name] = json.loads(getattr(bpy.context.window_manager, KB.RESULT))["folded"] + report = json.loads(getattr(bpy.context.window_manager, KB.RESULT)) + FOLDED[name] = report["folded"] + if "verts" in sheet: + print("CAGE", name, json.dumps({key: report[key] for key in ("cageVerts", "cageFaces", "triangles", "creases", "poles", "closed", "subdividedFaces", "facing")}), flush=True) if FOLDED[name]: print(f"FOLD {name}: {FOLDED[name]} inner faces of the wall fold at thickness {thickness:g}, levels {levels}", flush=True) obj = bpy.data.objects[name] @@ -759,6 +764,44 @@ def shell_action(name, sheet, build, mat, thickness=0.05, offset=-1.0, levels=3, return obj +def cage_wire(shell, width=0.012): + """Three objects drawn over a shell, children of it, for a picture of its cage: the cage's uncreased edges as dark + rods, its creased edges (the rim's included, where the rim carries a weight) as thicker red ones, and a yellow + ball on each pole (a vertex whose valence is not 4 off the boundary, or not 2 or 3 on it). Read from the cage mesh + and its crease_edge attribute as brokkr_kitbash.shell wrote them. Returns the objects, for the caller to remove.""" + cage = shell.data + weights = cage.attributes["crease_edge"].data + made = [] + for label, color, creased, depth in (("edges", (0.01, 0.01, 0.01), False, width), ("creases", (1.0, 0.02, 0.02), True, 1.6 * width)): + curve = bpy.data.curves.new(f"{shell.name}.wire.{label}", "CURVE") + curve.dimensions, curve.bevel_depth, curve.bevel_resolution = "3D", depth, 2 + for edge in cage.edges: + if (weights[edge.index].value > 0) == creased: + spline = curve.splines.new("POLY") + spline.points.add(1) + for point, v in zip(spline.points, edge.vertices): + point.co = (*cage.vertices[v].co, 1.0) + made.append((bpy.data.objects.new(curve.name, curve), color)) + bm = bmesh.new() + bm.from_mesh(cage) + balls = bmesh.new() + for v in bm.verts: + if len(v.link_edges) not in ((2, 3) if v.is_boundary else (4,)): + bmesh.ops.create_icosphere(balls, subdivisions=2, radius=3.0 * width, matrix=Matrix.Translation(v.co)) + bm.free() + mesh = bpy.data.meshes.new(f"{shell.name}.wire.poles") + balls.to_mesh(mesh) + balls.free() + made.append((bpy.data.objects.new(mesh.name, mesh), (1.0, 0.8, 0.0))) + for obj, color in made: + paint = bpy.data.materials.get("wire." + obj.name.rsplit(".", 1)[-1]) or material("wire." + obj.name.rsplit(".", 1)[-1], color, 0.0, 0.6, emission=(color, 1.5)) + obj.data.materials.append(paint) + obj.parent = shell + bpy.context.scene.collection.objects.link(obj) + update() + return [obj for obj, _ in made] + + def shells_sound(): """Every shell shell_action made, as built: the folded inner faces the action counted, and the edges of its whole evaluated stack (wall, cuts, bevel) that do not join exactly two faces. Prints a line a shell and the totals, diff --git a/surfaces/blender/experiments/mechs/paint.py b/surfaces/blender/experiments/mechs/paint.py index d69f1cb..4b9f4fc 100644 --- a/surfaces/blender/experiments/mechs/paint.py +++ b/surfaces/blender/experiments/mechs/paint.py @@ -7,9 +7,10 @@ The hook, after a mech is built and before it is rendered: import paint; paint.apply("seraph") -apply(preset, ground=0.0, objects=None, scale=1.0, **overrides) swaps, by material name, every armour paint for -the preset's paint, every bare-metal material for its metal, every marking for its worn stencil; it leaves glass, -rubber, glows and pits alone; called again with another preset it repaints. Returns {old material name: new material}. `ground` is the world height of the +apply(preset, ground=0.0, objects=None, scale=1.0, roles=None, glass="smoked", lens="lens", **overrides) swaps, by material name, every armour paint for +the preset's paint, every bare-metal material for its metal, every marking for its worn stencil, every glass for +a MechGlass (glass="smoked" on panes, lens="lens" on optics under `lens_below` metres across); it leaves rubber, +glows and pits alone; called again with another preset it repaints. Returns {old material name: new material}. `ground` is the world height of the soles (mud and wet are measured from it); `scale` multiplies every noise frequency (a mech half as tall wants 2). An override is any MechPaint input by its lower-case name with underscores, e.g. apply("mcr3", wear=1.4); it reaches the armour and the markings, not the bare metal (material() tunes one role alone). @@ -18,11 +19,35 @@ PRESETS seraph (cleaner, warm drab: 30.webp), mcr3 (grey drab, middli breaker (dark, heavy wear, mud to the knee: 24.webp), paladin (27.webp), kestrel (29.webp). material(name, role="armour", preset="seraph", **overrides) one material of a preset: role is armour, metal, mark or hazard. +glass(name, preset="smoked", **overrides) + one MechGlass material. GLASS: smoked (a near-black canopy pane: RAPTOR, 38.webp), amber (a + dark amber dome: WYVERN, 35.webp), faceted (smoked, broken into panes by a dark lattice), + lens (a coated blue optic), lens_amber (a laser's or lamp's warm optic). +shield(objects=None, lights=None) + light-links the glass out of the stage's area lights; only a glass with Reflect over 0 needs it. +mirrored(*matrices) + True where a chain of frames (4x4 or 3x3) reverses handedness: what a marking placed in it + must be flipped by to read left to right. surface.decal asks it of the plate and the frame. + +Why glass is its own group, and why it does not mirror the scene. mechlib.stage_field lights a mech with three +square area lights, the key 5 scene radii across at 4 radii: half the sky over a canopy. A smooth dielectric +mirrors that key at Fresnel strength, and the key's radiance is many times the sky's, so any glossy pane turned +up or forward renders pale whatever its colour. Measured on WYVERN pass 2's canopy (wyvern.blend, 16 samples, mean +scene-linear radiance of the pane): 0.236 as built (roughness 0.3, coat 0.15); 0.061 with the key hidden from +glossy rays; 0.037 under the world alone; 0.406 with mechlib's own "glass" (roughness 0.04, coat 1). Transmission, +the light path and the missing interior play no part: the pane is opaque, and with its specular off it renders +(0.012, 0.005, 0.002) brown. So MechGlass keeps Cycles' specular off (Reflect 0) and paints its reflection as +emission, from the reflected ray alone: a horizon-bright overcast sky in banks, a dark ground, a small sun's glint, all at +Fresnel strength. It reads the same on any stage. Reflect over 0 brings Cycles' own reflections back +(the mech's frames in the pane); then call shield() once the stage's lights exist, or the pane goes pale again. group() the MechPaint node group (built once per file). Its layers, bottom up: base paint Base Color, toned per plate by Object Info's Random and Geometry's Random Per Island (value, and a little hue and saturation: Tone Variation), mottled by two world-space noises (Mottle). cover a marking's own colour over the paint (Cover Color, Cover); Cover Wear opens it, by Alpha, to - the plate under the decal, in specks and in patches. + the plate under the decal, in specks and in patches. Legibility (0 to 2) lifts the marking back + out of the film, streaks and dust laid over it, brightens it past 1 and closes part of the + wear; chips and mud still take it. 0 is the paint of the first pass, where a number under + breaker's grime could not be read at figure scale. cavity grime Ambient Occlusion (4 samples, 0.45 m) darkens recesses, seams and the undersides of overhangs, and a thin film lies in patches on open faces (Grime, Grime Color). streaks noise stretched along world Z, on faces that stand upright, stronger where AO says something @@ -50,6 +75,7 @@ INPUTS = { "Cover Color": ("NodeSocketColor", (0.2, 0.19, 0.165, 1.0)), "Cover": ("NodeSocketFloat", 0.0), "Cover Wear": ("NodeSocketFloat", 0.5), + "Legibility": ("NodeSocketFloat", 0.0), "Grime": ("NodeSocketFloat", 1.0), "Grime Color": ("NodeSocketColor", (0.02, 0.017, 0.013, 1.0)), "Streaks": ("NodeSocketFloat", 1.0), @@ -75,32 +101,33 @@ PRESETS = { # SERAPH, 30.webp: a warm grey drab, the cleanest of the sheets; small chips, light streaks, mud on the feet only. "seraph": {"armour": {"base_color": (0.066, 0.056, 0.038), "wear": 0.85, "grime": 0.8, "streaks": 0.8, "dust": 0.6, "mud": 0.8, "mud_top": 1.2, "wet_top": 2.0}, "metal": {**_METAL, "wear": 0.6, "mud": 0.8, "mud_top": 1.2}, - "mark": {"cover_color": (0.22, 0.21, 0.18), "cover_wear": 0.55}}, + "mark": {"cover_color": (0.3, 0.29, 0.25), "cover_wear": 0.5, "legibility": 0.8}}, # MCR-3, 25.webp: greyer and darker, every plate chipped along its edges, streaked, dirty to the shin. "mcr3": {"armour": {"base_color": (0.048, 0.044, 0.034), "wear": 1.0, "grime": 1.0, "streaks": 1.0, "dust": 0.45, "mud": 1.0, "mud_top": 1.4, "wet_top": 2.4, "tone_variation": 0.32}, "metal": {**_METAL, "wear": 0.9}, - "mark": {"cover_color": (0.2, 0.195, 0.175), "cover_wear": 0.5}}, + "mark": {"cover_color": (0.3, 0.29, 0.26), "cover_wear": 0.45, "legibility": 0.9}}, # BREAKER, 24.webp: the same drab two stops down, the heaviest wear on any sheet, mud to the knee. "breaker": {"armour": {"base_color": (0.03, 0.028, 0.021), "wear": 1.5, "grime": 1.3, "streaks": 1.3, "dust": 0.35, "mud": 1.3, "mud_top": 2.2, "wet_top": 4.0, "tone_variation": 0.35, "primer_color": (0.12, 0.11, 0.09)}, "metal": {**_METAL, "wear": 1.3, "grime": 1.5, "mud": 1.3, "mud_top": 2.2}, - "mark": {"cover_color": (0.19, 0.18, 0.15), "cover_wear": 0.75}}, + "mark": {"cover_color": (0.3, 0.285, 0.24), "cover_wear": 0.6, "legibility": 0.75}}, # PALADIN, 27.webp: an olive greener than SERAPH's, middling wear. "paladin": {"armour": {"base_color": (0.05, 0.052, 0.033), "wear": 0.9, "grime": 0.9, "streaks": 0.9}, "metal": {**_METAL, "wear": 0.8}, - "mark": {"cover_wear": 0.5}}, + "mark": {"cover_color": (0.3, 0.29, 0.25), "cover_wear": 0.5, "legibility": 0.8}}, # KESTREL, 29.webp: a light grey-green scout paint, thin wear, long streaks. "kestrel": {"armour": {"base_color": (0.06, 0.062, 0.048), "wear": 0.8, "grime": 0.9, "streaks": 1.2, "mud_top": 1.0}, "metal": {**_METAL, "wear": 0.7}, - "mark": {"cover_wear": 0.5}}, + "mark": {"cover_color": (0.3, 0.29, 0.25), "cover_wear": 0.5, "legibility": 0.8}}, } ROLES = { "armour": {"khaki", "olive", "olive_light", "plate_olive", "plate_white", "plate_grey", "plate_sand", "drab", "drab_fit", "drab_dark", "drab_dark_fit"}, "metal": {"gunmetal", "frame", "machine", "structure", "plate_dark"}, "mark": {"stencil", "marking", "marking_fresh"}, "hazard": {"hazard", "accent_yellow"}, + "glass": {"glass", "canopy", "wyvern_canopy", "optic"}, } -HAZARD = {"cover_color": (0.32, 0.2, 0.025), "cover_wear": 0.7} +HAZARD = {"cover_color": (0.32, 0.2, 0.025), "cover_wear": 0.7, "legibility": 0.5} class _Net: @@ -163,11 +190,22 @@ class _Net: return node.outputs[0] +def _current(name, inputs): + """The file's node group of this name if its inputs are this module's, else a new, empty one: a .blend painted + by an older paint.py keeps its group under .old, for whatever still uses it.""" + old = bpy.data.node_groups.get(name) + if old and [i.name for i in old.interface.items_tree if i.item_type == "SOCKET" and i.in_out == "INPUT"] == list(inputs): + return old + if old: + old.name = name + ".old" + return bpy.data.node_groups.new(name, "ShaderNodeTree") + + def group(): """The MechPaint node group; built on first call, then the one in the file.""" - if GROUP in bpy.data.node_groups: - return bpy.data.node_groups[GROUP] - tree = bpy.data.node_groups.new(GROUP, "ShaderNodeTree") + tree = _current(GROUP, INPUTS) + if tree.nodes: + return tree for name, (kind, default) in INPUTS.items(): s = tree.interface.new_socket(name, in_out="INPUT", socket_type=kind) s.default_value = default @@ -197,10 +235,11 @@ def group(): shade = n.math("ADD", n.math("ADD", n.ramp(blotch, 0.3, 0.7, (-0.3, 0.3)), n.ramp(speck, 0.3, 0.7, (-0.2, 0.2))), n.ramp(n.noise(pos, 6.0, 5.0, 0.7), 0.3, 0.7, (-0.22, 0.22))) col = n.vec("SCALE", hsv.outputs["Color"], scale=n.math("MULTIPLY_ADD", shade, G["Mottle"], 1.0)) # a marking's own colour over it, worn through by Alpha - col = n.mix(col, n.vec("SCALE", G["Cover Color"], scale=n.ramp(n.noise(pos, 7.0, 4.0), 0.3, 0.7, (0.6, 1.05))), G["Cover"]) + cover = n.vec("SCALE", G["Cover Color"], scale=n.ramp(n.noise(pos, 7.0, 4.0), 0.3, 0.7, (0.6, 1.05))) + col = n.mix(col, cover, G["Cover"]) fine_lo, patch_lo = n.ramp(G["Cover Wear"], 0.0, 1.0, (0.7, 0.46)), n.ramp(G["Cover Wear"], 0.0, 1.0, (0.82, 0.46)) gone = n.math("MAXIMUM", n.ramp(n.noise(pos, 38.0, 3.0, 0.6, 1.2), fine_lo, n.math("ADD", fine_lo, 0.03)), n.ramp(n.noise(pos, 4.5, 5.0), patch_lo, n.math("ADD", patch_lo, 0.05))) - alpha = n.math("SUBTRACT", 1.0, n.mul(gone, n.math("MINIMUM", G["Cover"], 1.0)), clamp=True) + alpha = n.math("SUBTRACT", 1.0, n.mul(gone, n.math("MINIMUM", G["Cover"], 1.0), n.ramp(G["Legibility"], 0.0, 2.0, (1.0, 0.3))), clamp=True) # cavity grime ao = tree.nodes.new("ShaderNodeAmbientOcclusion") @@ -224,6 +263,8 @@ def group(): # dust on what looks up dust = n.mul(n.ramp(up, 0.45, 0.95), n.ramp(n.noise(pos, 3.0, 6.0, 0.7), 0.25, 0.7, (0.25, 1.0)), G["Dust"], 0.6, clamp=True) col = n.mix(col, G["Dust Color"], dust) + # legibility: the marking's paint lifted back out of the film, streaks and dust; chips and mud below still take it + col = n.mix(col, n.vec("SCALE", cover, scale=n.ramp(G["Legibility"], 1.0, 2.0, (1.0, 1.7))), n.mul(G["Cover"], G["Legibility"], clamp=True)) # edge wear: chips to metal with a primer ring, scuffs on open faces bevel = tree.nodes.new("ShaderNodeBevel") @@ -262,11 +303,195 @@ def group(): return tree -def _input_name(key): - for name in INPUTS: +GLASS_GROUP = "MechGlass" +GLASS_INPUTS = { + "Tint": ("NodeSocketColor", (0.006, 0.007, 0.008, 1.0)), # the pane's own colour, seen where nothing shows through + "Interior": ("NodeSocketFloat", 0.5), # how much of Interior Color shows where the eye looks straight in + "Interior Color": ("NodeSocketColor", (0.01, 0.011, 0.012, 1.0)), + "Roughness": ("NodeSocketFloat", 0.04), + "Reflect": ("NodeSocketFloat", 0.0), # Cycles' own specular, 1 a plain dielectric: see shield() + "Sky": ("NodeSocketFloat", 2.2), # 1 is the physical reflection of the sky; the sheets paint it stronger + "Sky Color": ("NodeSocketColor", (0.58, 0.61, 0.67, 1.0)), # stage_field's world: (0.5, 0.53, 0.58) at 1.15 + "Clouds": ("NodeSocketFloat", 1.0), # the reflected sky broken into banks, so a reflection has a shape + "Ground Color": ("NodeSocketColor", (0.06, 0.055, 0.05, 1.0)), + "Glint": ("NodeSocketFloat", 1.0), + "Glint Direction": ("NodeSocketVector", (0.35, 0.5, 0.8)), # toward the sun, in the world: high over the mech's front left, where the hero views stand + "Glint Size": ("NodeSocketFloat", 0.006), # 1 - cos of the sun's half angle: 0.006 is 6 degrees + "Facets": ("NodeSocketFloat", 0.0), # panes a metre; 0 is one pane + "Facet Tilt": ("NodeSocketFloat", 0.1), + "Mullion": ("NodeSocketFloat", 0.02), # the lattice bar's width, metres + "Mullion Color": ("NodeSocketColor", (0.003, 0.003, 0.003, 1.0)), + "Dirt": ("NodeSocketFloat", 1.0), + "Dirt Color": ("NodeSocketColor", (0.03, 0.028, 0.023, 1.0)), + "Scale": ("NodeSocketFloat", 1.0), +} +GLASS_OUTPUTS = {"Color": "NodeSocketColor", "Roughness": "NodeSocketFloat", "Specular": "NodeSocketFloat", "Normal": "NodeSocketVector", "Emission": "NodeSocketColor"} +_LENS = {"roughness": 0.02, "interior": 1.0, "dirt": 0.5} +GLASS = { + # RAPTOR, 38.webp, RECESSED COCKPIT: near-black panes in an armour lattice, a pale sky low on each, no interior. + "smoked": {}, + # WYVERN, 35.webp, COCKPIT & SENSOR CANOPY: a dark amber dome, the amber showing where the eye looks in. + "amber": {"tint": (0.006, 0.0025, 0.001), "interior": 1.0, "interior_color": (0.02, 0.0062, 0.0012)}, + # one blown pane read as a lattice of flat ones: for a canopy built as a single dome with no frames of its own. + "faceted": {"facets": 3.5, "facet_tilt": 0.12, "mullion": 0.022}, + # a coated optic: a blue-violet depth, a cold reflection (WYVERN's projector and helmet sensor; RAPTOR's emitters). + "lens": {**_LENS, "tint": (0.004, 0.005, 0.012), "interior_color": (0.0015, 0.005, 0.022), "sky_color": (0.3, 0.45, 0.95), "sky": 1.2}, + "lens_amber": {**_LENS, "tint": (0.012, 0.005, 0.002), "interior_color": (0.02, 0.0055, 0.0008), "sky_color": (0.95, 0.6, 0.3), "sky": 1.2}, +} + + +def glass_group(): + """The MechGlass node group; built on first call, then the one in the file. See the module header for why its + reflection is painted. Its layers: the pane (Tint, Interior Color where the view is square to it, broken by a + slow noise); facets (a Voronoi lattice in the object's frame: each cell's normal tilted its own way, a bar of + Mullion Color on the cell borders); dirt (Ambient Occlusion puts it in the corners a frame makes, a noise on + what looks up); the painted reflection (sky above the reflected horizon, brightest at it and broken into banks by Clouds; ground below; a + sun's disc and halo about Glint Direction), at Fresnel strength for IOR 1.5, dimmed by the dirt.""" + tree = _current(GLASS_GROUP, GLASS_INPUTS) + if tree.nodes: + return tree + for name, (kind, default) in GLASS_INPUTS.items(): + tree.interface.new_socket(name, in_out="INPUT", socket_type=kind).default_value = default + for name, kind in GLASS_OUTPUTS.items(): + tree.interface.new_socket(name, in_out="OUTPUT", socket_type=kind) + n = _Net(tree) + gin, gout = tree.nodes.new("NodeGroupInput"), tree.nodes.new("NodeGroupOutput") + G = gin.outputs + geo, coords = tree.nodes.new("ShaderNodeNewGeometry"), tree.nodes.new("ShaderNodeTexCoord") + own = n.vec("SCALE", coords.outputs["Object"], scale=G["Scale"]) + + def z_of(vector): + node = tree.nodes.new("ShaderNodeSeparateXYZ") + tree.links.new(vector, node.inputs[0]) + return node.outputs["Z"] + + # facets: a tilt a cell, a bar on the borders + on = n.ramp(G["Facets"], 0.0, 0.01) + cells = n.vec("SCALE", own, scale=G["Facets"]) + lattice = {} + for feature in ("F1", "DISTANCE_TO_EDGE"): + node = tree.nodes.new("ShaderNodeTexVoronoi") + node.voronoi_dimensions, node.feature = "3D", feature + node.inputs["Scale"].default_value, node.inputs["Randomness"].default_value = 1.0, 0.75 + tree.links.new(cells, node.inputs["Vector"]) + lattice[feature] = node + tilt = n.vec("SCALE", n.vec("SUBTRACT", lattice["F1"].outputs["Color"], (0.5, 0.5, 0.5)), scale=n.mul(G["Facet Tilt"], on, 2.0)) + normal = n.vec("NORMALIZE", n.vec("ADD", geo.outputs["Normal"], tilt)) + half = n.mul(G["Mullion"], G["Facets"], 0.5) + bar = n.mul(n.ramp(lattice["DISTANCE_TO_EDGE"].outputs["Distance"], n.math("MULTIPLY_ADD", half, 1.25, 0.002), half), on) + + # dirt: in the corners a frame makes, and on what looks up + ao = tree.nodes.new("ShaderNodeAmbientOcclusion") + ao.samples, ao.inputs["Distance"].default_value = 4, 0.22 + patchy = n.ramp(n.noise(own, 6.0, 5.0, 0.7), 0.3, 0.65, (0.35, 1.0)) + corner = n.mul(n.ramp(ao.outputs["AO"], 0.9, 0.45), patchy) + settled = n.mul(n.ramp(z_of(geo.outputs["Normal"]), 0.35, 0.95), n.ramp(n.noise(own, 2.2, 6.0, 0.7), 0.35, 0.7, (0.05, 0.45))) + dirt = n.mul(n.math("MAXIMUM", corner, settled), G["Dirt"], clamp=True) + + # the pane: its tint, the interior's colour where the eye looks straight in + facing = tree.nodes.new("ShaderNodeLayerWeight") + facing.inputs["Blend"].default_value = 0.5 + tree.links.new(normal, facing.inputs["Normal"]) + square = n.math("POWER", n.math("SUBTRACT", 1.0, facing.outputs["Facing"], clamp=True), 3.0) + inside = n.mul(square, G["Interior"], n.ramp(n.noise(own, 2.6, 3.0, 0.5), 0.3, 0.7, (0.35, 1.0)), clamp=True) + col = n.mix(G["Tint"], G["Interior Color"], inside) + col = n.mix(col, G["Mullion Color"], bar) + col = n.mix(col, G["Dirt Color"], n.math("MULTIPLY", dirt, 0.8)) + + # the painted reflection, from the reflected ray + ray = n.vec("REFLECT", n.vec("SCALE", geo.outputs["Incoming"], scale=-1.0), normal) + rz = z_of(ray) + banks = n.noise(n.vec("MULTIPLY", ray, (1.6, 1.6, 4.0)), 1.0, 3.0, 0.55, 0.6) + banks = n.math("MULTIPLY_ADD", n.math("SUBTRACT", n.ramp(banks, 0.4, 0.62, (0.3, 1.45)), 1.0), G["Clouds"], 1.0) + sky = n.vec("SCALE", G["Sky Color"], scale=n.mul(n.ramp(rz, -0.06, 0.04), n.ramp(rz, 0.0, 0.75, (1.25, 0.4)), banks, G["Sky"])) + env = n.mix(n.vec("SCALE", G["Ground Color"], scale=G["Sky"]), sky, n.ramp(rz, -0.06, 0.04)) + toward = n.vec("DOT_PRODUCT", ray, n.vec("NORMALIZE", G["Glint Direction"])) + edge = n.math("SUBTRACT", 1.0, G["Glint Size"]) + disc = n.math("POWER", n.ramp(toward, n.math("MULTIPLY_ADD", G["Glint Size"], -3.0, edge), 1.0), 3.0) + halo = n.math("POWER", n.ramp(toward, 0.6, 1.0), 10.0) + sun = n.mul(n.math("ADD", n.math("MULTIPLY", disc, 7.0), n.math("MULTIPLY", halo, 0.4)), G["Glint"]) + env = n.vec("ADD", env, n.vec("SCALE", (1.0, 0.96, 0.9), scale=sun)) + fresnel = tree.nodes.new("ShaderNodeFresnel") + fresnel.inputs["IOR"].default_value = 1.5 + tree.links.new(normal, fresnel.inputs["Normal"]) + clear = n.mul(n.math("SUBTRACT", 1.0, n.math("MULTIPLY", dirt, 0.6)), n.math("SUBTRACT", 1.0, bar)) + painted = n.vec("SCALE", env, scale=n.mul(fresnel.outputs[0], clear, n.math("SUBTRACT", 1.0, G["Reflect"], clamp=True))) + + tree.links.new(col, gout.inputs["Color"]) + tree.links.new(n.math("ADD", G["Roughness"], n.math("MAXIMUM", n.math("MULTIPLY", dirt, 0.55), n.math("MULTIPLY", bar, 0.5)), clamp=True), gout.inputs["Roughness"]) + tree.links.new(n.mul(G["Reflect"], 0.5, n.math("SUBTRACT", 1.0, n.math("MULTIPLY", dirt, 0.6))), gout.inputs["Specular"]) + tree.links.new(normal, gout.inputs["Normal"]) + tree.links.new(painted, gout.inputs["Emission"]) + return tree + + +def glass(name, preset="smoked", **overrides): + """One MechGlass material: GLASS[preset], then `overrides` (MechGlass inputs, lower case with underscores).""" + values = {**GLASS[preset], **overrides} + mat = bpy.data.materials.get(name) or bpy.data.materials.new(name) + mat.use_nodes = True + nodes, links = mat.node_tree.nodes, mat.node_tree.links + nodes.clear() + out, bsdf, grp = nodes.new("ShaderNodeOutputMaterial"), nodes.new("ShaderNodeBsdfPrincipled"), nodes.new("ShaderNodeGroup") + grp.node_tree = glass_group() + for key, value in values.items(): + socket = grp.inputs[_input_name(key, GLASS_INPUTS)] + socket.default_value = value if isinstance(value, (int, float)) or len(value) == len(socket.default_value) else (*value, 1.0) + for a, b in (("Color", "Base Color"), ("Roughness", "Roughness"), ("Specular", "Specular IOR Level"), ("Normal", "Normal"), ("Emission", "Emission Color")): + links.new(grp.outputs[a], bsdf.inputs[b]) + bsdf.inputs["Emission Strength"].default_value = 1.0 + links.new(bsdf.outputs[0], out.inputs[0]) + tint = values.get("tint", GLASS_INPUTS["Tint"][1]) + mat.diffuse_color = (*tint[:3], 1.0) + mat["paint_role"], mat["paint_glass"] = "glass", preset + return mat + + +_make_glass = glass # apply() has a parameter of that name + + +def shield(objects=None, lights=None): + """Light-link glass out of the stage's softboxes, so a pane with Reflect over 0 mirrors the world and the mech + and not a key light half the sky across (the module header has the measurement). objects: default every + object whose only material is a MechGlass; lights: default every area light in the scene. Call it after the + stage's lights exist; call it again after adding glass. Returns the objects shielded. An object that also + carries another material is left alone and named: linking is per object, and its paint needs the lights.""" + scene = bpy.context.scene + lights = lights or [o for o in scene.objects if o.type == "LIGHT" and o.data.type == "AREA"] + if objects is None: + objects = [o for o in scene.objects if o.type == "MESH" and any(s.material and s.material.get("paint_role") == "glass" for s in o.material_slots)] + mixed = [o.name for o in objects if any(not s.material or s.material.get("paint_role") != "glass" for s in o.material_slots)] + if mixed: + print("SHIELD left alone, glass beside another material:", ", ".join(mixed), flush=True) + objects = [o for o in objects if o.name not in mixed] + group_ = bpy.data.collections.get("paint.shielded") or bpy.data.collections.new("paint.shielded") + for obj in list(group_.objects): + group_.objects.unlink(obj) + for obj in objects: + group_.objects.link(obj) + for entry in group_.collection_objects: + entry.light_linking.link_state = "EXCLUDE" + for light in lights: + light.light_linking.receiver_collection = group_ if objects else None + return objects + + +def mirrored(*matrices): + """True where the product of these frames (4x4 or 3x3, outermost first) reverses handedness: a reflection in + the object's world matrix, in a Build's to_host, or in a frame written for the other side. A marking laid in + such a chain reads right to left until its own x is reversed; surface.decal does that.""" + sign = 1.0 + for m in matrices: + sign *= (m.to_3x3() if len(m) == 4 else m).determinant() + return sign < 0.0 + + +def _input_name(key, table=None): + table = INPUTS if table is None else table + for name in table: if name.lower().replace(" ", "_") == key: return name - raise KeyError(f"MechPaint has no input {key!r}; it has " + ", ".join(k.lower().replace(" ", "_") for k in INPUTS)) + raise KeyError(f"no input {key!r}; there are " + ", ".join(k.lower().replace(" ", "_") for k in table)) def material(name, role="armour", preset="seraph", **overrides): @@ -298,8 +523,11 @@ def material(name, role="armour", preset="seraph", **overrides): return mat -def apply(preset="seraph", ground=0.0, objects=None, scale=1.0, roles=None, **overrides): - """Repaint a built mech: see the module header. `roles` adds or moves material names, {name: role}.""" +def apply(preset="seraph", ground=0.0, objects=None, scale=1.0, roles=None, glass="smoked", lens="lens", lens_below=0.3, **overrides): + """Repaint a built mech: see the module header. `roles` adds or moves material names, {name: role}; a role of + None leaves that material alone. glass, lens: the GLASS preset (or a dict of MechGlass inputs, over "smoked" + unless it names a "preset") for panes and for optics, an optic being a glass object under `lens_below` metres + across at scale 1.""" role_of = {name: role for role, names in ROLES.items() for name in names} role_of.update(roles or {}) made, swapped = {}, {} @@ -307,11 +535,20 @@ def apply(preset="seraph", ground=0.0, objects=None, scale=1.0, roles=None, **ov if obj.type not in {"MESH", "CURVE", "FONT"} or obj.get("stage"): continue for slot in obj.material_slots: - role = slot.material and (slot.material.get("paint_role") or role_of.get(slot.material.name)) # a painted mech can be repainted + role = slot.material and role_of.get(slot.material.name, slot.material.get("paint_role")) # a painted mech can be repainted if not role: continue - if role not in made: - made[role] = material(f"paint_{preset}_{role}", role, preset, ground_z=ground, scale=scale, **({} if role == "metal" else overrides)) - swapped[slot.material.name] = made[role] - slot.material = made[role] + key = role + if role == "glass": + key = "lens" if max(obj.dimensions) * scale < lens_below else "pane" + if key not in made: + if role == "glass": + which = lens if key == "lens" else glass + made[key] = _make_glass(f"paint_glass_{key}", **({"preset": which} if isinstance(which, str) else which), scale=scale) + else: + made[key] = material(f"paint_{preset}_{role}", role, preset, ground_z=ground, scale=scale, **({} if role == "metal" else overrides)) + swapped[slot.material.name] = made[key] + slot.material = made[key] + if any(m.get("paint_role") == "glass" and m.node_tree.nodes["Group"].inputs["Reflect"].default_value > 0 for m in made.values()): + shield() return swapped diff --git a/surfaces/blender/experiments/mechs/raptor.py b/surfaces/blender/experiments/mechs/raptor.py index 93db1cc..40dc961 100644 --- a/surfaces/blender/experiments/mechs/raptor.py +++ b/surfaces/blender/experiments/mechs/raptor.py @@ -1,21 +1,20 @@ """RAPTOR: the operator's concept sheet (images/38.webp), its second hero (images/43.webp) and its design prompt, -built mass first. Third pass. +fourth pass: hard plates. -The character is the body's side profile: one long curve from the nose's low tip up the canopy, over the back and -along the raised equipment spine to the tail. raptor_trace.py takes it off the sheet's SIDE view; raptor_solve.py -solves the cameras (side, hero, image 43) and the hero views' poses; raptor_form.py blocks the hull's cage under the -curve; raptor_body.hull_mass builds it as ONE sculpted mass and fits its dorsal run and its chine to their traces -through the solved side camera (brokkr_reference: the trace fit), then laps the plates over it; the legs are -digitigrade.py's kit chain (hip, knee, hock, ankle), re-posed for each view; balance.py reads the centre of mass -against the feet in the standing pose. +The character is the body's side profile: one long line from the nose's low tip up the canopy, over the back and +along the raised equipment spine to the tail, over a slim wedge. raptor_trace.py takes it off the sheet's SIDE view; +raptor_solve.py solves the cameras (side, hero, image 43) and the hero views' poses; raptor_form.py holds the wedge's +sections and its plates; raptor_body builds every plate HARD, by its faces, over a dark core, with an open underbody; +the legs are digitigrade.py's kit chain (hip, knee, hock, ankle), re-posed for each view; balance.py reads the centre +of mass against the feet in the standing pose. -RAPTOR_STAGE stops the build early: volume (the fitted mass and the legs' cores alone), plates, full (default). +RAPTOR_STAGE stops the build early: volume (the wedge's core and the legs' cores alone), plates, full (default). MECH_QUICK renders by Workbench. RAPTOR_VIEWS names the views to render (side,front,rear,hero,balance,v43); RAPTOR_NO_DETAIL, _NO_EDGES and _NO_PARTS skip the detail pass, the built edges and the components' photographs. Writes under MECH_OUT/raptor/: _.png (each at its camera, the concept's own pixels), _sil_.png, _profile.png, _edges_side.json, full_edges_v43.json, _turn_*.png, part_.png, -raptor_skeleton.json, raptor_joints.json (the kit's joints reports), raptor_cages.json (the free cages' counts), -raptor_fit.json (the trace fit), raptor_plates.json (the plates' outlines as built) and raptor_balance.json.""" +raptor_skeleton.json, raptor_joints.json (the kit's joints reports), raptor_hard.json (every hard solid, the +counts of panels and fittings), raptor_plates.json (the plates' outlines) and raptor_balance.json.""" import json, math, os, sys, time from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) @@ -45,30 +44,27 @@ cams = RF.cameras() if "side_solved" in cams: cams["side"] = dict(cams["side"], **{k: cams["side_solved"][k] for k in ("C", "R", "f", "c", "distance", "model", "rms")}) cams["side"] = RB.near(cams["side"]) # the solved camera, levelled and drawn in: Blender's lens stops at 5000 mm and the stage's ground hides a camera under it -mass = RB.hull_mass(P if AT < 1 else RB.CORE, cam=cams["side"]) -(OUT / "raptor_fit.json").write_text(json.dumps(RB.FIT, indent=1), encoding="utf-8") +core = RB.hull_core(P if AT < 1 else RB.CORE) cores = RB.leg_cores(P if AT < 2 else RB.CORE) body = None if AT >= 1: - RB.hull_core() - torso = RB.hull_plates() + RB.beak() + import surface as S + S.materials() + torso = RB.hull_plates() + RB.canopy() + RB.beak() + RB.dorsal_spine() (OUT / "raptor_plates.json").write_text(json.dumps(RB.PLATES), encoding="utf-8") - if AT >= 2 and not os.environ.get("RAPTOR_NO_DETAIL"): - RB.detail() - print("detail s", round(time.time() - t0, 1), flush=True) - print("FROZEN", RB.freeze(torso + [mass]), "hull plates; s", round(time.time() - t0, 1), flush=True) - (OUT / "raptor_cages.json").write_text(json.dumps(RB.CAGES, indent=1), encoding="utf-8") + print("FROZEN", RB.freeze(torso), "hull objects; s", round(time.time() - t0, 1), flush=True) if AT >= 2: body = RB.full(cores) (OUT / "raptor_joints.json").write_text(json.dumps(RB.JOINTS, indent=1), encoding="utf-8") - (OUT / "raptor_cages.json").write_text(json.dumps(RB.CAGES, indent=1), encoding="utf-8") for root, rep in RB.JOINTS.items(): for j in rep.get("joints", []): print(f"JOINT {root}: {j.get('part')} {j.get('mechanism')} {j.get('kind')} value {j.get('value'):.1f} limits {j.get('limits')}", flush=True) -if RB.CAGES: - hull = [v for k, v in RB.CAGES.items() if k.startswith("Torso.")] - print(f"CAGES: {len(RB.CAGES)} free cages; hull {len(hull)} cages, {sum(v['verts'] for v in hull)} vertices, crease share {sum(v['creased'] for v in hull) / sum(v['edges'] for v in hull):.3f}; " - f"all {sum(v['creased'] for v in RB.CAGES.values()) / sum(v['edges'] for v in RB.CAGES.values()):.3f}", flush=True) +if AT >= 1: + kinds = {name: RF.KINDS.get(name.rstrip("LR"), "hard") for name in RB.HARD} + (OUT / "raptor_hard.json").write_text(json.dumps({"hard": RB.HARD, "kinds": kinds, "count": RB.COUNT, "soft": [k for k, v in kinds.items() if v != "hard"]}, indent=1), encoding="utf-8") + print(f"HARD: {len(RB.HARD)} hard solids, {RB.COUNT['panels']} detail panels, {RB.COUNT['fits']} fittings, {RB.COUNT['marks']} markings, {RB.COUNT['hoses']} hoses; soft plates: 0", flush=True) + for f in RB.COUNT["failed"]: + print(" FIT FAILED", f, flush=True) M.update() M.reskin({"frame": "gunmetal", "machine": "gunmetal", "structure": "gunmetal", "olive": "khaki"}) lo, hi = M.bounds() @@ -95,9 +91,12 @@ if body is not None: (OUT / "raptor_skeleton.json").write_text(json.dumps({"world": {p: {k: list(v) for k, v in RF.joints(p).items()} for p in RF.POSES}, "views": report}, indent=1), encoding="utf-8") if not QUICK: import paint - paint.apply("breaker") + paint.apply("mcr3", glass="faceted", legibility=1.7) # the 27 is read at figure scale: the marking lifted out of the grime rig, cam, centre, radius = M.stage_field(8 if QUICK else int(os.environ.get("MECH_SAMPLES", 48))) scene = bpy.context.scene +GROUND = bpy.data.objects.get("Ground") +M.material("ground_flat", (0.17, 0.165, 0.155), 0.0, 0.92) +MUD = GROUND.data.materials[0] if GROUND else None def pose(tag): @@ -121,6 +120,8 @@ VIEWS = [v for v in os.environ.get("RAPTOR_VIEWS", "side,front,rear,hero,balance HULL_BOX = [176, 650, 432, 765] for tag in VIEWS: pose(tag) + if GROUND: # a square-on camera 400 m off sees the mud's noise edge on, as stripes: those views stand on plain ground + GROUND.data.materials[0] = bpy.data.materials["ground_flat"] if tag in ("side", "balance", "front", "rear") else MUD if tag not in cams: continue cam.data.clip_start = max(0.1, cams[tag]["distance"] - 40.0) @@ -142,6 +143,8 @@ for tag in VIEWS: print("edges s", round(time.time() - t0, 1), flush=True) pose("side") cam.data.clip_start = 0.1 +if GROUND: + GROUND.data.materials[0] = MUD if STAGE == "full" and not os.environ.get("RAPTOR_NO_PARTS"): for name, (target, spanned, az, el) in RB.COMPONENTS.items(): M.closeup(rig, cam, Vector(target), spanned, az, el, OUT / f"part_{name}.png", size=(600, 600) if QUICK else (760, 760)) diff --git a/surfaces/blender/experiments/mechs/raptor_body.py b/surfaces/blender/experiments/mechs/raptor_body.py index 0700b26..9e29a58 100644 --- a/surfaces/blender/experiments/mechs/raptor_body.py +++ b/surfaces/blender/experiments/mechs/raptor_body.py @@ -1,15 +1,25 @@ -"""RAPTOR's parts (concept sheet images/38.webp, second hero images/43.webp), built mass first from the numbers in -raptor_form.py. One function a part; each returns its objects. Metres at the sheet's 6.8 m. Third pass. +"""RAPTOR's parts (concept sheet images/38.webp, second hero images/43.webp), fourth pass: every plate HARD, authored +by its bounding faces (the method of nibu/fable-bastion-2's bastion_form and nibu/fable-paladin-3's paladin_hard), +with stepped, bolted detail panels and fittings on top. One function a part. Metres at the sheet's 6.8 m. -Order of the build, which raptor.py follows and can stop after any step of (RAPTOR_STAGE): - volume hull_mass: ONE sculpted mass from the nose to the spine's tip, a mirrored free cage creased down the - dorsal line and along a chine a side; both runs fitted to their traces on the sheet's side view through - the side camera (brokkr_reference.core.fit_sheet: the trace fit); the legs' cores on the skeleton - plates hull_plates: the armour and glazing as free cages lapped over the mass, each cage vertex found on the - mass's own built surface (surf) - full the skeleton as kit joints (digitigrade.py), each link's sculpted armour (limb_shell: free cages), the - upper legs' actuators, the bearings, the feet (feet.raptor_claws), the arms, the lasers and the dorsal - battery from the weapons library, the rear equipment spine (cooling stacks, jump-jet nacelles) +The third pass's hull was one soft cage down to the belly's trace with free-cage plates lapped on it, and it read as +a rounded pod with a deep belly. None of that is kept. The hull here is a slim wedge (raptor_form.section): a dark +hard core, hard slabs over it each on its own plane at its own lift, a framed canopy over the whole front, and an +OPEN underbody: a narrow keel with ribs, pipes, tanks and hoses, nothing plated under the lip. + +Tools here, each used by more than one part: + slab(name, frame, outline, ...) a hard plate as a slab on a frame (z its outward normal): massing.hard on the + outline's chamfered face, its rim and its back + dress(obj, frame, ring, mat, ...) what stands on a slab's face: massing.clad's stepped, bolted panels and the + fits (bolt rows, handles, eyes, louvres, ports, numerals through + surface.numeral so a mirrored plate reads left to right) + wedge_plate(spec, side) a raptor_form.H plate: the plane through its corners on the wedge + limb(prefix, tag, sx, a, b, table) a link's hard armour in the link's frame: housings by section, slabs by face + block(name, pts, ...) / box_pts chamfered equipment blocks with detail panels + +Order of the build (RAPTOR_STAGE): volume (the wedge's core and the legs' cores), plates (the hull's plates, canopy, +beak, dorsal spine), full (underbody, skeleton as kit joints by digitigrade.py, limb armour, bearings, actuators, +feet, arms, lasers, battery, the rear equipment pack). The hull is authored in its own coordinates (raptor_form.SHEET) and stood in the world by OFF; W(yh) is a hull station's world y. @@ -31,19 +41,18 @@ T = Matrix.Translation I4 = Matrix.Identity(4) OFF = Matrix(RF.OFF) CORE = "gunmetal" -P = "khaki" -FIT = {} # the trace fit's report (hull_mass) -PLATES = {} # each hull plate's outline as built, hull coordinates: what the plate map draws -CAGES = {} # free-cage plates as built: {name: {"verts", "authored", "faces", "edges", "creased", "share", "poles"}} +P, P2 = RF.P1, RF.P2 +PLATES = {} # each hull plate's outline as built, hull coordinates (yh, z): what the plate map draws +HARD = {} # every hard solid's report: kind, corners, facets JOINTS = {} # the kit's joints reports, by root +COUNT = {"solids": 0, "panels": 0, "fits": 0, "marks": 0, "hoses": 0, "failed": []} +RZ = lambda d: Matrix.Rotation(math.radians(d), 4, "Z") # noqa: E731 def W(yh): return yh - RF.SHIFT - - def freeze(objects): """brokkr_kitbash.freeze on each finished object that has modifiers: its evaluated mesh becomes its mesh.""" n = 0 @@ -52,8 +61,6 @@ def freeze(objects): try: bpy.ops.brokkr_kitbash.freeze(object_name=o.name) n += 1 - if o.name in CAGES: - M.shade(o, 30.0) # a cage's facets and walls read flat; only its own soft turns are smoothed except RuntimeError as error: print(f"FREEZE {o.name}: {str(error).strip()[:160]}", flush=True) return n @@ -64,181 +71,380 @@ def faceted(obj, angle=14.0): return obj -def _shell(name, sheet, thickness, levels): - result = bpy.ops.brokkr_kitbash.shell(object_name=name, sheet=json.dumps(sheet), thickness=thickness, offset=-1.0, levels=levels, bevel=0.0, count_folds=True) - if "FINISHED" not in result: - raise SystemExit(f"shell {name}: {result}") - return json.loads(getattr(bpy.context.window_manager, M.KB.RESULT)) +# --- hard plates --------------------------------------------------------------------------------------------------------- + +def _ccw(flat): + area = 0.5 * sum(flat[i].x * flat[(i + 1) % len(flat)].y - flat[(i + 1) % len(flat)].x * flat[i].y for i in range(len(flat))) + return flat if area > 0 else flat[::-1] -def hull_mass(mat=P, cam=None): - """SIDE view, the whole body: ONE sculpted mass (raptor_form.hull_cage: 74 authored vertices, two hard runs). - The cage is blocked under the trace, built, and its dorsal run and its chine are then fitted to their traces on - the sheet's side view through `cam` (brokkr_reference.core.fit_sheet, the arithmetic of the fit_shell action: - each built run pulled onto its trace, accepted only where the built runs explain every trace) and the shell is - rebuilt from the fitted sheet. The dorsal run lies on the mirror plane, which decides its depth; the chine is - one trace of one half square-on, so its half-width stays the blocking's (the FRONT view's) and only its height - is the trace's: FIT says so per point. Returns the object; SURF is its built surface, for the plates.""" - import sys - if str(M.SURFACE) not in sys.path: - sys.path.append(str(M.SURFACE)) - from brokkr_reference import core as REF - c = RF.hull_cage() - name = "Torso.mass" - poles = poles_of(c["verts"], c["faces"], True) - sheet = {"verts": [list(map(float, v)) for v in c["verts"]], "faces": [list(f) for f in c["faces"]], "creases": [list(cr) for cr in c["creases"]], "poles": poles, "mirror": True, "rim": 0, "corners": []} - _shell(name, sheet, 0.08, 3) - obj = bpy.data.objects[name] - obj.matrix_world = OFF - M.update() - if cam is not None: - book = RF.BOOK["side"] - traces = [{"run": {"verts": c["dorsal"]}, "side": 1, "line": book["curve"]}, {"run": {"verts": c["chine"]}, "side": 1, "line": book["chine"]}] - parsed = M.KB.core.sheet(sheet) - try: - fit = REF.fit_sheet(sheet, parsed, np.array(OFF), traces, [cam, cam], share=0.1) - except REF.ReferenceFitError as error: - raise SystemExit(f"TRACE FIT refused: {error}") - moved = [p["moved_m"] for p in fit["points"]] - FIT.update(traces=[dict(t, run=n) for t, n in zip(fit["traces"], ("dorsal", "chine"))], points=fit["points"], moved_max_m=max(moved), moved_mean_m=float(np.mean(moved)), camera=cam.get("model")) - print("TRACE FIT", json.dumps(FIT["traces"]), "moved max", round(max(moved), 3), "mean", round(float(np.mean(moved)), 3), "worst prior_share dorsal", - max(p["prior_share"] for p in fit["points"] if p["vertex"] in c["dorsal"]), "chine", max(p["prior_share"] for p in fit["points"] if p["vertex"] in c["chine"]), flush=True) - sheet = fit["sheet"] - rep = _shell(name, sheet, 0.08, 3) - else: - rep = _shell(name, sheet, 0.08, 3) - M.assign(obj, mat) - M.shade(obj, 40.0) - edges = len(_edges(_built(sheet["verts"], sheet["faces"], True))) - creased = rep.get("creases") - CAGES[name] = {"authored": len(sheet["verts"]), "verts": rep.get("cageVerts"), "faces": rep.get("cageFaces"), "triangles": rep.get("triangles"), "edges": edges, "creased": creased, "share": round(creased / edges, 3), - "poles": rep.get("poles"), "folded": rep.get("folded")} - print(f"CAGE {name}: {CAGES[name]}", flush=True) - _survey(obj, sheet["verts"]) +def _hard(name, pts, mat, bevel, frame=None): + obj = MS.hard(name, pts, None, mat, bevel=bevel) + if frame is not None: + obj.matrix_world = Matrix(frame) + HARD[name] = {"kind": "hard", "corners": len(obj.data.vertices), "facets": len(obj.data.polygons)} + COUNT["solids"] += 1 return obj -SURF = {} +def slab(name, frame, outline, thick, mat=P, taper=0.035, back=0.94, bevel=0.012, gap=0.0, world=None): + """A hard plate as a slab: `outline` [(x, y)] on `frame`'s xy plane is its outer face (z the outward normal), + drawn in `gap`, the face's rim chamfered `taper`, the back face `thick` behind and scaled `back` about the + middle. `world` stands the object. Returns (object, the face's ring as drawn).""" + ring = _ccw([Vector(p) for p in outline]) + if gap: + ring = M._inset(ring, gap) + inner = M._inset(ring, taper) + mid = sum(ring, Vector((0.0, 0.0))) / len(ring) + pts = [frame @ Vector((p.x, p.y, 0.0)) for p in inner] + [frame @ Vector((p.x, p.y, -taper)) for p in ring] + pts += [frame @ Vector((mid.x + (p.x - mid.x) * back, mid.y + (p.y - mid.y) * back, -thick)) for p in ring] + return _hard(name, pts, mat, bevel, world), inner -def _survey(obj, verts): - """Read the mass's built outer surface (the Subdivision alone, the wall hidden for the reading) into a BVH, in - the hull's coordinates, and keep the fitted cage's sections: what surf() answers from.""" - import bmesh - from mathutils.bvhtree import BVHTree - wall = obj.modifiers["Kit Solidify"] - wall.show_viewport = False - bm = bmesh.new() - bm.from_object(obj, bpy.context.evaluated_depsgraph_get()) - wall.show_viewport = True - SURF["bvh"] = BVHTree.FromBMesh(bm) - SURF["bm"] = bm - v = np.array(verts, float) - SURF["rings"] = np.vstack([np.repeat(v[:1], RF.PER, 0)[None], v[1:-1].reshape(-1, RF.PER, 3), np.repeat(v[-1:], RF.PER, 0)[None]]) # nose to tail; the tips as collapsed sections - SURF["ys"] = SURF["rings"][:, 0, 1] - M.update() +def _geo_out(geos, obj): + made = [] + for mat, g in geos.items(): + if len(g.bm.verts): + o = g.to_object(f"{obj.name}.fit.{mat}", mat, obj, 1.0 if mat in (P, P2) else 30.0) + if mat in (P, P2): + mod = o.modifiers.new("Bevel", "BEVEL") + mod.width, mod.segments, mod.limit_method, mod.angle_limit = 0.009, 1, "ANGLE", math.radians(20) + for p in o.data.polygons: + p.use_smooth = False + made.append(o) + return made -def surf(yh, t, lift=0.0): - """(x, yh, z) on the mass's built surface at station yh, column t (0 dorsal, 1 deck edge, 2 shoulder, 3 chine, - 4 bilge, 5 keel), lifted `lift` along the surface's normal there. The cage's own point at (yh, t) is found by - interpolation and the surface's nearest point to it is taken.""" - rings, ys = SURF["rings"], SURF["ys"] - yh = min(max(yh, ys[-1] + 0.02), ys[0] - 0.02) - i = int(np.searchsorted(-ys, -yh)) - 1 - i = min(max(i, 0), len(ys) - 2) - f = (ys[i] - yh) / max(ys[i] - ys[i + 1], 1e-9) - ring = rings[i] + f * (rings[i + 1] - rings[i]) - j = min(int(math.floor(t)), RF.PER - 2) - q = ring[j] + (t - j) * (ring[j + 1] - ring[j]) - loc, normal, _, _ = SURF["bvh"].find_nearest(Vector(q)) - if (normal.x < 0) and loc.x > 0.02: - normal = -normal - if t <= 0 or t >= RF.PER - 1: - loc.x, normal.x = 0.0, 0.0 - normal.normalize() - p = loc + normal * lift - return (max(float(p.x), 0.0), float(p.y), float(p.z)) +def dress(obj, frame, ring, mat, clad=True, split=0.9, fit=(), seed=0, flip=1.0, lifts=(0.035, 0.06), inset=0.07): + """What stands on a slab's outer face. `frame` is the face's frame in the object's own coordinates, `ring` its + outline there. Panels: massing.clad on that facet (a raised, chamfered panel with a bolt in each corner, cut in + two at uneven lifts where the facet is over `split` m2). Fits: see raptor_form.H; (u, v) from the face's middle, + u reversed by `flip` -1 so a plate's twin on the other side carries its fits mirrored. A fit that fails is + listed in COUNT["failed"] and left out.""" + import hardpoint as HP + import surface as S + n = frame.col[2].xyz.normalized() + geos = {} + marked = any(f[0] == "num" for f in fit) + lift = 0.0 + clad = clad and not any(f[0] == "louvres" for f in fit) # a louvre bank is let into the slab's own face + if clad: + g = geos.setdefault(P2 if mat == P else P, M.Geo()) + plain = marked or any(f[0] in ("louvres", "port") for f in fit) + made = MS.clad(obj, g, keep=lambda fn, c: fn.dot(n) > 0.97, min_area=0.12, lifts=(lifts[0], lifts[0]) if plain else lifts, inset=inset, gap=0.04, split=99.0 if plain else split, seed=seed, + bolts=geos.setdefault("gunmetal", M.Geo())) + COUNT["panels"] += made + lift = lifts[0] if made else 0.0 + mid = sum(ring, Vector((0.0, 0.0))) / len(ring) + at = lambda u, v, z=0.0: frame @ Vector((mid.x + flip * u, mid.y + v, lift + z)) # noqa: E731 + up = frame.col[1].xyz + face = MS.Face(obj, "gunmetal") + for kind, *a in fit: + try: + if kind == "bolts": + rim = M._inset(ring, 0.05 if not clad else 0.028) + frames = [] + for i in range(len(rim)): + p, q = rim[i], rim[(i + 1) % len(rim)] + count = max(1, int((q - p).length / a[0])) + frames += [M.frame_at(frame @ Vector((*p.lerp(q, (j + 0.5) / count), 0.0)), n, up) for j in range(count)] + S.bolt_row(face, frames, r=0.017, mat="gunmetal") + elif kind == "handle": + S.grab_handle(face, M.frame_at(at(a[0], a[1]), n, up) @ RZ(90.0), length=a[2], lift=0.07, r=0.016) + elif kind == "eye": + S.lifting_eye(face, M.frame_at(at(a[0], a[1]), n, up), size=0.1) + elif kind == "louvres": + u, v, w, h, count = a[:5] + HP.louvres(geos.setdefault(CORE, M.Geo()), M.frame_at(at(u, v, -lift), n, up) @ RZ(a[5] if len(a) > 5 else 0.0), w, h, count, depth=0.05, frame=0.05) + elif kind == "port": + u, v, r = a + fr = M.frame_at(at(u, v), n, up) + geos.setdefault("machine", M.Geo()).lathe(fr, [(0, 0), (r, 0), (r, 0.035), (0.82 * r, 0.05), (0.82 * r, 0.022), (0.34 * r, 0.022), (0.34 * r, 0.045), (0, 0.045)], 24) + geos.setdefault("gunmetal", M.Geo()).bolts(fr @ T((0, 0, 0.035)), 0.91 * r, 8, 0.07 * r, 0.012) + elif kind == "num": + text, height = a[0], a[1] + u, v = (a[2], a[3]) if len(a) > 3 else (0.0, 0.0) + S.numeral(face, M.frame_at(at(u, v, 0.003), n, (0, 0, 1)), text, height, "marking") # upright in the world, whatever the plate's lean + COUNT["marks"] += 1 + continue + else: + raise ValueError(f"no fit named {kind}") + COUNT["fits"] += 1 + except Exception as error: + COUNT["failed"].append(f"{obj.name} {kind}: {type(error).__name__} {str(error)[:100]}") + return face.done() + _geo_out(geos, obj) + + +def box_pts(x0, x1, y0, y1, z0, z1, c=0.0): + """A block's corners, its four upright edges and its top's rim clipped `c`.""" + if not c: + return [(x, y, z) for x in (x0, x1) for y in (y0, y1) for z in (z0, z1)] + ring = lambda a, b, d, e, k: [(a + k, d), (b - k, d), (b, d + k), (b, e - k), (b - k, e), (a + k, e), (a, e - k), (a, d + k)] # noqa: E731 + return [(x, y, z0) for x, y in ring(x0, x1, y0, y1, c)] + [(x, y, z1 - c) for x, y in ring(x0, x1, y0, y1, c)] + [(x, y, z1) for x, y in ring(x0 + c, x1 - c, y0 + c, y1 - c, c)] + + +def block(name, pts, mat=P, frame=None, bevel=0.015, clad=None, seed=0, min_area=0.14, split=0.7): + """An equipment block: a hard solid on `pts`; `clad(normal, centre)` picks the facets that take detail panels.""" + obj = _hard(name, pts, mat, bevel, frame) + if clad: + g, bolts = M.Geo(), M.Geo() + made = MS.clad(obj, g, keep=clad, min_area=min_area, seed=seed, inset=0.06, lifts=(0.03, 0.055), gap=0.035, split=split, bolts=bolts) + COUNT["panels"] += made + _geo_out({(P2 if mat == P else P): g, "gunmetal": bolts}, obj) + return obj + + +def kin(obj): + """An object and what was dressed onto it.""" + return [obj] + [c for c in obj.children_recursive if c.type == "MESH"] + + +# --- the hull ------------------------------------------------------------------------------------------------------------ + +def keel(yh): + """(half-width, z) of the open keel's lower corner at station yh: the dark machinery spine under the lip.""" + s = RF.section(yh) + return 0.45 * s[4][0], s[4][2] - 0.3 * min(1.0, max(0.12, (5.5 - yh) / 0.9)) # drawn up into the beak ahead of the lasers def under(x, yh): - """z of the mass's underside at (x, station yh), hull coordinates.""" - hit = SURF["bvh"].ray_cast(Vector((x, yh, 0.0)), Vector((0, 0, 1))) - return float(hit[0].z) if hit[0] is not None else RF.bot(yh) + """z of the hull's underside at (x, station yh), hull coordinates: the keel's, or the lip's outboard of it.""" + wk, zk = keel(yh) + return zk if abs(x) <= wk else RF.section(yh)[4][2] def over(x, yh): - hit = SURF["bvh"].ray_cast(Vector((x, yh, 12.0)), Vector((0, 0, -1))) - return float(hit[0].z) if hit[0] is not None else RF.top(yh) + s = RF.section(yh) + f = min(abs(x) / max(s[1][0], 1e-6), 1.0) + return s[0][2] + f * (s[1][2] - s[0][2]) def belly(yh): - return under(0.0, yh) + return keel(yh)[1] -def hull_core(): - """The dark body under the plates and inside the mass's wall: the cage drawn in 0.12 m, closed. It is the hull's - volume for balance.py (the mass's own wall is a shell).""" - rings = SURF["rings"] - pts, faces, n = [], [], 2 * RF.PER - 2 - for r in rings[1:-1]: - mid = np.array([0.0, r[0][1], 0.5 * (r[0][2] + r[-1][2])]) - half = [p + (mid - p) * min(0.12 / max(np.linalg.norm(p - mid), 1e-6), 0.5) for p in r] - pts += [tuple(p) for p in half] + [(-p[0], p[1], p[2]) for p in half[-2:0:-1]] - R = len(rings) - 2 - for k in range(R - 1): +def hull_core(mat=CORE): + """SIDE and FRONT views: the wedge itself, a closed hard solid drawn in 0.05 m under the plates' seats, with the + keel under it: what shows dark in every seam between plates, and the hull's volume for balance.py. Sections at + raptor_form's stations, straight between them.""" + pts, faces = [], [] + ys = [5.62] + [r[0] for r in RF.STATIONS] + [-2.42] + for yh in ys: + s = RF.section(yh) + wk, zk = keel(yh) + k = 0.55 if yh > 5.5 else 1.0 + half = [(0.0, yh, s[0][2] - 0.05), (k * (s[1][0] - 0.04), yh, s[1][2] - 0.04), (k * (s[2][0] - 0.06), yh, s[2][2]), (k * (s[3][0] - 0.06), yh, s[3][2] + 0.02), (k * (s[4][0] - 0.04), yh, s[4][2] + 0.03), + (k * wk, yh, zk), (0.0, yh, zk - 0.04)] + pts += half + [(-x, y, z) for x, y, z in half[-2:0:-1]] + n = 12 + for k in range(len(ys) - 1): for i in range(n): j = (i + 1) % n faces.append((k * n + i, (k + 1) * n + i, (k + 1) * n + j, k * n + j)) - for k, tip in ((0, rings[0][0]), (R - 1, rings[-1][0])): - near = rings[1 if k == 0 else -2] - pts.append(tuple(0.7 * tip + 0.3 * np.array([0.0, near[0][1], 0.5 * (near[0][2] + near[-1][2])]))) - c = len(pts) - 1 - for i in range(n): - j = (i + 1) % n - faces.append((c, k * n + i, k * n + j) if k == 0 else (c, k * n + j, k * n + i)) - return faceted(MS.solid("Torso.core", pts, faces, OFF, CORE, levels=2, flat=False), 40.0) + faces.append(tuple(range(n))) + faces.append(tuple((len(ys) - 1) * n + i for i in reversed(range(n)))) + obj = MS.solid("Torso.core", pts, faces, OFF, mat, levels=0, flat=True) + HARD["Torso.core"] = {"kind": "hard", "corners": len(pts), "facets": len(faces)} + return obj -def plate_cage(spec, side=1): - """A plate's cage on the mass's surface, hull coordinates: (verts, faces, creases, corners, inside). Its four - grid corners are pinned (not one on the mirror seam); its outline is otherwise uncreased.""" - rows, cols = spec["rows"], spec["cols"] - nr, nc = len(rows), len(cols) - verts = [] - for yh, lift, rake in rows: - for t in cols: - x, y, z = surf(yh + rake * (t - cols[0]), t, lift) - verts.append((side * x, y, z)) - at = lambda r, k: r * nc + k # noqa: E731 - faces = [(at(r, k), at(r, k + 1), at(r + 1, k + 1), at(r + 1, k)) for r in range(nr - 1) for k in range(nc - 1)] - creases = [(at(r, k), at(r + 1, k), 1.0) for k in spec["crease"] for r in range(nr - 1)] - pins = [(at(r, k), 1.0) for r in (0, nr - 1) for k in (0, nc - 1) if not (spec["mirror"] and abs(verts[at(r, k)][0]) < 1e-6)] - ym = 0.5 * (rows[0][0] + rows[-1][0]) - ring = [at(0, k) for k in range(nc)] + [at(r, nc - 1) for r in range(1, nr)] + [at(nr - 1, k) for k in range(nc - 2, -1, -1)] + [at(r, 0) for r in range(nr - 2, -1, -1)] - PLATES[spec["name"]] = {"outline": [[verts[i][1], verts[i][2]] for i in ring], "creases": [[[verts[a][1], verts[a][2]], [verts[b][1], verts[b][2]]] for a, b, _ in creases]} - return verts, faces, creases, pins, (0.0, ym, 0.5 * (RF.top(ym) + RF.bot(ym))) +def _fit_plane(points, inside): + pts = np.array(points, float) + c = pts.mean(0) + n = np.linalg.svd(pts - c)[2][2] + if n.dot(c - np.array(inside, float)) < 0: + n = -n + return Vector(c), Vector(n).normalized() + + +def wedge_plate(spec, side=1, seed=0): + """One raptor_form.H plate on one side: its corners on the wedge (RF.surf), the plane through them (least + squares; the outward side is away from the hull's axis), a slab on that plane standing `lift` off it, dressed. + The plane is my own through the corners; the corners' stations and columns are read off the views by hand.""" + name = f"Torso.{spec['name']}{'R' if side > 0 else 'L'}" + corners = [RF.surf(yh, t) for yh, t in spec["outline"]] + corners = [(side * x, y, z) for x, y, z in corners] + ym = sum(c[1] for c in corners) / len(corners) + c, n = _fit_plane(corners, (0.0, ym, RF.chine(ym) + 0.25)) + frame = M.frame_at(c + n * spec["lift"], n, (0, 0, 1)) + inv = frame.inverted() + obj, ring = slab(name, frame, [(inv @ Vector(p)).to_2d() for p in corners], spec["thick"], spec["mat"], gap=spec["gap"], back=spec["back"], world=OFF) + if side > 0: + PLATES[spec["name"]] = {"outline": [[c_[1], c_[2]] for c_ in corners], "creases": []} + dress(obj, frame, ring, spec["mat"], spec["clad"], spec["split"], spec["fit"], seed, flip=float(side)) + return obj def hull_plates(): - """SIDE, FRONT and hero views, image 43, RECESSED COCKPIT inset: the hull's armour and glazing, every plate a - free cage whose vertices stand on the fitted mass's built surface (raptor_form.hull_plates, plate_cage), lapped - like scales. Returns the objects.""" + """Both hero views, the SIDE view: the wedge's armour (raptor_form.hull_plates), each plate built on both sides. + Returns the objects (plates with their panels and fittings).""" out = [] - for spec in RF.hull_plates(): - for tag, side in ((("R", 1), ("L", -1)) if spec["sided"] else (("", 1),)): - verts, faces, creases, pins, inside = plate_cage(spec, side) - out.append(cage(f"Torso.{spec['name']}{tag}", verts, faces, OFF, inside, creases=creases, mirror=spec["mirror"], mat=spec["mat"], thickness=spec["thick"], rim=0, corners=pins)) + for i, spec in enumerate(RF.hull_plates()): + for side in (1, -1): + out += kin(wedge_plate(spec, side, seed=17 * i + (side > 0))) + return out + + +def dorsal_spine(): + """Both hero views: the raised spine down the centre of the deck, in short hard lengths that step with the + decks.""" + out = [] + for i, (y0, y1) in enumerate(((3.44, 3.08), (3.02, 2.02), (1.98, 0.46), (0.4, -0.62), (-0.68, -1.48), (-1.52, -2.3))): + h = 0.07 + 0.03 * (i % 2) + pts = [(0.09, y, RF.top(y) + h) for y in (y0, y1)] + [(0.17, y, RF.top(y) - 0.06) for y in (y0, y1)] + obj = MS.hard(f"Torso.Spine{i}", pts, None, P2 if i % 2 else P, mirror=True, bevel=0.012) + obj.matrix_world = OFF + HARD[obj.name] = {"kind": "hard", "corners": len(obj.data.vertices), "facets": len(obj.data.polygons)} + COUNT["solids"] += 1 + out.append(obj) return out def beak(): - """Hero views: the nose's tip, a small solid cap ahead of the NoseCap plate, on the mass's own point.""" - b = M.Build("Torso.Beak", None, OFF) - pts = [surf(5.64, t, 0.07) for t in (0, 1, 2, 3, 3.7)] - tip = (0.0, RF.NOSE[0] + 0.05, RF.NOSE[1]) - b[P].hull(pts + [(-x, y, z) for x, y, z in pts[1:]] + [tip, (0.0, RF.NOSE[0] - 0.1, RF.NOSE[1] - 0.12)]) - return b.done(bevel=0.01) + """Hero views (the armoured snout under the canopy's last hoop, a lamp either side of its tip): one hard solid + from the foremost section to the nose's traced tip, with a chin under it; clad on its flanks.""" + y0 = RF.CANOPY_Y[-1] + 0.04 + s = RF.section(y0) + ny, nz = RF.NOSE + half = [(s[1][0] * 0.7, y0, s[1][2] + 0.03), (s[2][0] + 0.04, y0, s[2][2] + 0.03), (s[3][0] + 0.05, y0 - 0.1, s[3][2]), (s[4][0], y0 - 0.1, s[4][2] - 0.05), (0.0, y0, s[0][2] + 0.04), + (0.1, ny + 0.02, nz + 0.07), (0.12, ny + 0.03, nz - 0.03), (0.0, ny + 0.06, nz + 0.03), (0.0, ny - 0.04, nz - 0.1), (0.1, ny - 0.3, nz - 0.12)] + obj = block("Torso.Beak", half + [(-x, y, z) for x, y, z in half if x > 1e-6], P, OFF, bevel=0.015, clad=lambda n, c: abs(n.x) > 0.5, seed=5, min_area=0.08, split=9) + b = M.Build("Torso.BeakLamp", None, OFF) + for sx in (-1, 1): + f = M.frame_at((sx * 0.2, ny - 0.16, nz - 0.1), (sx * 0.5, 1, -0.1), (0, 0, 1)) + b[CORE].lathe(f, [(0, 0), (0.075, 0), (0.075, 0.07), (0.055, 0.07), (0.055, 0.04), (0, 0.04)], 16) + b["lamp"].lathe(f, [(0, 0.045), (0.05, 0.045), (0.0, 0.06)], 12) + return kin(obj) + b.done(bevel=0.0) + + +def canopy(): + """RECESSED COCKPIT inset and both hero views: the whole front of the wedge above the jaw band is glazed. The + glass is flat panes, two triangles a cell of the lattice (raptor_form.CANOPY_Y by CANOPY_T), lying 0.02 m off + the core; the lattice stands over it: a hoop at each station, rails down the ridge, the deck's edge and the belt, + a diagonal across every pane, each bar a dark box standing proud, a boss on every node. The panes are material + `glass`: paint.apply(glass="faceted") makes them smoked and breaks each into smaller facets. A hard brow in two + plates a side stands over the first hoop.""" + import bmesh + ys, ts = RF.CANOPY_Y, RF.CANOPY_T + axis = lambda y: Vector((0.0, y, RF.chine(y) + 0.1)) # noqa: E731 + + def node(i, j, sx, lift): + p = Vector(RF.surf(ys[i], ts[j])) + n = (p - axis(p.y)).normalized() + p = p + n * lift + return Vector((sx * p.x, p.y, p.z)), Vector((sx * n.x, n.y, n.z)) + + glass, bars = M.Geo(), M.Geo() + for sx in (1, -1): + for i in range(len(ys) - 1): + for j in range(len(ts) - 1): + a, b, c, d = (node(i, j, sx, 0.02)[0], node(i + 1, j, sx, 0.02)[0], node(i + 1, j + 1, sx, 0.02)[0], node(i, j + 1, sx, 0.02)[0]) + tris = ((a, b, c), (a, c, d)) if (i + j) % 2 == 0 else ((a, b, d), (b, c, d)) + for tri in tris: + glass.bm.faces.new([glass.bm.verts.new(p) for p in tri]) + bmesh.ops.remove_doubles(glass.bm, verts=glass.bm.verts[:], dist=1e-4) + pane = glass.to_object("Torso.Canopy.glass", "glass", None, 1.0) + for p in pane.data.polygons: + p.use_smooth = False + wall = pane.modifiers.new("Solidify", "SOLIDIFY") + wall.thickness, wall.offset = 0.03, -1.0 + pane.matrix_world = OFF + + def bar(a, b, w=0.07, d=0.06): + (pa, na), (pb, nb) = a, b + along = pb - pa + if along.length < 1e-4: + return + n = na + nb + n = (n - along * (n.dot(along) / along.length_squared)).normalized() # square to the bar: the canopy slopes, the nodes' normals do not + bars.box(M.frame_at((pa + pb) / 2 + n * (0.5 * d - 0.02), n, along), (w, along.length + 0.04, d)) + + count = 0 + for sx in (1, -1): + N = [[node(i, j, sx, 0.02) for j in range(len(ts))] for i in range(len(ys))] + for i in range(len(ys)): + for j in range(len(ts) - 1): + bar(N[i][j], N[i][j + 1], 0.09 if i == 0 else 0.07) + for j in range(len(ts)): + if j == 0 and sx < 0: + continue + for i in range(len(ys) - 1): + bar(N[i][j], N[i + 1][j], 0.09 if j else 0.11, 0.07) + for i in range(len(ys) - 1): + for j in range(len(ts) - 1): + if (i + j) % 2 == 0: + bar(N[i][j], N[i + 1][j + 1], 0.05, 0.05) + else: + bar(N[i + 1][j], N[i][j + 1], 0.05, 0.05) + count += 2 + for row in N: + for p, n in row: + bars.box(M.frame_at(p + n * 0.03, n, (0, 1, 0)), (0.13, 0.13, 0.09)) + if "lattice" not in M.MATS: # near black and left alone by paint.apply: both concepts draw the canopy's frames darker than any plate + M.material("lattice", (0.014, 0.015, 0.014), 0.3, 0.55) + frame = bars.to_object("Torso.Canopy.frame", "lattice", None, 1.0) + frame.matrix_world = OFF + for p in frame.data.polygons: + p.use_smooth = False + HARD["Torso.Canopy.glass"] = {"kind": "hard", "corners": len(pane.data.vertices), "facets": len(pane.data.polygons)} + HARD["Torso.Canopy.frame"] = {"kind": "hard", "corners": len(frame.data.vertices), "facets": len(frame.data.polygons), "panes": count} + out = [pane, frame] + for sx in (1, -1): + (p0, n0), (p1, n1), (p2, n2) = (node(0, j, sx, 0.0) for j in range(3)) + for k, (a, na, b, nb) in enumerate(((p0, n0, p1, n1), (p1, n1, p2, n2))): + n = (na + nb).normalized() + fr = M.frame_at((a + b) / 2 + n * 0.14 + Vector((0, 0.1, 0)), n, (0, 1, 0)) + inv = fr.inverted() + q = [(inv @ (a + Vector((0, -0.12, 0)))).to_2d(), (inv @ (b + Vector((0, -0.12, 0)))).to_2d(), (inv @ (b + Vector((0, 0.3, 0)))).to_2d(), (inv @ (a + Vector((0, 0.22, 0)))).to_2d()] + obj, ring = slab(f"Torso.Brow{k}{'R' if sx > 0 else 'L'}", fr, q, 0.1, P, taper=0.03, world=OFF) + out += kin(obj) + return out + + +def underbody(): + """Both hero views (under the chine: dark frames, drums, pipes and hose runs between the jaw and the hips, nothing + plated): the open underbody. Ribs across the keel every 0.45 m, hung from the lip; two pipe runs a side under + the lip; a tank a side behind the lasers; a gearbox under the chest between the lasers; junction boxes; hoses + from the keel out to the lip. All dark metal: it is machinery, and it stays open.""" + b = M.Build("Underbody", None, OFF) + d, m, s = b[CORE], b["machine"], b["steel"] + y = 4.9 + while y > -0.1: + sec = RF.section(y) + wk, zk = keel(y) + d.box(T((0, y, 0.5 * (sec[4][2] + zk) - 0.02)), (2 * sec[4][0] - 0.1, 0.06, sec[4][2] - zk + 0.1)) + m.box(T((0, y, zk - 0.06)), (2 * wk + 0.16, 0.1, 0.08)) + y -= 0.45 + for sx in (-1, 1): + for k, (fx, dz, r, mat) in enumerate(((0.92, -0.1, 0.035, m), (0.74, -0.16, 0.05, d))): + pts = [Vector((sx * fx * RF.section(yy)[4][0], yy, RF.section(yy)[4][2] + dz)) for yy in (5.0, 4.2, 3.4, 2.6, 1.8, 1.0, 0.3)] + for p, q in zip(pts, pts[1:]): + mat.rod(p, q, r, 10) + for p in pts[1:-1]: + m.cylinder(M.frame_at(p, (0, 1, 0)), r + 0.022, 0.08, 10) + sec = RF.section(2.1) + f = M.frame_at((sx * 0.5, 2.55, sec[4][2] - 0.28), (0, -1, 0.04), (0, 0, 1)) + d.lathe(f, [(0, 0), (0.17, 0), (0.2, 0.05), (0.2, 0.8), (0.17, 0.85), (0, 0.85)], 20) + for z in (0.16, 0.42, 0.68): + m.lathe(f @ T((0, 0, z)), [(0.2, 0), (0.22, 0), (0.22, 0.045), (0.2, 0.045)], 20) + sec = RF.section(4.2) + d.box(T((sx * 0.3, 4.2, sec[4][2] - 0.22)), (0.22, 0.5, 0.26)) + m.bolts(M.frame_at((sx * 0.3, 4.2, sec[4][2] - 0.35), (0, 0, -1), (0, 1, 0)), 0.08, 6, 0.02) + sec = RF.section(1.0) + d.box(T((sx * 0.38, 1.0, sec[4][2] - 0.2)), (0.3, 0.6, 0.24)) + wk, zk = keel(3.6) + d.lathe(M.frame_at((0, 3.95, zk - 0.02), (0, -1, 0), (0, 0, 1)), [(0, 0), (0.24, 0), (0.27, 0.06), (0.27, 0.5), (0.2, 0.6), (0, 0.6)], 12) + m.bolts(M.frame_at((0, 3.95, zk - 0.02), (0, 1, 0), (0, 0, 1)), 0.2, 8, 0.025) + out = b.done(bevel=0.0) + for sx in (-1, 1): + for k, (ya, yb, r) in enumerate(((4.6, 4.0, 0.04), (3.3, 2.7, 0.05), (2.2, 1.5, 0.04), (1.2, 0.5, 0.05))): + wa, za = keel(ya) + sb = RF.section(yb) + a = Vector((sx * wa, W(ya), za + 0.08)) + c = Vector((sx * (sb[4][0] - 0.1), W(yb), sb[4][2] - 0.05)) + out.append(M.hose(f"Underbody.hose{k}{'R' if sx > 0 else 'L'}", a, Vector((sx, 0, -0.6)), c, Vector((0, 0.4, 1)), r, sag=0.0, mat="rubber")) + COUNT["hoses"] += 1 + return out def near(cam, distance=400.0): @@ -258,75 +464,10 @@ def hull(name): return name.startswith(("Torso.",)) -# --- free cages (ruling minimal-cages-learned-from-operator) --------------------------------------------------------- - -def _edges(faces): - out = {} - for f in faces: - for a, b in zip(f, f[1:] + f[:1]): - out[frozenset((a, b))] = out.get(frozenset((a, b)), 0) + 1 - return out - - -def _built(verts, faces, mirror): - """The cage as built: (faces, seam flags) after the mirror about x = 0, vertices on the seam shared.""" - if not mirror: - return [list(f) for f in faces] - reach = max(max(abs(c) for c in v) for v in verts) - twin, k = {}, len(verts) - for i, v in enumerate(verts): - if abs(v[0]) <= 0.005 * reach: - twin[i] = i - else: - twin[i] = k - k += 1 - return [list(f) for f in faces] + [[twin[i] for i in reversed(f)] for f in faces] - - -def poles_of(verts, faces, mirror): - """The authored vertices of irregular valence on the cage as built: not 4 off the boundary, not 2 or 3 on it.""" - edges = _edges(_built(verts, faces, mirror)) - val, rim = {}, set() - for e, n in edges.items(): - for v in e: - val[v] = val.get(v, 0) + 1 - if n == 1: - rim.add(v) - return sorted(v for v in range(len(verts)) if (val[v] not in (2, 3) if v in rim else val[v] != 4)) - - -def cage(name, verts, faces, frame, inside, creases=(), mirror=False, mat=P, thickness=0.07, levels=2, corners=(), rim=0): - """A sculpted plate as a FREE cage (brokkr_kitbash.shell, docs/kitbash.md "A free cage"): the fewest vertices - that hold the form, creases only where it breaks. `verts` and `faces` in the plate's own frame; each face is - wound to look away from `inside` (a point under the plate); the poles are counted here and declared, as the - action's gate demands. `frame` stands it in the world. Records what the ruling asks for in CAGES.""" - c = Vector(inside) - wound = [] - for f in faces: - p = [Vector(verts[i]) for i in f] - n = sum(((p[i] - p[0]).cross(p[i + 1] - p[0]) for i in range(1, len(p) - 1)), Vector()) - mid = sum(p, Vector()) / len(p) - wound.append(list(f) if n.dot(mid - c) > 0 else list(reversed(f))) - poles = poles_of(verts, wound, mirror) - sheet = {"verts": [list(map(float, v)) for v in verts], "faces": wound, "creases": [list(cr) for cr in creases], "poles": poles, "mirror": mirror, "rim": rim, "corners": [list(k) for k in corners]} - result = bpy.ops.brokkr_kitbash.shell(object_name=name, sheet=json.dumps(sheet), thickness=thickness, offset=-1.0, levels=levels, bevel=0.0, count_folds=True) - if "FINISHED" not in result: - raise SystemExit(f"cage {name}: {result}") - rep = json.loads(getattr(bpy.context.window_manager, M.KB.RESULT)) - obj = bpy.data.objects[name] - obj.matrix_world = Matrix(frame) - M.assign(obj, mat) - edges = len(_edges(_built(verts, wound, mirror))) - creased = rep.get("creases", len(creases) * (2 if mirror else 1)) - CAGES[name] = {"authored": len(verts), "verts": rep.get("cageVerts"), "faces": rep.get("cageFaces"), "triangles": rep.get("triangles"), "edges": edges, "creased": creased, - "share": round(creased / edges, 3), "poles": rep.get("poles"), "folded": rep.get("folded")} - print(f"CAGE {name}: {CAGES[name]}", flush=True) - return obj - +# --- limbs ----------------------------------------------------------------------------------------------------------- def link_frame(a, b): - """A frame on a limb's link from joint a to joint b: z along it, y its front, x across (the sign does not - matter to a mirrored cage).""" + """A frame on a limb's link from joint a to joint b: z along it, y its front, x across (world -x).""" a, b = Vector(a), Vector(b) z = (b - a).normalized() x = Vector((-1.0, 0.0, 0.0)) @@ -336,63 +477,87 @@ def link_frame(a, b): return m -def limb_shell(name, a, b, rings, crease=(1,), face=1, thickness=0.07, mat=P): - """A link's sculpted armour: ONE free cage mirrored about the leg's own plane, in the link's frame (z along it - from joint a, y its front). `rings`: [(metres along the link, [(x, y), ...])], each from the middle (x = 0) - round one side; `face` -1 lays it on the link's rear. Creased down the columns named, nowhere else; the open - edge's two corners are pinned. The fewest points that hold the form: three or four a section.""" - nc = len(rings[0][1]) - verts = [(x, face * y, s) for s, pts in rings for x, y in pts] - at = lambda r, k: r * nc + k # noqa: E731 - faces = [(at(r, k), at(r, k + 1), at(r + 1, k + 1), at(r + 1, k)) for r in range(len(rings) - 1) for k in range(nc - 1)] - creases = [(at(r, k), at(r + 1, k), 1.0) for k in crease for r in range(len(rings) - 1)] - mid = 0.5 * (rings[0][0] + rings[-1][0]) - return cage(name, verts, faces, link_frame(a, b), (0, -face * 0.3, mid), creases=creases, mirror=True, mat=mat, thickness=thickness, rim=0, corners=[(at(0, nc - 1), 1.0), (at(len(rings) - 1, nc - 1), 1.0)]) +def limb(prefix, tag, sx, a, b, table, seed=0): + """A link's hard armour, authored in the link's frame (z along it from joint a, y its front) at the pose the leg + stands in, to be carried by the link afterwards. Rows: + ("house", name, sections, mat) massing.section_points: a faceted housing round the member + ("slab", name, face, offset, outline, thick, mat, clad split, fits) + a slab on the link's `out` (outboard), `front` or `rear` + face, its outer face `offset` from the link's axis; + outline (across, along): across is the link's front on an + outboard slab, world +x on a front or rear one + Returns the objects.""" + F = link_frame(a, b) + out_dir = Vector((-float(sx), 0.0, 0.0)) # the frame's x is world -x + made = [] + for i, row in enumerate(table): + name = f"{prefix}{tag}.{row[1]}" + if row[0] == "house": + obj = block(name, [F @ Vector(p) for p in MS.section_points(row[2])], row[3], bevel=0.02, clad=lambda n, c: True, seed=seed + i, min_area=0.1, split=0.45) + made += kin(obj) + continue + _, _, face, offset, outline, thick, mat, split, fits = row + if face == "out": + n, across = out_dir, Vector((0, 1, 0)) + else: + n, across = Vector((0, 1.0 if face == "front" else -1.0, 0)), Vector((-1, 0, 0)) + lz = Vector((0, 0, 1)) + x_axis = lz.cross(n) # right-handed: x, y = along, z = n + local = Matrix((x_axis, lz, n)).transposed().to_4x4() + local.translation = n * offset + k = across.dot(x_axis) # the outline's `across` on the frame's x + frame = F @ local + obj, ring = slab(name, frame, [(k * u, v) for u, v in outline], thick, mat, taper=0.04, back=0.9, bevel=0.014) + dress(obj, frame, ring, mat, True, split, fits, seed + i, flip=k) + made += kin(obj) + return made -def thigh_shell(tag, hip, knee): - """SIDE view (the far leg's long rounded housing from under the chine to the knee) and LEG DETAIL: the upper - leg's armour, a faired housing over the thigh's front and both flanks, deepest a third of the way down, drawn - in above the knee so the knee's bearing stands bare; open behind, where the actuators run. 20 vertices.""" - L = (Vector(knee) - Vector(hip)).length - return limb_shell(f"ThighShell{tag}", hip, knee, [(-0.46, [(0, 0.28), (0.34, 0.26), (0.50, -0.04), (0.48, -0.44)]), (0.12, [(0, 0.60), (0.38, 0.52), (0.53, 0.0), (0.51, -0.36)]), - (0.42 * L, [(0, 0.64), (0.40, 0.54), (0.52, 0.02), (0.49, -0.28)]), (0.72 * L, [(0, 0.50), (0.33, 0.42), (0.43, 0.0), (0.40, -0.22)]), - (0.9 * L, [(0, 0.36), (0.26, 0.31), (0.34, 0.0), (0.31, -0.16)])], thickness=0.08) - - -def shin_shell(tag, knee, hock): - """LEG DETAIL (composite armor): the sculpted calf, on the shin's upper rear face, swelling below the knee. 12 vertices.""" - L = (Vector(hock) - Vector(knee)).length - return limb_shell(f"ShinShell{tag}", knee, hock, [(0.3, [(0.0, 0.39), (0.29, 0.34), (0.39, 0.0)]), (0.42 * L, [(0.0, 0.57), (0.35, 0.47), (0.43, 0.03)]), (0.72 * L, [(0.0, 0.47), (0.29, 0.38), (0.36, 0.0)]), - (0.9 * L, [(0.0, 0.33), (0.22, 0.27), (0.3, 0.0)])], face=-1) - - -def cannon_shell(tag, hock, ankle): - """Hero views (the long shield down each lower leg, image 43's the one with the stencils): the cannon's front - armour. 9 vertices.""" - L = (Vector(ankle) - Vector(hock)).length - return limb_shell(f"CannonShell{tag}", hock, ankle, [(0.26, [(0.0, 0.38), (0.26, 0.33), (0.34, 0.0)]), (0.5 * L, [(0.0, 0.44), (0.29, 0.36), (0.35, 0.03)]), (0.84 * L, [(0.0, 0.33), (0.22, 0.27), (0.29, 0.0)])]) +def leg_armour(side, sx, hip, knee, hock, ank): + """Both hero views and LEG DETAIL (composite armor): the legs' armour, all hard. Image 43 draws each link as a + boxed housing with a flat shield bolted on: the thigh's hangs outboard under the hip's bearing, the shin's + covers the calf, the cannon's runs down its front. The third pass's free-cage shells were thinner than either + concept draws the lower leg: the shin's housing is 1.0 m across here, the cannon's 0.88.""" + Lt, Ls, Lc = ((Vector(q) - Vector(p)).length for p, q in ((hip, knee), (knee, hock), (hock, ank))) + thigh = [("house", "house", [(0.2, 0.80, -0.26, 0.50, 0.14), (0.45 * Lt, 0.86, -0.26, 0.62, 0.16), (0.74 * Lt, 0.74, -0.22, 0.50, 0.13), (0.9 * Lt, 0.62, -0.18, 0.40, 0.1)], P), + ("slab", "shield", "out", 0.56, [(-0.3, 0.44), (0.5, 0.32), (0.66, 0.85), (0.56, 1.5), (0.1, 1.68), (-0.3, 1.45)], 0.14, P2, 0.5, [("bolts", 0.2), ("handle", 0.1, 0.42, 0.3)]), + ("slab", "front", "front", 0.7, [(-0.3, 0.3), (0.3, 0.3), (0.34, 0.5 * Lt), (-0.34, 0.5 * Lt)], 0.16, P, 9, [("bolts", 0.2)]), + ("slab", "knee", "front", 0.62, [(-0.28, 0.55 * Lt), (0.28, 0.55 * Lt), (0.22, 0.93 * Lt), (-0.22, 0.93 * Lt)], 0.14, P2, 9, [("port", 0.0, 0.0, 0.07)])] + shin = [("house", "house", [(0.3, 0.90, -0.50, 0.38, 0.14), (0.45 * Ls, 1.0, -0.66, 0.44, 0.16), (0.75 * Ls, 0.84, -0.5, 0.38, 0.13), (0.93 * Ls, 0.66, -0.34, 0.3, 0.1)], P), + ("slab", "shield", "out", 0.6, [(-0.5, 0.42), (0.3, 0.36), (0.36, 0.75 * Ls), (0.1, 0.92 * Ls), (-0.34, 0.9 * Ls), (-0.62, 0.5 * Ls)], 0.13, P2, 0.5, [("bolts", 0.2)]), + ("slab", "calf", "rear", 0.72, [(-0.34, 0.38), (0.34, 0.38), (0.3, 0.78 * Ls), (-0.3, 0.78 * Ls)], 0.14, P, 0.3, [("bolts", 0.22)])] + cannon = [("house", "house", [(0.24, 0.80, -0.3, 0.44, 0.12), (0.5 * Lc, 0.88, -0.32, 0.52, 0.14), (0.86 * Lc, 0.68, -0.26, 0.38, 0.1)], P), + ("slab", "shield", "front", 0.6, [(-0.36, 0.22), (0.36, 0.22), (0.42, 0.5 * Lc), (0.3, 0.9 * Lc), (-0.3, 0.9 * Lc), (-0.42, 0.5 * Lc)], 0.14, P2, 0.35, [("bolts", 0.2), ("handle", 0.0, -0.45, 0.26)]), + ("slab", "side", "out", 0.5, [(-0.24, 0.32), (0.36, 0.32), (0.4, 0.8 * Lc), (-0.2, 0.8 * Lc)], 0.1, P, 9, [("louvres", 0.0, 0.0, 0.3, 0.2, 3)])] + return {"thigh": limb("Thigh", side, sx, hip, knee, thigh, seed=101), "shin": limb("Shin", side, sx, knee, hock, shin, seed=201), "cannon": limb("Cannon", side, sx, hock, ank, cannon, seed=301)} def pauldron(tag, side): - """Hero view (the plate over the arm) and image 43 (the boxed plate round the shoulder's bearing): two real - plates lapped over the shoulder pin, hard against the hull's flank. The upper is a free cage of nine vertices, - creased once along its waist: its top leans in under the hull's Shoulder plate, its skirt hangs square over - the arm, the front lower corner cut back. The lower lame is six vertices, uncreased, tucked under the skirt.""" + """Hero view (the boxed plate over the arm that carries the second 27) and image 43 (the plate round the + shoulder's bearing): hard. A five-sided shield outboard of the shoulder pin, a cap plate leaning in over it to + the hull's belt, a lame under it; the shield carries the number.""" sx, sy, sz = RF.SHOULDER - frame = T((side * (sx + 0.2), sy, sz)) @ Matrix.Scale(0.72, 4) - up = [(-0.18, -0.6, 0.46), (-0.18, 0.0, 0.5), (-0.18, 0.62, 0.42), - (0.1, -0.7, 0.16), (0.12, 0.0, 0.18), (0.1, 0.76, 0.12), - (0.1, -0.6, -0.44), (0.12, 0.0, -0.5), (0.1, 0.5, -0.36)] - lo = [(0.02, -0.5, -0.3), (0.04, 0.0, -0.36), (0.02, 0.42, -0.24), (0.0, -0.4, -0.86), (0.02, 0.0, -0.92), (0.0, 0.3, -0.74)] - quads = lambda nr, nc: [(r * nc + k, r * nc + k + 1, (r + 1) * nc + k + 1, (r + 1) * nc + k) for r in range(nr - 1) for k in range(nc - 1)] # noqa: E731 - a = cage(f"Pauldron{tag}", [(side * x, y, z) for x, y, z in up], quads(3, 3), frame, (-side * 1.0, 0, 0), creases=[(3, 4, 1.0), (4, 5, 1.0)], thickness=0.09, rim=0, corners=[(k, 1.0) for k in (0, 2, 6, 8)]) - b = cage(f"PauldronLame{tag}", [(side * x, y, z) for x, y, z in lo], quads(2, 3), frame, (-side * 1.0, 0, -0.5), thickness=0.07, rim=0, corners=[(k, 1.0) for k in (0, 2, 3, 5)]) - return [a, b] + c = Vector((side * (sx + 0.34), sy, sz + 0.16)) + n = Vector((side, 0, 0.12)).normalized() + fr = M.frame_at(c, n, (0, 0, 1)) + k = fr.col[0].xyz.dot(Vector((0, 1, 0))) # the outline's fore on the frame's x + out = [] + obj, ring = slab(f"Pauldron{tag}.shield", fr, [(k * u, v) for u, v in ((-0.5, -0.4), (0.4, -0.4), (0.62, 0.0), (0.46, 0.44), (-0.5, 0.44))], 0.2, P2, taper=0.04, back=0.9) + dress(obj, fr, ring, P2, False, 9, [("num", "27", 0.36, -0.06, 0.0), ("bolts", 0.2)], flip=k) + out += kin(obj) + n2 = Vector((side * 0.55, 0, 1)).normalized() + fr2 = M.frame_at(c + Vector((-side * 0.2, 0.0, 0.52)), n2, (0, 1, 0)) + obj, ring = slab(f"Pauldron{tag}.cap", fr2, [(-0.26, -0.52), (0.26, -0.52), (0.26, 0.44), (-0.26, 0.5)], 0.14, P, taper=0.03) + dress(obj, fr2, ring, P, True, 9, [("eye", 0.0, 0.0)]) + out += kin(obj) + fr3 = M.frame_at(c + Vector((-side * 0.04, -0.06, -0.56)), Vector((side, 0, -0.1)), (0, 0, 1)) + k3 = fr3.col[0].xyz.dot(Vector((0, 1, 0))) + obj, ring = slab(f"Pauldron{tag}.lame", fr3, [(k3 * u, v) for u, v in ((-0.36, -0.1), (0.22, -0.1), (0.34, 0.2), (-0.4, 0.2))], 0.12, P, taper=0.03) + dress(obj, fr3, ring, P, True, 9, [("bolts", 0.2)]) + out += kin(obj) + return out -# --- limbs ----------------------------------------------------------------------------------------------------------- - CORES = {"thigh": [(0.0, 0.30, 0.30, 0.32, 4.0), (1.0, 0.24, 0.24, 0.24, 4.0)], "shin": [(0.0, 0.25, 0.27, 0.27, 4.0), (1.0, 0.21, 0.22, 0.22, 4.0)], "cannon": [(0.0, 0.2, 0.22, 0.2, 4.0), (1.0, 0.17, 0.18, 0.17, 4.0)]} NAMES = {"thigh": "Thigh", "shin": "Shin", "cannon": "Cannon"} @@ -482,45 +647,10 @@ def pelvis_block(): return b.done(bevel=0.025) -def legs(cores): - """The digitigrade skeleton (digitigrade.build: axle, three links a leg, every joint a kit pivot with its - record), dressed: each link's core, its sculpted armour (limb_shell), the actuators, the struts and the bare - bearings are authored in the world at the SIDE pose and carried by their links, so they follow every pose; the - feet are feet.raptor_claws, whose core is the ankle. The joints' limits span the poses the sheets draw, with 15 - degrees to spare. Returns (body, objects).""" - import feet - hy, hz = RF.HIP - widths = [(0.5, 0.5), (0.36, 0.36), (0.3, 0.3)] - body = DG.build({"hip": (RF.HIP_X, hy, hz), "links": [(length, w, d) for length, (w, d) in zip(RF.LINKS, widths)], "pin_r": 0.09, "axle": {"r": 0.3, "block": 0.9, "hub": 0.4}, - "pose": RF.POSES["side"]}) - made = [body["pelvis"]] - body["feet"] = {} - for side in ("L", "R"): - sx = 1 if side == "R" else -1 - links = body["legs"][side]["links"] - hip, knee, hock, ank = (Vector((sx * RF.HIP_X, y, z)) for y, z in DG.chain(RF.HIP, RF.LINKS, RF.POSES["side"][side])) - dressed = {"thigh": [cores[f"thigh{side}"], thigh_shell(side, hip, knee)] + bearing(f"HipBearing{side}", hip, sx, 0.52, 0.56) + actuators(side, sx, hip, knee) + bearing(f"KneeBearing{side}", knee, sx, 0.4, 0.4), - "shin": [cores[f"shin{side}"], shin_shell(side, knee, hock)] + hydraulics(f"Shin{side}", knee, hock, face=1, r=0.08, off=0.33) + bearing(f"HockBearing{side}", hock, sx, 0.3, 0.3, cap=False), - "cannon": [cores[f"cannon{side}"], cannon_shell(side, hock, ank)] + hydraulics(side, hock, ank, off=0.31)} - for name, link in zip(("thigh", "shin", "cannon"), links): - freeze(dressed[name]) - DG.carry(dressed[name], link) - made += dressed[name] + [link] - foot = feet.raptor_claws(f"Foot{side}", links[-1], "clevis", width=1.55, length=2.4, drop=RF.ANKLE_Z, pin_r=0.09) - foot.level() - foot.done() - body["legs"][side]["foot"] = foot.core - body["feet"][side] = foot - made += foot.objects - DG.limits(body, RF.POSES, "side") - JOINTS["legs"] = DG.report(body["pelvis"]) - return body, made - - def arms(): """Hero view and image 43: compact arms hanging forward under the chest, part of the silhouette, no weapons (43's smaller arms are the guide): a second axle through the hull at the shoulders, an upper arm and a forearm - on kit pins (shoulder, elbow, each with its record); two lapped pauldron plates (free cages) over each + on kit pins (shoulder, elbow, each with its record); a hard pauldron (shield, cap, lame) over each shoulder, a slab of armour on each forearm, and the joints library's three-fingered gripper, half closed.""" import hands import jointlib as J @@ -621,82 +751,134 @@ def battery(): return made -def spine(): - """REAR EQUIPMENT SPINE inset (cooling systems, jump-jets), the REAR view and image 43's rear: the raised - equipment spine. On the boom's back, behind the battery, two cooling stacks in tandem, each a dark radiator - box under a louvred lid with a fin pack on its rear face. On each flank of the boom an armoured equipment - nacelle (the REAR view's blocks either side of the spine), louvred outboard, a jump-jet bell under its tail - canted down and back; between them under the boom a manifold, and feed pipes over the nacelles. In the boom's - tail the main jump jet, a ringed drum with its bell (image 43's rear drum).""" - import hardpoint as H - b = M.Build("Spine", None, OFF) # authored in the hull's coordinates - d, m, k = b[CORE], b["machine"], b[P] - for i, (y, w, ln, h) in enumerate(((-0.42, 0.62, 0.72, 0.5), (-1.3, 0.54, 0.66, 0.42))): +def legs(cores): + """The digitigrade skeleton (digitigrade.build: axle, three links a leg, every joint a kit pivot with its + record), dressed: each link's core, its hard armour (leg_armour), the actuators, the struts and the bare + bearings are authored in the world at the SIDE pose and carried by their links, so they follow every pose; the + feet are feet.raptor_claws, whose core is the ankle. The joints' limits span the poses the sheets draw, with 15 + degrees to spare. Returns (body, objects).""" + import feet + hy, hz = RF.HIP + widths = [(0.5, 0.5), (0.36, 0.36), (0.3, 0.3)] + body = DG.build({"hip": (RF.HIP_X, hy, hz), "links": [(length, w, d) for length, (w, d) in zip(RF.LINKS, widths)], "pin_r": 0.09, "axle": {"r": 0.3, "block": 0.9, "hub": 0.4}, + "pose": RF.POSES["side"]}) + made = [body["pelvis"]] + body["feet"] = {} + for side in ("L", "R"): + sx = 1 if side == "R" else -1 + links = body["legs"][side]["links"] + hip, knee, hock, ank = (Vector((sx * RF.HIP_X, y, z)) for y, z in DG.chain(RF.HIP, RF.LINKS, RF.POSES["side"][side])) + armour = leg_armour(side, sx, hip, knee, hock, ank) + dressed = {"thigh": [cores[f"thigh{side}"]] + armour["thigh"] + bearing(f"HipBearing{side}", hip, sx, 0.52, 0.46) + actuators(side, sx, hip, knee) + bearing(f"KneeBearing{side}", knee, sx, 0.38, 0.45), + "shin": [cores[f"shin{side}"]] + armour["shin"] + hydraulics(f"Shin{side}", knee, hock, face=1, r=0.08, off=0.56) + bearing(f"HockBearing{side}", hock, sx, 0.3, 0.42, cap=False), + "cannon": [cores[f"cannon{side}"]] + armour["cannon"] + hydraulics(side, hock, ank, off=0.47)} + for name, link in zip(("thigh", "shin", "cannon"), links): + freeze(dressed[name]) + DG.carry([o for o in dressed[name] if o.parent is None], link) + made += dressed[name] + [link] + foot = feet.raptor_claws(f"Foot{side}", links[-1], "clevis", width=1.55, length=2.4, drop=RF.ANKLE_Z, pin_r=0.09) + foot.level() + foot.done() + body["legs"][side]["foot"] = foot.core + body["feet"][side] = foot + made += foot.objects + DG.limits(body, RF.POSES, "side") + JOINTS["legs"] = DG.report(body["pelvis"]) + return body, made + + +# --- the rear equipment pack ---------------------------------------------------------------------------------------------- + +def pack(): + """REAR EQUIPMENT SPINE inset (cooling systems, jump-jets), the REAR view and image 43's rear: a dense equipment + pack on and round the boom, every housing a hard block with stepped panels. On the boom's back two cooling + stacks, each a dark radiator box under an armoured lid with louvres in its flanks and a fin pack behind, and two + ribbed exhaust stacks behind them; on each flank three stepped equipment blocks of different depth (louvres, + a fin pack), a stowage box and grab rails on their tops, a strapped canister outboard at the rear, a jump-jet + bell under the middle block; under the boom a manifold and its pipes; feed hoses from the stacks down to the + blocks; in the boom's tail the main jump jet, a ringed drum with its bell (image 43's rear drum); a whip aerial.""" + import hardpoint as HP + out = [] + up = lambda n, c: n.z > 0.5 # noqa: E731 + b = M.Build("Pack", None, OFF) # authored in the hull's coordinates + d, m, s = b[CORE], b["machine"], b["steel"] + for i, (y, w, ln, h) in enumerate(((-0.42, 0.66, 0.74, 0.5), (-1.28, 0.58, 0.66, 0.42))): z = RF.top(y) - 0.06 - d.box(T((0, y, z + 0.5 * h)), (w, ln, h)) - k.hull([(0.5 * w + 0.03, y + 0.5 * ln + 0.03, z + h), (0.5 * w + 0.03, y - 0.5 * ln - 0.03, z + h), (0.5 * w - 0.05, y + 0.5 * ln - 0.05, z + h + 0.07), (0.5 * w - 0.05, y - 0.5 * ln - 0.05, z + h + 0.07), - (0.5 * w + 0.03, y + 0.5 * ln + 0.03, z + h - 0.1), (0.5 * w + 0.03, y - 0.5 * ln - 0.03, z + h - 0.1)], mirror=True) - H.louvres(d, M.frame_at((0, y, z + h + 0.07), (0, 0, 1), (0, 1, 0)), w - 0.2, ln - 0.2, 5, depth=0.05) + out += kin(block(f"Pack.stack{i}", box_pts(-0.5 * w, 0.5 * w, y - 0.5 * ln, y + 0.5 * ln, z, z + h), CORE, OFF, bevel=0.01)) + out += kin(block(f"Pack.lid{i}", box_pts(-0.5 * w - 0.05, 0.5 * w + 0.05, y - 0.5 * ln - 0.05, y + 0.5 * ln + 0.05, z + h - 0.02, z + h + 0.12, 0.05), P if i else P2, OFF, clad=up, seed=40 + i, split=0.2)) for side in (-1, 1): - H.louvres(d, M.frame_at((side * 0.5 * w, y, z + 0.5 * h - 0.04), (side, 0, 0), (0, 0, 1)), ln - 0.16, h - 0.2, 4, depth=0.05) - H.heat_fins(m, M.frame_at((0, y - 0.5 * ln - 0.1, z + 0.5 * h), (1, 0, 0), (0, 0, 1)), 0.16, h - 0.08, 7, 0.07) + HP.louvres(d, M.frame_at((side * 0.5 * w, y, z + 0.5 * h - 0.04), (side, 0, 0), (0, 0, 1)), ln - 0.16, h - 0.2, 4, depth=0.05) + HP.heat_fins(m, M.frame_at((0, y - 0.5 * ln - 0.1, z + 0.5 * h), (1, 0, 0), (0, 0, 1)), 0.16, h - 0.08, 7, 0.07) + for side in (-1, 1): # exhaust stacks + f = M.frame_at((side * 0.2, -1.95, RF.top(-1.95) - 0.1), (0, -0.12, 1), (0, 1, 0)) + prof = [(0, 0), (0.13, 0)] + for k in range(5): + prof += [(0.13, 0.1 * k + 0.02), (0.155, 0.1 * k + 0.04), (0.155, 0.1 * k + 0.08), (0.13, 0.1 * k + 0.1)] + d.lathe(f, prof + [(0.13, 0.62), (0.1, 0.62), (0.1, 0.4), (0, 0.4)], 20) bell = [(0.0, 0.0), (0.2, 0.0), (0.2, 0.16), (0.15, 0.24), (0.25, 0.5), (0.33, 0.62), (0.29, 0.62), (0.21, 0.5), (0.1, 0.24), (0.0, 0.24)] + zt = lambda y: RF.chine(y) + 0.12 # noqa: E731 for side in (-1, 1): - x0, x1 = 0.5, 1.0 - y0, y1 = -1.75, 0.0 - zt = lambda y: RF.chine(y) + 0.1 # noqa: E731 - pts = [] - for y, w0, drop in ((y1, 0.0, 0.62), (-0.5, 0.06, 0.8), (-1.3, 0.04, 0.72), (y0, -0.06, 0.5)): - pts += [(side * (x0 - 0.12), y, zt(y)), (side * (x1 + w0 - 0.1), y, zt(y)), (side * (x1 + w0), y, zt(y) - 0.14), (side * (x1 + w0), y, zt(y) - drop + 0.1), (side * (x1 + w0 - 0.14), y, zt(y) - drop), (side * (x0 - 0.12), y, zt(y) - drop)] - k.hull(pts) - H.louvres(d, M.frame_at((side * (x1 + 0.06), -0.52, zt(-0.5) - 0.4), (side, 0, 0), (0, 0, 1)), 0.62, 0.4, 5, depth=0.05) - H.louvres(d, M.frame_at((side * (x1 + 0.04), -1.3, zt(-1.3) - 0.36), (side, 0, 0), (0, 0, 1)), 0.5, 0.34, 4, depth=0.05) - m.bolts(M.frame_at((side * 0.78, -0.9, zt(-0.9) + 0.005), (0, 0, 1), (0, 1, 0)), 0.16, 8, 0.03) - d.box(T((side * 0.78, -1.0, zt(-1.0) - 0.84)), (0.5, 0.56, 0.3)) # the jet's trunnion block under the nacelle - m.lathe(M.frame_at((side * 0.78, -1.05, zt(-1.0) - 0.92), (0, -0.5, -1.0), (1, 0, 0)), bell, 28) - d.lathe(M.frame_at((side * 0.78, -1.05, zt(-1.0) - 0.9), (0, -0.5, -1.0), (1, 0, 0)), [(0.0, 0.1), (0.24, 0.1), (0.24, 0.2), (0.0, 0.2)], 28) - d.box(T((0, -0.9, RF.bot(-0.9) - 0.16)), (1.0, 0.9, 0.3)) + tag = "R" if side > 0 else "L" + X = lambda a, c: (min(side * a, side * c), max(side * a, side * c)) # noqa: E731 + for k, (y0, y1, x1, drop, mat) in enumerate(((0.06, -0.56, 1.0, 0.62, P), (-0.6, -1.2, 1.1, 0.84, P2), (-1.24, -1.78, 0.96, 0.56, P))): + z1 = zt(0.5 * (y0 + y1)) + 0.03 * k + out += kin(block(f"Pack.block{k}{tag}", box_pts(*X(0.4, x1), y1, y0, z1 - drop, z1, 0.06), mat, OFF, clad=lambda n, c: True, seed=50 + 3 * k + (side > 0), split=0.3)) + ym = 0.5 * (y0 + y1) + if k == 1: + HP.heat_fins(m, M.frame_at((side * (x1 + 0.09), ym, z1 - 0.42), (0, 1, 0), (0, 0, 1)), 0.16, 0.5, 6, 0.08) + else: + HP.louvres(d, M.frame_at((side * (x1 + 0.055), ym, z1 - 0.5 * drop), (side, 0, 0), (0, 0, 1)), abs(y0 - y1) - 0.24, drop - 0.3, 4, depth=0.05) + m.bolts(M.frame_at((side * 0.72, ym, z1 + 0.058), (0, 0, 1), (0, 1, 0)), 0.11, 6, 0.02) + out += kin(block(f"Pack.stow{tag}", box_pts(*X(0.5, 0.92), -0.5, -0.06, zt(-0.3) + 0.04, zt(-0.3) + 0.3, 0.04), CORE, OFF, bevel=0.01)) + b["hazard"].box(T((side * 0.71, -0.28, zt(-0.3) + 0.303)), (0.34, 0.08, 0.012)) + for ya, yb in ((-0.66, -1.16), (-1.3, -1.72)): # grab rails on the blocks' tops + za = zt(0.5 * (ya + yb)) + 0.22 + s.rod((side * 0.94, ya, za), (side * 0.94, yb, za), 0.018, 8) + for yy in (ya, yb): + s.rod((side * 0.94, yy, za - 0.16), (side * 0.94, yy, za), 0.018, 8) + f = M.frame_at((side * 0.66, -2.06, zt(-2.0) - 0.62), (0, 0, 1), (0, 1, 0)) # the canister + d.lathe(f, [(0, 0), (0.17, 0), (0.2, 0.04), (0.2, 0.66), (0.16, 0.72), (0.07, 0.72), (0.07, 0.78), (0, 0.78)], 20) + for zz in (0.14, 0.5): + m.lathe(f @ T((0, 0, zz)), [(0.2, 0), (0.215, 0), (0.215, 0.05), (0.2, 0.05)], 20) + b["hazard"].lathe(f @ T((0, 0, 0.3)), [(0.203, 0), (0.203, 0.1)], 20) + d.box(T((side * 0.5, -2.02, zt(-2.0) - 0.3)), (0.3, 0.2, 0.36)) + d.box(T((side * 0.78, -0.92, zt(-0.9) - 0.94)), (0.5, 0.5, 0.24)) # the jet's trunnion block under the middle block + m.lathe(M.frame_at((side * 0.78, -0.98, zt(-0.9) - 1.02), (0, -0.5, -1.0), (1, 0, 0)), bell, 28) + d.lathe(M.frame_at((side * 0.78, -0.98, zt(-0.9) - 1.0), (0, -0.5, -1.0), (1, 0, 0)), [(0.0, 0.1), (0.24, 0.1), (0.24, 0.2), (0.0, 0.2)], 28) + d.box(T((0, -0.9, RF.chine(-0.9) - 0.34)), (1.0, 0.9, 0.3)) + # REAR view: the plated back of the hip block under the boom, a louvred centre plate between two stepped wings + for name, x, w, lift, mat, fits in (("skirt", 0.0, 0.5, 0.0, P, [("louvres", 0.0, 0.18, 0.5, 0.24, 4), ("bolts", 0.22)]), ("skirtR", 0.66, 0.3, -0.08, P2, [("bolts", 0.2)]), ("skirtL", -0.66, 0.3, -0.08, P2, [("bolts", 0.2)])): + fr = M.frame_at((x, 0.3 - lift, 4.62), (0.35 * (x > 0) - 0.35 * (x < 0), -1, -0.1), (0, 0, 1)) + obj, ring = slab(f"Pack.{name}", fr, [(-w, -0.62), (w, -0.62), (w - 0.06, 0.52), (-w + 0.06, 0.52)], 0.14, mat, world=OFF) + dress(obj, fr, ring, mat, True, 0.4, fits, seed=70) + out += kin(obj) + for x in (-0.3, 0.0, 0.3): + s.rod((x, -0.3, RF.chine(-0.3) - 0.4), (x, -1.9, RF.chine(-1.9) - 0.26), 0.035, 8) ty, tz = RF.TAIL - f = M.frame_at((0, ty + 0.3, tz - 0.22), (0, -1, -0.12), (1, 0, 0)) - d.lathe(f, [(0.0, 0.0), (0.36, 0.0), (0.36, 0.34), (0.3, 0.4), (0.0, 0.4)], 32) - for j in range(3): - m.lathe(f @ T((0, 0, 0.05 + 0.1 * j)), [(0.36, 0.0), (0.39, 0.0), (0.39, 0.04), (0.36, 0.04)], 32) - m.lathe(f @ T((0, 0, 0.36)), [(r * 1.15, z * 0.9) for r, z in bell], 32) - out = b.done(bevel=0.0) + f = M.frame_at((0, ty + 0.34, tz - 0.2), (0, -1, -0.1), (1, 0, 0)) + d.lathe(f, [(0.0, 0.0), (0.42, 0.0), (0.42, 0.4), (0.34, 0.47), (0.0, 0.47)], 32) + for j in range(4): + m.lathe(f @ T((0, 0, 0.04 + 0.095 * j)), [(0.42, 0.0), (0.455, 0.0), (0.455, 0.04), (0.42, 0.04)], 32) + m.lathe(f @ T((0, 0, 0.43)), [(r * 1.25, z * 0.9) for r, z in bell], 32) + s.rod((0.3, -2.2, RF.top(-2.2)), (0.32, -2.3, RF.top(-2.2) + 0.55), 0.012, 6) # the aerial + d.cylinder(T((0.3, -2.2, RF.top(-2.2) + 0.05)), 0.04, 0.12, 10) + out += b.done(bevel=0.0) for side in (-1, 1): - pts = [Vector((side * 0.72, W(y), RF.chine(y) + 0.19)) for y in (0.05, -0.8, -1.7)] - out.append(M.hose(f"Spine.pipe{side}", pts[0], pts[1] - pts[0], pts[2], pts[1] - pts[2], 0.05, sag=0.0, via=(pts[1],), mat=CORE)) - a, c = Vector((side * 0.3, W(-0.42), RF.top(-0.42) + 0.1)), Vector((side * 0.74, W(-0.6), RF.chine(-0.6) + 0.12)) - out.append(M.hose(f"Spine.feed{side}", a, Vector((side, 0, 0)), c, Vector((0, 0, 1)), 0.04, sag=0.0, mat=CORE)) + tag = "R" if side > 0 else "L" + runs = [((side * 0.33, -0.3, RF.top(-0.42) + 0.14), (side, 0, 0.3), (side * 0.7, -0.3, zt(-0.3) + 0.0), (0, 0, 1), 0.045), + ((side * 0.29, -1.2, RF.top(-1.3) + 0.12), (side, 0, 0.3), (side * 0.74, -0.95, zt(-0.9) + 0.03), (0, 0, 1), 0.04), + ((side * 0.29, -1.45, RF.top(-1.3) + 0.2), (side, -0.3, 0.2), (side * 0.72, -1.5, zt(-1.5) + 0.06), (0, 0, 1), 0.035), + ((side * 0.2, -1.95, RF.top(-1.95) + 0.05), (side, 0, -0.2), (side * 0.62, -2.06, zt(-2.0) + 0.14), (0, 0, 1), 0.03), + ((side * 1.0, -0.3, zt(-0.3) - 0.5), (side * 0.3, 0, -1), (side * 0.9, -0.92, zt(-0.9) - 0.86), (0, 1, 0.3), 0.04)] + for k, (a, da, c, dc, r) in enumerate(runs): + a, c = Vector((a[0], W(a[1]), a[2])), Vector((c[0], W(c[1]), c[2])) + out.append(M.hose(f"Pack.hose{k}{tag}", a, Vector(da), c, Vector(dc), r, sag=0.0, mat="rubber", stiffness=0.5)) + COUNT["hoses"] += 1 return out -def detail(): - """Hero view: the number 27 on each Cheek plate and a bolt row inside the rims of the big plates, by surface.py - on the cages as built, before they are frozen. Each feature is tried on its own: one that fails is reported, - not drawn. Returns (made, failed).""" - import surface as S - S.materials() - made, failed = 0, [] - for plate, what in [(f"Torso.{n}{t}", w) for t in ("L", "R") for n, w in (("CheekL", "27"), ("ShoulderU", "bolts"), ("Jaw", "bolts"))] + [("Torso.DeckA", "bolts"), ("Torso.Hood1", "bolts"), ("Torso.Hood2", "bolts")]: - try: - skin = S.Skin(plate) - if what == "27": - at = sum((v.co for v in skin.bm.verts), Vector()) / len(skin.bm.verts) - S.numeral(skin, S._frame(*skin.nearest(at), (0, 0, 1)), "27", 0.36, "marking_fresh") - else: - S.bolt_row(skin, S.along(skin, ("rim", 0), spacing=0.3, offset=0.07, margin=0.1), r=0.018) - skin.prune() - skin.commit() - made += 1 - except BaseException as error: - failed.append(f"{plate} {what}: {type(error).__name__} {str(error)[:120]}") - print(f"DETAIL: {made} features made, {len(failed)} failed" + "".join("\n DETAIL FAILED " + f for f in failed), flush=True) - return made, failed - - # What raptor.py photographs for the components sheet: {crop of concepts.json "components": (target, span, azimuth, elevation)} -COMPONENTS = {"cockpit": ((0.6, W(4.4), 5.2), 3.4, -60.0, 14.0), "lasers": ((0.0, W(3.4), 3.7), 2.6, -20.0, -12.0), "battery": ((0.0, W(1.75), 6.7), 3.6, -40.0, 12.0), +COMPONENTS = {"cockpit": ((0.6, W(4.4), 5.2), 3.4, -60.0, 14.0), "lasers": ((0.0, W(3.4), 3.9), 2.6, -20.0, -12.0), "battery": ((0.0, W(1.75), 6.7), 3.6, -40.0, 12.0), "spine": ((0.0, W(-1.0), 5.8), 4.2, -150.0, 8.0), "leg": ((-1.5, 0.3, 3.2), 4.2, 62.0, 2.0), "foot": ((-1.4, 0.4, 0.5), 3.4, 40.0, 10.0), "arm": ((1.4, W(3.2), 4.4), 2.4, -70.0, 4.0)} @@ -705,10 +887,12 @@ def full(cores): def done(objects): freeze(objects) return objects + done(underbody()) done(pelvis_block()) body, _ = legs(cores) arms() done(lasers()) done(battery()) - done(spine()) + done(pack()) + print("COUNT", json.dumps(COUNT), flush=True) return body diff --git a/surfaces/blender/experiments/mechs/raptor_form.py b/surfaces/blender/experiments/mechs/raptor_form.py index 7e83d1b..f795fca 100644 --- a/surfaces/blender/experiments/mechs/raptor_form.py +++ b/surfaces/blender/experiments/mechs/raptor_form.py @@ -1,16 +1,17 @@ -"""RAPTOR as numbers: the side view's scale, the traced profile, the hull's cage blocked under it (one mirrored free -cage, fitted to the trace by brokkr_reference in raptor_body.hull_mass), the plates' map in the cage's coordinates, +"""RAPTOR as numbers: the side view's scale, the traced profile, the hull's wedge under it (sections; hard +plates in the wedge's own coordinates), the digitigrade skeleton and its poses (digitigrade.py). Plain Python and numpy; no Blender. World: x to the mech's right, y forward, z up, metres at the sheet's 6.8 m, origin on the ground under the hips. The hull keeps its own coordinates (yh, z): the sheet's side view, yh = 0 on the trace's hip column; OFF stands it in the world, SHIFT back. -Third pass (sheet 38 the turnaround, image 43 the second hero): - hull ONE sculpted mass: a mirrored free cage of 12 six-point sections between a nose and a tail vertex, creased - down the dorsal line and along one chine a side, nothing else. Its section is the FRONT view's: a narrow - deck (1.1 m), flanks flaring to the chine low on the side (2.14 m), the underside tucked to a keel. The - second pass read the shoulder pods as hull (2.7 m) and stood a ten-sided box under the curve. +Fourth pass (sheet 38 the turnaround, image 43 the second hero): + hull a slim faceted WEDGE of hard plates over a dark core (section, surf, hull_plates): a deck, a flank that + leans in to it, an upright jaw band down to the chine and a lip tucked under it. The armour ends at the + lip; below it the hull is an open keel with its machinery. The third pass built one soft mass down to the + belly's traced line and it read as a pod with a deep round belly: that trace is the bottom of the lasers + and the machinery, not of the armour. hips the hip is where the far leg's thigh runs up to under the chine (sheet (338, 716), 4.67 m), and the legs' planes stand 2.8 m apart (FRONT view), outside the hull's 2.14 m: the thigh's housing stands under the chine's overhang, clear of the tucked underside. Nothing spreads the hips. @@ -55,39 +56,34 @@ chine = lambda yh: float(np.interp(yh, *_CHINE)) # noqa: E731 the chin NOSE = tuple(float(v) for v in SHEET.world(BOOK["side"]["curve"][0])) TAIL = tuple(float(v) for v in SHEET.world(BOOK["side"]["curve"][-1])) -# The hull's sections, nose to tail: (station yh, half-widths of the deck edge, the shoulder, the chine, the bilge). -# FRONT view: deck 32 px (1.1 m), chine 61 px (2.14 m) at v 705, the underside back in to 1.1 m. REAR view: the spine -# 40 px. The bilge is tucked under the chine all the way: at the hips' station it stands 0.5 m inside the thighs. -STATIONS = [(5.45, 0.10, 0.20, 0.24, 0.13), (5.0, 0.20, 0.42, 0.50, 0.26), (4.4, 0.34, 0.66, 0.78, 0.40), (3.6, 0.48, 0.88, 1.00, 0.52), (2.8, 0.55, 0.98, 1.07, 0.56), (2.0, 0.57, 1.00, 1.07, 0.56), - (1.2, 0.56, 0.96, 1.02, 0.52), (0.5, 0.50, 0.84, 0.90, 0.46), (-0.1, 0.38, 0.56, 0.60, 0.36), (-0.7, 0.32, 0.46, 0.50, 0.30), (-1.5, 0.28, 0.40, 0.43, 0.26), (-2.2, 0.22, 0.30, 0.32, 0.20)] -PER = 6 # a section's points: dorsal, deck edge, shoulder, chine, bilge, keel -RIDGE, CROWN, FS, FB = 0.05, 0.08, 0.52, 0.34 +# --- the hull: a slim faceted wedge of hard plates over a dark core ------------------------------------------------------ +# A section, nose to tail: (station yh, half-widths of the deck edge, the belt, the chine, the lip). FRONT view: deck +# 1.2 m, chine 2.14 m at v 705. The armour ends at the lip, 0.16 m under the chine: nothing is plated below it. Under +# the lip the hull is the open keel and its machinery (raptor_body.underbody), down to the belly's traced line. +STATIONS = [(5.45, 0.14, 0.27, 0.25, 0.14), (5.0, 0.24, 0.50, 0.49, 0.30), (4.4, 0.38, 0.77, 0.76, 0.48), (3.6, 0.52, 0.99, 0.98, 0.62), (2.8, 0.60, 1.08, 1.07, 0.66), (2.0, 0.62, 1.08, 1.07, 0.66), + (1.2, 0.60, 1.03, 1.02, 0.62), (0.5, 0.54, 0.91, 0.90, 0.56), (-0.1, 0.42, 0.62, 0.60, 0.42), (-0.7, 0.36, 0.50, 0.48, 0.34), (-1.5, 0.32, 0.43, 0.41, 0.30), (-2.3, 0.26, 0.34, 0.32, 0.24)] +COLS = 5 # a section's points: ridge, deck edge, belt, chine, lip (column t = 0..4) +CROWN, LIP = 0.07, 0.16 -def ring(row): - """One section's six cage points (x, yh, z), dorsal to keel. The dorsal point stands RIDGE over the trace (the - cage stands outside its limit curve) and the deck's edge CROWN under it: the raised dorsal line.""" - yh, wd, ws, wc, wb = row - zt, zb = top(yh), bot(yh) - zc = min(max(chine(yh), zb + 0.3 * (zt - zb)), zt - 0.3 * (zt - zb)) - return [(0.0, yh, zt + RIDGE), (wd, yh, zt - CROWN), (ws, yh, zc + FS * (zt - zc)), (wc, yh, zc), (wb, yh, zb + FB * (zc - zb)), (0.0, yh, zb - 0.03)] +def section(yh): + """The hull's section at station yh: five points (x, yh, z), ridge to lip. Widths run straight between the + stations (the wedge's facets); heights are the traced dorsal line and chine. The belt is the upper edge of the + jaw band: the flank above it leans in to the deck, the band below it stands upright.""" + ys = [r[0] for r in STATIONS] + yq = min(max(yh, ys[-1]), ys[0]) + w = [float(np.interp(-yq, [-y for y in ys], [r[k] for r in STATIONS])) for k in (1, 2, 3, 4)] + zt, zc = top(yh), chine(yh) + belt = zc + min(0.42, 0.46 * (zt - zc)) + return [(0.0, yh, zt), (w[0], yh, zt - CROWN), (w[1], yh, belt), (w[2], yh, zc), (w[3], yh, zc - LIP)] -def hull_cage(): - """The hull's mass as a mirrored free cage, authored on the right: {"verts", "faces" (wound outward), "creases", - "dorsal", "chine" (the two hard runs, nose to tail, by vertex)}. Vertex 0 is the nose's tip, the last the - tail's; ring i, point j is 1 + 6 i + j. 74 vertices.""" - R = len(STATIONS) - verts = [(0.0, NOSE[0], NOSE[1])] + [p for row in STATIONS for p in ring(row)] + [(0.0, TAIL[0], TAIL[1] - 0.04)] - at = lambda i, j: 1 + PER * i + j # noqa: E731 - N, T = 0, len(verts) - 1 - faces = [(N, at(0, j), at(0, j + 1)) for j in range(PER - 1)] - faces += [(at(i, j), at(i + 1, j), at(i + 1, j + 1), at(i, j + 1)) for i in range(R - 1) for j in range(PER - 1)] - faces += [(at(R - 1, j), T, at(R - 1, j + 1)) for j in range(PER - 1)] - run = lambda j: [N] + [at(i, j) for i in range(R)] + [T] # noqa: E731 - dorsal, ch = run(0), run(3) - creases = [(a, b, 1.0) for r in (dorsal, ch) for a, b in zip(r, r[1:])] - return {"verts": verts, "faces": faces, "creases": creases, "dorsal": dorsal, "chine": ch} +def surf(yh, t): + """(x, yh, z) on the wedge at station yh, column t (0 ridge, 1 deck edge, 2 belt, 3 chine, 4 lip).""" + s = section(yh) + j = min(int(math.floor(t)), COLS - 2) + f = t - j + return tuple(a + f * (b - a) for a, b in zip(s[j], s[j + 1])) def cameras(): @@ -102,62 +98,70 @@ def cameras(): return out -# --- the hull's plates: free cages on the mass's surface -------------------------------------------------------------- -Y_CANOPY = 3.55 # hull station of the canopy's brow hoop -GLASS, FRAME = 0.035, 0.1 # lifts: the glazing lies on the mass; its frame stands over it +# --- the hull's plates: every one HARD (mech-lessons-2026-12-03) -------------------------------------------------------- +Y_CANOPY = 3.5 # hull station of the canopy's brow hoop +P1, P2, DARK = "khaki", "olive_light", "gunmetal" -def P(name, rows, cols, crease=(), mat="khaki", thick=0.06, mirror=False, sided=False): - return {"name": name, "rows": rows, "cols": cols, "crease": tuple(crease), "mat": mat, "thick": thick, "mirror": mirror, "sided": sided} +def H(name, outline, lift=0.06, thick=0.10, mat=P1, clad=True, split=0.9, fit=(), gap=0.025, back=0.94): + """A hard plate on the wedge: `outline` [(yh, t)] its corners in the wedge's own coordinates, counter-clockwise or + not; built as a slab whose outer face is the plane through them, standing `lift` off the wedge, `thick` deep, + drawn in `gap` on every edge so a seam shows; `clad` panels its face, splitting it where it is over `split` m2; + `fit` is what stands on it: ("num", text, height), ("bolts", spacing), ("handle", u, v, length), ("eye", u, v), + ("louvres", u, v, w, h, n[, roll]), ("port", u, v, r), in the face's own metres from its middle (u aft to fore, v up).""" + return {"name": name, "outline": outline, "lift": lift, "thick": thick, "mat": mat, "clad": clad, "split": split, "fit": tuple(fit), "gap": gap, "back": back} def hull_plates(): - """The hull's armour and glazing: each plate a FREE cage, a grid of rows (station yh, lift, rake: metres of - station per column) by columns t on the fitted mass's surface (raptor_body.surf), where t is 0 on the dorsal - line, 1 the deck's edge, 2 the shoulder, 3 the chine, 4 the bilge, 5 the keel. + """The wedge's armour, one side (all are built a side): hero views of sheet 38 and image 43, the SIDE view for + the stations. Every plate is hard: both concepts draw the hull as flat facets with straight, chamfered edges, + lapped and stepped; nothing on it curves but the dorsal line's sweep, which the facets' stations carry. - The concepts' armour is flat facets lapped over a swept body, so most plates are FOUR vertices: one facet, - pinned at its corners, standing off the mass's curve by its own lift; the mass's sweep is carried by where the - facets stand, not by bending them. A plate has a third column, creased, only where it wraps the chine or the - dorsal line. Rows run aft to fore; the rear edge is lifted over the front edge of the plate behind. - - The cockpit is the whole front: glazing over the crown (GlassTop) and down each flank to above the chine - (GlassA, GlassF; these follow the mass's curve, three rows), under a Brow hoop, a Bar and a Pillar a side, over a Sill rail; the NoseCap is the beak, - faceted. The Jaw is the long strake that carries the chine from under the canopy to the beak. Behind: Cheek - (upper, and the lower that carries the number), Shoulder standing proud over the hip (upper, and the lower - round the chine), Flank; the Deck in two either side of the dorsal ridge and a Collar hoop; Bilge and Keel - under, the keel open under the chest for the lasers. The boom: three lapped hoods and a tail keel.""" + Fore to aft: the Jaw band, three thick slabs from the beak back along the chine under the canopy (sheet 38's + hero: the heavy strake under the glass); the Collar, a proud hoop behind the canopy; the Cheek, the five-sided + plate that carries the number; a Gill of upright louvres between Cheek and Shoulder (sheet 38's hero); the Shoulder, standing proudest, over + the hip; decks either side of the dorsal spine; the belt band under them in short plates; three lapped hoods + down the boom; the Lip under the chine, tucked in, in short dark plates.""" c = Y_CANOPY - hoop = dict(crease=[0, 1, 2], mirror=True) return [ - P("GlassTop", [(c + 0.05, GLASS, 0), (4.05, GLASS, 0), (4.6, GLASS, 0), (5.2, GLASS, 0)], [0, 1], mat="glass", thick=0.04, mirror=True), - P("GlassA", [(c + 0.05, GLASS, 0), (4.0, GLASS, 0), (4.45, GLASS, 0)], [1, 1.5, 2, 2.7], mat="glass", thick=0.04, sided=True), - P("GlassF", [(4.45, GLASS, 0), (4.85, GLASS, 0), (5.2, GLASS, 0)], [1, 1.5, 2, 2.7], mat="glass", thick=0.04, sided=True), - P("Brow", [(c - 0.18, 0.15, 0), (c + 0.13, 0.12, 0)], [0, 1, 2, 2.9], **hoop), - P("Bar", [(4.38, FRAME, 0), (4.52, FRAME, 0)], [0, 1, 2, 2.72], thick=0.05, **hoop), - P("Pillar", [(c + 0.1, FRAME, 0), (4.45, FRAME, 0), (5.22, FRAME, 0)], [0.86, 1.0, 1.14], crease=[1], thick=0.05, sided=True), - P("Sill", [(c - 0.02, 0.10, 0), (4.45, 0.10, 0), (5.24, 0.09, 0)], [2.62, 2.84], thick=0.06, sided=True), - P("NoseCap", [(5.14, 0.12, 0), (5.45, 0.08, 0), (5.7, 0.05, 0)], [0, 1, 2, 3, 3.7], crease=[0, 1, 2, 3], mirror=True), - P("Jaw", [(3.15, 0.13, 0), (4.3, 0.11, 0), (5.2, 0.08, 0)], [2.78, 3, 3.34], crease=[1], thick=0.07, sided=True), - P("Chin", [(3.8, 0.07, 0), (4.5, 0.06, 0), (5.18, 0.05, 0)], [3.4, 4.3, 5], sided=True, mat="gunmetal"), - P("CheekU", [(2.3, 0.14, -0.35), (c - 0.12, 0.09, 0)], [1.14, 2.06], thick=0.07, sided=True), - P("CheekL", [(2.15, 0.12, -0.35), (c - 0.14, 0.08, 0)], [1.98, 2.97], thick=0.07, sided=True), - P("ShoulderU", [(0.7, 0.24, -0.4), (2.45, 0.19, -0.4)], [1.08, 2.08], thick=0.08, mat="olive_light", sided=True), - P("ShoulderL", [(0.85, 0.22, -0.4), (2.4, 0.17, -0.4)], [1.98, 3, 3.14], crease=[1], thick=0.08, mat="olive_light", sided=True), - P("Flank", [(0.08, 0.11, 0), (0.95, 0.07, -0.2)], [1.2, 2, 3], crease=[1], sided=True), - P("DeckA", [(1.95, 0.14, 0), (c - 0.1, 0.08, 0)], [0, 1, 1.2], crease=[0, 1], mirror=True), - P("DeckB", [(0.3, 0.14, 0), (2.12, 0.07, 0)], [0, 1, 1.2], crease=[0, 1], mirror=True), - P("Collar", [(2.98, 0.22, 0), (c - 0.26, 0.19, 0)], [0, 1, 2, 2.6], thick=0.07, mat="olive_light", **hoop), - P("BilgeA", [(2.05, 0.09, 0), (3.4, 0.04, 0)], [3.14, 4, 4.6], crease=[1], sided=True, mat="gunmetal"), - P("BilgeB", [(0.2, 0.09, 0), (2.15, 0.04, 0)], [3.2, 4, 4.6], crease=[1], sided=True, mat="gunmetal"), - P("Keel", [(0.2, 0.07, 0), (2.0, 0.03, 0)], [4.64, 5], crease=[1], mirror=True, mat="gunmetal"), - P("Hood1", [(-0.75, 0.15, 0), (0.36, 0.07, 0)], [0, 1, 2, 3, 3.5], crease=[0, 1, 3], thick=0.07, mirror=True), - P("Hood2", [(-1.6, 0.13, 0), (-0.62, 0.06, 0)], [0, 1, 2, 3, 3.5], crease=[0, 1, 3], thick=0.07, mirror=True), - P("Hood3", [(-2.36, 0.10, 0), (-1.48, 0.05, 0)], [0, 1, 2, 3, 3.5], crease=[0, 1, 3], thick=0.07, mirror=True), - P("TailKeel", [(-2.3, 0.06, 0), (-0.3, 0.05, 0)], [3.6, 4.3, 5], crease=[1], mirror=True, mat="gunmetal"), + H("Jaw1", [(5.5, 2), (5.5, 3), (4.75, 3), (4.75, 2)], 0.10, 0.14, split=9, fit=[("bolts", 0.22)]), + H("Jaw2", [(4.72, 1.96), (4.72, 3), (3.95, 3), (3.95, 1.9)], 0.13, 0.16, P2, fit=[("bolts", 0.24), ("handle", 0.0, 0.02, 0.3)]), + H("Jaw3", [(3.92, 1.9), (3.92, 3), (3.05, 3), (3.25, 2)], 0.10, 0.14, fit=[("bolts", 0.24), ("port", -0.05, 0.0, 0.09)]), + H("JawLip1", [(5.4, 3), (5.4, 4), (4.5, 4), (4.5, 3)], 0.04, 0.08, DARK, clad=False), + H("JawLip2", [(4.46, 3), (4.46, 4), (3.4, 4), (3.4, 3)], 0.05, 0.08, P1, split=9), + H("CollarU", [(c, 0.12), (c, 1), (c - 0.36, 1), (c - 0.42, 0.12)], 0.17, 0.16, P2, split=9, fit=[("bolts", 0.2)]), + H("CollarF", [(c, 1), (c, 2), (c - 0.2, 2), (c - 0.36, 1)], 0.16, 0.16, P2, split=9, fit=[("bolts", 0.2)]), + H("Cheek", [(3.08, 1.04), (3.24, 1.96), (2.5, 1.96), (2.32, 1.7), (2.32, 1.04)], 0.11, 0.13, clad=False, fit=[("num", "27", 0.5), ("bolts", 0.26)]), + H("CheekDeck", [(3.04, 0.12), (3.04, 0.98), (2.0, 0.98), (2.0, 0.12)], 0.07, 0.10, fit=[("handle", 0.2, 0.0, 0.34), ("eye", -0.3, 0.1)]), + H("Gill", [(2.28, 1.04), (2.28, 1.96), (1.98, 1.96), (1.98, 1.04)], 0.05, 0.09, DARK, clad=False, fit=[("louvres", 0.0, 0.0, 0.56, 0.2, 4, 90.0)]), + H("Shoulder", [(1.94, 1.04), (1.94, 2.0), (0.62, 2.0), (0.42, 1.04)], 0.2, 0.16, P2, split=0.7, fit=[("bolts", 0.24), ("eye", 0.3, 0.2)]), + H("ShoulderDeck", [(1.96, 0.12), (1.96, 0.98), (0.44, 0.98), (0.44, 0.12)], 0.09, 0.10, split=0.6, fit=[("handle", -0.4, 0.0, 0.34)]), + H("Belt1", [(3.0, 2.04), (3.02, 3), (2.36, 3), (2.36, 2.04)], 0.07, 0.11, fit=[("port", 0.0, 0.0, 0.08)]), + H("Belt2", [(2.33, 2.04), (2.33, 3), (1.5, 3), (1.5, 2.04)], 0.11, 0.12, P2, split=9, fit=[("bolts", 0.22)]), + H("Belt3", [(1.47, 2.04), (1.47, 3), (0.78, 3), (0.62, 2.04)], 0.08, 0.11, fit=[("louvres", 0.0, 0.0, 0.42, 0.2, 4)], clad=False), + H("Lip1", [(3.36, 3), (3.36, 4), (2.4, 4), (2.4, 3)], 0.03, 0.08, DARK, clad=False), + H("Lip2", [(2.36, 3), (2.36, 4), (1.3, 4), (1.3, 3)], 0.05, 0.08, P1, split=9), + H("Lip3", [(1.26, 3), (1.26, 4), (0.5, 4), (0.5, 3)], 0.03, 0.08, DARK, clad=False), + H("Hood1D", [(0.4, 0.12), (0.4, 1), (-0.66, 1), (-0.66, 0.12)], 0.14, 0.11, split=9, fit=[("bolts", 0.22)]), + H("Hood1F", [(0.56, 1.04), (0.74, 3), (-0.1, 3), (-0.66, 3), (-0.66, 1.04)], 0.13, 0.12, split=0.5, fit=[("bolts", 0.24)]), + H("Hood2D", [(-0.6, 0.12), (-0.6, 1), (-1.5, 1), (-1.5, 0.12)], 0.10, 0.10, P2, split=9), + H("Hood2F", [(-0.62, 1.04), (-0.62, 3), (-1.5, 3), (-1.5, 1.04)], 0.09, 0.11, P2, fit=[("louvres", 0.0, 0.0, 0.4, 0.2, 4)], clad=False), + H("Hood3D", [(-1.46, 0.12), (-1.46, 1), (-2.3, 1), (-2.3, 0.12)], 0.06, 0.09, split=9, fit=[("bolts", 0.2)]), + H("Hood3F", [(-1.46, 1.04), (-1.46, 3), (-2.3, 3), (-2.3, 1.04)], 0.05, 0.10, split=9, fit=[("bolts", 0.22)]), + H("HoodLip", [(0.4, 3), (0.4, 4), (-2.2, 4), (-2.2, 3)], 0.03, 0.07, DARK, clad=False), ] +# The canopy (RECESSED COCKPIT inset; both heroes): the whole front of the wedge above the jaw band. Its lattice's +# nodes are (station, column): hoops at the stations, rails down the ridge, the deck edge and the belt, and a +# diagonal across each flank pane, as the inset draws its triangulated panes. +CANOPY_Y = [Y_CANOPY, 4.0, 4.5, 4.95, 5.36] +CANOPY_T = [0.0, 1.0, 2.0] +KINDS = {f"Torso.{p['name']}": "hard" for p in hull_plates()} +KINDS.update({"Torso.core": "hard", "Torso.Beak": "hard", "Torso.Canopy.glass": "hard", "Torso.Canopy.frame": "hard", "Torso.Roof": "hard", "Torso.Spine": "hard", "Thigh.house": "hard", "Thigh.shield": "hard", + "Shin.house": "hard", "Shin.shield": "hard", "Cannon.house": "hard", "Cannon.shield": "hard", "Pauldron": "hard", "Pack": "hard"}) # nothing on this mech is soft: the round forms are turned machinery + + # --- the skeleton ----------------------------------------------------------------------------------------------------- HIP = (0.0, float(LEGS.world(HIP_PX)[1])) # (y, z) of the hip's axis: the world's origin is under it HIP_X = 1.4 # FRONT view: the legs' centre planes stand 80 px (2.8 m) apart @@ -175,7 +179,7 @@ def _pose(marks, weights=(1.0, 1.0, 40.0)): _FIT = {side: _pose(MARKS[side]) for side in ("L", "R")} -STAND_Y = -0.45 # the standing pose's ankles, metres ahead of the hips: under the centre of mass (balance.py; raptor_balance.json) +STAND_Y = -0.75 # the standing pose's ankles, metres ahead of the hips: under the centre of mass (balance.py; raptor_balance.json) _STAND = _pose({"knee": (STAND_Y + 0.5, 3.36), "hock": (STAND_Y - 0.83, 2.37), "ankle": (STAND_Y, ANKLE_Z)}) POSES = {"side": {"L": _FIT["L"][0], "R": _FIT["R"][0]}, "hero": {"L": _FIT["R"][0], "R": _FIT["L"][0]}, "stand": {"L": _STAND[0], "R": _STAND[0]}} _path = HERE / "raptor_cameras.json" @@ -212,5 +216,5 @@ if __name__ == "__main__": print(f"LEG {side}: marked links", [round(v, 2) for v in DG.lengths(MARKS[side])], "fit angles", [round(v, 1) for v in _FIT[side][0]], "misses m (knee, hock, ankle)", [round(v, 2) for v in _FIT[side][1]]) print("STAND angles", [round(v, 1) for v in _STAND[0]], "misses", [round(v, 2) for v in _STAND[1]]) for row in STATIONS: - print("RING", row[0], [tuple(round(v, 2) for v in (p[0], p[2])) for p in ring(row)]) - print("cage", len(hull_cage()["verts"]), "verts") + print("SECTION", row[0], [tuple(round(v, 2) for v in (p[0], p[2])) for p in section(row[0])]) + print(len(hull_plates()), "hull plates a side") diff --git a/surfaces/blender/experiments/mechs/raptor_sheets.py b/surfaces/blender/experiments/mechs/raptor_sheets.py index d98ce73..45b501b 100644 --- a/surfaces/blender/experiments/mechs/raptor_sheets.py +++ b/surfaces/blender/experiments/mechs/raptor_sheets.py @@ -7,7 +7,7 @@ Reads MECH_OUT/raptor/ (raptor.py's renders per stage); writes under MECH_OUT/co raptor_character.png the same line close up on the nose and canopy, sheet | ours raptor_vs_concept.png hero and side, then front and rear: concept | ours | laid over; then image 43 | ours at its solved camera | laid over, and 43's traced roof and jaw lines against our built edges there - raptor_vs_pass2.png each view: concept | the second pass (3ced828) | this pass + raptor_vs_passes.png each view: concept | the second pass (3ced828) | the third (a9ec759) | this pass raptor_balance.png the standing pose from the side with the centre of mass (uniform density, balance.py) and the feet's contact under it; the same in plan; the masses raptor_flowlines.png the curve and the chines against the hull's built edges at the side camera @@ -35,6 +35,7 @@ if "side_solved" in cams: cams["side"]["px_per_m"] = cams["side"]["f"] / cams["side"]["distance"] second = Image.open(Path(os.environ["MECH_CONCEPTS"]) / spec["second"]["sheet"]).convert("RGB") PASS2 = Path(os.environ.get("RAPTOR_PASS2", r"F:\aeth-wt\fable-raptor-2\out\raptor")) +PASS3 = Path(os.environ.get("RAPTOR_PASS3", r"F:\aeth-wt\fable-raptor-3\out\raptor")) SIDE = spec["side"] HULL = [176, 650, 432, 765] FIG = SIDE["ground"] - SIDE["top"] @@ -155,27 +156,29 @@ W = 1200 # --- the profile sheet ------------------------------------------------------------------------------------------------- crop = fitw(view(HULL), W) chine = [("green", [tuple(p) for p in SIDE["chine"]])] -cells = [label(in_box(crop, HULL, lines=curve + chine, width=3), "sheet 38, SIDE view: the character curve (red) and the chine (green) as traced: the two runs the mass is fitted to")] -names = {"volume": "ours BEFORE plating: ONE sculpted mass, its dorsal run and chine fitted to the traces (red, green)", "plates": "ours AFTER plating: free cages lapped over the mass, the same lines", "full": "ours AFTER plating, in the build: the same curve (red)"} +cells = [label(in_box(crop, HULL, lines=curve + chine, width=3), "sheet 38, SIDE view: the character curve (red) and the chine (green) as traced: the wedge's dorsal line and the armour's lower edge")] +names = {"volume": "ours BEFORE plating: the wedge's hard core, sections on the two traces (red, green), the keel under the chine", "plates": "ours AFTER plating: hard slabs, each on its own plane, and the framed canopy; the same lines", "full": "ours AFTER plating, in the build: the same curve (red)"} notes = [] for stage in ("volume", "plates", "full"): if (src / f"{stage}_profile.png").exists(): scores[stage] = v = curve_miss(stage) cells.append(label(in_box(fitw(render(f"{stage}_profile.png"), W), HULL, lines=curve + (chine if stage == "volume" else []), width=3), names[stage])) notes.append(f"{stage:7s} mean {v['mean_px']:.2f} px ({100 * v['mean_m']:.1f} cm) p90 {v['p90_px']:.2f} max {v['max_px']:.2f} px ({100 * v['max_m']:.1f} cm) over {v['share_scored']:.2f} of the curve") -low = [label(in_box(crop, HULL, lines=curve + seam_lines(), width=2), "the plate map: each free cage's outline as built on the mass (green) and its creases (yellow)")] +low = [label(in_box(crop, HULL, lines=curve + seam_lines(), width=2), "the plate map: each hard plate's corners on the wedge (green), one side")] segs = [] if (src / "full_edges_side.json").exists(): segs = [e["seg"] for e in json.loads((src / "full_edges_side.json").read_text(encoding="utf-8"))] low.append(label(in_box(Image.new("RGB", crop.size, (30, 32, 36)), HULL, lines=curve, segs=segs, width=3), "our built plate edges at the side camera (cyan) under the curve (red)")) scores["curve_on_built_edges"] = on = fitshell.along([tuple(p) for p in SIDE["curve"]], segs, FIG) notes += ["", f"curve on built edges (fitshell.along): on {on['on']:.2f}, run {on['run']:.2f}, off {on['off']:.2f}% H"] -fitrep = json.loads((src / "raptor_fit.json").read_text(encoding="utf-8")) if (src / "raptor_fit.json").exists() else {} -scores["trace_fit"] = {k: fitrep.get(k) for k in ("traces", "moved_max_m", "moved_mean_m")} +hard = json.loads((src / "raptor_hard.json").read_text(encoding="utf-8")) if (src / "raptor_hard.json").exists() else {"hard": {}, "count": {}, "soft": []} +scores["hard"] = {"solids": len(hard["hard"]), "soft": len(hard["soft"]), **{k: v for k, v in hard["count"].items() if k != "failed"}, "failed": hard["count"].get("failed", [])} sc = cams["side"] -body = ["the traced curve against our silhouette's upper edge,", f"side camera, sheet pixels (1 px = {100 / RF.K:.1f} cm):", ""] + notes + ["", "TRACE FIT (brokkr_reference fit_sheet, tol 5.2 px):"] + [f" {t['run']:7s} unexplained {t['unexplained_px']:.2f} px, worst {t['worst_px']:.2f} px" for t in fitrep.get("traces", [])] + [ - f" cage points moved {100 * fitrep.get('moved_mean_m', 0):.0f} cm mean, {100 * fitrep.get('moved_max_m', 0):.0f} cm max", " the dorsal run is on the mirror plane: decided.", " the chine's half-width is the blocking's", " (one trace, square-on: prior_share 1.0).", "", - f"The side camera is SOLVED ({sc.get('model')}): rms {sc.get('rms') or 0:.2f} px", f"over 10 marks, {sc['px_per_m']:.2f} px a metre (set: {RF.K:.2f}).", f"The hull is on the sheet's pixels; the hips stand", f"{RF.BACK} m ahead of the sheet's (image 43).", +hc = hard["count"] +body = ["the traced curve against our silhouette's upper edge,", f"side camera, sheet pixels (1 px = {100 / RF.K:.1f} cm):", ""] + notes + ["", "HARD PLATES (raptor_hard.json):", f" {len(hard['hard'])} hard solids, 0 soft cages", + f" {hc.get('panels', 0)} stepped detail panels, {hc.get('fits', 0)} fittings,", f" {hc.get('marks', 0)} markings, {hc.get('hoses', 0)} hoses; {len(hc.get('failed', []))} fits failed", " Each hull plate's corners (station, column) are", + " read off the views by hand; its plane is the", " least-squares plane through them: my own", " plane, not a fit to a trace.", "", + f"The side camera is SOLVED ({sc.get('model')}): rms {sc.get('rms') or 0:.2f} px", f"over 10 marks, {sc['px_per_m']:.2f} px a metre (set: {RF.K:.2f}).", "The hull is on the sheet's pixels; the hips stand", f"{RF.BACK} m ahead of the sheet's (image 43).", "In the full build the dorsal banks and the", "cooling stacks stand on the curve: not scored."] low.append(text_panel(body, W, crop.height + 34)) stack([row(cells[:2]), row(cells[2:]), row(low[:2]), row(low[2:])]).save(dst / "raptor_profile.png") @@ -223,7 +226,7 @@ rows = [] for tag in ("hero", "side", "front", "rear", "v43"): c = fit(second if tag == "v43" else view(cams[tag]["box"]), 760) cells = [label(c, "image 43" if tag == "v43" else f"sheet 38, {tag} view")] - for root, name in ((PASS2, "second pass (3ced828)" + (", its view set by eye" if tag == "v43" else "")), (src, "THIS pass")): + for root, name in ((PASS2, "second pass (3ced828)" + (", its view set by eye" if tag == "v43" else "")), (PASS3, "third pass (a9ec759)"), (src, "THIS pass (fourth)")): if (root / f"full_{tag}.png").exists(): img = Image.open(root / f"full_{tag}.png").convert("RGBA") img = Image.alpha_composite(Image.new("RGBA", img.size, (150, 156, 164, 255)), img).convert("RGB") @@ -231,7 +234,7 @@ for tag in ("hero", "side", "front", "rear", "v43"): img = img.crop((round(0.2 * img.width), round(0.2 * img.height), round(0.88 * img.width), round(0.88 * img.height))) cells.append(label(fit(img, 760), name)) rows.append(row(cells)) -stack(rows).save(dst / "raptor_vs_pass2.png") +stack(rows).save(dst / "raptor_vs_passes.png") # --- balance ------------------------------------------------------------------------------------------------------------- if (src / "raptor_balance.json").exists() and (src / "full_balance.png").exists(): @@ -312,12 +315,6 @@ for name, box in crops.items(): o = Image.open(src / f"part_{name}.png").convert("RGB") m = round(o.width * 0.2) cells.append(label(row([fit(view(box), 460), fit(o.crop((m, m, o.width - m, o.height - m)), 460)], 4), f"{labels[name]}: sheet 38 | ours")) -cages = json.loads((src / "raptor_cages.json").read_text(encoding="utf-8")) if (src / "raptor_cages.json").exists() else {} -if cages: - hullc = [v for k, v in cages.items() if k.startswith("Torso.")] - share = lambda rows: sum(v["creased"] for v in rows) / sum(v["edges"] for v in rows) # noqa: E731 - scores["cages"] = {"count": len(cages), "hull": len(hullc), "hull_verts": sum(v["verts"] for v in hullc), "hull_crease_share": round(share(hullc), 3), "all_crease_share": round(share(list(cages.values())), 3), - "poles": {k: v["poles"] for k, v in cages.items() if v["poles"]}, "limbs": {k: {"verts": v["verts"], "share": v["share"]} for k, v in cages.items() if not k.startswith("Torso.")}} if cells: stack([row(cells[i:i + 2]) for i in range(0, len(cells), 2)]).save(dst / "raptor_components.png") (src / "raptor_scores.json").write_text(json.dumps(scores, indent=1), encoding="utf-8") diff --git a/surfaces/blender/experiments/mechs/surface.py b/surfaces/blender/experiments/mechs/surface.py index 8a47b6a..2eb3739 100644 --- a/surfaces/blender/experiments/mechs/surface.py +++ b/surfaces/blender/experiments/mechs/surface.py @@ -46,6 +46,7 @@ from mathutils import Matrix, Vector from mathutils.bvhtree import BVHTree import mechlib as M +from paint import mirrored T = Matrix.Translation RX = lambda deg: Matrix.Rotation(math.radians(deg), 4, "X") # noqa: E731 @@ -784,7 +785,12 @@ FONT = r"C:\Windows\Fonts\bahnschrift.ttf" def decal(skin, frame, curve, mat="marking", lift=0.0012, grid=0.03): """A flat 2D curve (in its own xy, metres, centred) laid on the surface along the frame's -z: filled, cut to a - `grid` so it bends over a curve or a crease, each vertex set `lift` off the face. Becomes .mark..""" + `grid` so it bends over a curve or a crease, each vertex set `lift` off the face. Becomes .mark.. + It reads left to right from outside the plate on either side of a mech: where the plate's world matrix and the + frame together reverse handedness (paint.mirrored(): a plate instanced at a negative scale, a frame carried + through a mirroring to_host or written for the other side), the curve's own x is reversed before it is laid. + paint_test.py pins that on a mirrored plate.""" + reading = -1.0 if mirrored(skin.obj.matrix_world, frame) else 1.0 holder = bpy.data.objects.new("decal.tmp", curve) bpy.context.scene.collection.objects.link(holder) M.update() @@ -803,7 +809,7 @@ def decal(skin, frame, curve, mat="marking", lift=0.0012, grid=0.03): bmesh.ops.bisect_plane(bm, geom=bm.verts[:] + bm.edges[:] + bm.faces[:], plane_co=normal * (k * grid), plane_no=normal) k += 1 for v in bm.verts: - seat = skin.sub(frame, v.co.x - centre.x, v.co.y - centre.y) + seat = skin.sub(frame, reading * (v.co.x - centre.x), v.co.y - centre.y) v.co = seat.translation + seat.col[2].xyz * lift bmesh.ops.recalc_face_normals(bm, faces=bm.faces[:]) probe = next(iter(bm.faces))