From 96c881f7db02ce682cdad745625781a5a5e8fc67 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 06:07:06 +0100 Subject: [PATCH] BASTION (sheet 36), first build, mass first: a quadruped whose hull is one closed free cage (45 authored vertices, 31% of edges creased, no poles) moved until its surface passes through its points and fitted at five solved cameras (front, side, rear and plan by quadruped.elevation_camera at 1.0 to 1.5 px rms, the hero by camsolve at 29 px), cut by cockpit and magazine wells and split into 16 plates; quadruped.py: the skeleton of any set of legs from elevations and plan, a bones kit with a joint record an axis (58 joints: hip splay, hip pitch, knee, ankle pitch and roll a leg, 36 toe joints, turret yaw, gun pitch), rams across a bone joint by ram core; feet.bastion_pads; magazines with doors open upward, eight perimeter interceptors and cooling under free-cage housings as the design prompt places them; massing.cage, cage_through, cage_shell; comparison sheets with a plan view Co-Authored-By: Claude Fable 5.2 --- surfaces/blender/experiments/mechs/bastion.py | 82 ++ .../blender/experiments/mechs/bastion_body.py | 28 + .../experiments/mechs/bastion_build.py | 523 ++++++++++++ .../experiments/mechs/bastion_cameras.json | 754 +++++++++++++++++ .../blender/experiments/mechs/bastion_form.py | 64 ++ .../experiments/mechs/bastion_overlay.py | 41 + .../experiments/mechs/bastion_sheets.py | 244 ++++++ .../blender/experiments/mechs/concepts.json | 472 ++++++++++- surfaces/blender/experiments/mechs/feet.py | 759 ++++++++++++++++++ .../blender/experiments/mechs/feet_bench.py | 151 ++++ .../blender/experiments/mechs/feet_dropin.py | 65 ++ .../blender/experiments/mechs/feet_sheets.py | 104 +++ surfaces/blender/experiments/mechs/gen_kit.py | 55 +- surfaces/blender/experiments/mechs/massing.py | 140 ++++ surfaces/blender/experiments/mechs/mechlib.py | 16 +- surfaces/blender/experiments/mechs/paint.py | 317 ++++++++ .../blender/experiments/mechs/paint_render.py | 58 ++ .../blender/experiments/mechs/paint_sheets.py | 73 ++ .../blender/experiments/mechs/quadruped.py | 418 ++++++++++ 19 files changed, 4358 insertions(+), 6 deletions(-) create mode 100644 surfaces/blender/experiments/mechs/bastion.py create mode 100644 surfaces/blender/experiments/mechs/bastion_body.py create mode 100644 surfaces/blender/experiments/mechs/bastion_build.py create mode 100644 surfaces/blender/experiments/mechs/bastion_cameras.json create mode 100644 surfaces/blender/experiments/mechs/bastion_form.py create mode 100644 surfaces/blender/experiments/mechs/bastion_overlay.py create mode 100644 surfaces/blender/experiments/mechs/bastion_sheets.py create mode 100644 surfaces/blender/experiments/mechs/feet.py create mode 100644 surfaces/blender/experiments/mechs/feet_bench.py create mode 100644 surfaces/blender/experiments/mechs/feet_dropin.py create mode 100644 surfaces/blender/experiments/mechs/feet_sheets.py create mode 100644 surfaces/blender/experiments/mechs/paint.py create mode 100644 surfaces/blender/experiments/mechs/paint_render.py create mode 100644 surfaces/blender/experiments/mechs/paint_sheets.py create mode 100644 surfaces/blender/experiments/mechs/quadruped.py diff --git a/surfaces/blender/experiments/mechs/bastion.py b/surfaces/blender/experiments/mechs/bastion.py new file mode 100644 index 0000000..635fc66 --- /dev/null +++ b/surfaces/blender/experiments/mechs/bastion.py @@ -0,0 +1,82 @@ +"""BASTION (sheet 36, images/36.webp): a quadruped, a broad low tortoise hull on four heavy legs, a ballistic turret. + +Mass first: the hull is one closed free cage fitted to the sheet's five views (hero, front, side, rear, plan) at their +solved cameras (bastion_cameras.json, by quadruped.cameras), then cut by its wells and split into plates. The legs are +quadruped.build's kit skeleton, a joint record an axis; the turret's yaw and the gun's pitch are two more. + +BASTION_STAGE stops early: volume (the hull's mass alone), legs (mass and skeleton with its legs), recess, plates, +full (default). MECH_QUICK renders by Workbench. Writes under MECH_OUT/bastion/: _.png for hero, front, +side, rear, top (the kept cameras, the sheet's own pixels; alpha is the silhouette), _turn_*.png.""" +import json, math, os, sys, time +from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import mechlib as M +import massing as MS +import bastion_form as BF +import bastion_body as BB +from mathutils import Matrix, Vector +import bpy + +t0 = time.time() +M.setup() +M.cache_kits() +STAGES = ("volume", "legs", "recess", "plates", "full") +STAGE = os.environ.get("BASTION_STAGE", "full") +AT = STAGES.index(STAGE) +QUICK = bool(os.environ.get("MECH_QUICK")) +OUT = Path(os.environ["MECH_OUT"]) / "bastion" +assert OUT.is_absolute() +OUT.mkdir(parents=True, exist_ok=True) +KEPT = BF.cameras() +CAMS, STAND = KEPT["cameras"], KEPT["stand"] + +mass = BB.hull_mass("khaki") +sheet = BB.hull_cage() +print("CAGE Hull", json.dumps(MS.cage_stats(sheet)), flush=True) +print("CAGE Hull (brokkr_kitbash.shell)", json.dumps(MS.cage_report(sheet)), flush=True) +if AT >= 1: + import bastion_build + bastion_build.run(mass, AT, STAND) +M.update() +lo, hi = M.bounds() +print("HEIGHT", round(hi.z - lo.z, 2), "LOW", round(lo.z, 2), "WIDTH", round(hi.x - lo.x, 2), "LENGTH", round(hi.y - lo.y, 2), "stage", STAGE, "build s", round(time.time() - t0, 1), flush=True) + +rig, cam, centre, radius = M.stage_field(8 if QUICK else int(os.environ.get("MECH_SAMPLES", 48))) +if not QUICK: + import paint + paint.apply(os.environ.get("BASTION_PAINT", "paladin")) +WIDTH = {"hero": 1536, "front": 711, "side": 855, "rear": 795, "top": 711} # three times the sheet's pixels; the hero one and a half +VIEWS = os.environ.get("BASTION_VIEWS", "hero,front,side,rear,top").split(",") +if AT >= 3 and not os.environ.get("BASTION_NO_EDGES"): + armour = lambda name: name.startswith(("Hull.", "Cooling.hood", "Thigh.guard", "Shin.guard", "Turret.housing")) and ".fit." not in name and ".mark." not in name # noqa: E731 + for tag in ("hero", "side", "top"): + (OUT / f"{STAGE}_edges_{tag}.json").write_text(json.dumps(M.built_edges(CAMS[tag], keep=armour)), encoding="utf-8") + print("edges s", round(time.time() - t0, 1), flush=True) +for tag in VIEWS: + if QUICK: + M.preview(rig, cam, CAMS[tag], OUT / f"{STAGE}_{tag}.png", WIDTH[tag]) + else: + M.preview(rig, cam, CAMS[tag], OUT / f"{STAGE}_sil_{tag}.png", WIDTH[tag]) + if tag == "hero": + M.shot(rig, cam, radius, 0, 0, OUT / f"{STAGE}_{tag}.png", (WIDTH[tag], 0), solved=CAMS[tag]) + else: # an elevation stands 600 m off, outside the field: the mech alone on a transparent film + scene = bpy.context.scene + hidden = [o for o in scene.objects if o.get("stage") and not o.hide_render] + for o in hidden: + o.hide_render = True + keep = scene.render.film_transparent, scene.render.image_settings.color_mode + scene.render.film_transparent, scene.render.image_settings.color_mode = True, "RGBA" + M.shot(rig, cam, radius, 0, 0, OUT / f"{STAGE}_{tag}.png", (WIDTH[tag], 0), solved=CAMS[tag]) + scene.render.film_transparent, scene.render.image_settings.color_mode = keep + for o in hidden: + o.hide_render = False +if not QUICK and not os.environ.get("BASTION_NO_TURNS"): + for az in (35, 145, 215): + M.shot(rig, cam, radius, az, 8.0, OUT / f"{STAGE}_turn_{az:03d}.png", (1200, 900), margin=0.8, lens=85.0) + if STAGE == "full": + CLOSE = {"cockpit": ((0, 6.0, 5.1), 2.4, 18, -2), "magazine": ((-5.0, 0.0, 6.3), 2.3, 72, 4), "turret": ((0, 1.2, 8.6), 3.6, 35, 10), "interceptor": ((-1.5, 4.25, 7.6), 1.1, 28, 12), + "rear_leg": ((-4.7, -5.7, 2.7), 3.6, 98, 4), "cooling": ((0, -6.0, 6.2), 3.4, 180, 8), "front_leg": ((-4.4, 5.0, 2.2), 3.0, 55, 4), "foot": ((-4.3, 5.4, 0.5), 1.9, 40, 14)} + for name, (target, span, az, el) in CLOSE.items(): + M.closeup(rig, cam, target, span, az, el, OUT / f"close_{name}.png", size=(640, 640)) + bpy.ops.wm.save_as_mainfile(filepath=str(OUT / "bastion.blend")) +print("total s", round(time.time() - t0, 1)) diff --git a/surfaces/blender/experiments/mechs/bastion_body.py b/surfaces/blender/experiments/mechs/bastion_body.py new file mode 100644 index 0000000..6b6aa16 --- /dev/null +++ b/surfaces/blender/experiments/mechs/bastion_body.py @@ -0,0 +1,28 @@ +"""BASTION's body, mass first (sheet 36): the hull as one closed free cage made a mass, its wells, its plates. +Runs inside Blender beside mechlib, massing and bastion_form.""" +import math + +import bpy +from mathutils import Matrix, Vector + +import bastion_form as BF +import massing as MS +import mechlib as M + +CORE = "gunmetal" +I4 = Matrix.Identity(4) + + +_CAGE = {} + + +def hull_cage(): + """The hull's cage, moved so its surface passes through bastion_form's points (massing.cage_through).""" + if "hull" not in _CAGE: + _CAGE["hull"] = MS.cage_through(BF.hull_sheet()) + return _CAGE["hull"] + + +def hull_mass(mat="khaki", levels=3): + """The hull: carapace and belly, one closed volume from the minimal cage (bastion_form.hull_sheet).""" + return MS.cage("Hull.mass", hull_cage(), I4, mat, levels=levels) diff --git a/surfaces/blender/experiments/mechs/bastion_build.py b/surfaces/blender/experiments/mechs/bastion_build.py new file mode 100644 index 0000000..2b63e01 --- /dev/null +++ b/surfaces/blender/experiments/mechs/bastion_build.py @@ -0,0 +1,523 @@ +"""BASTION beyond its hull's mass: the kit skeleton (quadruped.build), the wells, the plates, the hip housings, the +legs' dress and rams, the feet (feet.bastion_pads), the turret and gun, the magazines, the interceptors, the cooling. +Every part function takes the host it is authored on; every finished part is frozen (brokkr_kitbash.freeze). + +Reconciliations with the design prompt (ruling concept-prompt-is-design-intent), each built as the prompt says: + magazines the sheet draws an open recess in the flank and, in plan, a box outside the rim. The prompt: recessed + side compartments with segmented doors that open upward. Built: a recess in the flank band, a + three-segment door hinged on its upper edge and standing open (the plan's box is the open door). + interceptors the sheet's inset shows one launcher; the hero scatters seven boxes on the dome. The prompt: spread + round the shell's perimeter. Built: eight, evenly round the shoulder line, the inset's look. + cooling the rear view shows two bare radiator faces flush in the tail, the side view a block 2 m behind the + hull, the plan nothing behind the tail. The prompt: under sculpted protective housings. Built: two + housings (free cages) over the banks, standing 0.7 m behind the tail, the fins in their mouths. + hips the prompt: rotary housings at the hull's corners. Built: a fixed drum housing under each corner of the + overhang, the thigh's drum turning in it. + legs front shorter and heavily armoured, rear longer with exposed hydraulics: as the sheet draws them.""" +import json +import math +import os +import time + +import bpy +from mathutils import Matrix, Vector + +import bastion_form as BF +import bastion_body as BB +import massing as MS +import mechlib as M +import quadruped as Q + +F, T = M.frame_at, Matrix.Translation +P, P2, CORE = "olive", "olive_light", "gunmetal" +FOOT_PIN = 0.1 +RECORDS = {"hip_splay": ((-6.0, 14.0), "hip_splay"), "hip_pitch_front": ((-32.0, 32.0), "hip_pitch"), "hip_pitch_rear": ((-30.0, 34.0), "hip_pitch"), + "knee_front": ((-35.0, 40.0), "knee"), "knee_rear": ((-40.0, 45.0), "knee"), "turret_yaw": ((-180.0, 180.0), "turret_yaw"), "gun_pitch": ((-8.0, 28.0), "gun_pitch"), + "ankle": ((-30.0, 30.0), "ankle_pitch"), "ankle_roll": ((-22.0, 22.0), "ankle_roll")} +RX = lambda d: Matrix.Rotation(math.radians(d), 4, "X") # noqa: E731 +RY = lambda d: Matrix.Rotation(math.radians(d), 4, "Y") # noqa: E731 +RZ = lambda d: Matrix.Rotation(math.radians(d), 4, "Z") # noqa: E731 +TIMES = {} + + +def frozen(before): + n = 0 + for o in list(bpy.data.objects): + if o.name not in before and o.type == "MESH" and o.modifiers and not o.get("kit_frozen") and not o.hide_render: + try: + if "FINISHED" in bpy.ops.brokkr_kitbash.freeze(object_name=o.name): + n += 1 + except RuntimeError: + pass + return n + + +def part(name, fn, *args, **kw): + before, t = set(bpy.data.objects.keys()), time.time() + out = fn(*args, **kw) + M.update() + n = frozen(before) + TIMES[name] = round(time.time() - t, 1) + print(f"PART {name}: {TIMES[name]} s, {n} frozen", flush=True) + return out + + +def geo(name, mat, host, build, smooth=38.0, bevel=0.0): + g = M.Geo() + build(g) + obj = g.to_object(name, mat, host, smooth) + if bevel: + mod = obj.modifiers.new("Bevel", "BEVEL") + mod.width, mod.segments, mod.limit_method, mod.angle_limit = bevel, 1, "ANGLE", math.radians(25) + for p in obj.data.polygons: + p.use_smooth = False + return obj + + +def disc(g, at, r, w, rings=3, bolts=12): + """A rotary housing's face: a drum along at's z from 0 to w, its outer face stepped in `rings` rings to a hub.""" + prof = [(0, 0), (r, 0), (r, 0.72 * w)] + for k in range(rings): + r0, r1 = r * (1 - 0.8 * k / rings), r * (1 - 0.8 * (k + 0.55) / rings) + z = w * (0.72 + 0.28 * (k % 2)) + prof += [(r0, z), (r1, z)] + prof += [(0.16 * r, w * 1.05), (0, w * 1.05)] + g.lathe(at, prof, 48) + g.bolts(at @ T((0, 0, 0.72 * w)), 0.92 * r, bolts, 0.035 * r, 0.05 * r) + return g + + +# --- wells and plates --------------------------------------------------------------------------------------------------- +CROWN = 7.6 +MAG = dict(y0=-1.25, y1=1.05, z0=5.55, z1=6.55, depth=1.5) + + +def wells(): + """The cutters: the cockpit's recess under the nose's rim, a magazine's compartment in each flank band.""" + cuts = [MS.slab("Cockpit.cut", (0, 6.0, 5.2), (3.5, 1.9, 0.5), BB.I4)] + for sx in (-1, 1): + cuts.append(MS.slab(f"Magazine.cut.{'L' if sx < 0 else 'R'}", (sx * 4.6, 0.5 * (MAG["y0"] + MAG["y1"]), 0.5 * (MAG["z0"] + MAG["z1"])), (2 * MAG["depth"], MAG["y1"] - MAG["y0"], MAG["z1"] - MAG["z0"]), BB.I4)) + return cuts + + +def plates(skin, cuts): + """The carapace split into its plates along the shoulder line and the quarters: fewer, bigger, each at its own + depth. A plate is the mass's own surface (massing.plate), so they conform by construction.""" + g = 0.035 + up = lambda e: ((0, -0.065, -1), -(6.62 + e)) # noqa: E731 above the shoulder line + low = lambda e: ((0, 0.065, 1), 6.62 - e) # noqa: E731 below it + rim = ((0, -0.085, -1), -5.27) # above the rim: the overhang's underside stays the mass + H = MS.half + made = [] + + def add(name, keep, proud, wall, mat=P): + o = MS.plate(name, skin, keep, proud=proud, wall=wall, mat=mat, cutters=cuts, bevel=0.03) + if o is not None: + made.append(o) + add("Hull.Crown", [H("z", -1, CROWN)], 0.07, 0.1) + add("Hull.Glacis", [H("x", 1, 1.85), H("x", -1, -1.85), H("y", -1, 2.3), H("z", 1, CROWN - 2 * g), H("z", -1, 5.52)], 0.15, 0.16) + add("Hull.Tail", [H("x", 1, 1.15), H("x", -1, -1.15), H("y", 1, -2.7), H("z", 1, CROWN - 2 * g), rim], 0.12, 0.14) + for sx, tag in ((-1, "L"), (1, "R")): + side = lambda at: H("x", -sx, sx * at) # noqa: E731 outboard of |x| = at + for name, extra, proud, wall, mat in ( + ("CheekUp", [side(1.85 + 2 * g), H("y", -1, 1.5), up(g)], 0.08, 0.12, P), + ("CheekBand", [side(1.85 + 2 * g), H("y", -1, 1.5), low(g), rim], 0.13, 0.16, P), + ("FlankUp", [side(1.0), H("y", 1, 1.5 - 2 * g), H("y", -1, -2.0), up(g)], 0.05, 0.1, P2), + ("FlankBand", [side(1.0), H("y", 1, 1.5 - 2 * g), H("y", -1, -2.0), low(g), rim], 0.17, 0.2, P), + ("RearUp", [side(1.15 + 2 * g), H("y", 1, -2.0 - 2 * g), up(g)], 0.09, 0.12, P), + ("RearBand", [side(1.15 + 2 * g), H("y", 1, -2.0 - 2 * g), low(g), rim], 0.12, 0.15, P2)): + add(f"Hull.{name}.{tag}", [H("z", 1, CROWN - 2 * g)] + extra, proud, wall, mat) + add("Hull.Chin", [H("x", 1, 2.0), H("x", -1, -2.0), H("y", -1, 4.75), H("z", 1, 4.9), H("z", -1, 3.75)], 0.1, 0.14, P2) + return made + + +def cockpit(host): + """RECESSED COCKPIT & SENSOR SUITE inset: a narrow armoured visor deep under the nose's rim, a row of lamps.""" + def build(g): + g.box(T((0, 5.45, 5.2)), (3.3, 0.3, 0.46)) + for x in (-1.2, 0.0, 1.2): + g.box(T((x, 5.62, 5.2)), (0.12, 0.2, 0.46)) + geo("Cockpit.frame", CORE, host, build) + geo("Cockpit.visor", "glass", host, lambda g: [g.box(T((x, 5.61, 5.22)) @ RX(-12), (1.05, 0.05, 0.3)) for x in (-0.6, 0.6)]) + geo("Cockpit.lamps", "glow_blue", host, lambda g: [g.box(T((x, 5.64, 5.07)), (0.22, 0.04, 0.05)) for x in (-1.0, -0.45, 0.45, 1.0)]) + # the cheeks' lamp slots under the rim, either side (the hero's light bars) + for sx in (-1, 1): + at = F((sx * 3.3, 5.02, 4.98), (sx * 0.45, 1, -0.1)) + geo(f"Cheek.lamp.{sx}", CORE, host, lambda g: g.box(at, (1.3, 0.34, 0.5)), bevel=0.02) + geo(f"Cheek.glow.{sx}", "lamp", host, lambda g: g.box(at @ T((0.2, 0.0, 0.26)), (0.42, 0.09, 0.02))) + + +def magazine(host, sx): + """LATERAL MISSILE MAGAZINE inset: missiles lying in three tiers in a framed compartment in the flank band; the + prompt's segmented door, hinged on the upper edge, open upward.""" + import hardpoint as HP + tag = "L" if sx < 0 else "R" + y0, y1, z0, z1 = MAG["y0"], MAG["y1"], MAG["z0"], MAG["z1"] + w, h = y1 - y0, z1 - z0 + face = F((sx * 4.3, 0.5 * (y0 + y1), 0.5 * (z0 + z1)), (sx, 0, 0.0), (0, 0, 1)) # z outboard, y up, x along the hull + b = M.Build(f"Magazine.{tag}", host, None) + fr = b["gunmetal"] + for u in (-0.5 * w - 0.06, 0.5 * w + 0.06): + fr.box(face @ T((u, 0, -0.2)), (0.12, h + 0.24, 0.6)) + for v in (-0.5 * h - 0.06, 0.5 * h + 0.06): + fr.box(face @ T((0, v, -0.2)), (w + 0.24, 0.12, 0.6)) + fr.box(face @ T((0, 0, -0.95)), (w, h, 0.1)) + if "warhead" not in M.MATS: + M.material("warhead", (0.2, 0.07, 0.04), 0.1, 0.45, coat=0.3) + for row in range(3): + v = (row - 1) * 0.3 + for col in range(2): + for lane in range(2): + at = face @ T(((lane - 0.5) * 1.1, v, -0.3 - 0.36 * col)) @ RY(90) + b["machine"].lathe(at @ T((0, 0, -0.48)), [(0, 0), (0.12, 0), (0.12, 0.8), (0.07, 0.94), (0, 0.98)], 16) + b["warhead"].lathe(at @ T((0, 0, -0.48)), [(0.125, 0.12), (0.125, 0.2), (0.125, 0.2)], 16) + b["warhead"].lathe(at @ T((0, 0, 0.1)), [(0.123, 0), (0.123, 0.22), (0.072, 0.36), (0.0, 0.4)], 16) + fr.box(face @ T((0, v - 0.15, -0.5)), (w, 0.03, 0.8)) + # the door: three segments, each hinged on the last, standing open upward + hinge = face @ T((0, 0.5 * h + 0.08, 0.06)) + seg = h / 3 + 0.03 + at = hinge + for k, turn in enumerate((-78.0, -22.0, -14.0)): + at = at @ RX(turn) + b["gunmetal"].rod(at @ Vector((-0.5 * w, 0, 0)), at @ Vector((0.5 * w, 0, 0)), 0.035, 10) + b[P if k != 1 else P2].prism(at @ T((0, -0.5 * seg, 0.0)), M.rect(w + 0.2, seg - 0.03, 0.04), 0.08, 0.02) + at = at @ T((0, -seg, 0)) + for s in (-1, 1): + b["steel"].rod(face @ Vector((s * 0.46 * w, 0.45 * h, 0.0)), hinge @ RX(-78.0) @ Vector((s * 0.46 * w, -0.8 * seg, 0.0)), 0.03, 8) + return b.done() + + +def interceptor(name, host, at, yaw): + """PERIMETER INTERCEPTOR LAUNCHER inset: a small box of four tubes, two over two, with a hooded sight on its + cheek, trunnioned in a fork on a turning pedestal. `at` is the pedestal's foot, z out of the shell.""" + b = M.Build(name, host, at @ RZ(yaw)) + g, m = b[P2], b["gunmetal"] + m.lathe(Matrix.Identity(4), [(0, 0), (0.3, 0), (0.3, 0.06), (0.2, 0.1), (0.2, 0.22), (0, 0.22)], 20) + for s in (-1, 1): + m.box(T((s * 0.33, 0, 0.42)), (0.07, 0.24, 0.5)) + m.cylinder(T((s * 0.38, 0, 0.5)) @ RY(90), 0.08, 0.06, 12) + box = T((0, 0.02, 0.5)) @ RX(-12) + g.box(box, (0.56, 0.7, 0.46)) + for i in (-1, 1): + for j in (-1, 1): + m.tube(box @ T((i * 0.13, 0.3, j * 0.11)) @ RX(-90), 0.105, 0.08, 0.12, 14) + m.box(box @ T((0.2, -0.05, 0.3)), (0.14, 0.3, 0.12)) + b["glass"].cylinder(box @ T((0.2, 0.11, 0.3)) @ RX(90), 0.04, 0.02, 10) + return b.done() + + +def cooling(host): + """REAR COOLING ARRAYS inset under the prompt's sculpted housings: two fin banks on the tail, each under a + housing that is a minimal free cage (an arched hood open to the rear), a manifold between them.""" + out = [] + for sx in (-1, 1): + tag = "L" if sx < 0 else "R" + c = Vector((sx * 2.25, -5.6, 6.3)) + w, d, h = 1.6, 1.8, 2.2 + # the hood: authored on its right half and mirrored; front (toward the hull), crown and flank, open behind and below + verts = [[0.0, 0.5 * d, 0.5 * h + 0.05], [0.0, -0.5 * d, 0.5 * h + 0.2], + [0.5 * w, 0.5 * d, 0.32 * h], [0.5 * w, -0.5 * d, 0.4 * h], + [0.56 * w, 0.42 * d, -0.5 * h], [0.56 * w, -0.5 * d, -0.5 * h], + [0.0, 0.62 * d, -0.1 * h], [0.5 * w, 0.6 * d, -0.2 * h]] + faces = [[0, 1, 3, 2], [2, 3, 5, 4], [6, 0, 2, 7]] + sheet = {"verts": verts, "faces": faces, "creases": [[2, 3, 0.7], [0, 2, 0.5]], "mirror": True, "rim": 0.6} + out.append(MS.cage_shell(f"Cooling.hood.{tag}", sheet, host, T(c), mat=P, thickness=0.14, levels=2, bevel=0.03, inside=(0, 0, -0.3))) + + def fins(g): + n = 15 + for k in range(n): + g.box(T(c + Vector(((k - (n - 1) / 2) * 0.085, -0.25, -0.1))), (0.03, 1.2, 1.9)) + out.append(geo(f"Cooling.fins.{tag}", "machine", host, fins, smooth=5)) + + def core(g): + g.box(T(c + Vector((0, 0.1, -0.15))), (1.36, 1.5, 1.7)) + g.box(T(c + Vector((0, -0.86, -1.1))), (1.42, 0.12, 0.14)) + g.box(T(c + Vector((0, -0.86, 0.82))), (1.42, 0.12, 0.14)) + out.append(geo(f"Cooling.core.{tag}", CORE, host, core)) + + def manifold(g): + g.box(T((0, -5.5, 5.75)), (3.0, 1.2, 1.3)) + for z in (5.4, 5.9, 6.3): + g.rod((-1.5, -6.05, z), (1.5, -6.05, z), 0.11, 12) + g.box(T((0, -5.8, 4.9)), (1.8, 0.9, 0.7)) + out.append(geo("Cooling.manifold", CORE, host, manifold)) + return out + + +# --- legs ----------------------------------------------------------------------------------------------------------- +def hip_housing(tag, host, hip, rear): + """The rotary housing at a corner of the hull: a fixed drum under the overhang, on the hull's flank, the thigh's + drum turning in it. Authored in the world (the trunk's frame).""" + sx = -1 if tag[-1] == "l" else 1 + r = 1.3 if rear else 0.98 + hip = Vector(hip) + inner = 2.3 + + def fixed(g): + at = F((sx * inner, hip.y, hip.z), (sx, 0, 0), (0, 0, 1)) + g.lathe(at, [(0, 0), (1.02 * r, 0), (1.02 * r, abs(hip.x) - inner - 0.5), (0.9 * r, abs(hip.x) - inner - 0.42), (0, abs(hip.x) - inner - 0.42)], 48) + # the bracket up into the overhang + g.box(T((sx * (inner + 0.6), hip.y, hip.z + 0.75 * r)), (1.3, 1.5 * r, 1.4 * r)) + geo(f"Hip.housing.{tag}", CORE, host, fixed) + geo(f"Hip.collar.{tag}", "machine", host, lambda g: (g.lathe(F((sx * (abs(hip.x) - 0.52), hip.y, hip.z), (sx, 0, 0), (0, 0, 1)), + [(1.08 * r, 0), (1.08 * r, 0.14), (0.96 * r, 0.14), (0.96 * r, 0)], 48), + g.bolts(F((sx * (abs(hip.x) - 0.38), hip.y, hip.z), (sx, 0, 0), (0, 0, 1)), 1.02 * r, 20, 0.035, 0.04))) + + +def shield_sheet(w, top, bottom, lead, crown, back): + """A leg's guard plate as a minimal free cage, right half (mirrored): a front face from `top` to `bottom` (z, + down the limb is negative) standing `lead` before the limb's axis and `crown` further at its middle, a side + wrapped back to `back`, a hood over the top. Ten authored vertices.""" + mid = 0.45 * top + 0.55 * bottom + verts = [[0, lead + 0.1, top + 0.1], [0, lead + crown, mid], [0, lead + 0.05, bottom - 0.1], # the seam + [0.5 * w, lead - 0.05, top], [0.52 * w, lead + 0.7 * crown, mid], [0.44 * w, lead - 0.05, bottom], # the front's edge + [0.56 * w, back, top - 0.05], [0.58 * w, back + 0.05, mid], [0.5 * w, back + 0.1, bottom + 0.1], # the side's rear edge + [0, back + 0.1, top + 0.22]] # the hood's rear, on the seam + faces = [[0, 3, 4, 1], [1, 4, 5, 2], [3, 6, 7, 4], [4, 7, 8, 5], [9, 6, 3, 0]] + return {"verts": verts, "faces": faces, "creases": [[3, 4, 0.75], [4, 5, 0.75], [0, 3, 0.5]], "mirror": True, "rim": 0.7} + + +def leg_dress(tag, bones, pose): + """One leg's machinery and armour on its bones (z up the segment, toward its upper joint; x the pin). + Front: a short stout girder, a great guard plate before the thigh that hides the hip from the front, a smaller + one down the shin. Rear: REAR LEG PROPULSION ASSEMBLY inset - a long open twin-beam thigh, two exposed chromed + rams from the hip's housing to the hock, a great layered hip disc, a guard plate behind the lower thigh.""" + rear, sx = tag[0] == "r", (-1 if tag[-1] == "l" else 1) + th, sh, hipb = bones[f"Thigh.{tag}"], bones[f"Shin.{tag}"], bones[f"Bone.hip_splay.{tag}"] + l1, l2 = (float(json.loads(o["kit_params"])["length"]) for o in (th, sh)) + r_hip, r_knee = (1.22, 0.62) if rear else (0.9, 0.56) + out = F((0, 0, 0), (sx, 0, 0), (0, 0, 1)) # a frame whose z is outboard + + def thigh(g): + if rear: + for s in (-1, 1): + g.sweep([(s * 0.52, 0, 0), (s * 0.52, 0, -l1)], [(-0.09, -0.3), (0.09, -0.3), (0.09, 0.3), (-0.09, 0.3)], (0, 1, 0)) + for z in (0.3, 0.52, 0.74): + g.box(T((0, 0.12, -z * l1)), (1.0, 0.18, 0.24)) + g.cylinder(T((0, 0, -l1)) @ RY(90), 0.3, 1.3, 20) + else: + g.box(T((0, 0, -0.5 * l1)), (0.9, 0.8, l1)) + g.box(T((0, -0.36, -0.5 * l1)), (0.6, 0.3, 0.7 * l1)) + geo(f"Thigh.girder.{tag}", CORE, th, thigh, bevel=0.015) + + def drums(g): + disc(g, out @ T((0, 0, 0.1)), r_hip, 0.62 if rear else 0.5, rings=4 if rear else 3, bolts=20 if rear else 14) + g.cylinder(RY(90), 0.82 * r_hip, 1.0, 40) + kn = T((0, 0, -l1)) + disc(g, kn @ out @ T((0, 0, 0.42)), r_knee, 0.22, rings=2, bolts=10) + g.cylinder(kn @ RY(90), r_knee, 0.84, 32) + disc(g, kn @ F((0, 0, 0), (-sx, 0, 0), (0, 0, 1)) @ T((0, 0, 0.42)), 0.8 * r_knee, 0.14, rings=2, bolts=8) + geo(f"Thigh.drums.{tag}", "machine", th, drums) + + def shin(g): + g.box(T((0, 0, -0.5 * l2)), (0.74, 0.7, l2)) + g.cylinder(T((0, 0, -l2)) @ RY(90), 0.4, 1.0, 24) + if rear: + g.box(T((0, 0.3, -0.45 * l2)), (0.5, 0.4, 0.7 * l2)) + geo(f"Shin.column.{tag}", CORE, sh, shin, bevel=0.015) + made = [] + if rear: + # the guard plate behind the lower thigh (the hero's plate standing up from the hock), its face aft + sheet = shield_sheet(1.5, -0.42 * l1, -l1 - 0.25, 0.62, 0.16, 0.05) + made.append(MS.cage_shell(f"Thigh.guard.{tag}", sheet, th, RZ(180), mat=P, thickness=0.12, levels=2, bevel=0.025, inside=(0, 0, -0.7 * l1))) + # the propulsion rams: from the fixed housing under the hip, either side of the beams' middle, to the hock + M.update() + to_hip = hipb.matrix_world.inverted() @ th.matrix_world + a = [to_hip @ Vector((0, y, z)) for y in (0.7, 0.95, 1.2) for z in (0.3, 0.0, -0.3)] + fit, objs = Q.drive(f"Leg.ram.{tag}", hipb, th, a, [(0, 0.34, -k * l1) for k in (0.9, 0.8, 0.7)], 0.15, RECORDS["hip_pitch_rear"][0], twin=0.26) + made += objs + else: + # the thigh's guard hangs upright at the stance, a boxed shroud before the hip and over the knee: the concept's + # front leg reads as a pillar, whatever the thigh's lean under it + M.update() + upright = (th.matrix_world.inverted() @ hipb.matrix_world).to_3x3().to_4x4() + knee = upright.inverted() @ Vector((0, 0, -l1)) + sheet = shield_sheet(2.0, 1.0, knee.z - 0.45, knee.y + 0.55, 0.14, 0.4) + made.append(MS.cage_shell(f"Thigh.guard.{tag}", sheet, th, upright @ T((sx * 0.25, 0, 0)), mat=P, thickness=0.14, levels=2, bevel=0.03, inside=(0, 0, 0.5 * knee.z))) + sheet = shield_sheet(1.45, 0.25, -l2 + 0.1, 0.5, 0.12, -0.2) + made.append(MS.cage_shell(f"Shin.guard.{tag}", sheet, sh, T((sx * 0.1, 0, 0)), mat=P2, thickness=0.11, levels=2, bevel=0.025, inside=(0, 0, -0.5 * l2))) + to_hip = hipb.matrix_world.inverted() @ th.matrix_world + a = [to_hip @ Vector((0, y, z)) for y in (-0.5, -0.75, -1.0) for z in (0.9, 0.6, 0.3)] + fit, objs = Q.drive(f"Leg.ram.{tag}", hipb, th, a, [(0, -0.52, -k * l1) for k in (0.95, 0.8, 0.65)], 0.11, RECORDS["hip_pitch_front"][0]) + made += objs + return made + + +def foot(tag, bones, pose): + import feet + an = bones[f"Ankle.{tag}"] + drop = pose[f"ankle_{tag}"][2] + f = feet.bastion_pads(f"Foot.{tag}", None, width=2.3, length=2.7, drop=drop, pin_r=FOOT_PIN, heel=0.24 if tag[0] == "f" else 0.2) + M.attach(f.core, "tongue_roll", an, "roll", 0.0) + f.level(0.0) + Q.record(f.core, "ankle_roll", RECORDS) + f.done() + return f + + +# --- turret ------------------------------------------------------------------------------------------------------------- +def turret_ring(host): + """The reinforced circular bearing on the crown (the plan view's ring): a bolted outer race on the deck.""" + def build(g): + at = T(BF.RING) + r = BF.RING_R + g.lathe(at, [(1.42 * r, -0.2), (1.42 * r, 0.1), (1.3 * r, 0.16), (1.12 * r, 0.16), (1.12 * r, 0.3), (0.9 * r, 0.3), (0.9 * r, -0.2)], 72) + g.bolts(at @ T((0, 0, 0.16)), 1.2 * r, 36, 0.045, 0.05) + return geo("Turret.ring", "machine", host, build) + + +def turret(tb): + """MAIN BALLISTIC TURRET inset: a low faceted housing, the receiver built into it, a raised cupola block at its + rear left with a hatch, sight boxes on its roof. Authored on the Turret bone: origin on the ring's centre, the + trunnion ahead of it.""" + r = BF.RING_R + + def body(g): + g.hull([(1.45, 2.0, 0.28), (1.6, 0.6, 0.22), (1.55, -1.7, 0.25), (0.9, -2.3, 0.3), (1.2, 1.95, 1.0), (1.3, 0.3, 1.2), (1.2, -1.6, 1.25), (0.7, -2.1, 1.15), (0.6, 2.25, 0.35), (0.55, 2.2, 0.92)], mirror=True) + out = [geo("Turret.housing", P, tb, body, bevel=0.03)] + out.append(geo("Turret.race", "machine", tb, lambda g: g.lathe(Matrix.Identity(4), [(0, 0.05), (0.88 * r, 0.05), (0.88 * r, 0.3), (0, 0.3)], 64))) + + def top(g): + g.hull([(0.15, -1.8, 1.1), (1.1, -1.8, 1.1), (1.1, -0.45, 1.1), (0.15, -0.45, 1.1), (0.27, -1.68, 1.72), (0.98, -1.68, 1.72), (0.98, -0.62, 1.64), (0.27, -0.62, 1.64)]) + g.hull([(-1.05, -1.65, 1.1), (-0.2, -1.65, 1.1), (-0.2, -0.7, 1.1), (-1.05, -0.7, 1.1), (-0.95, -1.53, 1.48), (-0.3, -1.53, 1.48), (-0.3, -0.82, 1.42), (-0.95, -0.82, 1.42)]) + g.box(T((0.75, 0.9, 1.2)), (0.55, 0.75, 0.3)) + g.box(T((-0.7, 0.6, 1.2)), (0.7, 0.9, 0.16)) + out.append(geo("Turret.cupola", P2, tb, top, bevel=0.025)) + out.append(geo("Turret.hatch", CORE, tb, lambda g: (g.cylinder(T((0.62, -1.15, 1.72)), 0.32, 0.07, 20), g.box(T((0.75, 1.3, 1.2)), (0.32, 0.06, 0.18))))) + # cheek plates stepped off the housing's sides + for sx in (-1, 1): + out.append(geo(f"Turret.cheek.{sx}", P2, tb, lambda g: g.hull([(sx * 1.62, 1.6, 0.4), (sx * 1.72, 0.5, 0.36), (sx * 1.7, -1.3, 0.4), (sx * 1.42, 1.55, 0.95), (sx * 1.47, 0.3, 1.1), (sx * 1.42, -1.2, 1.14), + (sx * 1.5, 1.6, 0.4), (sx * 1.55, -1.3, 0.4)]), bevel=0.025)) + return out + + +def gun(gb): + """The gun on the Gun bone (origin on the trunnion, y down the bore): a boxed mantlet, a short heavy barrel of + stepped sleeves, a banded muzzle with a thick lip, the recoil sleeve at its root.""" + import hardpoint as HP + out = [geo("Gun.mantlet", P, gb, lambda g: g.hull([(0.66, -0.25, -0.34), (0.66, -0.25, 0.36), (0.55, 0.75, -0.3), (0.55, 0.75, 0.33), (0.36, 1.05, -0.25), (0.36, 1.05, 0.28)], mirror=True), bevel=0.025)] + + def tube(g): + at = HP.Y(0.9) + HP.barrel(g, at, [(0.0, 0.4), (0.8, 0.4), (0.85, 0.33), (1.7, 0.31), (1.75, 0.37), (1.95, 0.37), (2.0, 0.3), (2.35, 0.3), (2.4, 0.4), (3.05, 0.4), (3.1, 0.36)], 0.22, depth=1.4, lip=0.05) + for z in (2.5, 2.68, 2.86): + g.lathe(at, [(0.43, z), (0.43, z + 0.09), (0.4, z + 0.09), (0.4, z)], 40) + out.append(geo("Gun.barrel", "machine", gb, tube)) + out.append(geo("Gun.trunnion", CORE, gb, lambda g: g.cylinder(RY(90), 0.3, 1.5, 24))) + return out + + +def detail(): + """The detail pass by surface.py on the plates (its Skin reads a massing plate's own face): the 03 on each cheek + band, the wings on the chin, panel lines, bolt rows inside the rims, hatches on the upper plates. A feature that + misses its plate is reported, not drawn. Returns (made, failed).""" + import surface as S + S.materials() + made, failed = [0], [] + + def on(plate, steps): + if plate not in bpy.data.objects: + failed.append(f"{plate}: no such plate") + return + try: + skin = S.Skin(plate) + except BaseException as error: + failed.append(f"{plate}: {type(error).__name__} {error}") + return + for label, step in steps: + try: + step(skin) + made[0] += 1 + except BaseException as error: + failed.append(f"{plate} {label}: {type(error).__name__} {error}") + try: + skin.prune() + skin.commit() + except BaseException as error: + failed.append(f"{plate} commit: {type(error).__name__} {error}") + + def rim(k, spacing=0.4): + return (f"bolts on rim {k}", lambda s: S.bolt_row(s, S.along(s, ("rim", k), spacing=spacing, offset=0.12, margin=0.2), r=0.03)) + for sx, tag in ((-1, "L"), (1, "R")): + side = ((sx * 9.0, 3.2, 5.9), (-sx, 0, 0)) + on(f"Hull.CheekBand.{tag}", [("03", lambda s: S.numeral(s, s.at(*side), "03", 0.75, "marking_fresh")), rim(0), + ("hatch", lambda s: S.hatch(s, s.at((sx * 9.0, 2.0, 5.75), (-sx, 0, 0)), size=(0.6, 0.5)))]) + on(f"Hull.CheekUp.{tag}", [rim(0), ("hatch", lambda s: S.hatch(s, s.at((sx * 3.0, 3.2, 12.0), (0, 0, -1), up=(0, 1, 0)), size=(0.8, 0.6))), + ("port", lambda s: S.access_port(s, s.at((sx * 3.4, 2.2, 12.0), (0, 0, -1), up=(0, 1, 0)), r=0.16))]) + on(f"Hull.RearUp.{tag}", [rim(0), ("louvres", lambda s: S.louvre_bank(s, s.at((sx * 2.6, -3.4, 12.0), (0, 0, -1), up=(0, 1, 0)), size=(0.9, 0.6), slats=6))]) + on(f"Hull.RearBand.{tag}", [rim(0), ("port", lambda s: S.access_port(s, s.at((sx * 9.0, -3.2, 6.3), (-sx, 0, 0)), r=0.18))]) + on(f"Hull.FlankUp.{tag}", [rim(0)]) + on("Hull.Chin", [("wings", lambda s: S.emblem(s, s.at((0, 9.0, 4.45), (0, -1, 0)), "wings", 0.6, "marking_fresh")), rim(0)]) + on("Hull.Glacis", [rim(0), ("hatch", lambda s: S.hatch(s, s.at((0.9, 4.4, 12.0), (0, 0, -1), up=(0, 1, 0)), size=(0.7, 0.6))), + ("panel", lambda s: S.inset(s, s.at((-0.8, 4.6, 12.0), (0, 0, -1), up=(0, 1, 0)), size=(0.8, 0.5)))]) + on("Hull.Crown", [rim(0, 0.5)]) + print(f"DETAIL {made[0]} features made; {len(failed)} failed", flush=True) + for f in failed: + print(" DETAIL failed:", f, flush=True) + return made[0], failed + + +# --- the build ------------------------------------------------------------------------------------------------------------ +def run(mass, at, stand): + pose = {k: list(v) for k, v in stand.items()} + ring = BF.RING + trunnion = (0.0, 1.75, ring[2] + 0.68) + bones = part("skeleton", Q.build, pose, RECORDS, pin=2 * FOOT_PIN, turret={"ring": list(ring), "trunnion": list(trunnion), "yaw": 0.0, "pitch": 2.0}) + trunk = bones["Trunk"] + print("SKELETON miss", round(Q.miss(bones, pose), 4), "m", flush=True) + mass.parent = trunk + for t in Q.LEGS: + part(f"hip {t}", hip_housing, t, trunk, pose[f"hip_{t}"], t[0] == "r") + part(f"leg {t}", leg_dress, t, bones, pose) + part(f"foot {t}", foot, t, bones, pose) + part("turret ring", turret_ring, trunk) + part("turret", turret, bones["Aim.Turret"]) + part("gun", gun, bones["Aim.Gun"]) + part("cooling", cooling, trunk) + if at >= 2: + skin = mass.copy() + skin.data = mass.data.copy() + bpy.context.scene.collection.objects.link(skin) + skin.hide_render = True + M.update() + cuts = wells() + MS.carve(mass, cuts) + part("cockpit", cockpit, trunk) + for sx in (-1, 1): + part(f"magazine {sx}", magazine, trunk, sx) + if at >= 3: + M.assign(mass, CORE) + before = set(bpy.data.objects.keys()) + t = time.time() + made = plates(skin, cuts) + for o in made: + o.parent = trunk + if at >= 4: + detail() + M.update() + TIMES["plates"] = round(time.time() - t, 1) + print(f"PART plates: {TIMES['plates']} s, {frozen(before)} frozen", flush=True) + n = 8 + for k in range(n): + a = math.radians(22.5 + 360.0 * k / n) + d = Vector((math.sin(a), math.cos(a), 0)) + hit = ray_down(skin, d * 1.0 + Vector((d.x * 2.9, d.y * 3.6, 0))) + if hit: + part(f"interceptor {k}", interceptor, f"Interceptor.{k}", trunk, T(hit[0] - Vector((0, 0, 0.12))), -math.degrees(a)) + if at >= 2: + bpy.data.objects.remove(skin, do_unlink=True) + report = Q.report(trunk, more=[bones[f"Ankle.{t}"] for t in Q.LEGS]) + rows = report["joints"] + print("JOINTS", report["schema"], len(rows), "rows;", json.dumps({m: sum(1 for r in rows if r["mechanism"] == m) for m in sorted({str(r["mechanism"]) for r in rows})}), flush=True) + out = os.environ.get("MECH_OUT") + if out: + with open(os.path.join(out, "bastion", "bastion_joints.json"), "w", encoding="utf-8") as fh: + json.dump(report, fh, indent=1) + print("TIMES", json.dumps(TIMES), flush=True) + return bones + + +def ray_down(obj, xy): + """Where a ray straight down meets the mass at a plan point: (point, normal) in the world.""" + ok, loc, nor, _ = obj.ray_cast(obj.matrix_world.inverted() @ Vector((xy.x, xy.y, 20.0)), Vector((0, 0, -1))) + return (obj.matrix_world @ loc, (obj.matrix_world.to_3x3() @ nor).normalized()) if ok else None diff --git a/surfaces/blender/experiments/mechs/bastion_cameras.json b/surfaces/blender/experiments/mechs/bastion_cameras.json new file mode 100644 index 0000000..2a566c2 --- /dev/null +++ b/surfaces/blender/experiments/mechs/bastion_cameras.json @@ -0,0 +1,754 @@ +{ + "cameras": { + "side": { + "C": [ + -600.0, + -0.0, + 0.0 + ], + "R": [ + [ + 0.0, + -1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ], + [ + -1.0, + -0.0, + 0.0 + ] + ], + "f": 10549.880922862098, + "c": [ + 365.2180216639705, + 743.9939909588088 + ], + "box": [ + 237, + 570, + 522, + 770 + ], + "unit": 1024, + "names": [ + "ring", + "hip_fl", + "knee_fl", + "ankle_fl", + "hip_rl", + "knee_rl", + "ankle_rl", + "nose", + "tail", + "muzzle", + "trunnion", + "cupola", + "block", + "emblem" + ], + "model": "elevation", + "scale_m_per_px": 0.05687267983279046, + "rms": 1.5321926572259845, + "residuals": { + "ring": [ + 0.2180216639704895, + -1.2428670565559514 + ], + "hip_fl": [ + 0.04593864145988391, + -0.6582036164438705 + ], + "knee_fl": [ + -0.018879551606630685, + 0.12786938593023933 + ], + "ankle_fl": [ + -0.0138921575945119, + 1.5256890900922144 + ], + "hip_rl": [ + 0.3249497391885825, + -0.832180574321228 + ], + "knee_rl": [ + 0.672118244926196, + 0.11758989670329356 + ], + "ankle_rl": [ + 0.6202108219420097, + 0.43246697745144047 + ], + "nose": [ + -1.4229269419024035, + 0.4620842264175735 + ], + "tail": [ + -0.9131588857168822, + 0.5708331673771454 + ], + "muzzle": [ + 0.3444739988335641, + -4.561957334486692 + ], + "trunnion": [ + 0.38350918282208113, + 0.6417563897421132 + ], + "cupola": [ + 0.10927272301091762, + 0.7410489010529773 + ], + "block": [ + -0.44392841143576334, + 0.4857253005391158 + ], + "emblem": [ + 0.6908431464034948, + 0.5483091806593166 + ] + }, + "lens": 1332.616537624686, + "azimuth": 90.0, + "elevation": 0.0, + "distance": 600.0, + "worst": [ + "muzzle", + 4.57494448682706 + ] + }, + "front": { + "C": [ + -0.0, + 600.0, + -0.0 + ], + "R": [ + [ + -1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ], + [ + -0.0, + 1.0, + -0.0 + ] + ], + "f": 10243.955912558718, + "c": [ + 118.00000000000011, + 742.3042866937758 + ], + "box": [ + 0, + 570, + 237, + 770 + ], + "unit": 1024, + "names": [ + "hip_fl", + "hip_fr", + "knee_fl", + "knee_fr", + "ankle_fl", + "ankle_fr", + "muzzle", + "ring", + "flank_l", + "flank_r", + "emblem" + ], + "model": "elevation", + "scale_m_per_px": 0.05857112282808849, + "rms": 1.462801137908827, + "residuals": { + "hip_fl": [ + 1.2865472539539553, + -0.5353431206955293 + ], + "hip_fr": [ + -1.286547253953728, + -0.5353431206955293 + ], + "knee_fl": [ + 1.4642878560768224, + -0.5290292372160366 + ], + "knee_fr": [ + -1.464287856076595, + -0.5290292372160366 + ], + "ankle_fl": [ + 1.4501136316823988, + -0.73925023832021 + ], + "ankle_fr": [ + -1.4501136316821714, + -0.73925023832021 + ], + "muzzle": [ + 1.1368683772161603e-13, + 2.480229922947956 + ], + "ring": [ + 1.1368683772161603e-13, + 0.07601536501647388 + ], + "flank_l": [ + -0.19810083281382163, + -0.7216661984898565 + ], + "flank_r": [ + 0.198100832814049, + -0.7216661984898565 + ], + "emblem": [ + 1.1368683772161603e-13, + -1.4933161568810647 + ] + }, + "lens": 1556.0439360848684, + "azimuth": 0.0, + "elevation": -0.0, + "distance": 600.0, + "worst": [ + "muzzle", + 2.480229922947956 + ] + }, + "rear": { + "C": [ + -0.0, + -600.0, + -0.0 + ], + "R": [ + [ + 1.0, + 0.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ], + [ + -0.0, + -1.0, + -0.0 + ] + ], + "f": 10352.694133391838, + "c": [ + 651.4285714285712, + 742.0112732454559 + ], + "box": [ + 522, + 570, + 787, + 770 + ], + "unit": 1024, + "names": [ + "hip_rl", + "hip_rr", + "knee_rl", + "knee_rr", + "ankle_rl", + "ankle_rr", + "ring" + ], + "model": "elevation", + "scale_m_per_px": 0.05795592840560652, + "rms": 1.0198824491435732, + "residuals": { + "hip_rl": [ + -0.6437456768096581, + -0.36072657028705635 + ], + "hip_rr": [ + 0.500888533952093, + -0.36072657028705635 + ], + "knee_rl": [ + -1.270375107618861, + -0.4617362121722408 + ], + "knee_rr": [ + 1.1275179647612958, + -0.4617362121722408 + ], + "ankle_rl": [ + -1.177701465837913, + -0.37025075480130454 + ], + "ankle_rr": [ + 1.034844322980348, + -0.37025075480130454 + ], + "ring": [ + 0.42857142857121744, + 0.35818678332600484 + ] + }, + "lens": 1406.4037313287026, + "azimuth": 180.0, + "elevation": -0.0, + "distance": 600.0, + "worst": [ + "knee_rl", + 1.35168533456896 + ] + }, + "top": { + "C": [ + 0.0, + 0.0, + 600.0 + ], + "R": [ + [ + -1.0, + 0.0, + 0.0 + ], + [ + 0.0, + -1.0, + 0.0 + ], + [ + 0.0, + 0.0, + 1.0 + ] + ], + "f": 8366.282265132446, + "c": [ + 905.0000000000005, + 664.4412757357235 + ], + "box": [ + 787, + 570, + 1024, + 770 + ], + "unit": 1024, + "names": [ + "ring", + "nose", + "tail", + "flank_l", + "flank_r", + "muzzle" + ], + "model": "elevation", + "scale_m_per_px": 0.0717164423797386, + "rms": 1.1176700420396355, + "residuals": { + "ring": [ + 4.547473508864641e-13, + 0.44127573572347956 + ], + "nose": [ + 4.547473508864641e-13, + -0.5918800620850106 + ], + "tail": [ + 4.547473508864641e-13, + -0.8880028252954162 + ], + "flank_l": [ + 1.4926077771382324, + 0.4705676108375201 + ], + "flank_r": [ + -1.492607777137323, + 0.4705676108375201 + ], + "muzzle": [ + 4.547473508864641e-13, + 1.1237877607402424 + ] + }, + "lens": 1270.827685842903, + "azimuth": -0.0, + "elevation": 90.0, + "distance": 600.0, + "worst": [ + "flank_l", + 1.5650277482341541 + ] + }, + "hero": { + "C": [ + -21.401224826667082, + 20.832214777219917, + 1.5983239046664677 + ], + "R": [ + [ + -0.6937977676765082, + -0.7201698810468916, + 0.0 + ], + [ + -0.0770954889717917, + 0.0742723065130173, + 0.9942534435773592 + ], + [ + -0.7160313841915691, + 0.6898108196586529, + -0.10705180958098395 + ] + ], + "f": 1459.3742244264236, + "c": [ + 512.0, + 280.0 + ], + "box": [ + 0, + 0, + 1024, + 560 + ], + "unit": 1024, + "names": [ + "hip_fl", + "hip_fr", + "hip_rl", + "knee_rl", + "ankle_fl", + "ankle_fr", + "ankle_rl", + "muzzle", + "emblem" + ], + "rms": 28.830695433314496, + "rms_h": 0.05686527698878599, + "median": 18.65280182595586, + "worst": [ + "hip_rl", + 65.58658976067986 + ], + "left_out": 40.57531044119979, + "model": "upright", + "tried": { + "upright": { + "rms": 28.830695433314496, + "left_out": 40.57531044119979, + "lens": 51.30612507749145 + } + }, + "lens": 51.30612507749145, + "lens_range": [ + 34.39152412385434, + 126.19270486200558 + ], + "azimuth": 45.64390496556719, + "elevation": -3.1922127370566113, + "distance": 27.8768008864902, + "roll": 0.0, + "twist": 0.0, + "horizon": [ + 437.0, + 437.1316172852039 + ], + "residuals": { + "hip_fl": [ + -20.14885881211933, + -13.692356297364029 + ], + "hip_fr": [ + 6.755832757879091, + -2.83406741611617 + ], + "hip_rl": [ + -65.15173117749214, + 7.540071684772897 + ], + "knee_rl": [ + -1.0426390666935959, + -13.976272294239493 + ], + "ankle_fl": [ + 26.34853208550919, + 18.617022757220866 + ], + "ankle_fr": [ + -10.988721886978169, + 11.722351237037856 + ], + "ankle_rl": [ + 18.974495151886913, + 0.26636239069694057 + ], + "muzzle": [ + -12.857678146792637, + 12.781747952606338 + ], + "emblem": [ + 15.935587520105855, + -9.694537964618462 + ] + }, + "solved": { + "hip_fl": [ + -4.203947368421052, + 4.245283018867925, + 3.5382323733862955 + ], + "hip_fr": [ + 4.203947368421052, + 4.245283018867925, + 3.5382323733862955 + ], + "hip_rl": [ + -3.6870967741935488, + -4.245283018867925, + 4.62507608034084 + ], + "knee_rl": [ + -4.964516129032258, + -7.188679245283019, + 1.5158855751673768 + ], + "ankle_fl": [ + -4.322368421052631, + 5.264150943396227, + 0.8733862959285005 + ], + "ankle_fr": [ + 4.322368421052631, + 5.264150943396227, + 0.8733862959285005 + ], + "ankle_rl": [ + -4.848387096774194, + -6.735849056603774, + 0.6522215459525259 + ], + "muzzle": [ + 0.0, + 5.850694339622642, + 7.993793445878848 + ], + "emblem": [ + 0.0, + 5.660377358490567, + 4.745779543197616 + ] + } + } + }, + "stand": { + "ankle_fl": [ + -4.322368421052631, + 5.264150943396227, + 0.8733862959285005 + ], + "ankle_fr": [ + 4.322368421052631, + 5.264150943396227, + 0.8733862959285005 + ], + "ankle_rl": [ + -4.848387096774194, + -6.735849056603774, + 0.6522215459525259 + ], + "ankle_rr": [ + 4.848387096774194, + -6.735849056603774, + 0.6522215459525259 + ], + "block": [ + 0.0, + -7.9245283018867925, + 5.886792452830189 + ], + "cupola": [ + 0.0, + -1.3018867924528301, + 8.943396226415095 + ], + "emblem": [ + 0.0, + 5.660377358490567, + 4.745779543197616 + ], + "flank_l": [ + -5.081657894736842, + 0.2864, + 5.328947368421052 + ], + "flank_r": [ + 5.081657894736842, + 0.2864, + 5.328947368421052 + ], + "hip_fl": [ + -4.203947368421052, + 4.245283018867925, + 3.5382323733862955 + ], + "hip_fr": [ + 4.203947368421052, + 4.245283018867925, + 3.5382323733862955 + ], + "hip_rl": [ + -3.6870967741935488, + -4.245283018867925, + 4.62507608034084 + ], + "hip_rr": [ + 3.6870967741935488, + -4.245283018867925, + 4.62507608034084 + ], + "knee_fl": [ + -4.322368421052631, + 5.377358490566038, + 2.1380337636544193 + ], + "knee_fr": [ + 4.322368421052631, + 5.377358490566038, + 2.1380337636544193 + ], + "knee_rl": [ + -4.964516129032258, + -7.188679245283019, + 1.5158855751673768 + ], + "knee_rr": [ + 4.964516129032258, + -7.188679245283019, + 1.5158855751673768 + ], + "muzzle": [ + 0.0, + 5.850694339622642, + 7.993793445878848 + ], + "nose": [ + 0.0, + 6.178701886792453, + 5.60377358490566 + ], + "ring": [ + 0.0, + 0.0, + 7.861900566998751 + ], + "tail": [ + 0.0, + -5.907298113207547, + 6.90566037735849 + ], + "trunnion": [ + 0.0, + 1.9811320754716981, + 7.754716981132075 + ] + }, + "spread": { + "knee_rr": { + "x": 0.0, + "z": 0.018624467437614145 + }, + "hip_rr": { + "x": 0.0, + "z": 0.060255629945221933 + }, + "ankle_fr": { + "x": 0.0, + "z": 0.1333167825223437 + }, + "trunnion": {}, + "ankle_fl": { + "x": 0.0, + "z": 0.1333167825223437 + }, + "flank_l": { + "x": 0.1393157894736845, + "y": 0.0, + "z": 0.0 + }, + "ankle_rl": { + "x": 0.0, + "z": 0.04053560559951308 + }, + "emblem": { + "z": 0.017874875868917783 + }, + "nose": { + "y": 0.2441962264150943 + }, + "block": {}, + "ankle_rr": { + "x": 0.0, + "z": 0.04053560559951308 + }, + "knee_fl": { + "x": 0.0, + "z": 0.019364448857994265 + }, + "ring": { + "x": 0.02903225806451613, + "y": 0.0, + "z": 0.17949354518371408 + }, + "muzzle": { + "x": 0.0, + "y": 0.04101132075471714, + "z": 0.5913604766633558 + }, + "hip_fr": { + "x": 0.0, + "z": 0.04319761668321709 + }, + "flank_r": { + "x": 0.1393157894736845, + "y": 0.0, + "z": 0.0 + }, + "hip_fl": { + "x": 0.0, + "z": 0.04319761668321709 + }, + "knee_fr": { + "x": 0.0, + "z": 0.019364448857994265 + }, + "hip_rl": { + "x": 0.0, + "z": 0.060255629945221933 + }, + "knee_rl": { + "x": 0.0, + "z": 0.018624467437614145 + }, + "cupola": {}, + "tail": { + "y": 0.0721962264150946 + } + } +} \ No newline at end of file diff --git a/surfaces/blender/experiments/mechs/bastion_form.py b/surfaces/blender/experiments/mechs/bastion_form.py new file mode 100644 index 0000000..521490f --- /dev/null +++ b/surfaces/blender/experiments/mechs/bastion_form.py @@ -0,0 +1,64 @@ +"""BASTION's numbers (sheet 36): the hull's cage, the wells, the plates' cuts, the kept cameras. Plain Python. + +The hull is one closed free cage, authored on the mech's right (x >= 0) and mirrored: five rings of seven points +from the nose (on the seam) round the flank to the tail (on the seam), closed over the deck and under the belly by a +centre line each. The points are where the SURFACE passes: massing.cage_through moves the cage until its subdivided +surface goes through them. World metres: x right, y forward, z up, the origin on the ground under the turret ring. + + A the rim: the carapace's overhanging edge, the plan view's outline + B the shoulder: where the flank band breaks into the dome + C the deck's rim round the turret ring + D under the overhang, where the belly's box meets the carapace + E the belly's lower edge +""" +import json +from pathlib import Path + +HERE = Path(__file__).resolve().parent +N = 7 +RINGS = { + "A": [(0.0, 6.25, 5.55), (2.3, 5.95, 5.35), (4.4, 4.9, 5.1), (5.05, 2.6, 5.05), (5.05, -2.6, 5.5), (3.9, -4.9, 5.9), (0.0, -5.85, 5.95)], + "B": [(0.0, 5.35, 6.3), (1.9, 5.05, 6.35), (3.6, 4.0, 6.5), (4.1, 2.2, 6.8), (4.1, -2.4, 6.95), (3.1, -4.2, 7.0), (0.0, -5.0, 7.0)], + "C": [(0.0, 2.9, 7.55), (1.3, 2.7, 7.6), (2.35, 1.8, 7.7), (2.6, 0.6, 7.75), (2.6, -1.6, 7.75), (1.9, -2.9, 7.7), (0.0, -3.3, 7.65)], + "D": [(0.0, 5.70, 4.95), (1.7, 5.50, 4.9), (2.45, 4.6, 4.75), (2.45, 2.4, 4.7), (2.45, -2.6, 5.0), (2.0, -4.8, 5.3), (0.0, -5.6, 5.4)], + "E": [(0.0, 5.45, 3.9), (1.5, 5.25, 3.8), (2.15, 4.3, 3.3), (2.2, 2.2, 3.05), (2.2, -2.6, 3.2), (1.8, -4.6, 3.9), (0.0, -5.3, 4.2)], +} +DECK = [(0.0, 2.0, 7.82), (0.0, 1.2, 7.85), (0.0, 0.0, 7.86), (0.0, -1.3, 7.85), (0.0, -2.4, 7.8)] # the deck's centre line, under the turret ring +BELLY = [(0.0, 4.4, 3.5), (0.0, 3.0, 3.05), (0.0, 0.0, 3.0), (0.0, -2.6, 3.1), (0.0, -4.3, 3.8)] +# creases: (ring, from point, to point, weight) along a ring; (ring, ring, point, weight) a column between two rings +RING_CREASES = [("A", 0, 6, 1.0), ("B", 1, 6, 0.85), ("E", 1, 5, 0.6)] +COLUMN_CREASES = [("A", "B", 2, 0.6), ("A", "B", 5, 0.6), ("A", "D", 2, 0.5), ("B", "C", 2, 0.6), ("B", "C", 5, 0.6), ("B", "C", 3, 0.4), ("B", "C", 4, 0.4)] +RING = (0.0, 0.0, 7.86) # the turret ring's centre on the deck +RING_R = 1.95 + + +def hull_sheet(rings=None): + """The hull's cage as a free-cage sheet (brokkr_kitbash.shell's form): verts, faces, creases, mirror. Faces are + wound by massing.cage_sheet, which also declares the poles.""" + R = rings or RINGS + order = ["C", "B", "A", "D", "E"] + index = {(r, j): k * N + j for k, r in enumerate(order) for j in range(N)} + verts = [list(p) for r in order for p in R[r]] + deck0 = len(verts) + verts += [list(p) for p in DECK] + belly0 = len(verts) + verts += [list(p) for p in BELLY] + faces = [] + for a, b in zip(order, order[1:]): + for j in range(N - 1): + faces.append([index[a, j], index[a, j + 1], index[b, j + 1], index[b, j]]) + for ring, c0 in (("C", deck0), ("E", belly0)): + faces.append([index[ring, 0], index[ring, 1], c0]) + for j in range(1, N - 2): + faces.append([index[ring, j], index[ring, j + 1], c0 + j, c0 + j - 1]) + faces.append([index[ring, N - 2], index[ring, N - 1], c0 + N - 3]) + creases = [] + for ring, a, b, w in RING_CREASES: + creases += [[index[ring, j], index[ring, j + 1], w] for j in range(a, b)] + for ra, rb, j, w in COLUMN_CREASES: + creases.append([index[ra, j], index[rb, j], w]) + return {"verts": verts, "faces": faces, "creases": creases, "mirror": True} + + +def cameras(): + return json.loads((HERE / "bastion_cameras.json").read_text(encoding="utf-8")) diff --git a/surfaces/blender/experiments/mechs/bastion_overlay.py b/surfaces/blender/experiments/mechs/bastion_overlay.py new file mode 100644 index 0000000..73c6f0b --- /dev/null +++ b/surfaces/blender/experiments/mechs/bastion_overlay.py @@ -0,0 +1,41 @@ +"""python bastion_overlay.py : our build's silhouette at each kept camera drawn over the concept's view +(MECH_OUT/bastion/_.png over images/36.webp), one strip: _overlay.png. Plain Python and Pillow.""" +import json, os, sys +from pathlib import Path +from PIL import Image, ImageChops, ImageFilter + +HERE = Path(__file__).resolve().parent +OUT = Path(os.environ["MECH_OUT"]) / "bastion" +SHEET = Image.open(Path(os.environ["MECH_CONCEPTS"]) / "36.webp").convert("RGB") +VIEWS = json.loads((HERE / "concepts.json").read_text(encoding="utf-8"))["bastion"]["skeleton"]["views"] + + +def over(stage, tag, tint=(255, 60, 40)): + ours = Image.open(OUT / f"{stage}_{tag}.png").convert("RGBA") + box = VIEWS[tag]["box"] + concept = SHEET.crop(box).resize(ours.size, Image.LANCZOS) + alpha = ours.split()[3].point(lambda a: 255 if a > 96 else 0) + edge = ImageChops.difference(alpha.filter(ImageFilter.MaxFilter(5)), alpha.filter(ImageFilter.MinFilter(3))) + wash = Image.blend(concept, Image.new("RGB", ours.size, tint), 0.28) + out = Image.composite(wash, concept, alpha) + out.paste(Image.new("RGB", ours.size, (255, 255, 0)), mask=edge) + return out + + +def strip(stage, tags=("hero", "front", "side", "rear", "top"), h=620): + ims = [over(stage, t) for t in tags] + ims = [im.resize((round(im.width * h / im.height), h), Image.LANCZOS) for im in ims] + out = Image.new("RGB", (sum(im.width for im in ims) + 8 * (len(ims) - 1), h), (24, 24, 24)) + x = 0 + for im in ims: + out.paste(im, (x, 0)) + x += im.width + 8 + return out + + +if __name__ == "__main__": + stage = sys.argv[1] + hero = over(stage, "hero") + hero.save(OUT / f"{stage}_overlay_hero.png") + strip(stage, ("front", "side", "rear", "top"), 600).save(OUT / f"{stage}_overlay.png") + print(OUT / f"{stage}_overlay.png") diff --git a/surfaces/blender/experiments/mechs/bastion_sheets.py b/surfaces/blender/experiments/mechs/bastion_sheets.py new file mode 100644 index 0000000..87af59d --- /dev/null +++ b/surfaces/blender/experiments/mechs/bastion_sheets.py @@ -0,0 +1,244 @@ +"""python bastion_sheets.py: BASTION's comparison sheets under /out/compare, from MECH_OUT/bastion's renders, +the kept cameras (bastion_cameras.json) and the marks and traced lines of concepts.json. Plain Python and Pillow. + + bastion_camera.png the five views, each with its marks and the standing skeleton drawn through its solved camera + bastion_flowlines.png the traced lines on the concept beside the built edges through the same camera, scored + bastion_vs_concept.png hero and rear, concept beside ours, the whole mech in frame; side below + bastion_character.png the character line: the carapace's rim under the dome, the mass alone and the plated build + bastion_plan.png our top view against the concept's, and ours drawn over it + bastion_components.png each inset beside its built part + bastion_scores.json the cameras' errors, the flow scores, the silhouettes' overlap""" +import json, math, os, sys +from pathlib import Path +import numpy as np +from PIL import Image, ImageChops, ImageDraw, ImageFilter, ImageFont + +HERE = Path(__file__).resolve().parent +sys.path.insert(0, str(HERE)) +import camsolve + +OUT = Path(os.environ["MECH_OUT"]) / "bastion" +CMP = Path(os.environ["MECH_OUT"]) / "compare" +CMP.mkdir(exist_ok=True) +SHEET = Image.open(Path(os.environ["MECH_CONCEPTS"]) / "36.webp").convert("RGB") +SPEC = json.loads((HERE / "concepts.json").read_text(encoding="utf-8"))["bastion"] +VIEWS = SPEC["skeleton"]["views"] +KEPT = json.loads((HERE / "bastion_cameras.json").read_text(encoding="utf-8")) +CAMS, STAND = KEPT["cameras"], KEPT["stand"] +BG = (24, 24, 24) +try: + FONT, SMALL = ImageFont.truetype("arial.ttf", 22), ImageFont.truetype("arial.ttf", 16) +except OSError: + FONT = SMALL = ImageFont.load_default() +BONES = [(f"{a}_{t}", f"{b}_{t}") for t in ("fl", "fr", "rl", "rr") for a, b in (("hip", "knee"), ("knee", "ankle"))] + [("hip_fl", "hip_fr"), ("hip_rl", "hip_rr"), ("hip_fl", "hip_rl"), ("hip_fr", "hip_rr"), + ("ring", "trunnion"), ("trunnion", "muzzle"), ("nose", "ring"), ("ring", "tail")] + + +def fit(im, h): + return im.resize((max(1, round(im.width * h / im.height)), h), Image.LANCZOS) + + +def label(im, text, sub=None): + out = Image.new("RGB", (im.width, im.height + 34 + (22 if sub else 0)), BG) + out.paste(im, (0, out.height - im.height)) + d = ImageDraw.Draw(out) + d.text((6, 4), text, fill=(235, 235, 235), font=FONT) + if sub: + d.text((6, 32), sub, fill=(170, 170, 170), font=SMALL) + return out + + +def row(ims, gap=8): + h = max(i.height for i in ims) + out = Image.new("RGB", (sum(i.width for i in ims) + gap * (len(ims) - 1), h), BG) + x = 0 + for i in ims: + out.paste(i, (x, 0)) + x += i.width + gap + return out + + +def stack(ims, gap=10): + out = Image.new("RGB", (max(i.width for i in ims), sum(i.height for i in ims) + gap * (len(ims) - 1)), BG) + y = 0 + for i in ims: + out.paste(i, (0, y)) + y += i.height + gap + return out + + +def concept(tag, zoom=3): + box = VIEWS[tag]["box"] + return SHEET.crop(box).resize(((box[2] - box[0]) * zoom, (box[3] - box[1]) * zoom), Image.LANCZOS) + + +def ours(tag, stage="full", sil=False): + return Image.open(OUT / f"{stage}_{'sil_' if sil else ''}{tag}.png") + + +def mask_of(tag, stage="full"): + p = OUT / f"{stage}_sil_{tag}.png" + im = Image.open(p if p.exists() else OUT / f"{stage}_{tag}.png").convert("RGBA") + return im.split()[3].point(lambda a: 255 if a > 96 else 0) + + +def camera_sheet(scores): + panels = [] + for tag in ("hero", "front", "side", "rear", "top"): + z = 2 if tag == "hero" else 4 + im = concept(tag, z) + d = ImageDraw.Draw(im) + box, cam = VIEWS[tag]["box"], CAMS[tag] + px = lambda q: ((q[0] - box[0]) * z, (q[1] - box[1]) * z) # noqa: E731 + proj = {k: camsolve.project(cam, [p])[0] for k, p in STAND.items()} + for a, b in BONES: + if a in proj and b in proj: + d.line([px(proj[a]), px(proj[b])], fill=(0, 230, 255), width=2) + for k, m in VIEWS[tag]["joints"].items(): + x, y = px(m) + d.ellipse([x - 5, y - 5, x + 5, y + 5], outline=(255, 235, 0), width=2) + if k in proj: + d.line([(x, y), px(proj[k])], fill=(255, 60, 60), width=2) + scores["cameras"][tag] = {"rms_px": round(cam["rms"], 2), "marks": len(cam["names"]), "worst": cam["worst"], "model": cam["model"], "lens_mm": round(cam["lens"], 1)} + note = f"rms {cam['rms']:.1f} px over {len(cam['names'])} marks; worst {cam['worst'][0]} {cam['worst'][1]:.0f} px" + (f"; lens {cam['lens']:.0f} mm, {cam['distance']:.1f} m off, eye {cam['C'][2]:.1f} m" if tag == "hero" else f"; {cam['scale_m_per_px']:.4f} m a pixel") + panels.append(label(fit(im, 560 if tag != "hero" else 760), tag, note)) + sheet = stack([panels[0], row(panels[1:])]) + sheet = label(sheet, "BASTION cameras: marks (yellow), the standing skeleton through each solved camera (cyan), misses (red)") + sheet.save(CMP / "bastion_camera.png") + + +def seg_dist(points, segs): + """Per point: the distance to the nearest segment and that segment's direction.""" + P = np.asarray(points, float) + A, B = segs[:, :2], segs[:, 2:] + D = B - A + L = np.maximum((D * D).sum(1), 1e-9) + t = np.clip(((P[:, None] - A) * D).sum(2) / L, 0, 1) + off = P[:, None] - (A + t[:, :, None] * D) + dist = np.linalg.norm(off, axis=2) + k = dist.argmin(1) + return dist[np.arange(len(P)), k], D[k] / np.sqrt(L[k])[:, None] + + +def resampled(line, n=60): + p = np.asarray(line, float) + d = np.concatenate([[0], np.cumsum(np.linalg.norm(np.diff(p, axis=0), axis=1))]) + t = np.linspace(0, d[-1], n) + return np.stack([np.interp(t, d, p[:, k]) for k in range(2)], 1) + + +def flow_sheet(scores): + lines = SPEC["flow"]["lines"] + rows = [] + for tag in ("hero", "side", "top"): + path = OUT / f"full_edges_{tag}.json" + if not path.exists(): + continue + edges = json.loads(path.read_text(encoding="utf-8")) + segs = np.array([e["seg"] for e in edges], float) + box = VIEWS[tag]["box"] + height = VIEWS[tag]["ground"] - VIEWS[tag]["top"] + z = 2 if tag == "hero" else 4 + left, right = concept(tag, z), Image.alpha_composite(Image.new("RGBA", ours(tag).size, (40, 44, 50, 255)), ours(tag).convert("RGBA")).convert("RGB").resize(concept(tag, z).size, Image.LANCZOS) + right = Image.blend(right, Image.new("RGB", right.size, (0, 0, 0)), 0.45) + dl, dr = ImageDraw.Draw(left), ImageDraw.Draw(right) + px = lambda q: ((q[0] - box[0]) * z, (q[1] - box[1]) * z) # noqa: E731 + for e in edges: + u0, v0, u1, v1 = e["seg"] + dr.line([px((u0, v0)), px((u1, v1))], fill=(0, 230, 255) if e["kind"] == "crease" else (120, 255, 140), width=1) + notes = [] + for name, line in lines.get(tag, {}).items(): + pts = resampled(line) + dist, way = seg_dist(pts, segs) + tan = np.gradient(pts, axis=0) + tan /= np.maximum(np.linalg.norm(tan, axis=1), 1e-9)[:, None] + along = np.abs((tan * way).sum(1)) > math.cos(math.radians(25)) + on = float(((dist < 0.015 * height) & along).mean()) + off = float(dist.mean() / height * 100) + scores["flow"][f"{tag}.{name}"] = {"on": round(on, 2), "off_pct_height": round(off, 2)} + notes.append(f"{name}: on {on:.2f}, off {off:.1f}% H") + col = (255, 80, 60) if name == SPEC["flow"]["character"] else (255, 220, 0) + for im_d in (dl, dr): + im_d.line([px(q) for q in line], fill=col, width=3) + rows.append(label(row([fit(left, 620), fit(right, 620)]), f"{tag}: traced lines (the character line red) | built edges through the solved camera (creases cyan, contours green)", "; ".join(notes))) + label(stack(rows), "BASTION flow lines: on = share of a traced line with a built edge running along it within 1.5% of the figure's height").save(CMP / "bastion_flowlines.png") + + +def iou(tag): + """Our silhouette against nothing traced: the concept has no mask, so this is the hull's and legs' frame only.""" + return None + + +def framed(im, colour=(40, 44, 50)): + return Image.alpha_composite(Image.new("RGBA", im.size, (*colour, 255)), im.convert("RGBA")).convert("RGB") + + +def vs_sheet(): + rows = [] + for tag, h in (("hero", 840), ("rear", 600), ("side", 600), ("front", 600)): + c = concept(tag, 2) + rows.append(label(row([fit(c, h), fit(framed(ours(tag)), h)]), f"{tag}: concept | ours at the solved camera")) + top = rows[0] + rest = row([fit(r, 560) for r in rows[1:]]) + label(stack([top, rest]), "BASTION against its concept (sheet 36)").save(CMP / "bastion_vs_concept.png") + + +def character_sheet(): + box = [140, 70, 900, 330] # the hull in the hero view, the sheet's pixels + k = 1536 / 1024 + crop = lambda im: im.crop([round(v * k) for v in box]) # noqa: E731 + c = SHEET.crop(box).resize((round((box[2] - box[0]) * k), round((box[3] - box[1]) * k)), Image.LANCZOS) + panels = [label(c, "concept: the rim and the dome")] + for stage, text in (("volume", "the mass alone (one closed free cage, 45 authored vertices)"), ("full", "plated, at the solved hero camera")): + p = OUT / f"{stage}_hero.png" + if p.exists(): + panels.append(label(crop(framed(Image.open(p).resize((1536, 840), Image.LANCZOS))), text)) + side = [label(fit(concept("side", 3), 420), "concept, side"), label(fit(framed(ours("side")), 420), "ours, side")] + label(stack([row(panels), row(side)]), "BASTION character line: the carapace's overhanging rim under a low dome").save(CMP / "bastion_character.png") + + +def plan_sheet(scores): + c = concept("top", 3) + o = framed(ours("top")).resize(c.size, Image.LANCZOS) + alpha = mask_of("top").resize(c.size) + edge = ImageChops.difference(alpha.filter(ImageFilter.MaxFilter(5)), alpha.filter(ImageFilter.MinFilter(3))) + over = Image.composite(Image.blend(c, Image.new("RGB", c.size, (255, 60, 40)), 0.25), c, alpha) + over.paste(Image.new("RGB", c.size, (255, 255, 0)), mask=edge) + # the concept's own plan outline: what is lighter than the sheet's dark ground + g = np.asarray(c.convert("L"), float) + cm = Image.fromarray(((g > 62) * 255).astype(np.uint8)).filter(ImageFilter.MedianFilter(9)) + a, b = np.asarray(cm) > 0, np.asarray(alpha) > 0 + a[int(0.86 * a.shape[0]):] = False # the view's caption + scores["plan"] = {"iou": round(float((a & b).sum() / max((a | b).sum(), 1)), 3), "concept_px": int(a.sum()), "ours_px": int(b.sum()), "note": "the concept's plan hides its legs under the hull and draws no cooling behind the tail; ours shows feet and the cooling housings"} + label(row([label(fit(c, 700), "concept, top view"), label(fit(o, 700), "ours, the plan's camera"), label(fit(over, 700), "ours over the concept's", f"overlap {scores['plan']['iou']:.2f} (intersection over union)")]), + "BASTION plan: our top view against the concept's").save(CMP / "bastion_plan.png") + + +def components_sheet(): + cells = [] + names = {"cockpit": "recessed cockpit & sensor suite", "magazine": "lateral missile magazine (door open upward: the prompt)", "turret": "main ballistic turret", "interceptor": "perimeter interceptor launcher", + "rear_leg": "rear leg propulsion assembly", "cooling": "rear cooling arrays (under housings: the prompt)"} + for key, box in SPEC["insets"].items(): + p = OUT / f"close_{key}.png" + if not p.exists(): + continue + c = SHEET.crop(box) + cells.append(label(row([fit(c, 400), fit(Image.open(p).convert("RGB"), 400)]), names[key])) + extra = [label(fit(Image.open(OUT / f"close_{k}.png").convert("RGB"), 400), t) for k, t in (("front_leg", "front leg (no inset): guard plates, hip housing"), ("foot", "foot (no inset): feet.bastion_pads")) if (OUT / f"close_{k}.png").exists()] + rows = [row(cells[i:i + 2]) for i in range(0, len(cells), 2)] + ([row(extra)] if extra else []) + label(stack(rows), "BASTION components: the sheet's inset | the built part").save(CMP / "bastion_components.png") + + +if __name__ == "__main__": + scores = {"cameras": {}, "flow": {}} + camera_sheet(scores) + flow_sheet(scores) + vs_sheet() + character_sheet() + plan_sheet(scores) + components_sheet() + (CMP / "bastion_scores.json").write_text(json.dumps(scores, indent=1), encoding="utf-8") + for p in sorted(CMP.glob("bastion_*.png")): + im = Image.open(p) + im.convert("RGB").resize((round(im.width * 1400 / max(im.size)), round(im.height * 1400 / max(im.size))), Image.LANCZOS).save(p.with_name(p.stem + "_small.jpg"), quality=86) + print(json.dumps(scores, indent=1)) diff --git a/surfaces/blender/experiments/mechs/concepts.json b/surfaces/blender/experiments/mechs/concepts.json index 03b1131..6bfcb77 100644 --- a/surfaces/blender/experiments/mechs/concepts.json +++ b/surfaces/blender/experiments/mechs/concepts.json @@ -3209,5 +3209,475 @@ ] } }, - "_doc_skeleton": "skeleton: joints marked by hand on the sheet (pixels of the sheet scaled to skeleton.unit wide), the mech's own left and right; ground is the soles' line, top the figure's highest point in that view. skeleton.py reads it." + "_doc_skeleton": "skeleton: joints marked by hand on the sheet (pixels of the sheet scaled to skeleton.unit wide), the mech's own left and right; ground is the soles' line, top the figure's highest point in that view. skeleton.py reads it.", + "bastion": { + "sheet": "36.webp", + "unit": 1024, + "skeleton": { + "unit": 1024, + "height_m": 9.0, + "origin": "ring", + "note": "Marked by hand to about 3 px on elevations 155 px tall (0.17 m). Height 9.0 m from the hero's soldiers (85 px against the 310 px from the ground to the hull's top over the front leg). The plan states its own scale, 0.0716 m a pixel, at which its hull is as wide as the front view's and as long as the side view's; its magazine boxes then stand 1.2 m outside the rim, which no elevation shows.", + "views": { + "side": { + "kind": "side", + "faces": "left", + "box": [ + 237, + 570, + 522, + 770 + ], + "ground": 744, + "top": 585, + "joints": { + "ring": [ + 365, + 607 + ], + "hip_fl": [ + 290, + 682 + ], + "knee_fl": [ + 270, + 706 + ], + "ankle_fl": [ + 272, + 727 + ], + "hip_rl": [ + 440, + 663 + ], + "knee_rl": [ + 492, + 717 + ], + "ankle_rl": [ + 484, + 732 + ], + "nose": [ + 258, + 645 + ], + "tail": [ + 470, + 622 + ], + "muzzle": [ + 262, + 608 + ], + "trunnion": [ + 330, + 607 + ], + "cupola": [ + 388, + 586 + ], + "block": [ + 505, + 640 + ], + "emblem": [ + 265, + 660 + ] + } + }, + "front": { + "kind": "front", + "box": [ + 0, + 570, + 237, + 770 + ], + "ground": 742, + "top": 590, + "joints": { + "hip_fl": [ + 189, + 682 + ], + "hip_fr": [ + 47, + 682 + ], + "knee_fl": [ + 191, + 706 + ], + "knee_fr": [ + 45, + 706 + ], + "ankle_fl": [ + 191, + 728 + ], + "ankle_fr": [ + 45, + 728 + ], + "muzzle": [ + 118, + 602 + ], + "ring": [ + 118, + 608 + ], + "flank_l": [ + 205, + 652 + ], + "flank_r": [ + 31, + 652 + ], + "emblem": [ + 118, + 662 + ] + } + }, + "rear": { + "kind": "rear", + "box": [ + 522, + 570, + 787, + 770 + ], + "ground": 742, + "top": 587, + "joints": { + "hip_rl": [ + 588, + 662 + ], + "hip_rr": [ + 715, + 662 + ], + "knee_rl": [ + 566, + 716 + ], + "knee_rr": [ + 737, + 716 + ], + "ankle_rl": [ + 568, + 731 + ], + "ankle_rr": [ + 735, + 731 + ], + "ring": [ + 651, + 606 + ] + } + }, + "top": { + "kind": "top", + "front": "down", + "box": [ + 787, + 570, + 1024, + 770 + ], + "ground": 760, + "top": 575, + "scale": 0.0716, + "stretch": 1.0, + "joints": { + "ring": [ + 905, + 664 + ], + "nose": [ + 905, + 752 + ], + "tail": [ + 905, + 582 + ], + "flank_l": [ + 975, + 668 + ], + "flank_r": [ + 835, + 668 + ], + "muzzle": [ + 905, + 746 + ] + } + }, + "hero": { + "kind": "perspective", + "box": [ + 0, + 0, + 1024, + 560 + ], + "ground": 525, + "top": 18, + "joints": { + "hip_fl": [ + 533, + 332 + ], + "hip_fr": [ + 222, + 345 + ], + "hip_rl": [ + 855, + 283 + ], + "knee_rl": [ + 925, + 455 + ], + "ankle_fl": [ + 445, + 465 + ], + "ankle_fr": [ + 190, + 462 + ], + "ankle_rl": [ + 890, + 482 + ], + "muzzle": [ + 300, + 68 + ], + "emblem": [ + 277, + 270 + ] + }, + "horizon": 437, + "horizon_note": "The heads of three soldiers standing at different places on the field, all near v 437: the eye is at a standing man's height." + } + } + }, + "flow": { + "unit": 1024, + "note": "Traced by hand on the sheet, to about 4 px. The character line is the carapace's rim (the broad overhanging perimeter) under the dome's low profile.", + "character": "rim", + "lines": { + "side": { + "rim": [ + [ + 262, + 656 + ], + [ + 300, + 655 + ], + [ + 350, + 655 + ], + [ + 390, + 652 + ], + [ + 440, + 641 + ], + [ + 470, + 640 + ] + ], + "dome": [ + [ + 258, + 645 + ], + [ + 280, + 636 + ], + [ + 300, + 628 + ], + [ + 340, + 610 + ], + [ + 380, + 605 + ], + [ + 420, + 607 + ], + [ + 445, + 614 + ], + [ + 470, + 622 + ] + ] + }, + "hero": { + "rim": [ + [ + 400, + 230 + ], + [ + 505, + 227 + ], + [ + 560, + 250 + ], + [ + 660, + 256 + ] + ], + "dome": [ + [ + 190, + 205 + ], + [ + 255, + 150 + ], + [ + 330, + 125 + ], + [ + 420, + 103 + ], + [ + 500, + 93 + ] + ], + "shoulder": [ + [ + 455, + 170 + ], + [ + 545, + 160 + ], + [ + 640, + 172 + ] + ] + }, + "top": { + "rim": [ + [ + 905, + 752 + ], + [ + 948, + 745 + ], + [ + 967, + 735 + ], + [ + 975, + 700 + ], + [ + 975, + 630 + ], + [ + 957, + 600 + ], + [ + 925, + 585 + ], + [ + 905, + 582 + ] + ] + } + } + }, + "insets": { + "cockpit": [ + 0, + 778, + 165, + 925 + ], + "magazine": [ + 170, + 778, + 338, + 925 + ], + "turret": [ + 343, + 778, + 560, + 925 + ], + "interceptor": [ + 567, + 778, + 695, + 925 + ], + "rear_leg": [ + 703, + 778, + 857, + 925 + ], + "cooling": [ + 862, + 778, + 1024, + 925 + ] + } + } } \ No newline at end of file diff --git a/surfaces/blender/experiments/mechs/feet.py b/surfaces/blender/experiments/mechs/feet.py new file mode 100644 index 0000000..57aab1d --- /dev/null +++ b/surfaces/blender/experiments/mechs/feet.py @@ -0,0 +1,759 @@ +"""Articulated feet for the mech builds, one per concept sheet (23 to 31 and 34): toes of one to three segments, each +on its own hinge, splay hinges where the toes fan, heel spurs and rear toes, toe rams, stepped armour over the +segments. Ruling aetheria-release:ruling:mech-toes-articulated. + +Who owns what. The joints are the kit's: a foot is a tree of kit parts (kit mech: foot_core, toe_knuckle, link, toe) +seated on pivot sockets, and every hinge carries a kit joint record (brokkr_kitbash.joint: limits, a mechanism label +toe_pitch or toe_splay), so brokkr_kitbash.joints reports the foot and a walk drives it with brokkr_kitbash.roll. +The rams are ram core's (brokkr_kitbash/ram.py): seats come from ram.search over a grid on the two parts' backs, +its clearance gate reading the dress through ram.Signed, and the mechanism record it writes is kept on the driven part as the JSON property feet_ram, in the driving part's frame. +The armour, housings, hinge barrels and soles are this module's: jointlib.Link geometry authored in the frame of the +kit part that carries it and parented to it, so it follows any pose. Rams are drawn at the pose (Foot.draw_rams). + +A foot is a drop-in for the kit's foot, talon and trident: its root is a foot_core, which takes (width, length, drop, +pin_r), stands on the ankle pin by `tongue` (or `tongue_roll` under a cross ankle) and carries their instep and heel +sockets. mechlib.leg and humanoid seat a foot with attach(foot, "tongue", shin, "clevis"); every function here takes +the shin and that socket and does the same (shin None: the caller seats Foot.core, as under a cross ankle). +feet_dropin.py checks both against the kit's talon. + + Foot(name, dims, toes, shin, socket) the kit tree at rest: flat on the ground, toes fanned as the concept plants them + T(at, yaw, segs, ...) one toe: where its splay pin stands on the core, its heading, its segments + Foot.armour / housing / mass / pbox / drums dress, in the part's frame (the core's in plan coordinates) + Foot.ram(i, j, bore) a ram across a pitch joint, seated at done() clear of all the dress + Foot.level(pitch) the ankle: the core nose down by pitch degrees + Foot.drive(roll, strike, splay, curl) the walk's four inputs, written to the kit joints inside their limits + Foot.done() objects made, rams drawn; Foot.report() is the kit's joints report and the rams + FEET the concept feet, registered by @concept with their crop and view + +Conventions: a pitch joint's roll is positive lifting the toe. A toe's authored yaw is its heading when planted +(degrees from the foot's front toward the core's +x); `splay` is how far it closes inward from there. Plan +coordinates are (x, y, height above the ground) in the core's frame. +""" +import json +import math + +import bpy +import numpy as np +from mathutils import Matrix, Vector + +import jointlib as J +import mechlib as M +from jointlib import X, Y, Z + +TOES = "abcdef" +FEET = {} +_RAM = None + + +def ramcore(): + """brokkr_kitbash/ram.py of the add-on tree mechlib.setup() enabled.""" + global _RAM + if _RAM is None: + from brokkr_kitbash import ram + _RAM = ram + return _RAM + + +def concept(sheet, number, crop, view=(40.0, 14.0), variant=None, dims=None): + """Register a concept foot: the sheet's name and number, its crop of the sheet (pixels), the catalog view + (azimuth, elevation), a parameter variant for the catalog and its default (width, length, drop, pin_r).""" + def wrap(fn): + FEET[fn.__name__] = {"fn": fn, "sheet": sheet, "number": number, "crop": crop, "view": view, "variant": variant or {}, "dims": dims} + return fn + return wrap + + +def T(at, yaw=0.0, segs=(), role="front", splay=0.0, lim=None, fall=None, reach=None, pad=None): + """One toe. at: its splay pin on the core (x, y); yaw: its heading planted; segs: (length, width, depth) per + segment, root first; role: front or rear; splay: degrees it closes inward on a splay hinge (0: a fixed seat); + lim: (lo, hi) degrees about rest per pitch joint; fall: the share of the drop to the ground each segment but + the last takes (the last lies flat).""" + return {"at": at, "yaw": yaw, "dims": [tuple(s) for s in segs], "role": role, "splay": splay, "lim": lim, "fall": fall, "reach": reach, "pad": pad} + + +class Dress(J.Link): + """Geometry in one kit part's own frame, parented to it.""" + + def __init__(self, foot, part): + super().__init__(foot, part.name) + self.part = part + + def make(self, bevel): + made = [] + for (mat, tag), geo in self.geos.items(): + if not len(geo.bm.verts): + continue + armour = mat in J.ARMOR + obj = geo.to_object(f"{self.part.name}.{mat}.{tag}", mat, self.part, 12.0 if armour else 38.0) + obj["tag"], obj["mat"] = tag, mat + if armour: # faceted: a bevel's faces would be shaded round across a smooth hull + obj.data.polygons.foreach_set("use_smooth", [False] * len(obj.data.polygons)) + if armour and bevel: + mod = obj.modifiers.new("Bevel", "BEVEL") + mod.width, mod.segments, mod.limit_method, mod.angle_limit = bevel, 1, "ANGLE", math.radians(18) + made.append(obj) + self.geos = {} + return made + + +class _Fit: + """A ram core Fit as jointlib._draw_ram reads one.""" + + def __init__(self, fit): + self.fit, self.ram, self.axis, self.barrel = fit, fit.ram, tuple(fit.m.axis), fit.barrel + + def at(self, degrees): + ram = ramcore() + p = ram.pose(self.fit.m, degrees) + return {"base": p.base[0], "eye": p.eye[0], "dir": p.u[0], "length": float(p.L[0]), "extension": float(ram.extension(self.fit.m, self.ram, degrees)[0])} + + +class Foot: + def __init__(self, name, dims, toes, shin=None, socket="clevis", toe_pin=None, toe_h=None, plate="olive", plate2="olive_light", pad=None): + self.name, self.dims = name, dims + self.w, self.l, self.d, self.pin = dims + self.tp = tp = toe_pin or 0.42 * self.pin + self.pad = pad if pad is not None else 0.04 * self.d + self.plate, self.plate2 = plate, plate2 + self.dress, self.joints, self.drives, self.rams, self.notes, self.asked = {}, {}, [], [], [], [] + self.objects, self.ram_objects, self.clashes = [], [], [] + if len(toes) > len(TOES): + raise ValueError(f"{name}: a foot_core carries {len(TOES)} toes, got {len(toes)}") + if toe_h is None: # a one-segment front toe lies flat: the pins stand just above the ground + first = next((t for t in toes if t["role"] == "front"), toes[0]) + toe_h = 1.0 - (first["dims"][-1][2] / 2 + self.pad + 1.6 * tp) / self.d if len(first["dims"]) == 1 else 0.5 + self.toe_h = toe_h = max(0.15, min(0.95, toe_h)) + pins = {f"t{TOES[i]}{c}": t["at"][j] for i, t in enumerate(toes) for j, c in enumerate("xy")} + self.core = M.place("foot_core", name, mat="gunmetal", width=self.w, length=self.l, drop=self.d, pin_r=self.pin, toe_pin_r=tp, toe_h=toe_h, **pins) + if shin is not None: + M.attach(self.core, "tongue", shin, socket, 0.0) + self.hk = self.d * (1.0 - toe_h) - 1.6 * tp # the first pitch pins' height above the ground + self.toes = [self._toe(i, dict(t)) for i, t in enumerate(toes)] + + # -- the kit tree ----------------------------------------------------------------------------------------- + + def _joint(self, name, obj, kind, rest, lo, hi): + bpy.ops.brokkr_kitbash.joint(object_name=obj.name, record=json.dumps({"limits": [lo, hi], "mechanism": f"toe_{kind}"})) + self.joints[name] = {"obj": obj, "kind": kind, "rest": rest, "lo": lo, "hi": hi} + + def _toe(self, i, t): + tp, key, dims = self.tp, TOES[i], t["dims"] + n, pad = len(dims), t["pad"] if t["pad"] is not None else self.pad + t["pad"], t["i"] = pad, i + t["reach"] = reach = t["reach"] or 2.6 * tp + x, yaw = t["at"][0], t["yaw"] + side = 1 if x > 1e-6 else -1 if x < -1e-6 else 0 + t["out"] = out = side if abs((yaw + 180.0) % 360.0 - 180.0) < 90.0 else -side + kn = M.place("toe_knuckle", f"{self.name}.Toe{i}.Knuckle", mat="gunmetal", pin_r=tp, reach=reach, width=dims[0][1]) + if t["splay"] and out: + M.attach(kn, "splay", self.core, f"toe_{key}", -yaw) + closed = -(yaw - out * t["splay"]) + self._joint(f"toe{i}.splay", kn, "splay", -yaw, min(-yaw, closed), max(-yaw, closed)) + else: + t["splay"] = 0.0 + M.attach(kn, "seat", self.core, f"seat_{key}", -yaw) + t["knuckle"] = kn + last = dims[-1] + if n == 1: # one segment: it slopes until its tip's sole meets the ground + lo_a, hi_a = -0.6, 1.2 + for _ in range(40): + a = (lo_a + hi_a) / 2 + if self.hk - 0.92 * last[0] * math.sin(a) - (last[2] / 2 + pad) * math.cos(a) > 0: + lo_a = a + else: + hi_a = a + alphas = [a] + else: # the last lies flat; the others share the drop to it + drop = self.hk - (last[2] / 2 + pad) + fall = t["fall"] or [d[0] for d in dims[:-1]] + alphas = [math.asin(max(-0.9, min(0.9, f / sum(fall) * drop / d[0]))) for f, d in zip(fall, dims[:-1])] + [0.0] + t["alphas"] = alphas + rest = [-math.degrees(alphas[0])] + [math.degrees(alphas[k - 1] - alphas[k]) for k in range(1, n)] + lim = t["lim"] or [(-10.0, 30.0)] * (n - 1) + [(-12.0, 48.0)] + t["rest"], t["lim"], t["segs"] = rest, lim, [] + parent = kn + for k, (length, width, depth) in enumerate(dims): + seg = M.place("toe" if k == n - 1 else "link", f"{self.name}.Toe{i}.Seg{k}", mat="gunmetal", length=length, width=width, depth=depth, pin_r=tp) + M.attach(seg, "tongue", parent, "clevis", rest[k]) + self._joint(f"toe{i}.pitch{k}", seg, "pitch", rest[k], rest[k] + lim[k][0], rest[k] + lim[k][1]) + t["segs"].append(seg) + parent = seg + return t + + def set(self, name, value): + """Write a joint, `value` degrees from rest, held inside its limits. Returns what was written.""" + j = self.joints[name] + roll = max(j["lo"], min(j["hi"], j["rest"] + value)) + M.reroll(j["obj"], roll) + return roll - j["rest"] + + def level(self, pitch=0.0): + """Turn the core about the ankle pin until its sole faces down, then `pitch` degrees nose down.""" + M.update() + fwd = self.core.matrix_world.to_3x3() @ Y + fwd.z = 0.0 + fwd.normalize() + a = math.radians(pitch) + return M.aim_roll(self.core, (0, 0, 1), -Z * math.cos(a) - fwd * math.sin(a)) + + def drive(self, roll=0.0, strike=0.0, splay=1.0, curl=0.0): + """The walk's inputs, in degrees. roll: toe roll at push-off, the heel risen that far over toes that stay + on the ground (the last pitch joint takes most, the one before it the rest). strike: the heel-first + landing, the core nose up that far: the rear toes stay flat and the front toes cock up. splay: 0 closed + to 1 fanned. curl: every toe's first joint, positive lifting. The caller pitches the core (level).""" + for t in self.toes: + n, i = len(t["segs"]), t["i"] + add = [0.0] * n + if t["role"] == "front": + share = (1.0,) if n == 1 else (0.3, 0.7) if n == 2 else (0.0,) * (n - 2) + (0.35, 0.65) + for k in range(n): + add[k] += roll * share[k] + add[0] += 0.5 * strike + else: + add[-1] += strike + add[0] -= 0.25 * roll + add[0] += curl + for k in range(n): + self.set(f"toe{i}.pitch{k}", add[k]) + if t["splay"]: + self.set(f"toe{i}.splay", t["out"] * t["splay"] * (1.0 - splay)) + if self.objects: + self.draw_rams() + + # -- dress ------------------------------------------------------------------------------------------------ + + def on(self, part): + if part.name not in self.dress: + self.dress[part.name] = Dress(self, part) + return self.dress[part.name] + + def plan(self, x, y, h): + return Vector((x, y, self.d - h)) + + def mass(self, mat, points, mirror=True, tag="body"): + """A faceted block on the core: the hull of plan points (and their mirrors).""" + self.on(self.core).hull(mat, [self.plan(*p) for p in points], mirror, tag) + + def pbox(self, mat, centre, size, ch=0.0, yaw=0.0, tag="body"): + """A block on the core, in plan coordinates: size is (x, y, height), its top rim chamfered.""" + rot = Matrix.Rotation(math.radians(-yaw), 4, "Z") @ Matrix.Rotation(math.pi, 4, "X") + self.on(self.core).box(mat, self.plan(*centre), size, ch, rot, tag) + + def drums(self, r, x, width, cap=0.8, bolts=8, mat="machine"): + """The ankle's drums: a disc on the ankle pin either side of the core, capped.""" + core = self.on(self.core) + for s in (-1, 1): + core.cyl(mat, (s * x, 0, 0), r, width) + if cap: + core.cap(mat, (s * (x + width / 2), 0, 0), r * cap, X * s, bolts=bolts) + + def top_at(self, i, k, z): + """The height of toe i's segment k armour above its pin axis at z along it.""" + (z_r, y_r), (z_f, y_f) = self.toes[i]["line"][k] + return y_r + (y_f - y_r) * max(0.0, min(1.0, (z - z_r) / max(z_f - z_r, 1e-6))) + self.toes[i].get("plate", 0.0) + + def armour(self, i, tops, widen=1.3, cap="block", tab=False, plate=0.0, mat=None, mat2=None, nose=0.35, tip=(0.6, 0.35), ch=None, barrel=0.9, treads=3, + sole="rubber", over=0.0): + """Armour over toe i: per segment a faceted block from its sole to tops[k] = (rear, front) heights above + the pin axis, its end faces raked back from each hinge by half the joint's travel so two blocks close on + each other at the limit and no sooner (the first block's rear face is raked the same, which clears a + housing raked like it; against an instep mass above the pins it is not checked); a hinge barrel with bolted caps on every pin; an applique plate of + thickness `plate` on each back, a second step on its rear half; a sole pad with tread bars. The last + segment ends in a cap: block (a chamfered nose), claw (tapering to tip = (width, height) fractions) or + hoof (a block drawn in at the nose). tab: a steel wear tab let into the nose. over: the cap past the pin.""" + t = self.toes[i] + n, mat, mat2 = len(t["segs"]), mat or self.plate, mat2 or self.plate2 + t["line"], t["wa"], t["plate"] = [], [], 0.0 + for k, seg in enumerate(t["segs"]): + length, width, depth = t["dims"][k] + wa, half = width * widen, width * widen / 2 + c = ch if ch is not None else 0.1 * wa + dr, (top_r, top_f), (lo, hi) = self.on(seg), tops[k], t["lim"][k] + gap = 0.03 * length + rt, rb = math.tan(math.radians(hi) / 2), math.tan(math.radians(-lo) / 2) + z0 = gap + pts = [(half, -depth / 2, z0 + rb * depth / 2), (half, 0, z0), (half, top_r - c, z0 + rt * (top_r - c)), (half - c, top_r, z0 + rt * top_r)] + rear = (z0 + rt * top_r, top_r) + if k < n - 1: + lo2, hi2 = t["lim"][k + 1] + ft, fb, z1 = math.tan(math.radians(hi2) / 2), math.tan(math.radians(-lo2) / 2), length - gap + pts += [(half, -depth / 2, z1 - fb * depth / 2), (half, 0, z1), (half, top_f - c, z1 - ft * (top_f - c)), (half - c, top_f, z1 - ft * top_f)] + front = (z1 - ft * top_f, top_f) + else: + z1 = length * (1.0 + over) + zn = z1 - nose * length + if cap == "claw": + tw, th = tip[0] * half, -depth / 2 + tip[1] * (top_f + depth / 2) + pts += [(half, -depth / 2, zn), (half, top_f - c, zn), (half - c, top_f, zn), (tw, -depth / 2, z1), (tw, th - 0.3 * c, z1), (tw - 0.3 * c, th, z1)] + else: + nh = -depth / 2 + 0.5 * (top_f + depth / 2) + nw = half * (0.82 if cap == "hoof" else 1.0) + pts += [(half, -depth / 2, zn), (nw, -depth / 2, z1), (nw, nh - c, z1), (nw - c, nh, z1), (half, top_f - c, zn), (half - c, top_f, zn)] + if cap == "hoof": + pts += [(nw * 0.86, -depth / 2, z1 + 0.05 * length), (nw * 0.86, nh * 0.4 - depth * 0.3, z1 + 0.05 * length)] + front = (zn, top_f) + if tab: + dr.box("steel", (0, -depth / 2 + 0.16 * (top_f + depth / 2), z1 - 0.02 * length), (0.3 * wa, 0.3 * (top_f + depth / 2), 0.12 * length), tag="trim") + dr.box("gunmetal", (0, -depth / 2 + 0.42 * (top_f + depth / 2), z1 - 0.07 * length), (0.2 * wa, 0.08 * (top_f + depth / 2), 0.1 * length), tag="trim") + dr.hull(mat, pts, mirror=True) + t["line"].append((rear, front)) + t["wa"].append(wa) + if plate: + t["plate"] = 0.0 + span = front[0] - rear[0] + for z_a, z_b, thick, inset in ((rear[0] + 0.1 * span, front[0] - 0.08 * span, plate, 0.08), (rear[0] + 0.1 * span, rear[0] + 0.5 * span, 2.0 * plate, 0.16)): + px = half - c - inset * wa + y_a, y_b = self.top_at(i, k, z_a), self.top_at(i, k, z_b) + dr.hull(mat2, [(px, y_a - 0.01, z_a), (px, y_a + thick, z_a + 0.3 * thick), (px, y_b - 0.01, z_b), (px, y_b + thick, z_b - 0.3 * thick)], mirror=True, tag="trim") + t["plate"] = 2.0 * plate # what a ram's seat stands above + z_s0, z_s1 = z0 + 0.06 * length, (front[0] if k == n - 1 else z1) - 0.04 * length + pad = t["pad"] + if sole: + dr.g(sole, "trim").box(Matrix.Translation((0, -depth / 2 - 0.45 * pad, (z_s0 + z_s1) / 2)), (wa * 0.9, 0.9 * pad, z_s1 - z_s0)) + for m in range(treads): + z_t = z_s0 + (z_s1 - z_s0) * (m + 0.5) / treads + dr.g("gunmetal", "trim").box(Matrix.Translation((0, -depth / 2 - 0.9 * pad, z_t)), (wa * 0.96, 0.22 * pad, 0.16 * (z_s1 - z_s0) / treads + 0.01)) + if barrel: + r = barrel * 0.5 * min(depth, t["dims"][k - 1][2] if k else depth) + dr.cyl("machine", (0, 0, 0), r, wa * 1.03) + for s in (-1, 1): + dr.cap("machine", (s * wa * 0.515, 0, 0), r * 0.82, X * s, steps=((1.0, 0.16), (0.7, 0.26), (0.36, 0.34)), bolts=6) + + def housing(self, i, horn=0.0, mat=None, widen=None, back=2.4): + """Toe i's root: a block over its knuckle, from the pin's seat (or `horn` above it, where a ram's base + stands) to the toe's sole line, and on a splay hinge the pin's cap.""" + t = self.toes[i] + tp, dr = self.tp, self.on(t["knuckle"]) + wa = (widen * t["dims"][0][1]) if widen else t.get("wa", [t["dims"][0][1] * 1.3])[0] + half, c = wa / 2, 0.1 * wa + y_b, y_f = -(back + 3.0 * horn / max(wa, 1e-6)) * tp, t["reach"] - 0.2 * tp + z_t, z_b = -horn, 1.6 * tp + 0.42 * t["dims"][0][2] + lean = 0.45 * horn + dr.hull(mat or self.plate, [(half, y_b, z_t + c), (half - c, y_b, z_t), (half, y_f - lean, z_t + c), (half - c, y_f - lean, z_t), (half, y_f, min(z_t + c + 1.2 * lean, z_b)), + (half, y_b, z_b), (half, y_f, z_b)], mirror=True) + t["horn"] = horn + if t["splay"]: + dr.cyl("machine", (0, 0, z_t - 0.2 * tp), 2.4 * tp, 0.5 * tp, Z, 20, "trim") + dr.cyl("steel", (0, 0, z_t - 0.55 * tp), 1.1 * tp, 0.3 * tp, Z, 6, "trim") + + def ram(self, i, j, bore, **how): + """Ask for a ram across toe i's pitch joint j. It is seated when the foot is done, against all the dress + there is by then (_seat takes the rest: x, boot, mat, high, along, back, min_arm).""" + self.asked.append(dict(how, i=i, j=j, bore=bore)) + + def _shells(self, part, into): + """The closed shells of a part's dress as authored so far, their vertices carried through `into`: what ram + core's distance oracle (ram.Signed) reads. Clevis seats are left out: a ram's own pins stand in them.""" + out = [] + dr = self.dress.get(part.name) + for (mat, tag), geo in (dr.geos.items() if dr else ()): + if tag == "seat": + continue + bm = geo.bm + bm.faces.ensure_lookup_table() + bm.faces.index_update() + seen = set() + for start in bm.faces: + if start.index in seen: + continue + island, stack = [], [start] + seen.add(start.index) + while stack: + face = stack.pop() + island.append(face) + for edge in face.edges: + for other in edge.link_faces: + if other.index not in seen: + seen.add(other.index) + stack.append(other) + verts = {} + faces = [[verts.setdefault(v, len(verts)) for v in face.verts] for face in island] + out.append((np.array([list(into @ v.co) for v in verts]), faces)) + return out + + def _seat(self, i, j, bore, x=0.0, boot=False, mat="machine", high=(2.2, 3.4, 5.0), along=(0.3, 0.9), back=(0.15, 1.3), min_arm=None, tail=0.0): + """A ram across toe i's pitch joint j, seated by ram core's search: its base on the part before the joint + (the knuckle's housing and horn for j = 0, the segment's back otherwise), its eye on the segment's back, + both from a grid `high` bores above the armour, and clear over the joint's whole range of the dress of + the two parts and of the core (ram.Signed over their shells; the core as it stands at the planted splay). + `tail` (in bores) mounts the ram on a trunnion that far ahead of its barrel's back end, which leaves a short + span more barrel. The record is kept on the driven segment (feet_ram); a ram that finds no seat is reported + and not drawn.""" + ram, t = ramcore(), self.toes[i] + parent, child = (t["knuckle"] if j == 0 else t["segs"][j - 1]), t["segs"][j] + socket = M.local_sockets(parent)["clevis"] + rest0 = socket @ M.FLIP @ M.local_sockets(child)["tongue"].inverted() # the child at roll 0, in the parent's frame + pivot, axis = socket.translation.copy(), socket.to_3x3() @ Z + fwd, up = rest0.to_3x3() @ Z, rest0.to_3x3() @ Y + length = t["dims"][j][0] + steps = lambda a, b, n: [a + (b - a) * q / (n - 1) for q in range(n)] + seats_b = [rest0 @ Vector((0, self.top_at(i, j, z) + h * bore, z)) + axis * x for z in steps(along[0] * length, along[1] * length, 6) for h in high] + if j == 0: + base, run = t.get("horn", 0.0) + 1.6 * self.tp, t["reach"] + 2.4 * self.tp + seats_a = [pivot - fwd * s + up * (base + h * bore) + axis * x for s in steps(back[0] * run, back[1] * run, 6) for h in high] + else: + run = t["dims"][j - 1][0] + seats_a = [pivot - fwd * s + up * (self.top_at(i, j - 1, run - s) + h * bore) + axis * x for s in steps(back[0] * run, back[1] * run, 6) for h in high] + joint = self.joints[f"toe{i}.pitch{j}"] + name = f"toe{i}.ram{j}" + M.update() + shells = {"before": self._shells(parent, Matrix.Identity(4)), "segment": self._shells(child, rest0), + "core": self._shells(self.core, parent.matrix_world.inverted() @ self.core.matrix_world)} + parts = {"before": "parent", "segment": "child", "core": "parent"} + + def touch(m, body): + """The zones about the ram's two pins: within three bores of its base pin the barrel and rod may stand + beside the part the base's clevis stands on, and within three of the eye beside the segment's back (depth + 0: beside, never inside), no wider than the ram is long.""" + r = min(3.0 * body.bore, 0.45 * float(np.linalg.norm(m.b - m.a))) + return {member: [("before", "a", r, 0.0), ("segment", "b", r, 0.0)] for member in ("barrel", "rod")} + for scale in (1.0, 0.8, 0.64): # a slimmer ram is shorter closed: tried when the bore asked for finds no seat + body = ram.Ram(bore * scale, min_arm=min_arm, tail=tail * bore * scale) + oracle = ram.Signed(shells, cap=body.reach()) + found = ram.search("direct", {"pivot": list(pivot), "axis": list(axis), "lo": joint["lo"], "hi": joint["hi"]}, body, {"a": [list(p) for p in seats_a], "b": [list(p) for p in seats_b]}, + world=lambda m: (parts, touch(m, body), oracle)) + print(f"RAM {self.name}.{name} bore {bore * scale:.4f}: {found.report()}", flush=True) + if found.found: + break + entry = {"name": name, "ok": bool(found.found), "text": f"bore {body.bore:.4f}: {found.report()}", "parent": parent, "child": child, "boot": boot, "mat": mat} + self.drives.append(entry) + if not found.found: + return None + fit = found.best + child["feet_ram"] = json.dumps(ram.record(fit.m, body)) + entry["fit"] = _Fit(fit) + a, b = Vector(fit.m.a), rest0.inverted() @ Vector(fit.m.b) + bore = body.bore + self.on(parent).seat(a, -up, bore, axis, reach=(high[0] + 1.6) * bore) + self.on(child).seat(b, -Y, bore, X, reach=(high[0] + 1.6) * bore) + return fit + + def draw_rams(self): + """The rams at the joints' rolls as they stand: last pose's are removed, each is drawn from its record.""" + for obj in self.ram_objects: + if obj in self.objects: + self.objects.remove(obj) + bpy.data.objects.remove(obj, do_unlink=True) + self.ram_objects = [] + for entry in self.drives: + if entry["ok"]: + dr = Dress(self, entry["parent"]) + J._draw_ram(dr, entry["fit"], float(entry["child"]["kit_roll"]), Vector((0, 0, 0)), entry["boot"], entry["mat"]) + made = dr.make(0.0) + for obj in made: + obj["tag"] = "ram" if obj["tag"] == "ram" else "eye" + self.ram_objects += made + self.objects += self.ram_objects + M.update() + + def done(self): + for ask in self.asked: + self._seat(**ask) + self.asked = [] + bevel = 0.005 * self.w + for dr in self.dress.values(): + self.objects += dr.make(bevel) + self.draw_rams() + return self + + def check(self): + """Mesh overlaps between each ram (barrel and rod) and the armour, at the pose as it stands.""" + self.clashes = J.Rig._clashes(self) + return self.clashes + + def report(self): + """The kit's joints report of the foot, and each ram's fit.""" + bpy.ops.brokkr_kitbash.joints(object_name=self.core.name) + kit = json.loads(getattr(bpy.context.window_manager, "brokkr_mesh_polish_result")) + return {"foot": self.name, "dims": list(self.dims), "toes": len(self.toes), "segments": sum(len(t["segs"]) for t in self.toes), + "splay_hinges": sum(1 for t in self.toes if t["splay"]), "joints": kit, + "rams": [{"name": e["name"], "ok": e["ok"], "fit": e["text"]} for e in self.drives], "notes": self.notes} + + +# --- the concept feet ---------------------------------------------------------------------------------------------- + +@concept("KESTREL", 29, (775, 745, 908, 988), view=(52.0, 12.0), variant={"length": 2.3, "claw": 0.26, "splay": 26.0}, dims=(1.0, 1.9, 0.46, 0.07)) +def kestrel_talons(name, shin=None, socket="clevis", width=1.0, length=1.9, drop=0.46, pin_r=0.07, claw=0.34, splay=16.0, rams=True): + """KESTREL, FOOT (FRONT) and FOOT (REAR): two long talons, each a root block, a stepped mid plate and a long + tapering claw on three pitch pins, fanned on splay pins either side of a bare ankle drum in a yoke; two short + rear toes angled out behind; a booted ram from each talon's root horn to its first plate and a second from + that plate to the next.""" + w, l, d = width, length, drop + front = [(0.19 * l, 0.3 * w, 0.46 * d), (0.2 * l, 0.28 * w, 0.4 * d), (claw * l, 0.27 * w, 0.34 * d)] + rear = [(0.17 * l, 0.24 * w, 0.44 * d)] + f = Foot(name, (w, l, d, pin_r), [T((s * 0.25 * w, 0.06 * l), s * 9.0, front, splay=splay, fall=(0.75, 0.25)) for s in (-1, 1)] + + [T((s * 0.22 * w, -0.1 * l), s * 152.0, rear, role="rear", splay=splay * 0.6, lim=[(-14.0, 30.0)]) for s in (-1, 1)], shin, socket, toe_h=0.42) + for i in (0, 1): + f.armour(i, [(0.42 * d, 0.34 * d), (0.3 * d, 0.25 * d), (0.22 * d, 0.16 * d)], widen=1.25, cap="claw", plate=0.03 * d + 0.006, nose=0.6, tip=(0.5, 0.34), treads=2) + f.housing(i, horn=0.3 * d) + if rams: + f.ram(i, 0, 0.02 * w, boot=True) + f.ram(i, 1, 0.016 * w) + for i in (2, 3): + f.armour(i, [(0.28 * d, 0.16 * d)], widen=1.3, cap="block", plate=0.02 * d + 0.005, nose=0.3, treads=2) + f.housing(i) + f.drums(0.36 * d, 0.2 * w, 0.14 * w, cap=0.78) + core = f.on(f.core) + core.cyl("gunmetal", (0, 0, 0), 0.27 * d, 0.3 * w) + for x in (-0.08 * w, 0.0, 0.08 * w): + core.cyl("machine", (x, 0, 0), 0.3 * d, 0.025 * w) + f.mass("gunmetal", [(0.2 * w, -0.14 * l, 0.58 * d), (0.2 * w, 0.1 * l, 0.58 * d), (0.3 * w, -0.14 * l, 0.3 * d), (0.3 * w, 0.1 * l, 0.3 * d)]) + f.mass(f.plate, [(0.16 * w, 0.02 * l, 0.62 * d), (0.16 * w, 0.14 * l, 0.5 * d), (0.12 * w, 0.02 * l, 0.74 * d), (0.12 * w, 0.12 * l, 0.66 * d), (0.16 * w, 0.02 * l, 0.5 * d), (0.16 * w, 0.14 * l, 0.44 * d)]) + return f + + +def _heavy(f, drum=0.42, drum_x=0.36, drum_w=0.16, top=0.95, back=-0.16, front=0.2, half=0.34, nose=0.55, mat=None): + """The instep of a heavy foot: a faceted mass from the ankle's column down over the toes' roots, a stepped + plate on its slope, and the ankle's drums.""" + w, l, d = f.w, f.l, f.d + base = 1.0 - f.toe_h - 0.04 + f.mass(mat or f.plate, [(half * w, back * l, base * d), (half * w, front * l, base * d), (half * w, back * l, 0.7 * d), (0.8 * half * w, back * 0.8 * l, top * d), + (0.7 * half * w, 0.05 * l, top * d), (0.9 * half * w, front * l, nose * d)]) + # the ankle's housing between the drums, and three plates stepping down its front + f.mass(mat or f.plate, [(0.5 * half * w, back * 0.7 * l, top * d), (0.42 * half * w, back * 0.5 * l, (top + 0.34) * d), (0.42 * half * w, 0.03 * l, (top + 0.34) * d), + (0.5 * half * w, 0.09 * l, top * d)]) + for k in range(3): + y, h = (0.07 + 0.3 * (front - 0.07) * k) * l, (top + 0.12 - (top + 0.12 - nose) * k / 2.4) * d + f.pbox(f.plate2, (0, y, h), ((0.56 + 0.12 * k) * half * 2 * w * 0.8, 0.3 * (front - 0.04) * l, 0.1 * d), 0.025 * d, tag="trim") + f.drums(drum * d, drum_x * w, drum_w * w) + + +@concept("walker", 23, (700, 770, 1010, 950), view=(12.0, 12.0), variant={"outrigger": 0.3, "splay": 30.0}, dims=(1.5, 1.9, 0.6, 0.09)) +def walker_slabs(name, shin=None, socket="clevis", width=1.5, length=1.9, drop=0.6, pin_r=0.09, outrigger=0.22, splay=18.0, rams=True): + """walker (23), the hero view's two feet: two wide slab toes, each an upper plate sloping down from the instep + and a blunt toe block with a wear tab let into its nose; a ram on each slab's inner edge, from the upper + plate to the toe block, either side of the centre line; a wedge outrigger fanned out on a splay pin either side; and + behind, a tall tapered heel pylon on its own pin.""" + w, l, d = width, length, drop + slab = [(0.25 * l, 0.36 * w, 0.4 * d), (0.24 * l, 0.36 * w, 0.42 * d)] + f = Foot(name, (w, l, d, pin_r), [T((s * 0.23 * w, 0.08 * l), s * 5.0, slab) for s in (-1, 1)] + + [T((s * 0.44 * w, -0.03 * l), s * 62.0, [(outrigger * l, 0.2 * w, 0.4 * d)], splay=splay, lim=[(-14.0, 28.0)]) for s in (-1, 1)] + + [T((0, -0.17 * l), 180.0, [(0.21 * l, 0.36 * w, 0.44 * d)], role="rear", lim=[(-12.0, 26.0)])], shin, socket, toe_h=0.5) + for i in (0, 1): + f.armour(i, [(0.52 * d, 0.36 * d), (0.3 * d, 0.3 * d)], widen=1.22, cap="block", tab=True, plate=0.03 * d, nose=0.34) + f.housing(i) + if rams: + f.ram(i, 1, 0.024 * w, x=(0.1 if i == 0 else -0.1) * w, tail=2.5) + for i in (2, 3): + f.armour(i, [(0.62 * d, 0.3 * d)], widen=1.3, cap="block", nose=0.3, plate=0.025 * d) + f.housing(i, horn=0.2 * d) + f.armour(4, [(1.15 * d, 0.5 * d)], widen=1.15, cap="block", nose=0.2, plate=0.03 * d) + f.housing(4) + _heavy(f, drum=0.36, drum_x=0.33, drum_w=0.12, top=0.9, half=0.3, front=0.16) + core = f.on(f.core) + for x in (-0.04 * w, 0.04 * w): # the linkage between the slabs + core.box("gunmetal", f.plan(x, 0.2 * l, 0.36 * d), (0.03 * w, 0.2 * l, 0.3 * d)) + core.cyl("machine", f.plan(0, 0.27 * l, 0.42 * d), 0.07 * d, 0.14 * w) + return f + + +@concept("BREAKER", 24, (505, 785, 755, 985), view=(40.0, 14.0), variant={"toe": 0.3, "width": 1.7}, dims=(1.45, 1.6, 0.6, 0.09)) +def breaker_sections(name, shin=None, socket="clevis", width=1.45, length=1.6, drop=0.6, pin_r=0.09, toe=0.23): + """BREAKER, FOOT DETAIL (multi-section design): a stepped instep slab over two broad front toes, each a sloped + plate and a square toe block on two pins; a short block toe at each front corner; two heel blocks behind; + the ankle's disc on the side. No ram shows: the toes' drives are under the instep.""" + w, l, d = width, length, drop + f = Foot(name, (w, l, d, pin_r), [T((s * 0.22 * w, 0.1 * l), s * 5.0, [(0.25 * l, 0.36 * w, 0.42 * d), (toe * l, 0.36 * w, 0.44 * d)]) for s in (-1, 1)] + + [T((s * 0.46 * w, 0.0), s * 38.0, [(0.21 * l, 0.22 * w, 0.44 * d)], lim=[(-10.0, 30.0)]) for s in (-1, 1)] + + [T((s * 0.25 * w, -0.17 * l), s * 166.0, [(0.19 * l, 0.34 * w, 0.44 * d)], role="rear", lim=[(-12.0, 24.0)]) for s in (-1, 1)], shin, socket, toe_h=0.5) + for i in (0, 1): + f.armour(i, [(0.56 * d, 0.36 * d), (0.32 * d, 0.3 * d)], widen=1.2, cap="block", plate=0.035 * d, nose=0.3) + f.housing(i) + for i in (2, 3, 4, 5): + f.armour(i, [(0.42 * d, 0.3 * d)], widen=1.25, cap="block", plate=0.03 * d, nose=0.32) + f.housing(i) + _heavy(f, drum=0.4, drum_x=0.4, drum_w=0.14, top=1.0, half=0.36, front=0.2, nose=0.62) + f.pbox(f.plate2, (0, 0.1 * l, 0.82 * d), (0.5 * w, 0.2 * l, 0.1 * d), 0.03 * d) + f.pbox(f.plate, (0, 0.17 * l, 0.68 * d), (0.56 * w, 0.14 * l, 0.1 * d), 0.03 * d) + return f + + +@concept("MCR-3", 25, (280, 500, 480, 595), view=(48.0, 10.0), variant={"toes": 2, "heel": 0.3}, dims=(1.3, 1.6, 0.55, 0.085)) +def mcr3_wedges(name, shin=None, socket="clevis", width=1.3, length=1.6, drop=0.55, pin_r=0.085, toes=3, heel=0.24): + """MCR-3, the hero and side views and ANKLE (ACTUATOR): a rotary actuator's drum on each side of the ankle + over a wedge instep; chamfered wedge toes on two pins each, three across the front (`toes` 2: a pair), and + one long heel toe sloping back to the ground, so the foot stands as the side view's A.""" + w, l, d = width, length, drop + seg = lambda k: [(0.22 * l, k * w, 0.42 * d), (0.2 * l, k * w, 0.4 * d)] + front = [T((0, 0.1 * l), 0.0, seg(0.28))] if toes == 3 else [] + x = 0.33 if toes == 3 else 0.2 + front += [T((s * x * w, 0.06 * l), s * 13.0, seg(0.27)) for s in (-1, 1)] + f = Foot(name, (w, l, d, pin_r), front + [T((0, -0.12 * l), 180.0, [(heel * l, 0.42 * w, 0.46 * d)], role="rear", lim=[(-12.0, 26.0)])], shin, socket, toe_h=0.42) + for i in range(len(front)): + f.armour(i, [(0.5 * d, 0.34 * d), (0.3 * d, 0.24 * d)], widen=1.18, cap="block", plate=0.03 * d, nose=0.5) + f.housing(i) + f.armour(len(front), [(0.56 * d, 0.26 * d)], widen=1.15, cap="block", plate=0.03 * d, nose=0.4) + f.housing(len(front)) + _heavy(f, drum=0.5, drum_x=0.3, drum_w=0.2, top=0.9, half=0.27, front=0.16, nose=0.6) + return f + + +@concept("R-3", 26, (845, 725, 1015, 925), view=(20.0, 22.0), variant={"rear": 2, "splay": 34.0}, dims=(0.42, 0.62, 0.2, 0.035)) +def r3_tripod(name, shin=None, socket="clevis", width=0.42, length=0.62, drop=0.2, pin_r=0.035, rear=1, splay=24.0, rams=True): + """R-3, FOOT DESIGN (three-toed stability): a tripod. Two long front toes of three stepped segments fan out + on splay pins from under a twin-disc ankle, a ram from each one's first segment to its second; behind, one + shorter toe of two segments (`rear` 2: the inset's pair, angled out).""" + w, l, d = width, length, drop + front = [(0.26 * l, 0.26 * w, 0.44 * d), (0.22 * l, 0.25 * w, 0.4 * d), (0.2 * l, 0.24 * w, 0.36 * d)] + back = [(0.2 * l, 0.25 * w, 0.44 * d), (0.2 * l, 0.24 * w, 0.38 * d)] + rears = [T((0, -0.1 * l), 180.0, back, role="rear")] if rear == 1 else [T((s * 0.17 * w, -0.08 * l), s * 148.0, back, role="rear", splay=0.5 * splay) for s in (-1, 1)] + f = Foot(name, (w, l, d, pin_r), [T((s * 0.2 * w, 0.07 * l), s * splay, front, splay=0.6 * splay, fall=(0.7, 0.3)) for s in (-1, 1)] + rears, shin, socket, toe_h=0.3, pad=0.05 * d) + for i in (0, 1): + f.armour(i, [(0.44 * d, 0.36 * d), (0.34 * d, 0.3 * d), (0.28 * d, 0.2 * d)], widen=1.3, cap="block", plate=0.04 * d, nose=0.4) + f.housing(i, horn=0.3 * d) + if rams: + f.ram(i, 1, 0.03 * w, tail=2.5) + for i in range(2, len(f.toes)): + f.armour(i, [(0.42 * d, 0.34 * d), (0.3 * d, 0.2 * d)], widen=1.3, cap="block", plate=0.04 * d, nose=0.4) + f.housing(i, horn=0.2 * d) + f.drums(0.46 * d, 0.3 * w, 0.14 * w, cap=0.8, bolts=6) + core = f.on(f.core) + core.cyl("gunmetal", (0, 0, 0), 0.32 * d, 0.5 * w) + f.mass("gunmetal", [(0.24 * w, -0.1 * l, 0.72 * d), (0.24 * w, 0.1 * l, 0.72 * d), (0.3 * w, -0.12 * l, 0.5 * d), (0.3 * w, 0.12 * l, 0.5 * d)]) + return f + + +@concept("PALADIN", 27, (815, 740, 1012, 928), view=(-34.0, 16.0), variant={"lames": 2, "length": 2.4}, dims=(1.6, 2.0, 0.7, 0.1)) +def paladin_hoof(name, shin=None, socket="clevis", width=1.6, length=2.0, drop=0.7, pin_r=0.1, lames=3): + """PALADIN, FOOT & ANKLE: the instep steps down the centre in `lames` short plates, each on its own pin, to a + narrow centre toe; a heavy two-segment toe with a deep cap either side of it; two heel blocks angled out + behind; the ankle's drums under a boxed instep.""" + w, l, d = width, length, drop + centre = [(0.46 / lames * l, 0.3 * w, (0.42 - 0.03 * k) * d) for k in range(lames)] + f = Foot(name, (w, l, d, pin_r), [T((0, 0.13 * l), 0.0, centre)] + + [T((s * 0.34 * w, 0.05 * l), s * 12.0, [(0.24 * l, 0.3 * w, 0.46 * d), (0.2 * l, 0.3 * w, 0.44 * d)]) for s in (-1, 1)] + + [T((s * 0.3 * w, -0.15 * l), s * 150.0, [(0.21 * l, 0.3 * w, 0.46 * d)], role="rear", lim=[(-12.0, 24.0)]) for s in (-1, 1)], shin, socket, toe_h=0.46, + plate="khaki", plate2="olive_light") + f.armour(0, [((0.52 - 0.1 * k) * d, (0.44 - 0.1 * k) * d) for k in range(lames)], widen=1.2, cap="block", plate=0.035 * d, nose=0.4) + f.housing(0) + for i in (1, 2): + f.armour(i, [(0.6 * d, 0.42 * d), (0.38 * d, 0.3 * d)], widen=1.25, cap="hoof", plate=0.035 * d, nose=0.36) + f.housing(i) + for i in (3, 4): + f.armour(i, [(0.5 * d, 0.32 * d)], widen=1.25, cap="hoof", plate=0.03 * d, nose=0.34) + f.housing(i) + _heavy(f, drum=0.4, drum_x=0.4, drum_w=0.14, top=1.0, half=0.36, front=0.18, nose=0.66) + f.pbox(f.plate2, (0, 0.06 * l, 0.92 * d), (0.4 * w, 0.2 * l, 0.12 * d), 0.03 * d) + return f + + +@concept("CHIMERA (28)", 28, (460, 630, 680, 715), view=(-30.0, 9.0), variant={"toes": 2, "width": 1.9}, dims=(1.7, 2.1, 0.7, 0.1)) +def chimera_slabs(name, shin=None, socket="clevis", width=1.7, length=2.1, drop=0.7, pin_r=0.1, toes=3): + """CHIMERA (sheet 28), the hero view's feet: broad slab toes abreast, each a long sloped plate and a square + cap on two pins, under a low instep with the ankle's drum outboard; one wide heel block behind.""" + w, l, d = width, length, drop + xs = (-0.36, 0.0, 0.36) if toes == 3 else (-0.24, 0.24) + f = Foot(name, (w, l, d, pin_r), [T((x * w, (0.1 if x else 0.13) * l), x * 22.0, [(0.26 * l, (0.3 if toes == 3 else 0.4) * w, 0.4 * d), (0.2 * l, (0.3 if toes == 3 else 0.4) * w, 0.42 * d)]) for x in xs] + + [T((0, -0.17 * l), 180.0, [(0.2 * l, 0.56 * w, 0.44 * d)], role="rear", lim=[(-12.0, 24.0)])], shin, socket, toe_h=0.5) + for i in range(toes): + f.armour(i, [(0.5 * d, 0.34 * d), (0.3 * d, 0.3 * d)], widen=1.16, cap="block", plate=0.035 * d, nose=0.28) + f.housing(i) + f.armour(toes, [(0.46 * d, 0.3 * d)], widen=1.1, cap="block", plate=0.03 * d, nose=0.3) + f.housing(toes) + _heavy(f, drum=0.42, drum_x=0.42, drum_w=0.14, top=0.92, half=0.38, front=0.2, nose=0.6) + return f + + +@concept("SERAPH", 30, (605, 812, 818, 992), view=(34.0, 13.0), variant={"toe": 0.28, "skirt": False}, dims=(1.5, 2.2, 0.62, 0.12)) +def seraph_caps(name, shin=None, socket="clevis", width=1.5, length=2.2, drop=0.62, pin_r=0.12, toe=0.21, skirt=True, rams=True): + """SERAPH, FOOT DETAIL: two big toes, each a wedge plate off the instep and a deep toe cap with a skirt of + sole plates round its rim, on two pins; between them the instep's ribbed strut, a booted ram driving a narrow + centre toe; a short block toe on a splay pin at each side behind the ankle's drum; a heel block.""" + w, l, d = width, length, drop + f = Foot(name, (w, l, d, pin_r), [T((s * 0.27 * w, 0.1 * l), s * 6.0, [(0.24 * l, 0.36 * w, 0.42 * d), (toe * l, 0.36 * w, 0.44 * d)]) for s in (-1, 1)] + + [T((0, 0.17 * l), 0.0, [(0.22 * l, 0.13 * w, 0.3 * d)], lim=[(-12.0, 36.0)])] + + [T((s * 0.45 * w, -0.05 * l), s * 78.0, [(0.15 * l, 0.26 * w, 0.42 * d)], splay=12.0, lim=[(-10.0, 26.0)]) for s in (-1, 1)] + + [T((0, -0.19 * l), 180.0, [(0.16 * l, 0.52 * w, 0.42 * d)], role="rear", lim=[(-12.0, 24.0)])], shin, socket, toe_h=0.5, plate="khaki", plate2="olive_light") + for i in (0, 1): + f.armour(i, [(0.6 * d, 0.38 * d), (0.36 * d, 0.3 * d)], widen=1.2, cap="block", plate=0.035 * d, nose=0.36) + f.housing(i) + if skirt: # the cap's rim: sole plates round the nose + dr, (ln, wd, dp) = f.on(f.toes[i]["segs"][1]), f.toes[i]["dims"][1] + for x in (-0.4, 0.0, 0.4): + dr.box(f.plate2, (x * wd, -0.3 * dp, ln * 1.0), (0.34 * wd, 0.36 * dp, 0.06 * ln), tag="trim") + for s in (-1, 1): + dr.box(f.plate2, (s * 0.61 * wd, -0.3 * dp, 0.6 * ln), (0.04 * wd, 0.36 * dp, 0.5 * ln), tag="trim") + f.armour(2, [(0.2 * d, 0.16 * d)], widen=1.2, cap="block", nose=0.3, barrel=0.8, mat="gunmetal") + f.housing(2, horn=0.5 * d, mat="gunmetal") + if rams: + f.ram(2, 0, 0.034 * w, boot=True) + for i in (3, 4): + f.armour(i, [(0.44 * d, 0.3 * d)], widen=1.2, cap="block", plate=0.03 * d, nose=0.34) + f.housing(i, horn=0.1 * d) + f.armour(5, [(0.44 * d, 0.3 * d)], widen=1.1, cap="block", plate=0.03 * d, nose=0.3) + f.housing(5) + _heavy(f, drum=0.46, drum_x=0.36, drum_w=0.16, top=1.0, half=0.32, front=0.12, nose=0.7) + return f + + +@concept("SPECTRE", 31, (815, 718, 1017, 928), view=(6.0, 14.0), variant={"splay": 52.0, "spur": 0.36}, dims=(1.3, 1.6, 0.5, 0.07)) +def spectre_shocks(name, shin=None, socket="clevis", width=1.3, length=1.6, drop=0.5, pin_r=0.07, splay=38.0, spur=0.26, rams=True): + """SPECTRE, FOOT DETAIL (multi-surface foot, shock absorption system): three toes, the centre one ahead and + one fanned out on a splay pin either side, each a shrouded root and a toe plate with a wear tab on two pins, + and each hung on a booted damper from the horn of its root to its plate; a spur on its own pin behind.""" + w, l, d = width, length, drop + seg = [(0.2 * l, 0.26 * w, 0.4 * d), (0.23 * l, 0.26 * w, 0.36 * d)] + f = Foot(name, (w, l, d, pin_r), [T((0, 0.1 * l), 0.0, seg)] + [T((s * 0.3 * w, 0.02 * l), s * splay, seg, splay=0.6 * splay) for s in (-1, 1)] + + [T((0, -0.12 * l), 180.0, [(spur * l, 0.22 * w, 0.38 * d)], role="rear", lim=[(-14.0, 30.0)])], shin, socket, toe_h=0.36) + for i in (0, 1, 2): + f.armour(i, [(0.46 * d, 0.34 * d), (0.3 * d, 0.24 * d)], widen=1.25, cap="block", tab=True, plate=0.035 * d, nose=0.36) + f.housing(i, horn=0.34 * d) + if rams: + f.ram(i, 0, 0.024 * w, boot=True) + f.armour(3, [(0.4 * d, 0.2 * d)], widen=1.25, cap="claw", plate=0.03 * d, nose=0.5, tip=(0.6, 0.4)) + f.housing(3, horn=0.1 * d) + f.drums(0.36 * d, 0.2 * w, 0.12 * w) + f.mass(f.plate, [(0.2 * w, -0.12 * l, 0.6 * d), (0.2 * w, 0.1 * l, 0.6 * d), (0.16 * w, -0.1 * l, 0.98 * d), (0.14 * w, 0.06 * l, 0.98 * d), (0.2 * w, 0.13 * l, 0.72 * d)]) + return f + + +@concept("CHIMERA (34)", 34, (725, 628, 872, 812), view=(-52.0, 12.0), variant={"hoof": 0.3, "width": 1.9}, dims=(1.6, 1.9, 0.8, 0.1)) +def chimera_hooves(name, shin=None, socket="clevis", width=1.6, length=1.9, drop=0.8, pin_r=0.1, hoof=0.2): + """CHIMERA (sheet 34), LEG DETAIL (RIGHT) and (LEFT): three hooves abreast, each a sloped plate and a drawn-in + hoof on two pins; a block toe at each rear corner and a heel block; a tall stepped instep with the ankle's drum + cluster. No toe ram: the leg detail's twin struts are the ankle's, and a ram from the instep to a hoof found + no seat clear of the drums (ram core, 324 candidates).""" + w, l, d = width, length, drop + f = Foot(name, (w, l, d, pin_r), [T((x * w, (0.1 if x else 0.13) * l), x * 26.0, [(0.2 * l, 0.3 * w, 0.4 * d), (hoof * l, 0.3 * w, 0.4 * d)]) for x in (-0.34, 0.0, 0.34)] + + [T((s * 0.38 * w, -0.1 * l), s * 132.0, [(0.2 * l, 0.26 * w, 0.4 * d)], role="rear", lim=[(-10.0, 24.0)]) for s in (-1, 1)] + + [T((0, -0.2 * l), 180.0, [(0.19 * l, 0.5 * w, 0.4 * d)], role="rear", lim=[(-12.0, 24.0)])], shin, socket, toe_h=0.52) + for i in (0, 1, 2): + f.armour(i, [(0.46 * d, 0.34 * d), (0.3 * d, 0.26 * d)], widen=1.2, cap="hoof", plate=0.03 * d, nose=0.4) + f.housing(i) + for i in (3, 4, 5): + f.armour(i, [(0.36 * d, 0.24 * d)], widen=1.15, cap="block", plate=0.03 * d, nose=0.3) + f.housing(i) + _heavy(f, drum=0.36, drum_x=0.4, drum_w=0.14, top=1.0, half=0.36, front=0.2, nose=0.6) + f.pbox(f.plate2, (0, 0.08 * l, 0.9 * d), (0.46 * w, 0.2 * l, 0.1 * d), 0.03 * d) + f.pbox(f.plate, (0, 0.16 * l, 0.72 * d), (0.52 * w, 0.14 * l, 0.1 * d), 0.03 * d) + for s in (-1, 1): + f.on(f.core).cyl("machine", (s * 0.44 * w, -0.12 * l, 0.2 * d), 0.2 * d, 0.1 * w) + return f + + +@concept("BASTION", 36, (345, 440, 600, 545), view=(40.0, 14.0), variant={"toes": 2, "heel": 0.3}, dims=(2.3, 2.7, 0.85, 0.1)) +def bastion_pads(name, shin=None, socket="clevis", width=2.3, length=2.7, drop=0.85, pin_r=0.1, toes=3, heel=0.24, rams=False): + """BASTION (36), the hero view's front feet (the sheet has no foot inset): a broad round pad of chunky tread + blocks under a low stepped instep. `toes` slab toes abreast across the front, each a sloped upper plate and a + square tread block on two pins; a short block toe fanned out at each side; one wide heel block behind + (`heel`, its length as a share of the foot's).""" + w, l, d = width, length, drop + xs = (-0.31, 0.0, 0.31) if toes == 3 else (-0.2, 0.2) + tw = (0.27 if toes == 3 else 0.36) * w + f = Foot(name, (w, l, d, pin_r), [T((x * w, (0.11 if x else 0.14) * l), x * 40.0, [(0.2 * l, tw, 0.42 * d), (0.17 * l, tw, 0.46 * d)]) for x in xs] + + [T((s * 0.4 * w, -0.03 * l), s * 82.0, [(0.19 * l, 0.26 * w, 0.46 * d)], lim=[(-10.0, 28.0)]) for s in (-1, 1)] + + [T((0, -0.16 * l), 180.0, [(heel * l, min(0.6 * w, 1.2), 0.46 * d)], role="rear", lim=[(-12.0, 24.0)])], shin, socket, toe_h=0.5) + n = len(xs) + for i in range(n): + f.armour(i, [(0.52 * d, 0.36 * d), (0.34 * d, 0.3 * d)], widen=1.14, cap="block", plate=0.04 * d, nose=0.26, tab=True) + f.housing(i) + if rams: + f.ram(i, 1, 0.02 * w) + for i in (n, n + 1): + f.armour(i, [(0.44 * d, 0.3 * d)], widen=1.2, cap="block", plate=0.035 * d, nose=0.3) + f.housing(i) + f.armour(n + 2, [(0.5 * d, 0.3 * d)], widen=1.08, cap="block", plate=0.035 * d, nose=0.28) + f.housing(n + 2) + _heavy(f, drum=0.4, drum_x=0.33, drum_w=0.12, top=0.94, half=0.33, front=0.2, nose=0.6) + f.pbox(f.plate2, (0, 0.12 * l, 0.8 * d), (0.46 * w, 0.18 * l, 0.1 * d), 0.03 * d) + return f diff --git a/surfaces/blender/experiments/mechs/feet_bench.py b/surfaces/blender/experiments/mechs/feet_bench.py new file mode 100644 index 0000000..e552d65 --- /dev/null +++ b/surfaces/blender/experiments/mechs/feet_bench.py @@ -0,0 +1,151 @@ +"""Builds the feet library's feet alone on a shin stub and renders them. Environment: +FEET: comma-separated names of feet.FEET (default all). FEET_MODE: catalog (each foot planted, from its concept's +side, and its parameter variant), motion (each foot at heel strike, flat plant and toe-off, side by side), step +(FEET_STEP frames of one foot rolling through a step, to MECH_OUT/feet/step_/f%04d.png). FEET_FAST: EEVEE +in place of Cycles. FEET_NOVAR: no variants. FEET_SAMPLES: Cycles samples (default 48). Writes MECH_OUT/feet/.png, _var.png, +_motion.png and feet_report.json (the kit's joints report and the rams of every foot built).""" +import json, math, os, sys, time +from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import mechlib as M +from mathutils import Matrix, Vector +import bpy +import numpy as np + +M.setup() +M.cache_kits() +import feet + +OUT = Path(os.environ["MECH_OUT"]) / "feet" +assert OUT.is_absolute() +OUT.mkdir(parents=True, exist_ok=True) +MODE, FAST = os.environ.get("FEET_MODE", "catalog"), bool(os.environ.get("FEET_FAST")) +NAMES = [n for n in os.environ.get("FEET", "").split(",") if n] or list(feet.FEET) +SAMPLES = int(os.environ.get("FEET_SAMPLES", "48")) +POSES = {"heel strike": dict(pitch=-14.0, strike=14.0, splay=0.0, lean=-16.0), "flat plant": dict(pitch=0.0, splay=1.0, lean=0.0), + "toe-off": dict(pitch=38.0, roll=38.0, splay=0.35, lean=30.0)} + + +def clear(): + for obj in list(bpy.data.objects): + bpy.data.objects.remove(obj, do_unlink=True) + + +def stand(name, tag, y=0.0, pose=None, **params): + """A foot of the library on a shin stub at y, posed, its lowest point on the ground. Returns the Foot.""" + entry = feet.FEET[name] + w, l, d, pin = (params.get(k, v) for k, v in zip(("width", "length", "drop", "pin_r"), entry["dims"])) + pose = dict(pose or POSES["flat plant"]) + shin_len = 1.0 * d + 0.12 * l + shin = M.place("link", f"{tag}.Shin", mat="gunmetal", length=shin_len, width=min(0.3 * w, 1.0), depth=min(0.22 * w, 0.9), pin_r=pin) + lean = pose.pop("lean", 0.0) + shin.matrix_world = Matrix.Translation((0, y, 2.0 * d)) @ Matrix.Rotation(math.radians(-lean), 4, "X") @ Matrix.Rotation(math.pi, 4, "Y") @ Matrix.Translation((0, 0, -shin_len)) + M.update() + t1 = time.time() + foot = entry["fn"](tag, shin, "clevis", **params) + print("BUILT", tag, round(time.time() - t1, 1), "s", flush=True) + foot.level(pose.pop("pitch", 0.0)) + foot.done() + foot.drive(**pose) + M.update() + shin.matrix_world = Matrix.Translation((0, 0, -lowest(foot))) @ shin.matrix_world + M.update() + return foot + + +def lowest(foot): + """The least z of the foot's own vertices as it stands (a bounding box of a tilted part reaches below it).""" + M.update() + low = 1e9 + for obj in [foot.core] + list(foot.core.children_recursive): + if obj.type == "MESH" and len(obj.data.vertices): + co = np.empty(len(obj.data.vertices) * 3) + obj.data.vertices.foreach_get("co", co) + m = np.array(obj.matrix_world) + low = min(low, float((co.reshape(-1, 3) @ m[2, :3] + m[2, 3]).min())) + return low + + +def stage(): + rig, cam, centre, radius = M.stage(SAMPLES) + scene = bpy.context.scene + if FAST: + scene.render.engine = "BLENDER_EEVEE" + scene.eevee.taa_render_samples = 16 + return rig, cam, radius + + +report, t_all = {}, time.time() +for name in NAMES: + entry, t0 = feet.FEET[name], time.time() + az, el = entry["view"] + if MODE == "catalog": + for suffix, params in (("", {}), ("_var", entry["variant"])): + if suffix and (not params or os.environ.get("FEET_NOVAR")): + continue + clear() + foot = stand(name, name, **params) + if not suffix: + report[name] = dict(foot.report(), clashes=foot.check(), sheet=entry["sheet"], doc=" ".join(entry["fn"].__doc__.split()), variant=entry["variant"]) + rig, cam, radius = stage() + M.shot(rig, cam, radius, az, el, OUT / f"{name}{suffix}.png", (900, 760), margin=0.7, lens=85.0) + elif MODE == "motion": + clear() + gap = 1.55 * max(entry["dims"][0], entry["dims"][1]) + clashes = {} + for k, (label, pose) in enumerate(POSES.items()): + foot = stand(name, f"{name}{k}", y=(k - 1) * gap, pose=pose) + clashes[label] = foot.check() + report[name] = {"clashes": clashes} + rig, cam, radius = stage() + M.shot(rig, cam, radius, -68.0, 10.0, OUT / f"{name}_motion.png", (1800, 620), margin=0.4, lens=110.0) + elif MODE == "step": + clear() + w, l, d, pin = entry["dims"] + frames, out = int(os.environ.get("FEET_STEP", "48")), OUT / f"step_{name}" + out.mkdir(parents=True, exist_ok=True) + shin_len = 1.0 * d + 0.12 * l + shin = M.place("link", "Step.Shin", mat="gunmetal", length=shin_len, width=min(0.3 * w, 1.0), depth=min(0.22 * w, 0.9), pin_r=pin) + base = Matrix.Rotation(math.pi, 4, "Y") @ Matrix.Translation((0, 0, -shin_len)) + shin.matrix_world = Matrix.Translation((0, 0, 2.0 * d)) @ base + M.update() + foot = entry["fn"]("Step", shin, "clevis") + foot.level(0.0) + foot.done() + anchor = foot.toes[0]["segs"][-1] + foot.drive(splay=1.0) + at = anchor.matrix_world.translation + shin.matrix_world = Matrix.Translation((-at.x, 0.25 * l - at.y, -lowest(foot))) @ shin.matrix_world + rig, cam, radius = stage() + mix = lambda a, b, u: a + (b - a) * (u * u * (3 - 2 * u)) + log = [] + for k in range(frames): + t = k / (frames - 1) + if t < 0.18: # heel strike rolling down to the plant + u = t / 0.18 + pitch, strike, roll, splay, lean, lift = mix(-14, 0, u), mix(14, 0, u), 0.0, mix(0, 1, u), mix(-16, -8, u), 0.0 + elif t < 0.5: # planted, the shin passing over + u = (t - 0.18) / 0.32 + pitch, strike, roll, splay, lean, lift = 0.0, 0.0, 0.0, 1.0, mix(-8, 14, u), 0.0 + elif t < 0.82: # the heel rises, the toes roll + u = (t - 0.5) / 0.32 + pitch, strike, roll, splay, lean, lift = mix(0, 44, u), 0.0, mix(0, 44, u), mix(1, 0.3, u), mix(14, 36, u), 0.0 + else: # the foot leaves the ground and the toes fall back + u = (t - 0.82) / 0.18 + pitch, strike, roll, splay, lean, lift = mix(44, 26, u), 0.0, mix(44, 6, u), mix(0.3, 0.0, u), mix(36, 28, u), mix(0, 0.9 * d, u) + shin.matrix_world = Matrix.Translation((0, 0, 3.0 * d)) @ Matrix.Rotation(math.radians(-lean), 4, "X") @ base + M.update() + foot.level(pitch) + wrote = foot.drive(roll=roll, strike=strike, splay=splay) + M.update() + at = anchor.matrix_world.translation # the talon's last pin stays where it is planted + shin.matrix_world = Matrix.Translation((-at.x, 0.25 * l - at.y + (0.5 * lift if lift else 0.0), 0)) @ shin.matrix_world + shin.matrix_world = Matrix.Translation((0, 0, lift - lowest(foot))) @ shin.matrix_world + M.update() + log.append({"frame": k, "pitch": round(pitch, 1), "roll": round(roll, 1), "strike": round(strike, 1), "splay": round(splay, 2), + "joints": {n: round(float(j["obj"]["kit_roll"]) - j["rest"], 1) for n, j in foot.joints.items()}}) + M.shot(rig, cam, radius * 1.3, -62.0, 11.0, out / f"f{k:04d}.png", (960, 600), margin=0.85, lens=95.0, lift=0.12) + report[name] = {"frames": log} + print("FOOT", name, MODE, "s", round(time.time() - t0, 1), flush=True) +(OUT / f"feet_report_{MODE}.json").write_text(json.dumps(report, indent=1, default=str), encoding="utf-8") +print("DONE", MODE, len(NAMES), "feet", round(time.time() - t_all, 1), "s") diff --git a/surfaces/blender/experiments/mechs/feet_dropin.py b/surfaces/blender/experiments/mechs/feet_dropin.py new file mode 100644 index 0000000..d523f91 --- /dev/null +++ b/surfaces/blender/experiments/mechs/feet_dropin.py @@ -0,0 +1,65 @@ +"""Checks that a feet library foot seats where the kit's talon does: on a shin's clevis by `tongue`, as mechlib.leg +and humanoid seat a foot, and under a cross ankle's clevis by `tongue_roll`, as mechlib.ankle_cross does; that the +instep and heel sockets recessed_rams and the foot dress read are there; and that the kit reports its joints and +refuses a roll outside a toe's limits. Prints DROPIN lines and exits 1 on a miss.""" +import json, math, sys +from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import mechlib as M +from mathutils import Matrix, Vector +import bpy + +M.setup() +M.cache_kits() +import feet + +bad = 0 +w, l, d, pin = 1.5, 2.2, 0.62, 0.12 +shin = M.place("link", "Shin", length=2.4, width=0.8, depth=0.8, pin_r=pin) +shin.matrix_world = Matrix.Translation((0, 0, 4)) @ Matrix.Rotation(math.pi, 4, "Y") @ Matrix.Translation((0, 0, -2.4)) +M.update() +talon = M.attach(M.place("talon", "Talon", width=w, length=l, drop=d, pin_r=pin), "tongue", shin, "clevis", 0.0) +M.level_foot(talon) +pin_at = talon.matrix_world.translation.copy() +talon_sockets = set(M.local_sockets(talon)) +bpy.ops.brokkr_kitbash.detach(object_name=talon.name) +bpy.data.objects.remove(talon, do_unlink=True) +foot = feet.seraph_caps("Foot", shin, "clevis", width=w, length=l, drop=d, pin_r=pin) +foot.level(0.0) +foot.done() +M.update() +miss = (foot.core.matrix_world.translation - pin_at).length +down = foot.core.matrix_world.to_3x3() @ Vector((0, 0, 1)) +print("DROPIN tongue on the shin's clevis: ankle pin", round(miss, 6), "m from the talon's; sole normal", tuple(round(v, 3) for v in down)) +bad += miss > 1e-5 or down.z > -0.999 +lacking = talon_sockets - set(M.local_sockets(foot.core)) +print("DROPIN the talon's sockets the foot_core lacks:", sorted(lacking) or "none") +bad += bool(lacking) +report = foot.report() +rows = report["joints"]["joints"] +print("DROPIN kit joints report:", report["joints"]["schema"], len(rows), "rows;", sorted({r["mechanism"] for r in rows})) +bad += len(rows) != len(foot.joints) +seg = foot.joints["toe0.pitch1"] +before = float(seg["obj"]["kit_roll"]) +try: + bpy.ops.brokkr_kitbash.roll(object_name=seg["obj"].name, roll=seg["hi"] + 20.0) + refused = False +except RuntimeError as error: + refused = True + print("DROPIN a roll 20 past the limit is refused:", str(error).strip().splitlines()[-1][:160]) +print("DROPIN roll after the refused write:", float(seg["obj"]["kit_roll"]), "was", before) +bad += (not refused) or abs(float(seg["obj"]["kit_roll"]) - before) > 1e-6 +wrote = foot.set("toe0.pitch1", 30.0) +print("DROPIN brokkr_kitbash.roll inside the limits wrote", round(wrote, 3), "from rest; ram record on the centre toe:", "feet_ram" in foot.toes[2]["segs"][0]) +bad += abs(wrote - 30.0) > 1e-6 +# under a cross ankle, as Seraph stands +cross = M.attach(M.place("cross", "Cross", drop=0.3, width=0.6, pin_r=pin), "tongue", M.place("link", "Shin2", length=2.4, width=0.8, depth=0.8, pin_r=pin), "clevis", 0.0) +second = feet.kestrel_talons("Foot2", None, width=1.0, length=1.9, drop=0.46, pin_r=pin) +M.attach(second.core, "tongue_roll", cross, "clevis") +second.done() +M.update() +gap = (second.core.matrix_world.translation - M.sockets(cross)["clevis"].translation).length +print("DROPIN tongue_roll under a cross's clevis: pin", round(gap, 6), "m off; toes followed:", all(t["segs"][0].parent is not None for t in second.toes)) +bad += gap > 1e-5 +print("DROPIN", "FAILED" if bad else "OK") +sys.exit(1 if bad else 0) diff --git a/surfaces/blender/experiments/mechs/feet_sheets.py b/surfaces/blender/experiments/mechs/feet_sheets.py new file mode 100644 index 0000000..152b211 --- /dev/null +++ b/surfaces/blender/experiments/mechs/feet_sheets.py @@ -0,0 +1,104 @@ +"""The feet library's two sheets, from feet_bench.py's renders. Plain Python (Pillow), no Blender. +usage: python feet_sheets.py MECH_OUT: where feet/ is and where the sheets go; MECH_CONCEPTS: the concept sheets. +catalog_feet.png: per foot, its concept crop, the foot planted, its parameter variant, and its name, parameters, +joints and rams (feet_report_catalog.json). feet_motion.png: per foot, heel strike, flat plant and toe-off.""" +import ast, json, os, textwrap +from pathlib import Path +from PIL import Image, ImageDraw, ImageFont + +HERE = Path(__file__).resolve().parent +OUT, CONCEPTS = Path(os.environ["MECH_OUT"]), Path(os.environ["MECH_CONCEPTS"]) +assert OUT.is_absolute() +SRC = OUT / "feet" +try: + FONT, BOLD, MONO = ImageFont.truetype("arial.ttf", 19), ImageFont.truetype("arialbd.ttf", 26), ImageFont.truetype("consola.ttf", 17) +except OSError: + FONT = BOLD = MONO = ImageFont.load_default() +BG = (22, 22, 22) + + +def registry(): + """feet.FEET as the source declares it, read without Blender: each @concept call and its function's signature.""" + out = {} + for node in ast.parse((HERE / "feet.py").read_text(encoding="utf-8")).body: + if isinstance(node, ast.FunctionDef) and node.decorator_list and getattr(node.decorator_list[0].func, "id", "") == "concept": + call = node.decorator_list[0] + args = [ast.literal_eval(a) for a in call.args] + names = [a.arg for a in node.args.args] + defaults = [ast.literal_eval(d) for d in node.args.defaults] + params = dict(zip(names[len(names) - len(defaults):], defaults)) + out[node.name] = {"sheet": args[0], "number": args[1], "crop": args[2], "params": {k: v for k, v in params.items() if k not in ("shin", "socket")}, + "doc": " ".join(ast.get_docstring(node).split())} + return out + + +def fit(img, w, h): + s = min(w / img.width, h / img.height) + img = img.resize((max(1, round(img.width * s)), max(1, round(img.height * s))), Image.LANCZOS) + cell = Image.new("RGB", (w, h), BG) + cell.paste(img, ((w - img.width) // 2, (h - img.height) // 2)) + return cell + + +def caption(cell, text): + d = ImageDraw.Draw(cell) + d.rectangle((0, 0, d.textlength(text, font=FONT) + 16, 28), fill=(0, 0, 0)) + d.text((8, 3), text, font=FONT, fill=(235, 235, 235)) + return cell + + +def catalog(): + reg = registry() + report = json.loads((SRC / "feet_report_catalog.json").read_text(encoding="utf-8")) if (SRC / "feet_report_catalog.json").exists() else {} + cw, ch, tw = 470, 400, 640 + names = [n for n in reg if (SRC / f"{n}.png").exists()] + sheet = Image.new("RGB", (3 * cw + tw + 5 * 8, len(names) * (ch + 8) + 8), BG) + for row, name in enumerate(names): + e, y = reg[name], 8 + row * (ch + 8) + crop = Image.open(CONCEPTS / f"{e['number']}.webp").convert("RGB").crop(tuple(e["crop"])) + sheet.paste(caption(fit(crop, cw, ch), f"concept {e['number']}: {e['sheet']}"), (8, y)) + sheet.paste(caption(fit(Image.open(SRC / f"{name}.png").convert("RGB"), cw, ch), "built, planted"), (16 + cw, y)) + rep = report.get(name, {}) + var = SRC / f"{name}_var.png" + if var.exists(): + vt = ", ".join(f"{k}={v}" for k, v in rep.get("variant", {}).items()) or "variant" + sheet.paste(caption(fit(Image.open(var).convert("RGB"), cw, ch), vt), (24 + 2 * cw, y)) + d = ImageDraw.Draw(sheet) + x = 32 + 3 * cw + d.text((x, y + 4), f"feet.{name}", font=BOLD, fill=(240, 240, 240)) + lines = textwrap.wrap(", ".join(f"{k}={v}" for k, v in e["params"].items()), 60) + joints = rep.get("joints", {}).get("joints", []) + if rep: + pitch = sum(1 for j in joints if j.get("mechanism") == "toe_pitch") + splay = sum(1 for j in joints if j.get("mechanism") == "toe_splay") + rams = rep.get("rams", []) + lines += ["", f"{rep['toes']} toes, {rep['segments']} segments; kit joints: {pitch} pitch, {splay} splay", + f"rams seated by ram core: {sum(1 for r in rams if r['ok'])} of {len(rams)}" + (f"; ram/armour overlaps: {len(rep.get('clashes', []))}" if rams else "")] + for k, line in enumerate(lines): + d.text((x, y + 42 + 21 * k), line, font=MONO, fill=(170, 210, 170) if k < len(lines) - (3 if rep else 0) else (210, 200, 150)) + for k, line in enumerate(textwrap.wrap(e["doc"], 66)[:11]): + d.text((x, y + 42 + 21 * len(lines) + 12 + 22 * k), line, font=FONT, fill=(200, 200, 200)) + sheet.save(OUT / "catalog_feet.png") + print("WROTE", OUT / "catalog_feet.png", sheet.size, len(names), "feet") + + +def motion(): + reg = registry() + names = [n for n in reg if (SRC / f"{n}_motion.png").exists()] + w, h = 1800, 620 + sheet = Image.new("RGB", (w + 16, len(names) * (h + 8) + 8), BG) + for row, name in enumerate(names): + y = 8 + row * (h + 8) + strip = Image.open(SRC / f"{name}_motion.png").convert("RGB") + d = ImageDraw.Draw(strip) + d.rectangle((0, 0, w, 34), fill=(0, 0, 0)) + d.text((10, 3), f"feet.{name} ({reg[name]['sheet']})", font=BOLD, fill=(240, 240, 240)) + for k, text in enumerate(("heel strike: nose up 14, rear toes flat, toes closed", "flat plant: toes fanned", "toe-off: heel up 38, toes rolled and left on the ground")): + d.text((w * (2 * k + 1) // 6 - d.textlength(text, font=FONT) // 2, h - 30), text, font=FONT, fill=(20, 20, 20)) + sheet.paste(strip, (8, y)) + sheet.save(OUT / "feet_motion.png") + print("WROTE", OUT / "feet_motion.png", sheet.size, len(names), "feet") + + +catalog() +motion() diff --git a/surfaces/blender/experiments/mechs/gen_kit.py b/surfaces/blender/experiments/mechs/gen_kit.py index 7191eb1..acaadaa 100644 --- a/surfaces/blender/experiments/mechs/gen_kit.py +++ b/surfaces/blender/experiments/mechs/gen_kit.py @@ -2,7 +2,8 @@ import json, sys from pathlib import Path -SURFACE = Path(__file__).resolve().parents[2] +import os +SURFACE = Path(os.environ["BROKKR_SURFACE"]) if os.environ.get("BROKKR_SURFACE") else Path(__file__).resolve().parents[2] # the add-on tree the kit is written into sys.path.insert(0, str(SURFACE)) @@ -51,7 +52,7 @@ parts = [] parts.append({ "name": "link", "doc": "Limb girder along +z: a tongue on a pin axis (x) at z=0, a clevis at z=length, side plates, web, ribs and bolt rows. Pin sockets lie on the centre plane, so links of any width hinge centred.", - "params": [P("length", 0.3, 5.0, 1.2), P("width", 0.08, 1.0, 0.3, "x extent"), P("depth", 0.08, 1.0, 0.3, "y extent"), P("pin_r", 0.015, 0.2, 0.05)], + "params": [P("length", 0.08, 5.0, 1.2), P("width", 0.04, 1.2, 0.3, "x extent"), P("depth", 0.03, 1.0, 0.3, "y extent"), P("pin_r", 0.008, 0.2, 0.05)], "bevel": "0.02*min(width,depth)", "shapes": [ xtube("1.6*pin_r", "0.6*width", "-0.3*width", 0, 0, 32), @@ -385,6 +386,54 @@ parts.append({ ], "sockets": [S("mount", "mount", "0.8*r", [0, 0, 0], "-z", "+y"), S("cap", "mount", "0.6*r", [0, 0, "t"], "+z", "+y")]}) +# --- articulated feet (feet.py): a core on the ankle pin, a knuckle per toe on a vertical splay pin, toe segments on pitch pins +TOES = "abcdef" +parts.append({ + "name": "foot_core", "doc": "The carriage of an articulated foot on an ankle pin (x) at z=0, the ground at z=drop, +y the front: hub, column and a deck with six vertical toe pins under it at (tNx, tNy), each a splay hinge (toe_N, a pivot: the roll is the toe's yaw) and a fixed seat (seat_N, a mount) on one frame. A pin left at 0, 0 stands inside the column. Takes the sockets of the kit's other feet (tongue, tongue_roll, instep, heel), so it seats where they do.", + "params": [P("width", 0.1, 3.0, 0.6), P("length", 0.2, 4.0, 1.0), P("drop", 0.1, 1.5, 0.36), P("pin_r", 0.015, 0.25, 0.05), P("toe_pin_r", 0.008, 0.2, 0.03, "every toe pin's radius"), + P("toe_h", 0.15, 0.95, 0.6, "the toe pins' seat plane, as a fraction of drop below the ankle pin")] + + [P(f"t{k}{c}", -3.0, 3.0, 0.0, f"toe pin {k}: {c} in the core's frame") for k in TOES for c in "xy"], + "bevel": "0.02*width", + "shapes": [ + xtube("1.6*pin_r", "0.6*width", "-0.3*width", 0, 0, 32), + box(["0.6*width", "3.4*pin_r", "toe_h*drop"], [0, 0, "0.5*toe_h*drop"]), + box(["0.7*width", "0.4*length", "0.3*toe_h*drop"], [0, "0.04*length", "0.85*toe_h*drop"]), + ] + [ztube("1.9*toe_pin_r", "0.2*toe_h*drop", f"t{k}x", f"t{k}y", "0.8*toe_h*drop", 16) for k in TOES], + "sockets": [S("tongue", "pivot", "2*pin_r", [0, 0, 0], "+x", "+z"), + S("instep", "mount", "0.3*width", [0, "0.22*length", "0.7*drop"], "-z", "+y"), S("heel", "mount", "0.3*width", [0, "-0.36*length", "0.72*drop"], "-z", "+y")] + + [S(f"{name}{sfx}", "mount", "0.4*width", [f"{sign}0.27*width", y, z], "-z", "+y") for name, y, z in (("instep", "0.22*length", "0.7*drop"), ("heel", "-0.3*length", "0.72*drop")) + for sfx, sign in (("_l", "-"), ("_r", ""))] + + [S("tongue_roll", "pivot", "2*pin_r", [0, 0, 0], "+y", "+z")] + + [S(f"toe_{k}", "pivot", "2*toe_pin_r", [f"t{k}x", f"t{k}y", "toe_h*drop"], "+z", "+y") for k in TOES] + + [S(f"seat_{k}", "mount", "2*toe_pin_r", [f"t{k}x", f"t{k}y", "toe_h*drop"], "+z", "+y") for k in TOES]}) + +parts.append({ + "name": "toe_knuckle", "doc": "A toe's root, z down and +y along the toe: a bush on a vertical pin at the origin (splay, a pivot whose roll is the toe's yaw; seat, the same frame as a fixed mount) and, `reach` ahead and 1.6 pin_r below, a clevis on a pin along x for the toe's first segment (its roll is the toe's pitch, positive lifting the toe).", + "params": [P("pin_r", 0.008, 0.2, 0.03), P("reach", 0.02, 1.5, 0.1), P("width", 0.04, 1.2, 0.2, "the toe's width")], + "bevel": "0.1*pin_r", + "shapes": [ + ztube("1.9*pin_r", "0.4*pin_r", 0, 0, 0, 16), + box(["width", "3.8*pin_r", "2.4*pin_r"], [0, 0, "1.6*pin_r"]), + rep(2, ["0.86*width", 0, 0], box(["0.14*width", "reach", "2.4*pin_r"], ["-0.43*width", "0.5*reach", "1.6*pin_r"])), + rep(2, ["0.86*width", 0, 0], xtube("1.9*pin_r", "0.14*width", "-0.5*width", "reach", "1.6*pin_r", 24)), + xtube("pin_r", "1.2*width", "-0.6*width", "reach", "1.6*pin_r"), + rep(2, ["1.24*width", 0, 0], xtube("1.5*pin_r", "0.08*width", "-0.66*width", "reach", "1.6*pin_r", 6, False)), + ], + "sockets": [S("splay", "pivot", "2*pin_r", [0, 0, 0], "-z", "+y"), S("seat", "mount", "2*pin_r", [0, 0, 0], "-z", "+y"), + S("clevis", "pivot", "2*pin_r", [0, "reach", "1.6*pin_r"], "-x", "+y")]}) + +parts.append({ + "name": "toe", "doc": "A toe's last segment along +z: a tongue on a pin axis (x) at z=0 and a beam to z=length, +y its back (the armour's side), -y its sole. No clevis: nothing hinges beyond it.", + "params": [P("length", 0.08, 3.0, 0.4), P("width", 0.04, 1.2, 0.2), P("depth", 0.03, 1.0, 0.16), P("pin_r", 0.008, 0.2, 0.03)], + "bevel": "0.02*min(width,depth)", + "shapes": [ + xtube("1.6*pin_r", "0.6*width", "-0.3*width", 0, 0, 32), + box(["0.6*width", "min(depth,3.2*pin_r)", "0.5*length"], [0, 0, "0.25*length"]), + box(["0.5*width", "0.5*depth", "0.5*length"], [0, 0, "0.45*length"]), + ], + "sockets": [S("tongue", "pivot", "2*pin_r", [0, 0, 0], "+x", "+z"), S("top", "mount", "0.5*width", [0, "0.4*depth", "0.6*length"], "+y", "+z"), + S("sole", "mount", "0.5*width", [0, "-0.4*depth", "0.6*length"], "-y", "+z")]}) + talon = next(p for p in parts if p["name"] == "talon") trident = json.loads(json.dumps(talon)) trident["name"], trident["doc"] = "trident", "A three-toed foot on an ankle pin (x) at z=0: the talon with a middle toe and a short heel." @@ -392,7 +441,7 @@ trident["shapes"] += [box(["0.26*width", "0.62*length", "0.46*drop"], [0, "0.5*l parts.append(trident) kit = {"schema": "brokkr.kit.v0", "kit": "mech", "doc": "Mech-scale structure for the armor-shell experiment: girders, yokes, slew rings, rams, lugs, feet, hull frames, guns.", - "socketTypes": {"flange": {"match": "equal", "doc": "bolted pipe or duct face; size is the bore diameter"}, "mount": {"match": "fits", "doc": "flat seat; size is the free diameter around the socket"}, "pivot": {"match": "equal", "doc": "pin joint on the pin's centre plane; size is the pin diameter"}}, + "socketTypes": {"flange": {"match": "equal", "doc": "bolted pipe or duct face; size is the bore diameter"}, "mount": {"match": "fits", "doc": "flat seat; size is the free diameter around the socket"}, "pivot": {"match": "equal", "dof": "revolute", "doc": "pin joint on the pin's centre plane; size is the pin diameter; the child turns about the socket's z"}}, "parts": parts} out = SURFACE / "brokkr_kitbash" / "kits" / "mech.v0.json" out.write_text(json.dumps(kit, indent=1), encoding="utf-8") diff --git a/surfaces/blender/experiments/mechs/massing.py b/surfaces/blender/experiments/mechs/massing.py index dd436df..f9f5900 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` @@ -62,6 +66,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 diff --git a/surfaces/blender/experiments/mechs/mechlib.py b/surfaces/blender/experiments/mechs/mechlib.py index 895f0d1..abb3006 100644 --- a/surfaces/blender/experiments/mechs/mechlib.py +++ b/surfaces/blender/experiments/mechs/mechlib.py @@ -38,6 +38,9 @@ Round 4 (massing first, then attachment, then layering), none of it a Brokkr act silhouette / closeup / field_views, compare.py masks, joint close-ups and the comparison sheets. Needs: a concept outline that is not traced by hand (concepts.json). + cache_kits each checked kit kept for the session. Needs: core.load_kit to keep a kit + by its file's modification time (it checks the whole file at every call of every action). + Round 8: canted_hip / lay(cant=True) the legs' splay: the hip's slew ring on a wedge, its axis tipped by the lean of @@ -99,6 +102,15 @@ def setup(): materials() +def cache_kits(): + """Keep each checked kit for the session. core.load_kit reads and checks the whole kit file at every call, and + every kit action calls it several times: 183 calls and 23 of the 27 seconds of one 13-part foot. A kit file + edited after this is not read again.""" + import functools + if not hasattr(KB.core.load_kit, "cache_info"): + KB.core.load_kit = functools.lru_cache(maxsize=None)(KB.core.load_kit) + + def material(name, color, metallic=0.0, rough=0.5, emission=None, coat=0.0): mat = bpy.data.materials.new(name) mat.use_nodes = True @@ -1282,7 +1294,7 @@ def turntable(rig, cam, radius, out_dir, prefix, views=8, size=(1100, 1100), ele # --- limbs ------------------------------------------------------------------------------------------------------- SIDE_SOCKETS = {"link": {"front": ("front_a", "front_b"), "back": ("back_a", "back_b")}, "thigh": {"front": ("front_a", "front_b"), "back": ("back_a", "back_b")}, "yoke": {"front": ("front",), "back": ("back",)}, - "wrist": {"front": ("front",), "back": ("back",)}, "foot": {"front": ("instep",), "back": ("heel",)}, "talon": {"front": ("instep",), "back": ("heel",)}, "trident": {"front": ("instep",), "back": ("heel",)}} + "wrist": {"front": ("front",), "back": ("back",)}, "foot": {"front": ("instep",), "back": ("heel",)}, "talon": {"front": ("instep",), "back": ("heel",)}, "trident": {"front": ("instep",), "back": ("heel",)}, "foot_core": {"front": ("instep",), "back": ("heel",)}} def occupied(part, socket): @@ -1848,7 +1860,7 @@ def canted_hip(tag, saddle, sock, slew, r, cant, sx): # --- joint designs: one axis each, each a helper ------------------------------------------------------------------- -TWIN = {sfx: {kind: {"front": tuple(n + sfx for n in v["front"]), "back": tuple(n + sfx for n in v["back"])} for kind, v in SIDE_SOCKETS.items() if kind in ("link", "thigh", "talon", "foot", "trident")} +TWIN = {sfx: {kind: {"front": tuple(n + sfx for n in v["front"]), "back": tuple(n + sfx for n in v["back"])} for kind, v in SIDE_SOCKETS.items() if kind in ("link", "thigh", "talon", "foot", "trident", "foot_core")} for sfx in ("_l", "_r")} diff --git a/surfaces/blender/experiments/mechs/paint.py b/surfaces/blender/experiments/mechs/paint.py new file mode 100644 index 0000000..d69f1cb --- /dev/null +++ b/surfaces/blender/experiments/mechs/paint.py @@ -0,0 +1,317 @@ +"""Field paint for the mech experiments: one Cycles node group, MechPaint, and the materials that set its inputs. + +Render only, from geometry alone: no UVs, no bakes, no image textures, so it costs no texture memory. It needs +bpy and nothing else of this folder, so any track can drop it beside its build. + +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 +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). + +PRESETS seraph (cleaner, warm drab: 30.webp), mcr3 (grey drab, middling wear: 25.webp), + 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. +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. + 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 + hangs over them: dark runs and paler washed ones (Streaks). + dust pale dust on faces that look up (Dust). + edge wear the Bevel node's rounded normal leaves the true one near an edge; where the edge is exposed + (AO) and a noise passes a threshold, the paint is chipped to Chip Color with a ring of + Primer Color round it; scuffs on open faces (Wear). + mud and wet by height over Ground Z: wet darkening and gloss below Wet Top, mud thick below Mud Top and + in splashes to twice that (Mud, Wet). +Every noise reads the world position, so a pattern runs unbroken across neighbouring plates and under a decal; +that also means it swims if the mech moves: this is paint for stills. +""" +import bpy + +GROUP = "MechPaint" + +# name: (socket type, default). The order is the group's input order. +INPUTS = { + "Base Color": ("NodeSocketColor", (0.05, 0.044, 0.032, 1.0)), + "Roughness": ("NodeSocketFloat", 0.62), + "Metallic": ("NodeSocketFloat", 0.0), + "Tone Variation": ("NodeSocketFloat", 0.3), + "Mottle": ("NodeSocketFloat", 1.0), + "Cover Color": ("NodeSocketColor", (0.2, 0.19, 0.165, 1.0)), + "Cover": ("NodeSocketFloat", 0.0), + "Cover Wear": ("NodeSocketFloat", 0.5), + "Grime": ("NodeSocketFloat", 1.0), + "Grime Color": ("NodeSocketColor", (0.02, 0.017, 0.013, 1.0)), + "Streaks": ("NodeSocketFloat", 1.0), + "Dust": ("NodeSocketFloat", 0.5), + "Dust Color": ("NodeSocketColor", (0.17, 0.155, 0.125, 1.0)), + "Wear": ("NodeSocketFloat", 1.0), + "Chip Color": ("NodeSocketColor", (0.016, 0.015, 0.014, 1.0)), + "Chip Metallic": ("NodeSocketFloat", 0.85), + "Primer Color": ("NodeSocketColor", (0.1, 0.092, 0.074, 1.0)), + "Mud": ("NodeSocketFloat", 1.0), + "Mud Top": ("NodeSocketFloat", 1.4), + "Mud Color": ("NodeSocketColor", (0.026, 0.019, 0.013, 1.0)), + "Wet": ("NodeSocketFloat", 0.6), + "Wet Top": ("NodeSocketFloat", 3.0), + "Ground Z": ("NodeSocketFloat", 0.0), + "Scale": ("NodeSocketFloat", 1.0), +} +OUTPUTS = {"Color": "NodeSocketColor", "Metallic": "NodeSocketFloat", "Roughness": "NodeSocketFloat", "Normal": "NodeSocketVector", "Alpha": "NodeSocketFloat"} + +_METAL = {"base_color": (0.03, 0.03, 0.03), "metallic": 0.75, "roughness": 0.5, "tone_variation": 0.3, "chip_color": (0.11, 0.11, 0.11), "chip_metallic": 1.0, "primer_color": (0.03, 0.03, 0.03), + "dust": 0.8, "grime": 1.2} +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}}, + # 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}}, + # 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}}, + # 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}}, + # 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}}, +} +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"}, +} +HAZARD = {"cover_color": (0.32, 0.2, 0.025), "cover_wear": 0.7} + + +class _Net: + """Node wiring shorthand: a value is a socket or a constant.""" + + def __init__(self, tree): + self.tree, self.nodes, self.links = tree, tree.nodes, tree.links + + def put(self, socket, value): + if value is None: + return + if hasattr(value, "is_linked"): + self.links.new(value, socket) + elif isinstance(value, (int, float)): + socket.default_value = float(value) + else: + socket.default_value = tuple(value) if len(value) == len(socket.default_value) else (*value, 1.0) + + def math(self, op, a, b=None, c=None, clamp=False): + node = self.nodes.new("ShaderNodeMath") + node.operation, node.use_clamp = op, clamp + for socket, value in zip(node.inputs, (a, b, c)): + self.put(socket, value) + return node.outputs[0] + + def mul(self, *values, clamp=False): + out = values[0] + for v in values[1:]: + out = self.math("MULTIPLY", out, v, clamp=clamp) + return out + + def ramp(self, value, lo, hi, to=(0.0, 1.0)): + """lo maps to to[0], hi to to[1], clamped; lo may exceed hi. lo and hi may be sockets.""" + node = self.nodes.new("ShaderNodeMapRange") + for socket, v in zip(node.inputs, (value, lo, hi, to[0], to[1])): + self.put(socket, v) + return node.outputs[0] + + def mix(self, a, b, fac, blend="MIX"): + node = self.nodes.new("ShaderNodeMix") + node.data_type, node.blend_type = "RGBA", blend + self.put(node.inputs[0], fac) + self.put(node.inputs[6], a) + self.put(node.inputs[7], b) + return node.outputs[2] + + def vec(self, op, a, b=None, scale=None): + node = self.nodes.new("ShaderNodeVectorMath") + node.operation = op + self.put(node.inputs[0], a) + self.put(node.inputs[1], b) + self.put(node.inputs[3], scale) + return node.outputs["Value" if op == "DOT_PRODUCT" else "Vector"] + + def noise(self, vector, scale, detail=4.0, rough=0.55, distortion=0.0): + node = self.nodes.new("ShaderNodeTexNoise") + node.inputs["Scale"].default_value, node.inputs["Detail"].default_value = scale, detail + node.inputs["Roughness"].default_value, node.inputs["Distortion"].default_value = rough, distortion + self.links.new(vector, node.inputs["Vector"]) + return node.outputs[0] + + +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") + for name, (kind, default) in INPUTS.items(): + s = tree.interface.new_socket(name, in_out="INPUT", socket_type=kind) + s.default_value = default + for name, kind in 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, info = tree.nodes.new("ShaderNodeNewGeometry"), tree.nodes.new("ShaderNodeObjectInfo") + pos = n.vec("SCALE", geo.outputs["Position"], scale=G["Scale"]) + xyz = tree.nodes.new("ShaderNodeSeparateXYZ") + tree.links.new(geo.outputs["Position"], xyz.inputs[0]) + nrm = tree.nodes.new("ShaderNodeSeparateXYZ") + tree.links.new(geo.outputs["Normal"], nrm.inputs[0]) + up = nrm.outputs["Z"] + height = n.math("SUBTRACT", xyz.outputs["Z"], G["Ground Z"]) + + # base paint: one tone per plate, mottled + rand = n.math("FRACT", n.math("ADD", info.outputs["Random"], n.math("MULTIPLY", geo.outputs["Random Per Island"], 0.7))) + rand2 = n.math("FRACT", n.math("MULTIPLY_ADD", rand, 7.31, 0.37)) + hsv = tree.nodes.new("ShaderNodeHueSaturation") + tree.links.new(G["Base Color"], hsv.inputs["Color"]) + n.put(hsv.inputs["Hue"], n.math("MULTIPLY_ADD", n.math("SUBTRACT", rand2, 0.5), n.math("MULTIPLY", G["Tone Variation"], 0.2), 0.5)) + n.put(hsv.inputs["Saturation"], n.math("MULTIPLY_ADD", n.math("SUBTRACT", rand2, 0.5), G["Tone Variation"], 1.0)) + n.put(hsv.inputs["Value"], n.math("MULTIPLY_ADD", n.math("MULTIPLY_ADD", rand, 2.0, -1.0), G["Tone Variation"], 1.0)) + blotch, speck = n.noise(pos, 0.9, 5.0, 0.6), n.noise(pos, 28.0, 3.0, 0.6) + 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"]) + 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) + + # cavity grime + ao = tree.nodes.new("ShaderNodeAmbientOcclusion") + ao.samples, ao.inputs["Distance"].default_value = 4, 0.45 + occ = ao.outputs["AO"] + cavity = n.mul(n.ramp(occ, 0.93, 0.5), n.ramp(n.noise(pos, 5.0, 6.0, 0.7), 0.3, 0.6, (0.5, 1.0)), G["Grime"], clamp=True) + film = n.mul(n.ramp(n.noise(pos, 2.3, 7.0, 0.7), 0.5, 0.68), 0.5, G["Grime"]) + grime = n.math("MAXIMUM", cavity, film) + col = n.mix(col, G["Grime Color"], n.math("MINIMUM", grime, 0.85)) + + # streaks down the upright faces + stretch = n.vec("MULTIPLY", pos, (13.0, 13.0, 0.5)) + upright = n.ramp(n.math("ABSOLUTE", up), 0.8, 0.35) + under = n.ramp(occ, 0.98, 0.7, (0.45, 1.0)) + broken = n.ramp(n.noise(pos, 1.4, 3.0), 0.35, 0.55, (0.15, 1.0)) + dark_run = n.mul(n.ramp(n.noise(stretch, 1.0, 3.0, 0.5), 0.5, 0.66), upright, under, broken, G["Streaks"], clamp=True) + pale_run = n.mul(n.ramp(n.noise(n.vec("ADD", stretch, (31.0, 17.0, 5.0)), 1.0, 2.0, 0.5), 0.6, 0.74), upright, 0.32, G["Streaks"], clamp=True) + col = n.mix(col, G["Dust Color"], pale_run) + col = n.mix(col, G["Grime Color"], n.math("MULTIPLY", dark_run, 0.85)) + + # 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) + + # edge wear: chips to metal with a primer ring, scuffs on open faces + bevel = tree.nodes.new("ShaderNodeBevel") + bevel.samples, bevel.inputs["Radius"].default_value = 4, 0.14 + edge = n.ramp(n.vec("DOT_PRODUCT", bevel.outputs["Normal"], geo.outputs["Normal"]), 0.9995, 0.98) + exposed = n.ramp(occ, 0.45, 0.85) + chip_noise = n.math("ADD", n.ramp(n.noise(pos, 5.0, 7.0, 0.72), 0.3, 0.7, (0.0, 0.6)), n.ramp(n.noise(pos, 45.0, 2.0), 0.3, 0.7, (-0.05, 0.05))) # 0 to 0.6, about evenly + level = n.math("ADD", chip_noise, n.mul(edge, exposed, G["Wear"], 0.5)) + scuff = n.mul(n.ramp(n.noise(pos, 4.0, 9.0, 0.82), 0.66, 0.69), n.ramp(G["Wear"], 0.0, 1.5, (0.0, 1.0))) + metal = n.math("MAXIMUM", n.ramp(level, 0.74, 0.77), n.math("MULTIPLY", scuff, 0.85)) + primer = n.math("MAXIMUM", n.ramp(level, 0.7, 0.73), scuff) + col = n.mix(col, G["Primer Color"], n.math("MULTIPLY", primer, 0.75)) + col = n.mix(col, G["Chip Color"], metal) + + # wet, then mud, from the ground up + wet = n.mul(n.ramp(height, G["Wet Top"], 0.0), G["Wet"], clamp=True) + col = n.vec("SCALE", col, scale=n.math("MULTIPLY_ADD", wet, -0.5, 1.0)) + mud_noise = n.noise(pos, 3.2, 7.0, 0.7) + thick = n.mul(n.ramp(height, G["Mud Top"], 0.0), n.ramp(mud_noise, 0.35, 0.62, (0.1, 1.5)), n.ramp(occ, 0.95, 0.5, (0.7, 1.6)), G["Mud"]) + splash = n.mul(n.ramp(n.noise(pos, 11.0, 4.0, 0.6), 0.62, 0.66), n.ramp(height, n.math("MULTIPLY", G["Mud Top"], 2.2), n.math("MULTIPLY", G["Mud Top"], 0.4)), G["Mud"], 0.85) + mud = n.math("MAXIMUM", n.ramp(thick, 0.2, 0.5), splash, clamp=True) + col = n.mix(col, n.vec("SCALE", G["Mud Color"], scale=n.ramp(mud_noise, 0.3, 0.7, (0.7, 1.3))), mud) + + tree.links.new(col, gout.inputs["Color"]) + tree.links.new(n.mul(n.math("MAXIMUM", G["Metallic"], n.math("MULTIPLY", metal, G["Chip Metallic"])), n.math("SUBTRACT", 1.0, mud), n.math("SUBTRACT", 1.0, n.math("MULTIPLY", grime, 0.7))), gout.inputs["Metallic"]) + rough = n.math("ADD", G["Roughness"], n.math("ADD", n.math("MULTIPLY", grime, 0.25), n.math("MULTIPLY", metal, -0.22))) + rough = n.math("ADD", rough, n.math("MULTIPLY", wet, -0.12)) + rough = n.math("ADD", rough, n.math("MULTIPLY", mud, 0.12), clamp=True) + tree.links.new(rough, gout.inputs["Roughness"]) + bump = tree.nodes.new("ShaderNodeBump") + bump.inputs["Strength"].default_value, bump.inputs["Distance"].default_value = 0.35, 0.006 + relief = n.math("ADD", n.math("MULTIPLY", speck, 0.25), n.math("ADD", n.math("MULTIPLY", metal, -1.0), n.mul(mud, mud_noise, 3.0))) + tree.links.new(relief, bump.inputs["Height"]) + tree.links.new(bump.outputs["Normal"], gout.inputs["Normal"]) + tree.links.new(alpha, gout.inputs["Alpha"]) + return tree + + +def _input_name(key): + for name in INPUTS: + 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)) + + +def material(name, role="armour", preset="seraph", **overrides): + """One MechPaint material: the preset's values for `role` (armour, metal, mark, hazard), then `overrides`.""" + p = PRESETS[preset] + values = dict(p["armour"]) + if role == "metal": + values = {**{k: v for k, v in values.items() if k in ("mud", "mud_top", "wet_top", "streaks")}, **p["metal"]} + elif role in ("mark", "hazard"): + values.update({"cover": 1.0, **(HAZARD if role == "hazard" else p["mark"])}) + values.update(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 = group() + for key, value in values.items(): + socket = grp.inputs[_input_name(key)] + socket.default_value = value if isinstance(value, (int, float)) else (*value, 1.0) + for a, b in (("Color", "Base Color"), ("Metallic", "Metallic"), ("Roughness", "Roughness"), ("Normal", "Normal")) + ((("Alpha", "Alpha"),) if role in ("mark", "hazard") else ()): + links.new(grp.outputs[a], bsdf.inputs[b]) + bsdf.inputs["Specular IOR Level"].default_value = 0.35 # a matt paint under a bright sky: the default sheen greys every dark plate + links.new(bsdf.outputs[0], out.inputs[0]) + key = "cover_color" if role in ("mark", "hazard") else "base_color" + base = values.get(key, INPUTS[_input_name(key)][1]) + mat.diffuse_color = (*base[:3], 1.0) + mat["paint_role"] = role + 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}.""" + role_of = {name: role for role, names in ROLES.items() for name in names} + role_of.update(roles or {}) + made, swapped = {}, {} + for obj in objects or bpy.context.scene.objects: + 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 + 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] + return swapped diff --git a/surfaces/blender/experiments/mechs/paint_render.py b/surfaces/blender/experiments/mechs/paint_render.py new file mode 100644 index 0000000..b10c8ec --- /dev/null +++ b/surfaces/blender/experiments/mechs/paint_render.py @@ -0,0 +1,58 @@ +"""Render a saved mech .blend at a solved camera with the paint it was saved with, then with paint.apply(): +the proof renders for paint.py. + +blender --background --python paint_render.py -- [width] [samples] [crops] + cameras.json camsolve cameras, {"hero": ...}, at the build's scale + crops JSON, {tag: [x0, y0, x1, y1]} in the concept sheet's pixels: extra renders of the hero view cropped +Writes, under MECH_OUT: _old.png, _new.png, _new_.png (and _old_.png with +PAINT_OLD_CROPS set). PAINT_ONLY=new skips the old paint. A .blend without a stage gets mechlib.stage_field(). +PAINT_VARIANTS=seraph,breaker,... instead renders the first crop once per preset, _variant_.png: the +presets' catalog (paint_sheets.py lays them out). +""" +import json, os, sys +from pathlib import Path +sys.path.insert(0, str(Path(__file__).resolve().parent)) +import bpy +import mechlib as M +import paint + +args = sys.argv[sys.argv.index("--") + 1:] +blend, cams_path, stem, preset = args[:4] +width = int(args[4]) if len(args) > 4 else 1100 +samples = int(args[5]) if len(args) > 5 else 64 +crops = json.loads(args[6]) if len(args) > 6 else {} +OUT = Path(os.environ["MECH_OUT"]) +assert OUT.is_absolute() +bpy.ops.wm.open_mainfile(filepath=blend) +scene = bpy.context.scene +M.MATS.update({m.name: m for m in bpy.data.materials}) +if "Rig" in bpy.data.objects and scene.camera: + rig, cam = bpy.data.objects["Rig"], scene.camera + M.gpu(scene) +else: + if "mud" not in M.MATS: + M.mud_ground() + rig, cam, _, _ = M.stage_field(samples) +scene.cycles.samples, scene.cycles.use_denoising = samples, True +hero = json.loads(Path(cams_path).read_text(encoding="utf-8"))["hero"] +only = os.environ.get("PAINT_ONLY") + + +def shots(tag): + M.shot(rig, cam, 0, 0, 0, OUT / f"{stem}_{tag}.png", (width, width), solved=hero) + if tag == "new" or os.environ.get("PAINT_OLD_CROPS"): + for name, box in crops.items(): + M.shot(rig, cam, 0, 0, 0, OUT / f"{stem}_{tag}_{name}.png", (min(width, 900), 0), solved=hero, box=box) + + +if os.environ.get("PAINT_VARIANTS"): + name, box = next(iter(crops.items())) + for p in os.environ["PAINT_VARIANTS"].split(","): + paint.apply(p) + M.shot(rig, cam, 0, 0, 0, OUT / f"{stem}_variant_{p}.png", (width, 0), solved=hero, box=box) + raise SystemExit(0) +if only != "new": + shots("old") +overrides = json.loads(os.environ.get("PAINT_OVERRIDES", "{}")) +print("PAINTED", {k: v.name for k, v in paint.apply(preset, **overrides).items()}, flush=True) +shots("new") diff --git a/surfaces/blender/experiments/mechs/paint_sheets.py b/surfaces/blender/experiments/mechs/paint_sheets.py new file mode 100644 index 0000000..f1c2064 --- /dev/null +++ b/surfaces/blender/experiments/mechs/paint_sheets.py @@ -0,0 +1,73 @@ +"""The paint track's two sheets, from paint_render.py's renders (plain Python, PIL): + + paint_compare.png per mech: the concept's hero view, the build in its old paint, the build after paint.apply() + paint_variants.png the presets, each on the MCR-3 from chest to knee (paint_render.py under PAINT_VARIANTS) + paint_closeups.png per mech, chest, knee and foot: the concept's inset, the concept's hero view cropped to the + part, the old paint cropped the same, the new paint rendered at that crop + +python paint_sheets.py MECH_OUT holds the renders and takes the sheets; MECH_CONCEPTS holds the concept sheets. +""" +import os +from pathlib import Path +from PIL import Image, ImageDraw, ImageFont + +OUT, CONCEPTS = Path(os.environ["MECH_OUT"]), Path(os.environ["MECH_CONCEPTS"]) +# stem, title, concept sheet, the hero view's box on it, the old hero render, {part: (inset box, hero crop box)} +MECHS = ( + ("seraph", "SERAPH (30.webp), preset seraph", "30.webp", (0, 0, 700, 810), os.environ["PAINT_OLD_SERAPH"], + {"chest": ((703, 453, 857, 598), (200, 90, 520, 300)), "knee": ((436, 815, 598, 998), (400, 330, 600, 530)), "foot": ((606, 815, 818, 998), (400, 620, 660, 810))}), + ("mcr3", "MCR-3 (25.webp), preset mcr3", "25.webp", (40, 0, 500, 600), os.environ["PAINT_OLD_MCR3"], + {"chest": ((5, 607, 203, 798), (200, 60, 400, 220)), "knee": ((208, 805, 363, 1010), (290, 310, 430, 450)), "foot": ((369, 805, 543, 1010), (280, 490, 480, 590))}), +) +BG, INK = (24, 25, 27), (225, 225, 220) + + +def font(size): + try: + return ImageFont.truetype("arial.ttf", size) + except OSError: + return ImageFont.load_default() + + +def fit(im, w, h): + """im scaled to fit w x h, centred on the background.""" + k = min(w / im.width, h / im.height) + im = im.resize((max(1, round(im.width * k)), max(1, round(im.height * k))), Image.LANCZOS) + cell = Image.new("RGB", (w, h), BG) + cell.paste(im, ((w - im.width) // 2, (h - im.height) // 2)) + return cell + + +def grid(rows, cell, heads, path, pad=10, head=34): + """rows: [(row label, [images])]; heads: the column titles.""" + w, h = cell + cols = len(heads) + sheet = Image.new("RGB", (pad + cols * (w + pad), head + len(rows) * (h + pad + 26) + pad), BG) + d = ImageDraw.Draw(sheet) + for c, t in enumerate(heads): + d.text((pad + c * (w + pad), 8), t, INK, font(20)) + for r, (label, ims) in enumerate(rows): + y = head + r * (h + pad + 26) + d.text((pad, y + 2), label, INK, font(17)) + for c, im in enumerate(ims): + sheet.paste(fit(im, w, h), (pad + c * (w + pad), y + 24)) + sheet.save(path) + print("WROTE", path, sheet.size) + + +compare, close = [], [] +for stem, title, sheet_name, box, old_path, parts in MECHS: + concept = Image.open(CONCEPTS / sheet_name).convert("RGB") + old, new = Image.open(old_path).convert("RGB"), Image.open(OUT / f"{stem}_new.png").convert("RGB") + compare.append((title, [concept.crop(box), old, new])) + k = old.width / (box[2] - box[0]) + for part, (inset, crop) in parts.items(): + local = [round((crop[i] - box[i % 2]) * k) for i in range(4)] + close.append((f"{title}: {part}", [concept.crop(inset), concept.crop(crop), old.crop(local), Image.open(OUT / f"{stem}_new_{part}.png").convert("RGB")])) +grid(compare, (760, 900), ("concept, hero view", "old paint (the build as its track rendered it)", "new paint: paint.apply()"), OUT / "paint_compare.png") +grid(close, (560, 440), ("concept inset", "concept hero, cropped", "old paint, same crop", "new paint, rendered at the crop"), OUT / "paint_closeups.png") +variants = sorted(OUT.glob("mcr3_variant_*.png")) +if variants: + order = ["seraph", "kestrel", "paladin", "mcr3", "breaker"] + variants.sort(key=lambda f: order.index(f.stem.split("_variant_")[1])) + grid([("paint.apply(preset) on the MCR-3 build, cleanest to most worn", [Image.open(f).convert("RGB") for f in variants])], (460, 740), [f.stem.split("_variant_")[1] for f in variants], OUT / "paint_variants.png") diff --git a/surfaces/blender/experiments/mechs/quadruped.py b/surfaces/blender/experiments/mechs/quadruped.py new file mode 100644 index 0000000..8d9a107 --- /dev/null +++ b/surfaces/blender/experiments/mechs/quadruped.py @@ -0,0 +1,418 @@ +"""Bodies on more than two legs: the skeleton read off a concept sheet's elevations and plan, the cameras of those +views, and the skeleton stood as kit parts with a joint record on every axis. skeleton.py, skel3d.py and mechlib.lay +assume a biped (hip_l, hip_r, a waist, arms); this module takes any set of legs, each named by a tag. + +Plain Python and numpy (no Blender): + + LEGS ("fl", "fr", "rl", "rr"): a tag's first letter is its end (front, rear), its last its + side (l, r). Joints are _: hip_fl, knee_fl, ankle_fl. Any other mark is + a landmark (nose, muzzle, ring ...); _l / _r is a mirrored pair. + stand(name) {mark: [x, y, z]} metres: x to the mech's right, y forward, z up, the origin on the + ground under the landmark concepts.json names as "origin". Heights are the mean of + the elevations that mark the point; x from front and rear (and the plan), y from + the side view and the plan. A point marked on one side takes its twin's mirror. + spread(name) how far the views disagree, metres, per mark: {"z": ..., "x": ..., "y": ...} + elevation_camera(view, world) an elevation's or a plan's camera: far off, square to the sheet, its scale and + centre fitted to the view's marks (two numbers and a scale, least squares). A + camsolve camera dict, so mechlib.shot(solved=...) stands in it. + cameras(name) {view: camera} of every view of concepts.json[name]["skeleton"]: the elevations by + elevation_camera, a perspective view by camsolve.solve + python quadruped.py prints the standing skeleton, the spread and the cameras + +Inside Blender (imports mechlib late): + + write_kit() kits/quadbones.v0.json: `trunk` (the root: a hip socket a leg, a turret socket) and + `bone` (one axis of a joint; a segment). Every socket is a pivot, so every + connection is revolute and takes a joint record. + build(pose, records, legs, ...) the tree stood at `pose`: per leg hip_splay (about y), hip_pitch (x) = the thigh, + knee (x) = the shin, ankle pitch (x) = Ankle., a bone of no length whose `roll` + socket (axis y) takes a foot_core's tongue_roll: a splayed leg stands on a flat foot. A turret: turret_yaw (z), gun_pitch (x). Returns {name: object}. + record(obj, key, records) brokkr_kitbash.joint on a connection + report(root) the brokkr.joints report of the tree + +The sheet's conventions are stated per view in concepts.json: "kind" is front, rear, side, top or perspective; a side +view says "faces": "left" or "right" (where the nose points on the sheet); a top view says "front": "down" or "up".""" +import json +import math +import sys +from pathlib import Path + +import numpy as np + +HERE = Path(__file__).resolve().parent +LEGS = ("fl", "fr", "rl", "rr") +FAR = 600.0 # metres an elevation's camera stands off: at 15 m of depth the scale changes by 2.5% + + +def spec(name): + return json.loads((HERE / "concepts.json").read_text(encoding="utf-8"))[name]["skeleton"] + + +def twin(mark): + """The mirrored mark's name, or None for one on the centre line.""" + if mark[-3:-1] in ("_f", "_r") and mark[-1] in "lr": + return mark[:-1] + ("r" if mark[-1] == "l" else "l") + if mark.endswith("_l"): + return mark[:-2] + "_r" + if mark.endswith("_r"): + return mark[:-2] + "_l" + return None + + +def side_of(mark): + t = twin(mark) + return 0 if t is None else (-1 if mark[-1] == "l" else 1) + + +def _axes(view): + """(right, up) of a view's sheet axes in the world: u grows along right, v falls along up.""" + kind = view["kind"] + if kind == "front": + return (-1, 0, 0), (0, 0, 1) + if kind == "rear": + return (1, 0, 0), (0, 0, 1) + if kind == "side": # nose to the sheet's left: the camera stands on the mech's left, the sheet's u runs aft + return ((0, -1, 0) if view.get("faces", "left") == "left" else (0, 1, 0)), (0, 0, 1) + if kind == "top": # nose down the sheet: u runs to the mech's left, v forward + return ((-1, 0, 0), (0, -1, 0)) if view.get("front", "down") == "down" else ((1, 0, 0), (0, 1, 0)) + raise ValueError(kind) + + +def _readings(name): + s = spec(name) + H, origin = s["height_m"], s.get("origin", "ring") + X, Y, Z = {}, {}, {} + scale = {} + for tag, view in s["views"].items(): + if view["kind"] == "perspective": + continue + J = view["joints"] + k = view.get("scale") or H / (view["ground"] - view["top"]) # a plan has no height: it states metres a pixel + scale[tag] = k + right, up = _axes(view) + for mark, (u, v) in J.items(): + if view["kind"] in ("front", "rear"): + mids = [(J[m][0] + J[twin(m)][0]) / 2 for m in J if twin(m) in J] + u0 = float(np.mean(mids)) if mids else J[origin][0] + X.setdefault(mark, []).append(right[0] * (u - u0) * k) + Z.setdefault(mark, []).append((view["ground"] - v) * k) + elif view["kind"] == "side": + Y.setdefault(mark, []).append(right[1] * (u - J[origin][0]) * k) + Z.setdefault(mark, []).append((view["ground"] - v) * k) + else: + X.setdefault(mark, []).append(right[0] * (u - J[origin][0]) * k) + Y.setdefault(mark, []).append(-up[1] * (v - J[origin][1]) * k * view.get("stretch", 1.0)) + return X, Y, Z, scale + + +def stand(name): + X, Y, Z, _ = _readings(name) + marks = sorted(set(X) | set(Y) | set(Z)) + marks += [twin(m) for m in marks if twin(m) and twin(m) not in marks] + out = {} + for m in marks: + t, sgn = twin(m), side_of(m) + zs = Z.get(m, []) + (Z.get(t, []) if t else []) + ys = Y.get(m, []) + (Y.get(t, []) if t else []) + xs = [abs(x) for x in X.get(m, []) + (X.get(t, []) if t else [])] + if not zs: + continue + out[m] = [sgn * float(np.mean(xs)) if (sgn and xs) else 0.0, float(np.mean(ys)) if ys else 0.0, float(np.mean(zs))] + return out + + +def spread(name): + X, Y, Z, _ = _readings(name) + out = {} + for m in set(X) | set(Y) | set(Z): + t = twin(m) + row = {} + for key, S, mag in (("x", X, True), ("y", Y, False), ("z", Z, False)): + v = S.get(m, []) + (S.get(t, []) if t else []) + v = [abs(q) for q in v] if mag else v + if len(v) > 1: + row[key] = float(max(v) - min(v)) + out[m] = row + return out + + +def elevation_camera(view, world, unit=None): + """A far, square camera of an elevation or a plan, fitted to its marks: u = u0 + k right.p, v = v0 - k up.p.""" + right, up = (np.array(a, float) for a in _axes(view)) + names = [m for m in view["joints"] if m in world] + W, P = np.array([world[m] for m in names], float), np.array([view["joints"][m] for m in names], float) + a, b = W @ right, W @ up + # least squares over k, u0, v0 + A = np.zeros((2 * len(names), 3)) + A[0::2, 0], A[0::2, 1] = a, 1.0 + A[1::2, 0], A[1::2, 2] = -b, 1.0 + k, u0, v0 = np.linalg.lstsq(A, P.ravel(), rcond=None)[0] + look = np.cross(up, right) # the camera's -z in the world + R = np.stack([right, up, -look]) + C = -look * FAR # the scale is exact on the plane through the origin across the line of sight + f = k * FAR + cam = {"C": [float(c) for c in C], "R": [[float(c) for c in row] for row in R], "f": float(f), "c": [float(u0), float(v0)], "box": list(view["box"]), "unit": unit, + "names": names, "model": "elevation", "scale_m_per_px": float(1.0 / k)} + import camsolve + res = camsolve.project(cam, W) - P + cam["rms"] = float(np.sqrt((res ** 2).sum(1).mean())) + cam["residuals"] = {m: [float(c) for c in r] for m, r in zip(names, res)} + cam["lens"] = float(f * 36.0 / (view["box"][2] - view["box"][0])) + cam["azimuth"], cam["elevation"], cam["distance"] = float(math.degrees(math.atan2(-C[0], C[1]))), float(math.degrees(math.asin(C[2] / FAR))), FAR + worst = int(np.argmax(np.linalg.norm(res, axis=1))) + cam["worst"] = [names[worst], float(np.linalg.norm(res[worst]))] + return cam + + +def cameras(name, world=None, models=None): + import camsolve + s = spec(name) + world = world or stand(name) + out = {} + for tag, view in s["views"].items(): + if view["kind"] == "perspective": + marks = {m: p for m, p in view["joints"].items() if m in world} + out[tag] = camsolve.solve(world, marks, view["box"], model=(models or {}).get(tag, "auto"), unit=s["unit"], height_px=view["ground"] - view["top"], horizon=view.get("horizon")) + else: + out[tag] = elevation_camera(view, world, s["unit"]) + return out + + +# --- the skeleton as kit parts ------------------------------------------------------------------------------------------ +KIT = "quadbones" + + +def write_kit(pin=0.2, legs=LEGS): + """kits/quadbones.v0.json in the Brokkr surface the build loads. `pin` is every socket's size: a foot_core seats + on a shin's out_x, so it is twice the foot's pin_r.""" + import mechlib as M + + def P(name, lo, hi, default): + return {"name": name, "type": "number", "min": lo, "max": hi, "default": default, "doc": name} + + def S(name, at, z, y): + return {"name": name, "type": "pivot", "size": "pin", "at": at, "z": z, "y": y} + + stub = {"shape": "box", "size": [0.02, 0.02, 0.02], "at": [0, 0, 0]} + trunk = {"name": "trunk", "doc": "The root of a body on several legs, at the point on the ground its pose is counted from: a hip socket a leg (axis y, the splay; the pitch hangs under it), a turret socket (axis z).", + "params": [P("pin", 0.01, 1.0, pin), P("turret_y", -10.0, 10.0, 0.0), P("turret_z", 0.0, 20.0, 1.0)] + [P(f"{t}_{c}", -20.0, 20.0, 0.0) for t in legs for c in "xyz"], + "shapes": [stub], "sockets": [S(f"hip_{t}", [f"{t}_x", f"{t}_y", f"{t}_z"], "+y", "+z") for t in legs] + [S("turret", [0, "turret_y", "turret_z"], "+z", "+y")]} + bone = {"name": "bone", "doc": "A segment from its origin down -z to `length`, then `ahead` along +y (a turret's trunnion stands ahead of its ring); length 0 for one axis of a joint with several. in_ sockets at the origin, out_ sockets at the tip, one an axis.", + "params": [P("pin", 0.01, 1.0, pin), P("length", -20.0, 20.0, 1.0), P("ahead", -20.0, 20.0, 0.0)], "shapes": [stub], + "sockets": [S("in_x", [0, 0, 0], "-x", "+y"), S("in_y", [0, 0, 0], "-y", "+z"), S("in_z", [0, 0, 0], "-z", "+y"), S("roll", [0, "ahead", "-length"], "-y", "-z"), + S("out_x", [0, "ahead", "-length"], "+x", "+y"), S("out_y", [0, "ahead", "-length"], "+y", "+z"), S("out_z", [0, "ahead", "-length"], "+z", "+y"), + S("clevis", [0, "ahead", "-length"], "-x", "-z")]} + kit = {"schema": "brokkr.kit.v0", "kit": KIT, "doc": "A many-legged skeleton: a revolute socket an axis, metres. An armature, not machinery: hidden from renders.", + "socketTypes": {"pivot": {"match": "equal", "dof": "revolute", "doc": "pin joint; size is the pin diameter"}}, "parts": [trunk, bone]} + path = M.SURFACE / "brokkr_kitbash" / "kits" / f"{KIT}.v0.json" + text = json.dumps(kit, indent=1) + if not path.exists() or path.read_text(encoding="utf-8") != text: + path.write_text(text, encoding="utf-8") + return path + + +def record(obj, key, records, flip=False): + """State a joint's record: the limits are travel either way from the value it stands at; `flip` mirrors them (a + left leg's splay opens the other way round).""" + import bpy + limits, label = records[key] + if flip: + limits = (-limits[1], -limits[0]) + value = float(obj["kit_roll"]) + result = bpy.ops.brokkr_kitbash.joint(object_name=obj.name, record=json.dumps({"limits": [value + limits[0], value + limits[1]], "mechanism": label})) + if "FINISHED" not in result: + raise SystemExit(f"joint record on {obj.name}: {result}") + + +def leg_angles(hip, knee, ankle, sx): + """(splay, pitch, knee) degrees of one leg whose hip is two axes, y then x, and whose knee is one (x): the leg's + plane holds hip, knee and ankle as nearly as a plane through the hip's fore-and-aft axis can (its tilt is the + splay, from the hip to the mean of knee and ankle), the thigh hangs from the hip to the knee's foot in that + plane, the shin on to the ankle's.""" + hip, knee, ankle = (np.array(p, float) for p in (hip, knee, ankle)) + low = (knee + ankle) / 2 - hip + splay = math.atan2(low[0], -low[2]) # about y: positive swings the foot toward +x + c, s = math.cos(splay), math.sin(splay) + out = np.array([c, 0.0, s]) # the plane's normal: the pitch axis (the bone's x after the splay) + down = np.array([s, 0.0, -c]) + fwd = np.array([0.0, 1.0, 0.0]) + + def in_plane(v): + return float(v @ fwd), float(v @ down) + ty, td = in_plane(knee - hip) + sy, sd = in_plane(ankle - knee) + pitch = math.atan2(ty, td) # thigh from straight down toward the front + shin = math.atan2(sy, sd) + return math.degrees(splay), math.degrees(pitch), math.degrees(shin - pitch), math.hypot(ty, td), math.hypot(sy, sd) + + +def build(pose, records, legs=LEGS, pin=0.2, turret=None): + """The tree stood at `pose` ({mark: [x, y, z]}: hip_, knee_, ankle_ a leg). `turret` is {"ring": [x, y, z], + "trunnion": [x, y, z], "yaw": degrees, "pitch": degrees} or None. Returns {name: object}: Trunk, Thigh., + Shin., Ankle., Bone.hip_splay., Aim.Turret, Aim.Gun (named to sort before the legs: a receipt + carries 16000 characters of rows, depth first by name, and the toes of the last foot are what it leaves out). The bones are hidden from renders; each is the host its armour + and machinery are authored on (z up the segment, toward its parent joint; x the pin; y forward at rest).""" + import bpy + from mathutils import Matrix + import mechlib as M + write_kit(pin, legs) + bones = {} + + def place(part, name, **params): + obj = M.place(part, name, kit=KIT, mat="frame", pin=pin, **params) + obj.hide_render = True + obj["armature"] = 1 + bones[name] = obj + return obj + + hips = {f"{t}_{c}": pose[f"hip_{t}"][i] for t in legs for i, c in enumerate("xyz")} + tr = turret or {"ring": [0, 0, 1.0]} + trunk = place("trunk", "Trunk", turret_y=tr["ring"][1], turret_z=tr["ring"][2], **hips) + M.update() + for t in legs: + sx = -1 if t[-1] == "l" else 1 + splay, pitch, knee, l1, l2 = leg_angles(pose[f"hip_{t}"], pose[f"knee_{t}"], pose[f"ankle_{t}"], sx) + b = M.attach(place("bone", f"Bone.hip_splay.{t}", length=0.0), "in_y", trunk, f"hip_{t}", 0.0) + _aim(b, splay_dir(splay)) + record(b, "hip_splay", records, flip=sx > 0) + th = M.attach(place("bone", f"Thigh.{t}", length=l1), "in_x", b, "out_x", 0.0) + _aim(th, np.array(pose[f"knee_{t}"]) - np.array(pose[f"hip_{t}"])) + record(th, "hip_pitch_" + ("front" if t[0] == "f" else "rear"), records) + sh = M.attach(place("bone", f"Shin.{t}", length=l2), "in_x", th, "out_x", 0.0) + _aim(sh, np.array(pose[f"ankle_{t}"]) - np.array(pose[f"knee_{t}"])) + record(sh, "knee_" + ("front" if t[0] == "f" else "rear"), records) + an = M.attach(place("bone", f"Ankle.{t}", length=0.0), "in_x", sh, "out_x", 0.0) # the ankle's pitch; the foot's core rolls on its `roll` socket + _aim(an, (0.0, 1.0, 0.0), axis=(0, 1, 0)) + record(an, "ankle", records) + for o, key in ((b, "hip_splay"), (th, "hip_pitch"), (sh, "knee"), (an, "ankle_pitch")): + o["joint"] = f"{key}_{t}" + if turret: + ring, trun = np.array(turret["ring"], float), np.array(turret["trunnion"], float) + tb = M.attach(place("bone", "Aim.Turret", length=-(trun[2] - ring[2]), ahead=trun[1] - ring[1]), "in_z", trunk, "turret", 0.0) + bpy.ops.brokkr_kitbash.roll(object_name=tb.name, roll=float(tb["kit_roll"]) + turret.get("yaw", 0.0)) + record(tb, "turret_yaw", records) + gun = M.attach(place("bone", "Aim.Gun", length=0.0), "in_x", tb, "out_x", 0.0) + _aim(gun, (0.0, math.cos(math.radians(turret.get("pitch", 0.0))), math.sin(math.radians(turret.get("pitch", 0.0)))), axis=(0, 1, 0)) + record(gun, "gun_pitch", records) + tb["joint"], gun["joint"] = "turret_yaw", "gun_pitch" + M.update() + return bones + + +def splay_dir(splay): + s = math.radians(splay) + return (math.sin(s), 0.0, -math.cos(s)) + + +def _aim(obj, toward, axis=(0, 0, -1)): + """Turn an attached bone about its pin until its own `axis` points as near `toward` as the pin lets it + (brokkr_kitbash.aim: solved, not searched).""" + import mechlib as M + M.aim_roll(obj, axis, toward) + + +def miss(bones, pose, legs=LEGS): + """The worst distance, metres, between the tree's joints and the pose's.""" + import mechlib as M + from mathutils import Vector + M.update() + worst = 0.0 + for t in legs: + th, sh = bones[f"Thigh.{t}"], bones[f"Shin.{t}"] + L = float(json.loads(sh["kit_params"])["length"]) + for got, want in ((th.matrix_world.translation, pose[f"hip_{t}"]), (sh.matrix_world.translation, pose[f"knee_{t}"]), (sh.matrix_world @ Vector((0, 0, -L)), pose[f"ankle_{t}"])): + worst = max(worst, (got - Vector(want)).length) + return worst + + +def report(root, more=()): + """The brokkr.joints report of the tree under `root`. A receipt carries 53 rows and counts the rest in + jointsOmitted (four feet of nine toe joints each fill it); `more` names sub-trees to report on their own, whose + rows are added where the first report left them out (a row's parent stays the id it names).""" + import bpy + import mechlib as M + + def one(obj): + result = bpy.ops.brokkr_kitbash.joints(object_name=obj.name) + if "FINISHED" not in result: + raise SystemExit(f"joints report: {result}") + return json.loads(getattr(bpy.context.window_manager, M.KB.RESULT)) + out = one(root) + have = {r["id"] for r in out["joints"]} + for obj in more: + sub = one(obj) + if obj.get("kit_parent") and obj.name not in have: # the sub-tree's own connection to the tree + pass + for r in sub["joints"]: + if r["id"] not in have: + out["joints"].append(dict(r, frame=obj.name)) + have.add(r["id"]) + out["jointsOmitted"] = max(0, out.get("jointsOmitted", 0) - sum(1 for r in out["joints"] if r.get("frame"))) + return out + + +if __name__ == "__main__": + name = sys.argv[1] + J, S = stand(name), spread(name) + for k, (x, y, z) in J.items(): + print(f" {k:12s} x {x:6.2f} y {y:6.2f} z {z:5.2f} views disagree by " + ", ".join(f"{a} {v:.2f}" for a, v in S.get(k, S.get(twin(k) or "", {})).items())) + import camsolve + for tag, cam in cameras(name).items(): + if cam["model"] == "elevation": + print(f"CAMERA {tag}: elevation, {len(cam['names'])} marks, rms {cam['rms']:.1f} px, worst {cam['worst'][0]} {cam['worst'][1]:.1f}; {cam['scale_m_per_px']:.4f} m/px") + else: + print("\n".join(camsolve.report(tag, cam))) + for k, (du, dv) in cam["residuals"].items(): + print(f" {k:11s} {du:+6.1f} {dv:+6.1f}") + + +# --- rams across a bone's joint ---------------------------------------------------------------------------------------- +def drive(name, parent, child, a, b, bore, limits, mat="machine", twin=0.0): + """A ram across the revolute joint that hangs `child` (a bone) on `parent`, by ram core (brokkr_kitbash/ram.py): + its base at `a` in the parent's frame, its eye at `b` in the child's frame (each one point or a list of seats: the + best of the grid is taken by ram.search, and a grid none of which fits draws nothing), both at the pose as it + stands, which is the mechanism's angle 0; `limits` are the joint's travel either way from there (lo, hi), degrees. The gates + (assembly, stroke, arm) are read over that range and printed; the record is kept on the child as the JSON + property quad_ram. Drawn at the pose: a barrel on a clevis and trunnion block, a gland, a chromed rod, an eye, + as a child of `parent` (the barrel) - `twin` draws a pair that far either side along the pin. Returns the Fit.""" + import bpy + from mathutils import Matrix, Vector + import mechlib as M + from brokkr_kitbash import ram as R + M.update() + to_parent = parent.matrix_world.inverted() @ child.matrix_world + pivot = to_parent.translation + axis = (to_parent.to_3x3() @ Vector((1, 0, 0))).normalized() + many = lambda q: [q] if isinstance(q[0], (int, float)) else list(q) # noqa: E731 + seats = {"a": [list(Vector(q)) for q in many(a)], "b": [list(to_parent @ Vector(q)) for q in many(b)]} + found = None + for scale in (1.0, 0.8, 0.64): + body = R.Ram(bore * scale) + found = R.search("direct", {"pivot": list(pivot), "axis": list(axis), "lo": float(limits[0]), "hi": float(limits[1])}, body, seats) + print(f"RAM {name} bore {bore * scale:.3f}: {found.report()}", flush=True) + if found.found: + break + if not found.found: + return None, [] + fit, bore = found.best, body.bore + m = fit.m + child["quad_ram"] = json.dumps(R.record(m, body)) + p = R.pose(m, [0.0]) + base, eye, u, L = Vector(p.base[0]), Vector(p.eye[0]), Vector(p.u[0]), float(p.L[0]) + barrel = fit.barrel if fit.barrel and fit.barrel > 0 else 0.55 * L + g, rod, lug = M.Geo(), M.Geo(), M.Geo() + side = Vector(axis) + for off in ((-twin, twin) if twin else (0.0,)): + o = side * off + at = M.frame_at(base + o, u, side) + g.lathe(at, [(0, body.e_a), (body.barrel_r, body.e_a), (body.barrel_r, body.e_a + barrel - 0.6 * bore), (1.15 * body.barrel_r, body.e_a + barrel - 0.6 * bore), (1.15 * body.barrel_r, body.e_a + barrel), (0, body.e_a + barrel)], 24) + g.lathe(at, [(0, 0.3 * bore), (0.8 * bore, 0.3 * bore), (0.8 * bore, body.e_a), (0, body.e_a)], 16) + g.cylinder(M.frame_at(base + o, side), 0.9 * bore, 1.5 * bore, 16) + g.rod(base + o + u * (body.e_a + 0.2 * barrel) + side.cross(u) * 1.3 * body.barrel_r, base + o + u * (body.e_a + 0.9 * barrel) + side.cross(u) * 1.3 * body.barrel_r, 0.22 * bore, 8) + rod.lathe(at, [(0, body.e_a + 0.5 * barrel), (body.rod, body.e_a + 0.5 * barrel), (body.rod, L - 0.9 * bore), (0, L - 0.9 * bore)], 20) + g.cylinder(M.frame_at(eye + o, side), 1.0 * bore, 1.2 * bore, 16) + for end in (base + o, eye + o): + for s in (-1, 1): + lug.cylinder(M.frame_at(end + side * s * 1.05 * bore, side), 1.3 * bore, 0.5 * bore, 12) + out = [g.to_object(f"{name}.barrel", mat, parent), rod.to_object(f"{name}.rod", "steel", parent), lug.to_object(f"{name}.lugs", "gunmetal", parent)] + return fit, out