experiments/mechs: KESTREL (sheet 29) on its skeleton; canted hips, a drum shoulder, flow lines, masses, a parts bench with variants, per-component sheets

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-12-02 16:53:23 +01:00
commit 818ec96243
7 changed files with 1639 additions and 38 deletions

View file

@ -10,6 +10,13 @@ with `quick`). Writes, under MECH_OUT/compare/:
<name>_trace.png the traced outline drawn on the concept, to check the trace itself
<name>_components.png each component crop of the sheet (concepts.json "components") beside that part built alone
(part_bench.py)
<name>_component_<part>.png, <name>_catalog.png a sheet a component (the crop, the part alone, the frame under its
plates, its parameter variant, the same place on the mech) and all of them stacked: the catalog
the silhouette sheet's second row, where concepts.json gives "flat" (the sheet's front, rear and side views on their
flat backdrop): each view's mask read off the backdrop, against the build's same view
<name>_flow.png the concept's main flow lines (concepts.json "flow", marked by hand on the hero view) beside
the same lines on the build (mechlib.flow: points on the parts that carry each line), with
each line's largest and summed turn: ruling mech-flow-lines-across-parts
<name>_proportions.png the concept's rear and hero views with their marked skeleton (concepts.json) drawn on,
each beside the build's same view with its own joints projected on (<name>_skeleton.json,
from mechlib.field_views), and skeleton.table() of each pair: joint heights, spans and
@ -129,7 +136,42 @@ if "icon" in spec:
both, iou, ar_c, ar_o = overlay(icon, front, H - 60)
panels += [label(black(icon, H - 60), "concept, front icon from the sheet"), label(both, f"icon red, our front blue; overlap {iou:.2f}; w/h {ar_c:.2f} vs {ar_o:.2f}")]
print(f"SILHOUETTE {name} front icon: overlap {iou:.3f}, width/height concept {ar_c:.3f} ours {ar_o:.3f}")
row(panels, H).save(dst / f"{name}_silhouette.png")
sil_rows = [row(panels, H)]
if "flat" in spec: # the sheet's front, rear and side views stand on a flat backdrop: their masks are read, not traced
from PIL import ImageFilter, ImageChops
def flat_mask(box):
"""A view on a flat backdrop as a mask: what differs from the backdrop's own grey (the median of the crop's top
corners) by more than 9 of 255 in any channel, closed over 7 px and filled where the backdrop is enclosed."""
img = crop(box)
corners = [img.getpixel(q) for q in ((2, 2), (img.width - 3, 2), (2, 12), (img.width - 3, 12), (img.width // 2, 2))]
back = tuple(sorted(c[i] for c in corners)[len(corners) // 2] for i in range(3))
diff = ImageChops.difference(img, Image.new("RGB", img.size, back))
m = diff.convert("L").point(lambda v: 255 if v > 9 else 0)
r, g, b = diff.split()
m = ImageChops.lighter(ImageChops.lighter(r, g), b).point(lambda v: 255 if v > 9 else 0)
m = m.resize((m.width * 4, m.height * 4), Image.LANCZOS).point(lambda v: 255 if v > 127 else 0)
m = m.filter(ImageFilter.MaxFilter(7)).filter(ImageFilter.MinFilter(7))
from PIL import ImageDraw as _D
hole = m.copy()
frame = Image.new("L", (m.width + 2, m.height + 2), 0)
frame.paste(hole, (1, 1))
_D.floodfill(frame, (0, 0), 128)
filled = frame.point(lambda v: 0 if v == 128 else 255).crop((1, 1, m.width + 1, m.height + 1))
return trimmed(filled)
flats = []
for tag, box in spec["flat"].items():
path = src / f"{name}_sil_{tag}.png"
if not path.exists():
continue
concept_m, ours_m = flat_mask(box), render_mask(tag)
both, iou, ar_c, ar_o = overlay(concept_m, ours_m, H - 60)
print(f"SILHOUETTE {name} {tag} (read from the sheet): overlap {iou:.3f}, width/height concept {ar_c:.3f} ours {ar_o:.3f}")
flats += [label(black(concept_m, H - 60), f"concept, {tag} view (read off the backdrop)"), label(both, f"{tag}: red concept, blue ours; overlap {iou:.2f}; w/h {ar_c:.2f} vs {ar_o:.2f}")]
if flats:
sil_rows.append(row(flats, H))
stack(sil_rows).save(dst / f"{name}_silhouette.png")
rows = []
for tag, box in spec["joints"].items():
@ -163,6 +205,28 @@ if "components" in spec and (src / "parts").is_dir():
x += c.width + 8
canvas.save(dst / f"{name}_components.png")
canvas.resize((2400, max(1, round(canvas.height * 2400 / canvas.width))), Image.LANCZOS).save(dst / f"{name}_components_small.jpg", quality=88)
# a sheet a component, and the catalog: the crop, the part alone, its frame view, its parameter variant, its name and sizes
notes = json.loads((src / "parts" / "catalog.json").read_text(encoding="utf-8")) if (src / "parts" / "catalog.json").exists() else {}
lines = []
for tag, box in comp["crops"].items():
path = src / "parts" / f"{tag}.png"
if not path.exists():
continue
note = notes.get(tag, {})
cells = [label(fit(sheet.crop(tuple(int(v * kc) for v in box)), 520), "concept: " + comp["labels"][tag]), label(fit(Image.open(path), 520), f"{note.get('module', name + '_parts')}.{note.get('function', tag)}()")]
for suffix, text in (("_frame", "the frame under its plates"), ("_var", "variant: " + ", ".join(f"{k}={v}" for k, v in note.get("variant", {}).items()))):
extra = src / "parts" / f"{tag}{suffix}.png"
if extra.exists():
cells.append(label(fit(Image.open(extra), 520), text))
if (src / f"{stem}_insitu_{tag}.png").exists():
cells.append(label(fit(Image.open(src / f"{stem}_insitu_{tag}.png"), 520), "on the mech, the same side"))
line = row(cells, 520)
line.save(dst / f"{name}_component_{tag}.png")
lines.append(line)
if lines:
sheet_all = stack(lines)
sheet_all.save(dst / f"{name}_catalog.png")
sheet_all.resize((2000, max(1, round(sheet_all.height * 2000 / sheet_all.width))), Image.LANCZOS).save(dst / f"{name}_catalog_small.jpg", quality=86)
BONES = (("shoulder_l", "shoulder_r"), ("hip_l", "hip_r"), ("waist", "shoulder_l"), ("waist", "shoulder_r"), ("waist", "hip_l"), ("waist", "hip_r")) + tuple(
(a + s, b + s) for s in ("_l", "_r") for a, b in (("shoulder", "elbow"), ("elbow", "wrist"), ("hip", "knee"), ("knee", "ankle")))
@ -212,7 +276,50 @@ if "skeleton" in spec and sk_path.exists():
panels += [label(fit(concept_img, H), f"concept, {view}: marked skeleton"), label(fit(ours_img, H), f"ours, {view}: the build's joints"), text]
row(panels, H).save(dst / f"{name}_proportions.png")
for f in ("vs_concept", "silhouette", "joints", "proportions"):
def turns(points):
"""The largest and the summed turn, in degrees, along a polyline: a line that flows turns a little at a time."""
import math
out = []
for a, b, c_ in zip(points, points[1:], points[2:]):
u, v = (b[0] - a[0], b[1] - a[1]), (c_[0] - b[0], c_[1] - b[1])
out.append(abs(math.degrees(math.atan2(u[0] * v[1] - u[1] * v[0], u[0] * v[0] + u[1] * v[1]))))
return (max(out), sum(out)) if out else (0.0, 0.0)
if "flow" in spec and sk_path.exists() and "flow" in json.loads(sk_path.read_text(encoding="utf-8"))["views"].get("hero", {}):
ours_flow = json.loads(sk_path.read_text(encoding="utf-8"))["views"]["hero"]
colours = [(255, 60, 40), (255, 200, 0), (60, 220, 90), (60, 180, 255), (230, 90, 255), (255, 140, 0), (0, 230, 220)]
box = spec["hero"]
a_img, b_img = crop(box).convert("RGB"), hero.convert("RGB")
da, db = ImageDraw.Draw(a_img), ImageDraw.Draw(b_img)
kb = hero.width / ours_flow["size"][0]
rows_txt = [f"{'line':13s} {'concept':>15s} {'ours':>15s}", f"{'':13s} {'max / sum turn':>15s} {'max / sum turn':>15s}"]
worst = 0.0
for i, (line, pts) in enumerate(spec["flow"].items()):
col = colours[i % len(colours)]
cp = [((x - box[0]) * k, (y - box[1]) * k) for x, y in pts]
da.line(cp, fill=col, width=5)
op = [(x * kb, y * kb) for x, y in ours_flow["flow"].get(line, [])]
if len(op) > 1:
db.line(op, fill=col, width=5)
for x, y in op:
db.ellipse((x - 5, y - 5, x + 5, y + 5), fill=col, outline=(0, 0, 0))
(cm, cs), (om, os_) = turns(cp), turns(op)
worst = max(worst, om - cm)
rows_txt.append(f"{line:13s} {cm:6.0f} /{cs:5.0f} {om:6.0f} /{os_:5.0f}")
print(f"FLOW {name}: worst excess turn at one point {worst:.0f} degrees")
for line in rows_txt:
print(" " + line)
try:
mono = ImageFont.truetype("consola.ttf", 24)
except OSError:
mono = font
text = Image.new("RGB", (640, H), (24, 24, 24))
ImageDraw.Draw(text).text((14, 44), chr(10).join(["flow lines, hero view: turn in degrees", "(a line that flows turns a little at a", " time; a step or a zigzag turns a lot)", ""] + rows_txt + ["", f"worst excess turn {worst:.0f}"]),
fill=(235, 235, 235), font=mono, spacing=8)
row([label(fit(a_img, H), "concept: its main flow lines (marked by hand)"), label(fit(b_img, H), "ours: the same lines, on the parts that carry them"), text], H).save(dst / f"{name}_flow.png")
for f in ("vs_concept", "silhouette", "joints", "proportions", "flow"):
p = dst / f"{name}_{f}.png"
if p.exists():
im = Image.open(p)

View file

@ -891,5 +891,711 @@
}
}
},
"_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.",
"kestrel": {
"sheet": "29.webp",
"unit": 1024,
"hero": [
0,
0,
520,
800
],
"rear": [
700,
10,
862,
335
],
"joints": {},
"labels": {},
"flat": {
"front": [
522,
10,
695,
330
],
"rear": [
700,
10,
862,
330
],
"side": [
866,
10,
1020,
330
]
},
"outline": [
[
316,
26
],
[
368,
20
],
[
392,
24
],
[
400,
58
],
[
437,
62
],
[
439,
89
],
[
463,
97
],
[
466,
126
],
[
453,
158
],
[
476,
211
],
[
497,
232
],
[
497,
337
],
[
495,
400
],
[
474,
437
],
[
447,
426
],
[
439,
368
],
[
437,
295
],
[
426,
232
],
[
416,
174
],
[
405,
247
],
[
416,
274
],
[
416,
437
],
[
437,
458
],
[
458,
526
],
[
474,
674
],
[
492,
684
],
[
495,
737
],
[
505,
758
],
[
474,
774
],
[
400,
789
],
[
363,
774
],
[
400,
737
],
[
421,
684
],
[
416,
579
],
[
368,
489
],
[
337,
474
],
[
326,
368
],
[
311,
337
],
[
274,
337
],
[
253,
347
],
[
221,
437
],
[
268,
500
],
[
263,
553
],
[
237,
684
],
[
247,
726
],
[
263,
742
],
[
226,
753
],
[
174,
737
],
[
126,
758
],
[
68,
753
],
[
63,
742
],
[
142,
700
],
[
195,
679
],
[
189,
553
],
[
174,
489
],
[
132,
474
],
[
129,
421
],
[
158,
358
],
[
200,
274
],
[
174,
337
],
[
32,
426
],
[
11,
416
],
[
8,
400
],
[
105,
263
],
[
142,
247
],
[
158,
174
],
[
153,
137
],
[
179,
95
],
[
216,
89
],
[
247,
74
]
],
"skeleton": {
"unit": 1024,
"height_m": 9.8,
"views": {
"rear": {
"box": [
700,
10,
862,
335
],
"ground": 320,
"top": 25,
"joints": {
"shoulder_l": [
730,
75
],
"shoulder_r": [
827,
75
],
"elbow_l": [
721,
127
],
"elbow_r": [
843,
127
],
"waist": [
779,
117
],
"hip_l": [
750,
137
],
"hip_r": [
810,
137
],
"knee_l": [
740,
215
],
"knee_r": [
819,
215
],
"ankle_l": [
730,
295
],
"ankle_r": [
832,
295
]
}
},
"hero": {
"box": [
0,
0,
520,
800
],
"ground": 779,
"top": 21,
"joints": {
"shoulder_r": [
174,
153
],
"shoulder_l": [
416,
124
],
"elbow_r": [
163,
258
],
"elbow_l": [
474,
232
],
"wrist_r": [
105,
316
],
"wrist_l": [
468,
358
],
"waist": [
295,
226
],
"hip_r": [
234,
295
],
"hip_l": [
392,
263
],
"knee_r": [
197,
447
],
"knee_l": [
397,
437
],
"ankle_r": [
213,
684
],
"ankle_l": [
468,
697
]
}
}
}
},
"components": {
"unit": 1024,
"crops": {
"hull": [
523,
352,
776,
530
],
"cooling": [
780,
352,
1022,
530
],
"shoulder": [
523,
552,
720,
728
],
"weapon_arm": [
724,
552,
890,
728
],
"manipulator": [
894,
552,
1022,
728
],
"knee": [
523,
748,
666,
985
],
"lower_leg": [
668,
748,
776,
985
],
"foot": [
779,
748,
910,
985
],
"foot_rear": [
913,
748,
1022,
985
],
"thigh": [
300,
225,
420,
470
],
"pelvis": [
225,
215,
350,
340
]
},
"labels": {
"hull": "COCKPIT / SENSOR ARRAY",
"cooling": "REAR COOLING UNITS",
"shoulder": "SHOULDER ASSEMBLY",
"weapon_arm": "WEAPON ARM",
"manipulator": "MANIPULATOR",
"knee": "KNEE ASSEMBLY",
"lower_leg": "LOWER LEG",
"foot": "FOOT (FRONT)",
"foot_rear": "FOOT (REAR)",
"thigh": "left thigh and hip (hero view)",
"pelvis": "pelvis (hero view)"
}
},
"flow": {
"ridge": [
[
379,
24
],
[
316,
47
],
[
253,
84
],
[
224,
118
],
[
211,
184
],
[
218,
253
]
],
"chine": [
[
368,
124
],
[
326,
168
],
[
268,
224
],
[
221,
258
]
],
"leg_l_outer": [
[
405,
247
],
[
415,
342
],
[
406,
437
],
[
442,
526
],
[
466,
632
],
[
476,
695
],
[
489,
758
]
],
"leg_l_front": [
[
332,
284
],
[
337,
395
],
[
368,
489
],
[
416,
579
],
[
429,
679
],
[
389,
774
]
],
"leg_r_front": [
[
221,
295
],
[
158,
379
],
[
132,
463
],
[
184,
532
],
[
196,
679
],
[
95,
737
]
],
"arm_l": [
[
442,
124
],
[
463,
174
],
[
480,
232
],
[
474,
295
],
[
471,
358
],
[
461,
432
]
],
"arm_r": [
[
174,
153
],
[
158,
205
],
[
164,
258
],
[
95,
337
],
[
16,
405
]
]
}
}
}

View file

@ -0,0 +1,87 @@
"""KESTREL: the operator's concept sheet 29 (images/29.webp), a 9.8 m recon and strike walker, assembled from its
components on its skeleton. kestrel_parts.py builds each component to its inset (detail) and to the front, rear, side
and hero views (orientation and exposure); this file lays the biped on the solved skeleton and seats them.
The joints, as the sheet draws them: canted side-bearing hips (the feet stand 0.7 m wider than the hips), disc-capped
pin knees, a two-axis ankle, drum shoulders (one pitch bearing, no abduction), a waist ring on a thin spine.
MECH_STAGE=1 stops at the bare skeleton."""
import math, os, sys, time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
import mechlib as M
import skeleton
import kestrel_parts as KP
from mathutils import Matrix, Vector
import bpy
t0 = time.time()
M.setup()
F, T = M.frame_at, Matrix.Translation
STAGE = int(os.environ.get("MECH_STAGE", "3"))
SK = skeleton.solve("kestrel")
CROSS = 0.3
CFG = dict(pelvis=dict(ring_r=0.36, top_r=0.3, depth=0.9), hip_h=0.22, links=[(0, 0.5, 0.55), (0, 0.42, 0.5)], pin_r=0.1, bore=0.08, foot=(0.5, 0.7, 0.8), foot_part="trident",
knee="none", ankle="cross", ankle_drive="none", cross_drop=CROSS, waist_h=0.12, twist=0,
chassis=dict(width=1.8, depth=0.8, top_r=0.2, side_r=0.35), arms="drum",
arm=dict(pin_r=0.08, width=0.4, depth=0.45, fore={"L": 1.3, "R": 0.7}, face_r=0.2),
aims={"L": (None, None, (-0.25, 0.2, -1)), "R": (None, None, (0.25, 1, -0.7))}, guns={})
M.lay(SK, CFG, hull_top=8.31, depth={"L": (0.95, -0.2), "R": (0.7, -0.45)}, elbow_y={"L": 0.15, "R": -0.25}, splay=0.0, cant=skeleton.cant(SK))
CFG["foot"] = (CFG["foot"][0], CFG["foot"][1], CFG["foot"][2] - CROSS)
print("CFG", {k: v for k, v in CFG.items() if k in ("pelvis", "links", "chassis", "arm", "hip_cant")})
body = M.biped(CFG)
pel, legs, core, arms = body["pelvis"], body["legs"], body["core"], body["arms"]
CH = CFG["chassis"]["height"]
MIR = Matrix.Diagonal((-1.0, 1.0, 1.0, 1.0))
def put(name, fn, host, to_host, lines=None, **kw):
"""Build one component on its host, put its cut shells to rest, and add its edges to the figure's flow lines:
`lines` maps a line of the component (Build.lines, set by the function) to a flow line of the figure."""
before, t = set(bpy.data.objects.keys()), time.time()
build = M.Build(name, host, to_host)
fn(build, **kw)
build.done()
M.rest(before)
for own, line in (lines or {}).items():
M.flow(line, host, to_host, build.lines[own])
print("PUT", name, round(time.time() - t, 1), flush=True)
return build
if STAGE > 1:
# the leg's two long lines, hip to ankle: the plates' width and the stand-off of their faces, carried through the knee
W, FACE = (0.8, 0.62, 0.42), (0.46, 0.52, 0.36)
# --- torso: the hull on the torso frame, the cooling units on its roof and down its back, a shoulder assembly a side ---
put("Hull", KP.hull, core, None, lines={"ridge": "ridge", "chine": "chine"})
put("Cooling", KP.cooling, core, None)
to_core = core.matrix_world.inverted()
for side, arm in arms.items():
sx, up, fore = arm["sx"], arm["upper"], arm["fore"]
line = {"outer": "arm_l" if side == "L" else "arm_r"}
put(f"Shoulder{side}", KP.shoulder, core, T(to_core @ up.matrix_world.translation) @ (MIR if sx > 0 else Matrix.Identity(4)), lines=line, drum=CFG["arm"]["drum"] + 0.42)
put(f"UpperArm{side}", KP.upper_arm, up, M.seat(up, outboard=-1, side=sx), lines=line, length=CFG["arm"]["upper"])
if side == "L":
put("Manipulator", KP.manipulator, fore, M.seat(fore, outboard=-1, side=sx), lines=line, fore=CFG["arm"]["fore"]["L"])
else:
put("WeaponArm", KP.weapon_arm, fore, M.seat_along(fore), lines=line)
# --- pelvis and legs --------------------------------------------------------------------------------------------------
put("PelvisDress", KP.pelvis, pel, None, span=CFG["pelvis"]["span"], drum=CFG["hip_h"] + 0.04)
(L1, _, _), (L2, _, _) = CFG["links"]
for side, leg in legs.items():
sx = -1 if side == "L" else 1
thigh, shin = leg["links"]
line = {"outer": "leg_l_outer", "inner": "leg_l_front"} if side == "L" else {"outer": "leg_r_front"}
put(f"Thigh{side}", KP.thigh, thigh, M.seat(thigh, outboard=-1, side=sx), lines=line, length=L1, width=W[:2], front=FACE[:2])
put(f"Knee{side}", KP.knee, shin, M.seat(shin, outboard=-1, side=sx), lines=line, cap=(W[1], 0.86), front=FACE[1])
put(f"LowerLeg{side}", KP.lower_leg, shin, M.seat(shin, outboard=-1, side=sx), lines=line, length=L2, width=W[1:], front=FACE[1:])
put(f"Foot{side}", KP.foot, leg["foot"], M.seat(leg["foot"], (0, 0, -CROSS), outboard=-1, side=sx), lines=line, drop=SK["joints"]["ankle"][1])
M.wake()
lo, _ = M.bounds()
pel.location.z -= lo.z
M.update()
M.reskin({"frame": "gunmetal", "machine": "gunmetal", "structure": "gunmetal"})
lo, hi = M.bounds()
print("HEIGHT", round(hi.z - lo.z, 2), "WIDTH", round(hi.x - lo.x, 2), "DEPTH", round(hi.y - lo.y, 2))
M.report_skeleton("kestrel", body)
M.field_views("kestrel", t0, hero=(24.0, 3.0), rear=(180.0, 2.0), turns=(90,), samples=64, hero_size=(1600, 2400), joints=M.joint_points(body),
hero_cam=dict(lens=30.0, eye=2.4, margin=0.8), rear_cam=dict(lens=70.0, eye=3.0, margin=0.8))

View file

@ -0,0 +1,435 @@
"""KESTREL's components (concept sheet 29, images/29.webp), one function per component, each built to its inset of
the sheet for detail and to the front, rear, side and hero views for orientation and exposure. A function takes a
mechlib.Build and keyword sizes in metres at the sheet's 9.8 m, and draws in the Build's frame: x to the mech's
right, y forward, z up. A sided component is drawn as the mech's LEFT one (outboard is -x); the assembly mirrors it.
Armour is brokkr_kitbash.shell sheets (M.shell_action), cut by cut_many (M.cuts_action) and stood on ribs
(M.ribs_action); solid blocks (toes, the knee cap, the shoulder's shield) are M.mass, cut by M.cuts_on; machinery is
Geo on the Build. part_bench.py builds each alone; compare.py sets it beside its crop.
PARTS: name -> function. VIEWS: name -> (azimuth, elevation, margin, pitch) of the bench camera, the inset's side.
VARIANTS: name -> keyword sizes of a second build for the catalog. GROUND: origin heights on the bench."""
import math
from mathutils import Matrix, Vector
import mechlib as M
F, T = M.frame_at, Matrix.Translation
RX = lambda deg: Matrix.Rotation(math.radians(deg), 4, "X")
RY = lambda deg: Matrix.Rotation(math.radians(deg), 4, "Y")
RZ = lambda deg: Matrix.Rotation(math.radians(deg), 4, "Z")
ALONG_Y = F((0, 0, 0), (0, 1, 0), (0, 0, 1)) # a frame whose z is y: lathes and prisms that run forward
OUT = lambda x, y, z: F((x, y, z), (-1, 0, 0), (0, 0, 1)) # a frame on a left part's outer face: z out (-x), y up
P, D = "khaki", "gunmetal"
def red():
if "sensor_red" not in M.MATS:
M.material("sensor_red", (0.03, 0.005, 0.003), 0.0, 0.25, emission=((1.0, 0.12, 0.03), 4.0))
return "sensor_red"
def both(cuts):
"""Each cut and its mirror across x, for a mirrored sheet: a ray reaches one side only."""
out = []
for cut in cuts:
flip = lambda v: [-v[0], v[1], v[2]]
out += [{**cut, "name": cut["name"] + "_l"}, {**cut, "name": cut["name"] + "_r", **{k: flip(cut[k]) for k in ("origin", "direction", "up", "axis") if k in cut}}]
return out
def slab(name, origin, direction, up, length, gap=0.022, depth=0.016):
return {"name": name, "part": "slab", "params": f"gap={gap:g}; length={length:g}; depth={depth:g}", "origin": list(origin), "direction": list(direction), "up": list(up)}
def box(name, origin, direction, width, height, depth, up=(0, 0, 1), lift=0.05, **kw):
return {"name": name, "part": "box", "params": f"width={width:g}; height={height:g}; depth={depth:g}; lift={lift:g}", "origin": list(origin), "direction": list(direction), "up": list(up), **kw}
def cyl(name, origin, direction, r, depth, **kw):
return {"name": name, "part": "cyl", "params": f"r={r:g}; depth={depth:g}", "origin": list(origin), "direction": list(direction), **kw}
def ribbed_drum(g, frame, r, length, ribs, groove=0.06):
"""A drum of raised bands: the shoulder's and the hip's bearing housing. z along the frame's z from 0 to length."""
step = length / ribs
profile = [(0.0, 0.0)]
for k in range(ribs):
z0 = k * step
profile += [(r - groove, z0), (r - groove, z0 + 0.15 * step), (r, z0 + 0.25 * step), (r, z0 + 0.8 * step), (r - groove, z0 + 0.9 * step)]
profile += [(r - groove, length), (0.0, length)]
return g.lathe(frame, profile, 40)
# --- hull -----------------------------------------------------------------------------------------------------------
def hull(b, nose=2.56, drop=0.95, half=1.04, tail=1.5, slope=32.0, crest=1.72, number="07", lenses=4):
"""COCKPIT / SENSOR ARRAY (inset 1) and the hull of the front and hero views. Origin at the foot of the torso
frame, on the waist's axis. A long wedge carried nose-down: a roof plate of two facets a side falling `slope`
degrees (the front and hero views show its top; the side view draws it flatter) from the tail to a brow lip, its
ridge `crest` above the origin there; under it the body, one mirrored sheet whose stem runs from under the brow
down to a beak `drop` below the origin and `nose` ahead of it, creased down the stem, at the front corner, along
the cheek and along the belly chine. The roof's edge runs on into the front corner and the chine into the beak:
the hull's two flow lines. A sensor bay cut into the stem under the brow with `lenses` red lenses, two to a row;
the number stencilled on the left cheek; panel breaks across the roof and down the cheeks; a port through each
cheek for the shoulder's drum; a tooth notched out of the beak's edge. Under roof and body their frames."""
g = b[D]
k = nose / 2.56
fall = math.tan(math.radians(slope))
top = lambda y: crest - fall * y # the roof's ridge line
body = {"mirror": True, "rings": [
[[0, 2.3 * k, top(2.3 * k) - 0.18], [0.52, 2.24 * k, top(2.3 * k) - 0.27], [half, 0.3, top(0.3) - 0.32], [0.92 * half, -tail, top(-tail) - 0.32]],
[[0, 2.42 * k, 0.7 - drop], [0.46, 2.3 * k, 0.7 - drop], [half + 0.04, 0.3, 0.6], [0.95 * half, -tail, 1.5]],
[[0, 2.5 * k, 0.33 - drop], [0.32, 2.38 * k, 0.35 - drop], [0.87 * half, 0.4, 0.0], [0.73 * half, -tail, 0.7]],
[[0, nose, -drop], [0.16, 2.44 * k, 0.05 - drop], [0.5, 0.75, -0.2], [0.36, 0.2 - tail, 0.35]]],
"creases": [{"column": 0, "from": 0, "to": 3, "weight": 1.0}, {"column": 1, "from": 0, "to": 3, "weight": 1.0}, {"ring": 1, "from": 1, "to": 3, "weight": 0.8},
{"ring": 2, "from": 1, "to": 3, "weight": 1.0}, {"ring": 2, "from": 0, "to": 1, "weight": 0.6}]}
name = b.name + ".body"
M.shell_action(name, M.face_out(body, (0, 1, 0)), b, P, thickness=0.035, levels=2, bevel=0.012)
sh_z, bay = min(1.28, top(0) - 0.5), 0.5 * (body["rings"][0][0][2] + body["rings"][1][0][2])
M.cuts_action(name, [box(name + ".bay", (0, 6, bay), (0, -1, 0), 0.62, 0.26, 0.5, lift=0.1, axis=[0, 1, 0])] + both([
slab(name + ".cheek_a", (4, 1.25 * k, 0.1), (-1, 0, 0), (0, 0, 1), 0.9),
slab(name + ".cheek_b", (4, -0.75, 1.2), (-1, 0, 0), (0, 0, 1), 1.0),
slab(name + ".cheek_c", (4, 0.3, 0.4), (-1, 0, 0), (0, 1, 0), 1.6),
slab(name + ".nose_a", (0.25, 6, 0.5 - drop), (0, -1, 0), (1, 0, 0), 0.3),
cyl(name + ".port", (4, 0.0, sh_z), (-1, 0, 0), 0.43, 0.4),
box(name + ".tooth", (4, 2.36 * k, 0.14 - drop), (-1, 0, 0), 0.1, 0.18, 0.3),
cyl(name + ".bolt_a", (4, 1.7 * k, -0.1), (-1, 0, 0), 0.035, 0.02), cyl(name + ".bolt_b", (4, -1.1, 1.0), (-1, 0, 0), 0.035, 0.02)]))
M.ribs_action(name, [{"origin": [0, y, 0], "normal": [0, 1, 0]} for y in (1.4 * k, -1.0)], standoff=0.03, depth=0.12, thickness=0.03, holes=0.4, posts=0.5, post_r=0.02)
stations = ((-tail - 0.1, 0.94 * half, 0.26), (-0.5, half, 0.3), (0.7, 0.96 * half, 0.26), (1.7 * k, 0.72, 0.2), (2.3 * k, 0.56, 0.16))
roof = {"mirror": True, "rings": [[[0, y, top(y)], [0.62 * w, y, top(y) - 0.06], [w, y, top(y) - sag]] for y, w, sag in stations],
"creases": [{"column": 1, "from": 0, "to": 4, "weight": 1.0}, {"column": 0, "from": 0, "to": 4, "weight": 0.5}, {"ring": 3, "from": 0, "to": 2, "weight": 0.5}]}
lid = b.name + ".roof"
M.shell_action(lid, M.face_out(roof, (0, 0, 1)), b, P, thickness=0.07, levels=2, bevel=0.012)
M.cuts_action(lid, both([slab(f"{lid}.break{j}", (0.45, y, 6), (0, 0, -1), (1, 0, 0), 0.8) for j, y in enumerate((1.3 * k, 0.45, -0.4, -1.1))] +
[slab(lid + ".edge", (0.84, -0.2, 6), (0, 0, -1), (0, 1, 0), 1.9), cyl(lid + ".bolt", (0.3, 2.0 * k, 6), (0, 0, -1), 0.03, 0.02)]))
M.ribs_action(lid, [{"origin": [0, y, 0], "normal": [0, 1, 0]} for y in (1.2 * k, 0.1, -1.0)], standoff=0.03, depth=0.1, thickness=0.03, holes=0.35, posts=0.45, post_r=0.02)
b.lines = {"ridge": [(-w, y, top(y) - sag) for y, w, sag in stations] + [(-r[1][0], r[1][1], r[1][2]) for r in body["rings"]] + [(0, nose, -drop)],
"chine": [(-q[0], q[1], q[2]) for q in body["rings"][2][::-1][:3]] + [(0, nose, -drop)]}
g.box(T((0, 2.06 * k, bay)), (0.8, 0.3, 0.42)) # the sensor block, behind the bay
for j in range(lenses):
at = T((0.15 * (1 if j % 2 else -1), 2.2 * k, bay + 0.07 - 0.14 * (j // 2))) @ ALONG_Y
g.tube(at, 0.065, 0.048, 0.16, 20)
b[red()].cylinder(at @ T((0, 0, 0.1)), 0.044, 0.02, 16)
g.box(T((0, -tail + 0.12, 0.5 * (0.7 + top(-tail) - 0.3))), (1.8 * half, 0.1, top(-tail) - 1.0)) # the tail bulkhead
if number:
M.update()
M.stencil_text(b.name + ".number", b.host, (Matrix.Identity(4) if b.to_host is None else Matrix(b.to_host)) @ F((-0.87, 1.2 * k, 0.3), (-1, 0.26, 0.1), (0, 0, 1)), number, 0.36)
def cooling(b, length=2.6, width=0.7, height=0.36, deep=2.5, gap=1.1, bars=5, slope=32.0, crest=1.72, start=-1.72):
"""REAR COOLING UNITS (inset 2), with the rear and side views. Origin as the hull's. Two long units, `gap`
apart: each lies along the roof as a low pod, falling with it to a nose, and at the tail turns down the hull's
back as a tall housing `deep` high, open to the rear. One closed sleeve of five facets each (two walls, two
shoulders, a crown), stepped where the pod leaves the housing, its crown broken into panels; in the rear mouth a
frame, `bars` uprights and nine cross bars; between the units a ribbed spine over the roof and down the back."""
g = b[D]
fall = math.tan(math.radians(slope))
top = lambda y: crest - fall * y
y0, w = start, 0.5 * width
for s in (-1, 1):
x = s * 0.5 * gap
def ring(y, h, floor=None, kw=1.0):
crown = top(y) - 0.05 + h
floor = crown - h if floor is None else floor
sag = min(0.16, 0.36 * h)
return [[x + u * kw, y, z] for u, z in ((-w, floor), (-w, crown - sag), (-0.6 * w, crown), (0.6 * w, crown), (w, crown - sag), (w, floor))]
low = top(y0) - 0.05 + height - deep
columns = [{"column": j, "from": 0, "to": 1, "weight": 1.0} for j in range(6)]
housing = {"closed": True, "rings": [ring(y0, height, low), ring(y0 + 0.5, height, low)], "creases": columns}
pod = {"closed": True, "rings": [ring(y0 + 0.3, 0.96 * height), ring(y0 + 0.5 * length, 0.9 * height), ring(y0 + 0.82 * length, 0.62 * height, None, 0.92), ring(y0 + length, 0.45 * height, None, 0.84)],
"creases": [{"column": j, "from": 0, "to": 3, "weight": 1.0} for j in range(6)]}
side = "L" if s < 0 else "R"
name, house = f"{b.name}.pod{side}", f"{b.name}.housing{side}"
M.shell_action(house, M.face_out(housing, None), b, P, thickness=0.05, levels=1, bevel=0.01)
M.cuts_action(house, [slab(f"{house}.side", (x - s * 3, y0 + 0.2, low + 0.5 * deep), (s, 0, 0), (0, 0, 1), 0.6 * deep), cyl(f"{house}.bolt", (x - s * 3, y0 + 0.36, low + 0.2), (s, 0, 0), 0.025, 0.02)])
M.shell_action(name, M.face_out(pod, None), b, P, thickness=0.022, levels=1, bevel=0.008)
M.cuts_action(name, [slab(f"{name}.break{j}", (x, y0 + t * length, 6), (0, 0, -1), (1, 0, 0), 0.5 * width) for j, t in enumerate((0.26, 0.42, 0.58, 0.74))])
crown = top(y0) - 0.05 + height
back = T((x, y0 + 0.1, 0))
g.box(back @ T((0, 0.12, 0.5 * (low + crown) - 0.05)), (0.9 * width, 0.05, deep - 0.2)) # the mouth's back plate
for j in range(bars):
g.box(back @ T((0.66 * width * (j / (bars - 1) - 0.5), 0.04, 0.5 * (low + crown) - 0.08)), (0.022, 0.1, deep - 0.34))
for j in range(9):
g.box(back @ T((0, 0.0, low + 0.16 + j * (deep - 0.5) / 8)), (0.82 * width, 0.03, 0.025))
g.box(back @ T((0, -0.04, low + 0.05)), (0.92 * width, 0.14, 0.07)) # the sill
rib = min(0.34, gap - width - 0.04)
M.track(g, (0, y0 + 0.2, top(y0) + 0.12), (0, -0.3, top(-0.3) + 0.06), rib, 11, 0.16, (0, fall, 1))
M.track(g, (0, y0 + 0.2, top(y0) + 0.1), (0, y0 + 0.5, 0.5), rib, 11, 0.14, (0, -1, -0.1))
# --- shoulder and arms ----------------------------------------------------------------------------------------------
def shoulder(b, r=0.41, drum=0.84, shield=0.56, cap=True):
"""SHOULDER ASSEMBLY (inset 3), the mech's left: outboard is -x; origin at the shoulder's pivot. A black drum of
raised bands on the pitch axis, `drum` long from the hull's side; on its outer end a shield, a seven-sided
plate scribed with a cross about a hub; over the drum the pauldron, one sheet bent along two edges (a back skirt,
a top, a front lip) and turned down at its outboard end, a panel break across the top, an inset in the lip."""
g = b[D]
ribbed_drum(g, F((0.62, 0, 0), (-1, 0, 0), (0, 0, 1)), r, drum, 6)
disc = M.Geo()
angles = (12, 62, 112, 158, 204, 258, 312)
disc.prism(OUT(-0.24, 0, 0), [(shield * math.cos(math.radians(a)), shield * math.sin(math.radians(a))) for a in angles], 0.1, 0.03)
name = b.name + ".shield"
M.mass(b, name, disc, P)
M.cuts_on(name, [slab(name + ".h", (-4, 0, 0.02), (1, 0, 0), (0, 1, 0), 2.2 * shield), slab(name + ".v", (-4, 0.03, 0), (1, 0, 0), (0, 0, 1), 2.2 * shield),
cyl(name + ".hub", (-4, 0, 0), (1, 0, 0), 0.14, 0.03), cyl(name + ".bolt", (-4, 0.3 * shield, 0.5 * shield), (1, 0, 0), 0.03, 0.02)])
M.ringed_disc(g, OUT(-0.31, 0, 0), 0.12, 0.06)
b.lines = {"outer": [(-0.36, 0.0, 0.0)]}
if not cap:
return
pts = ((-0.72, 0.16), (-0.66, 0.62), (0.5, 0.7), (0.88, 0.26)) # back skirt, back top, front top, front lip: (y, z)
rings = [[[x, y, z] for y, z in pts] for x in (0.66, 0.12, -0.42)] + [[[-0.58, 0.94 * y, z - 0.1] for y, z in pts]]
sheet = {"rings": rings, "creases": [{"column": 1, "from": 0, "to": 3, "weight": 1.0}, {"column": 2, "from": 0, "to": 3, "weight": 1.0}, {"ring": 2, "from": 0, "to": 3, "weight": 1.0}]}
name = b.name + ".cap"
M.shell_action(name, M.face_out(sheet, (0, 0, 1)), b, P, thickness=0.05, levels=2, bevel=0.012)
M.cuts_action(name, [slab(name + ".top", (0.1, -0.1, 4), (0, 0, -1), (1, 0, 0), 0.9), slab(name + ".out", (-0.3, 0.1, 4), (0, 0, -1), (0, 1, 0), 0.8),
box(name + ".lip", (0.15, 4, 0.47), (0, -1, 0), 0.4, 0.14, 0.02, up=(1, 0, 0)),
cyl(name + ".bolt_a", (0.45, -0.45, 4), (0, 0, -1), 0.03, 0.02), cyl(name + ".bolt_b", (-0.2, 0.3, 4), (0, 0, -1), 0.03, 0.02)])
M.ribs_action(name, [{"origin": [x, 0, 0], "normal": [1, 0, 0]} for x in (0.4, -0.15)], standoff=0.03, depth=0.09, thickness=0.03, holes=0.3, posts=0.4, post_r=0.018)
def upper_arm(b, length=1.8, half=(0.27, 0.3)):
"""The upper arm under the drum, from the hero and front views; origin at the shoulder's pivot, hanging along -z.
A sleeve of eight facets over the girder's middle, a panel break round it and bolts; at the elbow a ringed disc a
side."""
w, d = half
section = lambda kx, z: [[kx * u * w, kx * v * d, z] for u, v in ((-1, -0.6), (-1, 0.6), (-0.6, 1), (0.6, 1), (1, 0.6), (1, -0.6), (0.6, -1), (-0.6, -1))]
sleeve = {"closed": True, "rings": [section(0.94, -0.3 * length), section(1.0, -0.42 * length), section(1.0, -0.7 * length), section(0.9, -0.8 * length)],
"creases": [{"column": j, "from": 0, "to": 3, "weight": 1.0} for j in range(8)]}
name = b.name + ".sleeve"
M.shell_action(name, M.face_out(sleeve, None), b, P, thickness=0.04, levels=1, bevel=0.01)
M.cuts_action(name, [slab(name + ".a", (-4, 0, -0.55 * length), (1, 0, 0), (0, 1, 0), 0.9 * d), slab(name + ".b", (0, 4, -0.55 * length), (0, -1, 0), (1, 0, 0), 0.9 * w),
cyl(name + ".bolt", (-4, 0, -0.38 * length), (1, 0, 0), 0.03, 0.02)])
b.lines = {"outer": [(-w - 0.02, 0, -0.3 * length), (-w - 0.02, 0, -0.8 * length), (-0.36, 0, -length)]}
for s in (-1, 1):
M.ringed_disc(b[D], F((s * 0.26, 0, -length), (s, 0, 0), (0, 0, 1)), 0.24, 0.1)
def weapon_arm(b, length=3.2, barrels=2):
"""WEAPON ARM (inset 4), the right forearm. Origin at the elbow's pin, the bores along y. A receiver of stepped
housings: a rear housing under a bent cover plate (one sheet, a panel break and an inset on top, a rail slot down
each side), a narrower fore housing with side rails; from it `barrels` barrels one over the other, the upper an
eight-sided shroud with a square muzzle block, the lower a tube in a collar; a ringed disc on the elbow's side."""
g = b[D]
L = length
g.box(T((0, 0.19 * L, 0)), (0.62, 0.38 * L, 0.74)) # the rear housing
g.box(T((0, 0.5 * L, -0.04)), (0.5, 0.26 * L, 0.6)) # the fore housing
for s in (-1, 1):
g.box(T((s * 0.27, 0.47 * L, 0.02)), (0.05, 0.3 * L, 0.16))
g.box(T((s * 0.33, 0.2 * L, -0.2)), (0.05, 0.3 * L, 0.2))
M.ringed_disc(g, F((s * 0.31, 0.02, 0), (s, 0, 0), (0, 0, 1)), 0.26, 0.1)
cover = {"rings": [[[x, y, z] for x, z in ((-0.36, -0.12), (-0.36, 0.3), (-0.24, 0.43), (0.24, 0.43), (0.36, 0.3), (0.36, -0.12))] for y in (-0.05 * L, 0.14 * L, 0.3 * L, 0.4 * L)],
"creases": [{"column": j, "from": 0, "to": 3, "weight": 1.0} for j in (1, 2, 3, 4)]}
cover["rings"][3] = [[0.86 * x, y, z - 0.07] for x, y, z in cover["rings"][3]]
name = b.name + ".cover"
M.shell_action(name, M.face_out(cover, (0, 0, 1)), b, "olive", thickness=0.05, levels=2, bevel=0.01)
M.cuts_action(name, [slab(name + ".break", (0, 0.2 * L, 4), (0, 0, -1), (1, 0, 0), 0.44), box(name + ".inset", (0, 0.08 * L, 4), (0, 0, -1), 0.26, 0.3, 0.02, up=(0, 1, 0)),
{"name": name + ".slot_l", "part": "slot", "params": "width=0.5; height=0.07; depth=0.02", "origin": [-4, 0.15 * L, 0.1], "direction": [1, 0, 0], "up": [0, 0, 1], "roll": 90},
{"name": name + ".slot_r", "part": "slot", "params": "width=0.5; height=0.07; depth=0.02", "origin": [4, 0.15 * L, 0.1], "direction": [-1, 0, 0], "up": [0, 0, 1], "roll": 90}])
M.ribs_action(name, [{"origin": [0, y * L, 0], "normal": [0, 1, 0]} for y in (0.05, 0.25)], standoff=0.02, depth=0.07, thickness=0.025, holes=0.0, posts=0.3, post_r=0.016)
b.lines = {"outer": [(0, 0.4 * L, 0.38), (0, L, 0.32)]}
octagon = [(0.17 * math.cos(math.radians(22.5 + 45 * j)), 0.17 * math.sin(math.radians(22.5 + 45 * j))) for j in range(8)]
for j in range(barrels):
z = 0.14 - 0.33 * j
if j == 0:
g.prism(T((0, 0.45 * L, z)) @ ALONG_Y, octagon, 0.5 * L)
g.box(T((0, 0.95 * L, z)), (0.38, 0.12 * L, 0.36))
b["rubber"].box(T((0, 1.005 * L, z)), (0.2, 0.02, 0.2))
g.box(T((0, 0.74 * L, z + 0.2)), (0.1, 0.2 * L, 0.06))
else:
g.tube(T((0, 0.45 * L, z)) @ ALONG_Y, 0.12, 0.07, (0.5 - 0.04 * j) * L, 24)
g.tube(T((0, (0.86 - 0.04 * j) * L, z)) @ ALONG_Y, 0.16, 0.07, 0.09 * L, 24)
g.box(T((0, 0.62 * L, z)), (0.3, 0.05 * L, 0.26))
b["accent_yellow"].box(T((-0.255, 0.56 * L, 0.02)), (0.012, 0.14, 0.05))
def manipulator(b, fore=1.3, fingers=4, curl=22.0, spread=6.0):
"""MANIPULATOR (inset 5), the left forearm and hand. Origin at the elbow's pin, the forearm hanging `fore` along
-z, the back of the hand outboard (-x). A forearm sleeve of eight facets tapering to a stepped cuff; a wrist; a
back-of-hand plate over the palm block; `fingers` fingers of three links on knuckle pins, each link turned `curl`
degrees toward the palm, fanned `spread` degrees apart; a thumb of two links off the front edge."""
g = b[D]
section = lambda w, d, z: [[u * w, v * d, z] for u, v in ((-1, -0.55), (-1, 0.55), (-0.55, 1), (0.55, 1), (1, 0.55), (1, -0.55), (0.55, -1), (-0.55, -1))]
sleeve = {"closed": True, "rings": [section(0.27, 0.3, -0.18 * fore), section(0.3, 0.34, -0.36 * fore), section(0.25, 0.28, -0.72 * fore)],
"creases": [{"column": j, "from": 0, "to": 2, "weight": 1.0} for j in range(8)]}
name = b.name + ".sleeve"
M.shell_action(name, M.face_out(sleeve, None), b, P, thickness=0.04, levels=1, bevel=0.01)
M.cuts_action(name, [slab(name + ".a", (-4, 0, -0.5 * fore), (1, 0, 0), (0, 1, 0), 0.5), box(name + ".inset", (-4, 0, -0.3 * fore), (1, 0, 0), 0.26, 0.16, 0.02),
cyl(name + ".bolt", (-4, 0.12, -0.62 * fore), (1, 0, 0), 0.025, 0.02)])
b.lines = {"outer": [(-0.3, 0, -0.36 * fore), (-0.26, 0, -0.72 * fore), (-0.1, 0, -fore - 0.25), (0.12, 0, -fore - 0.95)]}
cuff = M.Geo()
cuff.prism(T((0, 0, -0.74 * fore)) @ RX(180), M.rect(0.6, 0.66, 0.12), 0.14 * fore, 0.03, 0.86)
cname = b.name + ".cuff"
M.mass(b, cname, cuff, P)
M.cuts_on(cname, [{"name": cname + ".slot", "part": "slot", "params": "width=0.3; height=0.05; depth=0.02", "origin": [-4, 0, -0.8 * fore], "direction": [1, 0, 0], "up": [0, 0, 1], "roll": 90}])
wz = -fore
g.cylinder(T((0, 0, wz + 0.06)), 0.14, 0.2, 20)
g.hull([(x, y, z) for x in (-0.07, 0.07) for y, z in ((-0.2, wz - 0.05), (0.2, wz - 0.05), (-0.23, wz - 0.42), (0.23, wz - 0.42))]) # the palm
b[P].prism(OUT(-0.07, 0, wz - 0.22), [(-0.17, -0.16), (0.17, -0.16), (0.2, 0.06), (0.1, 0.17), (-0.1, 0.17), (-0.2, 0.06)], 0.035, 0.012) # the back plate
links = (0.25, 0.19, 0.15)
for f in range(fingers):
u = (f - 0.5 * (fingers - 1)) / max(fingers - 1, 1)
at = T((0, 0.4 * u, wz - 0.44)) @ RX(-spread * 2 * u)
for j, ln in enumerate(links):
at = at @ RY(-curl * (0.5 if j == 0 else 1.0))
g.cylinder(at @ RX(90), 0.05 - 0.006 * j, 0.11 - 0.012 * j, 12)
g.box(at @ T((0, 0, -0.5 * ln)), (0.085 - 0.01 * j, 0.09 - 0.012 * j, ln * 0.92))
b[P].box(at @ T((-0.045 + 0.004 * j, 0, -0.5 * ln)), (0.02, 0.07 - 0.01 * j, ln * 0.6))
at = at @ T((0, 0, -ln))
at = T((0.02, 0.24, wz - 0.16)) @ RX(-48) @ RY(-20)
for j, ln in enumerate((0.2, 0.17)):
g.cylinder(at @ RX(90), 0.05, 0.11, 12)
g.box(at @ T((0, 0, -0.5 * ln)), (0.085, 0.09, ln * 0.92))
at = at @ T((0, 0, -ln)) @ RY(-25)
# --- pelvis and legs ------------------------------------------------------------------------------------------------
def pelvis(b, span=1.05, r=0.42, drum=0.34):
"""The pelvis of the hero and front views (the sheet has no inset of it). Origin on the hip axis, mid-way. A
narrow block between two black hip drums of raised bands, `drum` long each; in front a cod plate, one mirrored
sheet creased down its middle and across its shoulder, a panel break and two bolts; behind, a tail plate."""
g = b[D]
for s in (-1, 1):
ribbed_drum(g, F((s * 0.5 * span, 0, 0), (s, 0, 0), (0, 0, 1)), r, drum, 4, 0.05)
cod = {"mirror": True, "rings": [[[0, 0.5, 0.42], [0.3, 0.44, 0.4]], [[0, 0.62, 0.05], [0.36, 0.52, 0.05]], [[0, 0.56, -0.5], [0.26, 0.47, -0.48]], [[0, 0.36, -0.86], [0.13, 0.32, -0.82]]],
"creases": [{"ring": 1, "from": 0, "to": 1, "weight": 0.8}]}
name = b.name + ".cod"
M.shell_action(name, M.face_out(cod, (0, 1, 0)), b, P, thickness=0.06, levels=2, bevel=0.012)
M.cuts_action(name, [slab(name + ".break", (0.0, 4, -0.2), (0, -1, 0), (1, 0, 0), 0.5, depth=0.02)] + both([cyl(name + ".bolt", (0.2, 4, 0.22), (0, -1, 0), 0.03, 0.02)]))
tail = {"mirror": True, "rings": [[[0, -0.5, 0.4], [0.3, -0.46, 0.4]], [[0, -0.58, 0.0], [0.34, -0.5, 0.0]], [[0, -0.5, -0.6], [0.2, -0.44, -0.58]]], "creases": []}
M.shell_action(b.name + ".tail", M.face_out(tail, (0, -1, 0)), b, P, thickness=0.06, levels=2, bevel=0.012)
def thigh(b, length=2.68, r=0.45, width=(0.8, 0.62), front=(0.46, 0.52)):
"""The left thigh and hip of the hero view (crop; the sheet has no inset). Origin at the hip's pivot, the thigh
hanging `length` along -z, outboard -x. On the hip's outer end a ringed bearing cap; down the front a long plate,
one sheet bent round the outer corner, its outer flank starting below the cap so the cap stays bare; a top lame
over its head; two panel breaks, an inset and bolts; under it three ribs on posts. `width` and `front` are the
plate's width and its face's stand-off at the hip and at the knee: its two edges are straight lines between them,
which the knee cap and the shin's plate carry on (the leg's flow lines)."""
M.ringed_disc(b[D], OUT(-0.3, 0, 0), r, 0.16)
rows = ((0.3, 0.0, 0.3), (-0.22, 0.08, 0.3), (-0.62, 0.24, -0.12), (-0.62 * length, 0.7, -0.16), (-0.9 * length, 1.0, -0.02)) # z, how far down the taper, how far back the outer flank reaches (y)
half = lambda t: 0.5 * (width[0] + (width[1] - width[0]) * t)
face = lambda t: front[0] + (front[1] - front[0]) * t
w = half(0.5)
plate = {"rings": [[[half(t), face(t) - 0.16, z], [0.7 * half(t), face(t), z], [-half(t), face(t), z], [-half(t) - 0.04, back, z]] for z, t, back in rows][::-1],
"creases": [{"column": 2, "from": 0, "to": 4, "weight": 1.0}, {"column": 1, "from": 0, "to": 4, "weight": 0.6}]}
name = b.name + ".plate"
M.shell_action(name, M.face_out(plate, (-0.4, 1, 0)), b, P, thickness=0.05, levels=2, bevel=0.012)
M.cuts_action(name, [slab(name + ".a", (-0.05, 4, -0.3 * length), (0, -1, 0), (1, 0, 0), 0.6), slab(name + ".b", (-0.05, 4, -0.66 * length), (0, -1, 0), (1, 0, 0), 0.5),
box(name + ".inset", (-0.06, 4, -0.48 * length), (0, -1, 0), 0.24, 0.42, 0.02), slab(name + ".flank", (-4, 0.2, -0.5 * length), (1, 0, 0), (0, 0, 1), 0.9),
cyl(name + ".bolt_a", (-0.2, 4, -0.16 * length), (0, -1, 0), 0.03, 0.02), cyl(name + ".bolt_b", (0.1, 4, -0.76 * length), (0, -1, 0), 0.03, 0.02)])
M.ribs_action(name, [{"origin": [0, 0, z * length], "normal": [0, 0, 1]} for z in (-0.3, -0.52, -0.74)], standoff=0.03, depth=0.09, thickness=0.03, holes=0.0, posts=0.3, post_r=0.018)
lame = {"rings": [[[0.9 * half(0), 0.34, z], [-0.9 * half(0), 0.5, z]] for z in (0.44, 0.1)], "creases": []}
M.shell_action(b.name + ".lame", M.face_out(lame, (0, 1, 0)), b, P, thickness=0.06, levels=1, bevel=0.01)
b.lines = {"outer": [(-half(t) - 0.04, face(t), z) for z, t, _ in rows], "inner": [(half(t), face(t) - 0.16, z) for z, t, _ in rows]}
def knee(b, r=0.34, cap=(0.62, 0.86), boss=0.17, front=0.52):
"""KNEE ASSEMBLY (inset 6), the left knee from its outer side: outboard -x; origin on the knee's axis. A ringed
cap on each end of the pin; in front of it the knee cap, a tall block (`cap`: width, height) with clipped corners,
a panel break, an inset and two bolts on its outer face; behind and below, on the shin's outer side, the calf
plate, six-sided, carrying a ringed boss of radius `boss`."""
g = b[D]
M.ringed_disc(g, OUT(-0.28, 0, 0), r, 0.14)
M.ringed_disc(g, F((0.28, 0, 0), (1, 0, 0), (0, 0, 1)), 0.8 * r, 0.1)
w, h = cap
block = M.Geo()
block.hull([(x, y, z) for x in (-0.5 * w, 0.5 * w) for y, z in ((0.3, -0.5 * h), (0.3, 0.5 * h), (front - 0.08, 0.56 * h), (front + 0.1, 0.3 * h), (front + 0.1, -0.36 * h), (front - 0.06, -0.56 * h))], T((0, 0, -0.08)))
b.lines = {"outer": [(-0.5 * w - 0.04, front, 0.0)], "inner": [(0.5 * w, front - 0.16, 0.0)]}
name = b.name + ".cap"
M.mass(b, name, block, P)
M.cuts_on(name, [slab(name + ".a", (-4, 0.45, 0.06 * h - 0.08), (1, 0, 0), (0, 1, 0), 0.26), box(name + ".inset", (-4, 0.45, -0.3 * h), (1, 0, 0), 0.16, 0.19 * h, 0.02),
cyl(name + ".bolt_a", (-4, 0.4, 0.3 * h), (1, 0, 0), 0.028, 0.02), cyl(name + ".bolt_b", (-4, front, 0.23 * h - 0.08), (1, 0, 0), 0.028, 0.02),
slab(name + ".front", (0, 4, -0.06 * h), (0, -1, 0), (1, 0, 0), 0.77 * w)])
calf = M.Geo()
calf.prism(OUT(-0.3, -0.3, -0.62), [(0.0, -0.46), (0.3, -0.32), (0.34, 0.2), (0.12, 0.46), (-0.26, 0.34), (-0.3, -0.24)], 0.09, 0.03) # in OUT's frame x is -y (back): the plate leans back
cname = b.name + ".calf"
M.mass(b, cname, calf, P)
M.cuts_on(cname, [cyl(cname + ".seat", (-4, -0.3, -0.62), (1, 0, 0), boss + 0.03, 0.025)])
M.ringed_disc(g, OUT(-0.37, -0.3, -0.62), boss, 0.06)
g.box(T((0, -0.1, -0.5)), (0.4, 0.4, 0.5)) # the shin's head, behind the plates
def lower_leg(b, length=2.78, pistons=2, r=0.3, width=(0.62, 0.42), front=(0.52, 0.36)):
"""LOWER LEG (inset 7), the left shin: outboard -x; origin on the knee's axis, the shin hanging `length` along -z
to the ankle. Down the front a long narrow plate of three facets (an inner flank, a face, an outer flank), panel
breaks and two yellow marks; down the open back `pistons` rams side by side, each a barrel, a gland and a bright
rod; a guard plate over their heads; at the ankle a ringed cap a side."""
g = b[D]
rows = ((-0.2 * length, 0.0, 0.12), (-0.4 * length, 0.3, -0.04), (-0.74 * length, 0.76, -0.02), (-0.92 * length, 1.0, 0.1)) # z, how far down the taper, how far back the flanks reach
half = lambda t: 0.5 * (width[0] + (width[1] - width[0]) * t)
face = lambda t: front[0] + (front[1] - front[0]) * t
b.lines = {"outer": [(-half(t) - 0.04, face(t), z) for z, t, _ in rows], "inner": [(half(t), face(t) - 0.12, z) for z, t, _ in rows]}
plate = {"rings": [[[half(t), back, z], [0.5 * half(t), face(t), z], [-0.5 * half(t), face(t), z], [-half(t) - 0.04, back, z]] for z, t, back in rows][::-1],
"creases": [{"column": 1, "from": 0, "to": 3, "weight": 1.0}, {"column": 2, "from": 0, "to": 3, "weight": 1.0}]}
name = b.name + ".plate"
M.shell_action(name, M.face_out(plate, (0, 1, 0)), b, P, thickness=0.05, levels=2, bevel=0.012)
M.cuts_action(name, [slab(name + ".a", (0, 4, -0.5 * length), (0, -1, 0), (1, 0, 0), 0.2), slab(name + ".b", (0, 4, -0.7 * length), (0, -1, 0), (1, 0, 0), 0.16),
slab(name + ".flank", (-4, 0.2, -0.56 * length), (1, 0, 0), (0, 0, 1), 0.8), cyl(name + ".bolt", (0, 4, -0.34 * length), (0, -1, 0), 0.025, 0.02)])
M.ribs_action(name, [{"origin": [0, 0, z * length], "normal": [0, 0, 1]} for z in (-0.4, -0.6, -0.8)], standoff=0.03, depth=0.07, thickness=0.025, holes=0.0, posts=0.25, post_r=0.016)
for z in (-0.47, -0.63):
b["accent_yellow"].box(T((-half(0.5) - 0.045, 0.2, z * length)), (0.012, 0.1, 0.04))
for j in range(pistons):
x = 0.26 * (j - 0.5 * (pistons - 1))
top, end = Vector((x, -0.3, -0.2 * length)), Vector((x, -0.24, -0.93 * length))
along = F(top, end - top, (0, 1, 0))
ln = (end - top).length
g.lathe(along, [(0, 0), (0.085, 0), (0.085, 0.03), (0.075, 0.04), (0.075, 0.5 * ln), (0.09, 0.51 * ln), (0.09, 0.56 * ln), (0.06, 0.57 * ln), (0, 0.57 * ln)], 20)
b["steel"].cylinder(along @ T((0, 0, 0.77 * ln)), 0.042, 0.44 * ln, 16)
g.box(along @ T((0, 0, ln)), (0.14, 0.16, 0.12))
guard = {"rings": [[[0.3, -0.38, z], [-0.3, -0.38, z]] for z in (-0.12 * length, -0.3 * length)], "creases": []}
M.shell_action(b.name + ".guard", M.face_out(guard, (0, -1, 0)), b, P, thickness=0.05, levels=1, bevel=0.01)
for s in (-1, 1):
M.ringed_disc(g, F((s * 0.25, 0, -length), (s, 0, 0), (0, 0, 1)), r, 0.12)
def foot(b, drop=0.83, toes=3, splay=24.0, toe=1.55, heel=2):
"""FOOT (FRONT) and FOOT (REAR) (insets 8 and 9); the hero view gives the three toes. Origin at the ankle's pin,
the sole `drop` below. A bright shank into a drum on the pin's axis with a ringed cap a side; `toes` long wedge
toes fanned `splay` degrees apart, each a block cut across into a root and a claw, an inset on its root and a
bolt; `heel` short blocks behind."""
g = b[D]
b["steel"].cylinder(T((0, 0, 0.36)), 0.1, 0.5, 20)
g.cylinder(T((0, 0, 0.12)), 0.15, 0.14, 20)
g.cylinder(RY(90), 0.33, 0.62, 32)
for s in (-1, 1):
M.ringed_disc(g, F((s * 0.31, 0, 0), (s, 0, 0), (0, 0, 1)), 0.34, 0.1)
g.box(T((0, 0.1, -0.5 * drop)), (0.5, 0.5, drop - 0.2))
for j in range(toes):
u = j - 0.5 * (toes - 1)
ln = toe * (1.0 if u else 1.06)
at = T((0.27 * u, 0.12, -drop)) @ RZ(-splay * u)
wedge = M.Geo()
wedge.hull([(-0.2, 0, 0), (0.2, 0, 0), (-0.21, 0.5 * ln, 0), (0.21, 0.5 * ln, 0), (-0.1, ln, 0), (0.1, ln, 0), (-0.17, 0.02, 0.5), (0.17, 0.02, 0.5),
(-0.17, 0.4 * ln, 0.42), (0.17, 0.4 * ln, 0.42), (-0.08, 0.98 * ln, 0.1), (0.08, 0.98 * ln, 0.1)], at)
name = f"{b.name}.toe{j}"
M.mass(b, name, wedge, P)
up = at @ Vector((0, 0, 4))
fwd = (at.to_3x3() @ Vector((0, 1, 0)))
side = (at.to_3x3() @ Vector((1, 0, 0)))
M.cuts_on(name, [slab(name + ".joint", at @ Vector((0, 0.52 * ln, 4)), (0, 0, -1), side, 0.5, gap=0.035, depth=0.05),
box(name + ".inset", at @ Vector((0, 0.24 * ln, 4)), (0, 0, -1), 0.18, 0.24, 0.02, up=fwd),
cyl(name + ".bolt", at @ Vector((0, 0.72 * ln, 4)), (0, 0, -1), 0.025, 0.02)])
tip = lambda j: tuple((T((0.27 * (j - 0.5 * (toes - 1)), 0.12, -drop)) @ RZ(-splay * (j - 0.5 * (toes - 1)))) @ Vector((0, toe, 0.1)))
b.lines = {"outer": [(-0.3, 0.3, 0.0), tip(0)], "inner": [(0.3, 0.3, 0.0), tip(toes // 2)]}
for j in range(heel):
u = j - 0.5 * (heel - 1)
at = T((0.42 * u, -0.2, -drop)) @ RZ(180 + 16 * u)
b[P].hull([(-0.15, 0, 0), (0.15, 0, 0), (-0.13, 0.42, 0), (0.13, 0.42, 0), (-0.13, 0, 0.34), (0.13, 0, 0.34), (-0.1, 0.36, 0.16), (0.1, 0.36, 0.16)], at)
def foot_rear(b, **kw):
"""FOOT (REAR) (inset 9): foot(), seen from behind."""
foot(b, **kw)
PARTS = {f.__name__: f for f in (hull, cooling, shoulder, upper_arm, weapon_arm, manipulator, pelvis, thigh, knee, lower_leg, foot, foot_rear)}
VIEWS = {"hull": (42, 22, 0.85, 0), "cooling": (165, 14, 0.9, 0), "shoulder": (32, 4, 0.9, 0), "upper_arm": (40, 0, 1.0, 0), "weapon_arm": (36, 8, 0.8, -22), "manipulator": (72, 0, 1.0, 0),
"pelvis": (20, 0, 0.95, 0), "thigh": (28, -4, 1.0, 0), "knee": (90, 0, 0.95, 0), "lower_leg": (-150, 0, 1.0, 0), "foot": (38, 12, 0.9, 0), "foot_rear": (164, 6, 0.9, 0)}
GROUND = {"foot": 0.83, "foot_rear": 0.83}
VARIANTS = {"hull": dict(nose=3.0, drop=0.6, slope=20.0, crest=1.4, number="12"), "cooling": dict(gap=1.3, width=0.5, bars=4, length=2.4, deep=1.2), "shoulder": dict(shield=0.42, drum=0.6),
"weapon_arm": dict(length=2.6, barrels=3), "manipulator": dict(fingers=3, curl=38.0, spread=12.0), "thigh": dict(length=2.0, width=(1.0, 0.5)), "knee": dict(cap=(0.5, 0.6), boss=0.24),
"lower_leg": dict(length=2.2, pistons=3), "foot": dict(toes=2, splay=34.0, toe=1.2), "upper_arm": dict(length=1.4, half=(0.32, 0.26)), "pelvis": dict(span=1.5, drum=0.2)}

View file

@ -22,7 +22,7 @@ Helpers that have held up across six mechs, and what Brokkr would need to make e
Geo.sweep / beam / truss / gusset structural sections. Needs: an extrude shape in the kit format.
hose / hose_bundle Bezier hoses between frames. Needs: hose-port sockets, clamps, avoidance.
stage / shot / turntable / gpu a cyclorama, a light rig that turns with the camera, a camera distance
fitted to the bounding sphere. Needs: turntable_recipe.py to fit its radius the same way, and a GPU choice
fitted to the bounding sphere. MECH_ENGINE=eevee|workbench renders iterations without Cycles. Needs: turntable_recipe.py to fit its radius the same way, and a GPU choice
made per session (it lives in preferences, not in the .blend).
Round 4 (massing first, then attachment, then layering), none of it a Brokkr action yet:
@ -37,6 +37,23 @@ Round 4 (massing first, then attachment, then layering), none of it a Brokkr act
foot_blocks a layered, splayed foot over a kit foot. Needs: the mass action above.
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).
New-mechs track (KESTREL, CHIMERA):
canted / biped(hip_cant) / lay(cant) a hip bearing tipped up outboard, so a leg leans out to its foot in one
plane (skeleton.cant reads the angle off the rear view). Needs: a kit flange that takes a tilt, or attach
with a frame offset (today the bearing is a loose seat, not a kit connection).
arms_drum a drum shoulder: one pitch bearing, a kit thigh as the upper arm, a wrist.
face_out sets a shell sheet's flip from the side its surface should face.
mass / cuts_on a closed block (a toe wedge, a knee block) as its own object on a Build's
host, cut by brokkr_kitbash.cut_many. Needs: a solid-mass action beside shell (a hull of points with a bevel).
ringed_disc / track a bearing cap of concentric rings; a ribbed strip. Used by every mech's joints.
seat_along seat() for a component drawn along +y, laid along a host's +z (a forearm gun).
flow / flow_lines the figure's flow lines as points on the parts that carry them, projected
into the hero and rear views (ruling mech-flow-lines-across-parts). Needs: a line read off a part's crease or
rim by name instead of points typed twice.
rest / wake cut shells disabled in viewports while later components are built. Needs: an
assembly that does not re-evaluate every live Boolean at each new datablock (apply, or a cut that bakes).
"""
import json
import math
@ -727,11 +744,59 @@ def shell_action(name, sheet, build, mat, thickness=0.05, offset=-1.0, levels=3,
return obj
RESTING = []
def rest(before):
"""Put to rest every object made since `before` (a set of object names) that carries a Boolean: disabled in
viewports, so Blender stops evaluating its cuts each time a later component is built (an assembly of twenty cut
shells took 141 s to build awake and a fraction of that at rest; every new datablock re-evaluates every live
Boolean in the scene). wake() shows them again; shells_sound() and the renders see them whole. A resting shell
cannot be cut or ribbed again: finish a component before the next."""
for obj in bpy.data.objects:
if obj.name not in before and obj.type == "MESH" and any(m.type == "BOOLEAN" for m in obj.modifiers) and not obj.hide_viewport:
obj.hide_viewport = True
RESTING.append(obj.name)
def wake():
for name in RESTING:
if name in bpy.data.objects:
bpy.data.objects[name].hide_viewport = False
RESTING.clear()
update()
def blame(name):
"""Which cutter leaves a shell open: each of the shell's cutters taken out of its Boolean in turn, the open edges
of the evaluated plate counted without it (one Boolean evaluation a cutter). Prints a line a cutter whose
removal changes the count. A debugging aid: brokkr_kitbash reports no such thing."""
obj = bpy.data.objects[name]
def loose():
update()
mesh = bmesh.new()
mesh.from_mesh(obj.evaluated_get(bpy.context.evaluated_depsgraph_get()).data)
count = sum(1 for edge in mesh.edges if not edge.is_manifold)
mesh.free()
return count
base = loose()
for mod in obj.modifiers:
if mod.type == "BOOLEAN" and mod.collection is not None:
for cutter in list(mod.collection.objects):
mod.collection.objects.unlink(cutter)
without = loose()
mod.collection.objects.link(cutter)
if without != base:
print(f"BLAME {name}: without {cutter.name} {without} open edges, with it {base}", flush=True)
update()
def shells_sound():
"""Every shell shell_action made, as built: the folded inner faces the action counted, and the edges of its whole
evaluated stack (wall, cuts, bevel) that do not join exactly two faces. Prints a line a shell and the totals,
and stops the build when either is over 0: a wall that passes through itself, or a cut that left the plate open."""
update()
wake()
depsgraph = bpy.context.evaluated_depsgraph_get()
folded = unsound = 0
for name in sorted(FOLDED):
@ -741,8 +806,12 @@ def shells_sound():
mesh.free()
folded, unsound = folded + FOLDED[name], unsound + loose
print(f"SHELL {name} folded {FOLDED[name]} openEdges {loose}", flush=True)
if loose and os.environ.get("MECH_BLAME"):
blame(name)
print(f"SHELLS {len(FOLDED)} folded {folded} openEdges {unsound}", flush=True)
if folded or unsound:
if (folded or unsound) and os.environ.get("MECH_SOUND") == "warn":
print(f"SHELLS UNSOUND (warn): {folded} folded inner faces, {unsound} open edges", flush=True)
elif folded or unsound:
raise SystemExit(f"shells: {folded} folded inner faces and {unsound} open edges after cuts; thin the wall where it folds, or move the cut")
@ -751,7 +820,7 @@ def cuts_action(name, cuts):
component's frame (carried into the shell's by the stretch shell_action wrote into it; cutter sizes are metres
as stated). The cutters stay as the shell's children, hidden from the render."""
stretch = STRETCH[name]
cuts = [{**cut, **{key: list(stretch @ Vector(cut[key])) for key in ("origin", "direction", "up") if key in cut}} for cut in cuts]
cuts = [{**cut, **{key: list(stretch @ Vector(cut[key])) for key in ("origin", "direction", "up", "axis") if key in cut}} for cut in cuts]
result = bpy.ops.brokkr_kitbash.cut_many(object_name=name, cuts=json.dumps(cuts))
if "FINISHED" not in result:
raise SystemExit(f"cuts on {name}: {result}")
@ -1125,6 +1194,13 @@ def ground(root):
def gpu(scene):
"""Cycles on the GPU for this session. The device choice lives in preferences, not in a .blend, so a scene
opened in a fresh Blender renders on the CPU until this runs."""
engine = os.environ.get("MECH_ENGINE", "cycles").lower()
if engine != "cycles": # iteration: EEVEE or Workbench, so a shared machine's GPU is left to the final renders
scene.render.engine = "BLENDER_WORKBENCH" if engine == "workbench" else "BLENDER_EEVEE"
if engine == "eevee":
scene.eevee.taa_render_samples = 16
print("ENGINE", scene.render.engine)
return engine
scene.render.engine = "CYCLES"
try:
prefs = bpy.context.preferences.addons["cycles"].preferences
@ -1747,7 +1823,11 @@ def biped(cfg):
fw, fl, fd = cfg["foot"]
for side in ("L", "R"):
tag, sock = f"Leg{side}", "hip_l" if side == "L" else "hip_r"
slew = attach(place("slew_ring", f"{tag}.HipSlew", mat="machine", r=r, height=cfg["hip_h"], bolts=20, teeth=64), "base", sad, sock, 0 if side == "L" else 180)
slew = place("slew_ring", f"{tag}.HipSlew", mat="machine", r=r, height=cfg["hip_h"], bolts=20, teeth=64)
if cfg.get("hip_cant"): # CANTED HIP: the bearing's axis tipped up outboard, so the leg swings in a plane that leans out to the foot
seat_loose(slew, "base", sad, canted(local_sockets(sad)[sock], cfg["hip_cant"]), 0 if side == "L" else 180)
else:
attach(slew, "base", sad, sock, 0 if side == "L" else 180)
th = attach(place("thigh", f"{tag}.Thigh", length=l1, width=w1, depth=d1, pin_r=pin, ring_r=r), sock, slew, "top")
aim_roll(th, (0, 0, 1), cfg["leg_aims"][side][0])
sh = attach(place("link", f"{tag}.Shin", length=l2, width=w2, depth=d2, pin_r=pin), "tongue", th, "clevis")
@ -1772,7 +1852,34 @@ def biped(cfg):
ring = cfg["pelvis"]["top_r"]
waist = attach(place("slew_ring", "Waist", mat="machine", r=ring, height=cfg["waist_h"], bolts=30, teeth=90), "base", sad, "top")
core = attach(place("chassis", "Core", ring_r=ring, **cfg["chassis"]), "bottom", waist, "top", cfg.get("twist", 0.0))
return dict(pelvis=sad, legs=legs, waist=waist, core=core, arms=arms_on(core, cfg))
return dict(pelvis=sad, legs=legs, waist=waist, core=core, arms=(arms_drum if cfg.get("arms") == "drum" else arms_on)(core, cfg))
def canted(frame, degrees):
"""A side flange's frame (its z out along x) tipped about the fore-and-aft axis through its own origin, so its
normal points `degrees` above level: what hangs on it swings in a plane leaning outward toward the ground."""
frame = Matrix(frame)
turn = Matrix.Rotation(math.radians(degrees) * (-1 if frame.col[2].x > 0 else 1), 4, "Y")
return Matrix.Translation(frame.translation) @ turn @ Matrix.Translation(-frame.translation) @ frame
def arms_drum(core, cfg):
"""DRUM SHOULDER: per arm one pitch bearing on the chassis's side face (a slew ring `drum` long, its axis
canted `cant` degrees up outboard), the upper arm a kit thigh hanging from its drum on that bearing, and a
forearm (kit wrist) pinned in its clevis: two parallel axes, no abduction and no twist, as a walker's light
arm is drawn (KESTREL). cfg: arm {pin_r, drum, cant, upper, width, depth, fore, face_r}, chassis.side_r, aims
{side: (unused, upper dir, forearm dir)}. Returns {side: {slew, upper, fore, sx, cannon}}."""
a, sr, arms = cfg["arm"], cfg["chassis"]["side_r"], {}
for side, sock, sx in (("L", "left", -1), ("R", "right", 1)):
_, upper_dir, fore_dir = cfg["aims"][side]
sl = place("slew_ring", f"Shoulder{side}", mat="machine", r=sr, height=a["drum"], bolts=18, teeth=60)
seat_loose(sl, "base", core, canted(local_sockets(core)[sock], a.get("cant", 0.0)), 90)
up = attach(place("thigh", f"UpperArm{side}", length=a["upper"], width=a["width"], depth=a["depth"], pin_r=a["pin_r"], ring_r=sr), "hip_l" if side == "L" else "hip_r", sl, "top")
aim_roll(up, (0, 0, 1), upper_dir)
fore = attach(place("wrist", f"Forearm{side}", ring_r=a["face_r"], drop=a["fore"][side], width=0.9 * a["width"], pin_r=a["pin_r"]), "tongue", up, "clevis")
aim_roll(fore, (0, 0, 1), fore_dir)
arms[side] = dict(slew=sl, upper=up, fore=fore, cannon=None, sx=sx)
return arms
# --- joint designs: one axis each, each a helper -------------------------------------------------------------------
@ -1937,10 +2044,17 @@ def field_views(name, t0, hero=(30.0, 3.0), rear=(180.0, 6.0), hero_size=(2000,
size = (1000, 1200) if quick else hero_size
cams = {"hero": {"lens": 60.0, "margin": 0.86, **(hero_cam or {})}, "rear": {"lens": 60.0, "margin": 0.86, **(rear_cam or {})}, "front": dict(lens=60.0, margin=0.86)}
views = {}
for tag, (az, el) in (("hero", hero), ("rear", rear), ("front", (0.0, 3.0))):
cams["side"] = dict(lens=60.0, margin=0.86)
for tag, (az, el) in (("hero", hero), ("rear", rear), ("front", (0.0, 3.0)), ("side", (90.0, 3.0))):
silhouette(rig, cam, radius, az, el, out / f"{name}_sil_{tag}.png", (1000, 1200), **cams[tag])
if joints:
views[tag] = {"size": [1000, 1200], "joints": project(cam, joints, (1000, 1200))}
if joints and FLOW:
lines = flow_lines()
for tag in ("hero", "rear"):
az, el = hero if tag == "hero" else rear
silhouette(rig, cam, radius, az, el, out / f"{name}_sil_{tag}.png", (1000, 1200), **cams[tag])
views[tag]["flow"] = {k: [project(cam, {"p": p}, (1000, 1200))["p"] for p in pts] for k, pts in lines.items()}
if joints:
(out / f"{name}_skeleton.json").write_text(json.dumps({"views": views, "world": {k: [round(c, 3) for c in v] for k, v in joints.items()}}, indent=1), encoding="utf-8")
if os.environ.get("MECH_SKELETON_ONLY"):
@ -1996,38 +2110,55 @@ def joint_points(body):
out[f"ankle_{s}"] = sockets(sh)["clevis"].translation
for side, arm in body["arms"].items():
s = side.lower()
out[f"shoulder_{s}"] = sockets(arm["yoke"])["clevis"].translation
out[f"elbow_{s}"] = sockets(arm["elbow"])["clevis"].translation
if "yoke" in arm:
out[f"shoulder_{s}"] = sockets(arm["yoke"])["clevis"].translation
out[f"elbow_{s}"] = sockets(arm["elbow"])["clevis"].translation
else: # a drum shoulder (arms_drum): the pivot is the upper arm's own origin
out[f"shoulder_{s}"] = arm["upper"].matrix_world.translation.copy()
out[f"elbow_{s}"] = sockets(arm["upper"])["clevis"].translation
out[f"wrist_{s}"] = sockets(arm["fore"])["face"].translation
return out
def lay(sk, cfg, hull_top, depth, elbow_y, splay=1.0):
def lay(sk, cfg, hull_top, depth, elbow_y, splay=1.0, cant=None):
"""A biped() cfg laid on a solved skeleton (skeleton.solve): link lengths, the feet's drop, the pelvis's span
and height, the chassis's width, height and shoulder line, the upper arm's length and the leg and upper-arm
aims are derived; widths, radii and the pose in depth stay the caller's. `hull_top` is the chassis's top in
metres (the skeleton's height is the figure's, radiators and all). `depth` is {side: (knee, ankle)}: how far
each stands in front of the hip axis; the links take the left leg's lengths and the right is re-solved by
biped(). `elbow_y` is {side: the elbow's depth}. The legs have no splay joint, so they stand between the hip's
half-span (`splay` 0) and the mean of the hip's, knee's and ankle's (`splay` 1). Returns cfg, changed."""
half-span (`splay` 0) and the mean of the hip's, knee's and ankle's (`splay` 1). With `cant` (degrees;
skeleton.cant() reads it off the rear view) the hips are canted instead (biped's hip_cant): the legs hang from
the hip's own half-span and lean out to the ankles, and the links are as long as that leaning plane needs. With
cfg["arms"] "drum" the arm is arms_drum's: the bearing's length and the upper arm's are derived. Returns cfg."""
J = sk["joints"]
hip, knee, ankle, sh, el, waist = (Vector(J[k]) for k in ("hip", "knee", "ankle", "shoulder", "elbow", "waist"))
(_, w1, d1), (_, w2, d2) = cfg["links"]
ky, ay = depth["L"]
cfg["links"] = [(math.hypot(hip.y - knee.y, ky), w1, d1), (math.hypot(knee.y - ankle.y, ky - ay), w2, d2)]
lean = math.tan(math.radians(cant or 0.0))
cos = math.cos(math.radians(cant or 0.0))
cfg["links"] = [(math.hypot((hip.y - knee.y) / cos, ky), w1, d1), (math.hypot((knee.y - ankle.y) / cos, ky - ay), w2, d2)]
cfg["foot"] = (cfg["foot"][0], cfg["foot"][1], ankle.y)
cfg["leg_aims"] = {side: ((0, k, knee.y - hip.y), (0, a - k, ankle.y - knee.y)) for side, (k, a) in depth.items()}
cfg["leg_aims"] = {side: (((-1 if side == "L" else 1) * lean * (hip.y - knee.y), k, knee.y - hip.y), ((-1 if side == "L" else 1) * lean * (knee.y - ankle.y), a - k, ankle.y - knee.y))
for side, (k, a) in depth.items()}
leg_x = hip.x + splay * ((hip.x + knee.x + ankle.x) / 3 - hip.x)
if cant:
cfg["hip_cant"], leg_x = cant, hip.x
cfg["pelvis"].update(span=2 * (leg_x - cfg["hip_h"] - 0.5 * w1), height=2 * (waist.y - hip.y))
ch, arm = cfg["chassis"], cfg["arm"]
ch["height"] = hull_top - waist.y - cfg["waist_h"]
ch["shoulder"] = (sh.y - waist.y - cfg["waist_h"]) / ch["height"]
ch["width"] = 2 * (sh.x - 0.47 * ch["side_r"] - arm["yoke"][0])
drum = cfg.get("arms") == "drum"
if drum: # the chassis's width is the caller's; the bearing fills what is left to the arm's centre plane
arm["drum"] = sh.x - 0.5 * ch["width"] - 0.5 * arm["width"]
arm["cant"] = math.degrees(math.atan2(el.x - sh.x, sh.y - el.y))
else:
ch["width"] = 2 * (sh.x - 0.47 * ch["side_r"] - arm["yoke"][0])
aims = {}
for side, sx in (("L", -1), ("R", 1)):
upper = Vector((sx * (el.x - sh.x), elbow_y[side], el.y - sh.y))
aims[side] = (cfg["aims"][side][0], tuple(upper), cfg["aims"][side][2])
arm["upper"] = upper.length - 0.42 * arm["twist_r"] - arm["elbow"][0]
arm["upper"] = upper.length if drum else upper.length - 0.42 * arm["twist_r"] - arm["elbow"][0]
cfg["aims"] = aims
return cfg
@ -2253,3 +2384,118 @@ def seat(host, origin=(0, 0, 0), outboard=None, side=1, scale=1.0):
m = Matrix((x * scale, y * scale, z * scale)).transposed().to_4x4()
m.translation = Vector(origin)
return m
# --- the new-mechs track: tools more than one component uses ------------------------------------------------------------
def face_out(sheet, outward):
"""A shell sheet with `flip` set so its surface faces `outward` (a direction in the sheet's own frame): the mean
normal of the authored quads, by the action's winding (P[i][j], P[i][j+1], P[i+1][j+1], P[i+1][j]), is turned to
that side. On a mirrored sheet the x of both is left out, since the two halves cancel there."""
rings = [[Vector(p) for p in ring] for ring in sheet["rings"]]
normal = Vector((0, 0, 0))
closed = sheet.get("closed", False)
for i in range(len(rings) - 1):
n = len(rings[i])
for j in range(n if closed else n - 1):
a, b, c, d = rings[i][j], rings[i][(j + 1) % n], rings[i + 1][(j + 1) % n], rings[i + 1][j]
normal += (c - a).cross(d - b)
if closed: # a sleeve faces away from its own middle; `outward` is not read
middle = sum((p for ring in rings for p in ring), Vector((0, 0, 0))) / sum(len(ring) for ring in rings)
away = 0.0
for i in range(len(rings) - 1):
n = len(rings[i])
for j in range(n):
a, b, c, d = rings[i][j], rings[i][(j + 1) % n], rings[i + 1][(j + 1) % n], rings[i + 1][j]
away += (c - a).cross(d - b).dot((a + b + c + d) / 4 - middle)
return {**sheet, "flip": away < 0}
outward = Vector(outward)
if sheet.get("mirror"):
normal.x = outward.x = 0.0
return {**sheet, "flip": normal.dot(outward) < 0}
def mass(build, name, geo, mat="khaki", bevel=0.014):
"""A closed block as an object of its own on a Build's host, now (Build.done makes one object a material at the
end, which nothing can cut before): `geo` is a Geo in the component's frame. It stands where Build.done would put
it; a to_host that sizes it is written into its points. Cut it with cuts_on. Returns the object."""
to_host = Matrix.Identity(4) if build.to_host is None else Matrix(build.to_host)
turn, stretch = _turn_and_stretch(name, to_host)
bmesh.ops.transform(geo.bm, matrix=stretch.to_4x4(), verts=geo.bm.verts[:])
if stretch.determinant() < 0:
bmesh.ops.reverse_faces(geo.bm, faces=geo.bm.faces[:])
obj = geo.to_object(name, mat, build.host, 22.0)
obj.matrix_parent_inverse = Matrix.Identity(4)
obj.matrix_local = turn
STRETCH[name] = stretch
MASS_BEVEL[name] = bevel
update()
return obj
def cuts_on(name, cuts):
"""cuts_action for a mass(): panel lines, insets and notches by brokkr_kitbash.cut_many, rays in the component's
frame; then the block's bevel, after the cut, so a recess's edges catch light as the block's own do."""
cuts_action(name, cuts)
obj = bpy.data.objects[name]
if MASS_BEVEL.get(name):
mod = obj.modifiers.new("Bevel", "BEVEL")
mod.width, mod.segments, mod.limit_method, mod.angle_limit = MASS_BEVEL[name], 1, "ANGLE", math.radians(18)
obj.hide_viewport = True # a block is finished once cut: at rest until wake()
RESTING.append(name)
return obj
MASS_BEVEL = {}
def ringed_disc(g, frame, r, t, hub=True):
"""A bearing cap of concentric rings on a Geo: a rim, a groove, a raised race, a dished face and, with `hub`, a
hub and its bolt. z out of the face. Every joint of the organic sheets (27 to 31) is capped by one."""
profile = [(r, 0), (r, 0.5 * t), (0.9 * r, 0.6 * t), (0.86 * r, 0.6 * t), (0.86 * r, 0.42 * t), (0.8 * r, 0.42 * t), (0.8 * r, 0.82 * t), (0.64 * r, 0.82 * t), (0.64 * r, 0.6 * t),
(0.54 * r, 0.6 * t)]
profile += [(0.54 * r, t), (0.32 * r, t), (0.32 * r, 0.8 * t), (0.15 * r, 0.8 * t), (0.15 * r, 1.06 * t), (0, 1.06 * t)] if hub else [(0, 0.6 * t)]
return g.lathe(frame, profile, 48)
def track(g, a, b, width, n, t, normal):
"""A ribbed strip on a Geo from a to b: n bars across `width`, standing `t` along `normal`. A flexible cover, a
belt, a spine."""
a, b = Vector(a), Vector(b)
step = (b - a).length / n
for k in range(n):
g.box(frame_at(a.lerp(b, (k + 0.5) / n), normal, b - a), (width, 0.6 * step, t))
g.box(frame_at((a + b) / 2 - Vector(normal).normalized() * 0.4 * t, normal, b - a), (0.92 * width, (b - a).length, 0.3 * t))
return g
def seat_along(host, origin=(0, 0, 0), side=1, outboard=None, scale=1.0):
"""seat() for a component drawn along +y (a gun, a forearm with its bore forward): its y is laid along the host's
+z, whatever way that points, and its z along whichever of the host's x and y axes points highest. `outboard`
and `side` mirror it as seat() does."""
update()
R = host.matrix_world.to_3x3()
y = Vector((0, 0, 1))
z = max((Vector(a) for a in ((1, 0, 0), (-1, 0, 0), (0, 1, 0), (0, -1, 0))), key=lambda a: (R @ a).z)
x = y.cross(z)
if outboard is not None and ((R @ x).x > 0) != (outboard * side > 0):
x = -x
m = Matrix((x * scale, y * scale, z * scale)).transposed().to_4x4()
m.translation = Vector(origin)
return m
FLOW = {}
def flow(line, host, to_host, points):
"""Add points to one of the figure's flow lines (ruling mech-flow-lines-across-parts): `points` in a component's
frame, on the edge or crease of the part that carries the line there. Lines are named as concepts.json names the
concept's ("flow"); field_views projects them into the hero and rear views for compare.py's flow sheet."""
at = Matrix.Identity(4) if to_host is None else Matrix(to_host)
FLOW.setdefault(line, []).extend((host, at @ Vector(p)) for p in points)
def flow_lines():
update()
return {k: [(host.matrix_world @ p) if host is not None else p for host, p in pts] for k, pts in FLOW.items()}

View file

@ -1,6 +1,8 @@
"""Builds components alone and renders each from its concept inset's side.
MECH_PARTS: comma-separated names from <MECH_SET>_parts.PARTS (default all); MECH_SET: the mech (default seraph).
Writes MECH_OUT/<mech>/parts/<name>.png, 800 px, for compare.py's components sheet."""
Writes MECH_OUT/<mech>/parts/<name>.png, 800 px, for compare.py's components sheet; <name>_frame.png where the
library names a FRAMES view (the frame a plate stands on); <name>_var.png where it names VARIANTS (the same function
at other sizes: the catalog's parameter variant). Prints, a part, its shells' folded faces and open edges."""
import importlib, math, os, sys, time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent))
@ -15,23 +17,34 @@ out = Path(os.environ["MECH_OUT"]) / mech / "parts"
assert out.is_absolute()
out.mkdir(parents=True, exist_ok=True)
names = [n for n in os.environ.get("MECH_PARTS", "").split(",") if n] or list(lib.PARTS)
import json
(out / "catalog.json").write_text(json.dumps({n: {"module": lib.__name__, "function": f.__name__, "doc": (f.__doc__ or "").strip().split(". ")[0], "variant": getattr(lib, "VARIANTS", {}).get(n, {})}
for n, f in lib.PARTS.items()}, indent=1), encoding="utf-8")
for name in names:
t0 = time.time()
for obj in list(bpy.data.objects):
bpy.data.objects.remove(obj, do_unlink=True)
az, el, margin, pitch = lib.VIEWS[name]
host = bpy.data.objects.new("Bench", None)
bpy.context.scene.collection.objects.link(host)
host.matrix_world = Matrix.Translation((0, 0, getattr(lib, "GROUND", {}).get(name, 5.0))) @ Matrix.Rotation(math.radians(pitch), 4, "X")
build = M.Build(name, host)
lib.PARTS[name](build)
build.done()
M.update()
rig, cam, centre, radius = M.stage_field(int(os.environ.get("MECH_SAMPLES", "32")))
M.shot(rig, cam, radius, az, el, out / f"{name}.png", (800, 800), margin=margin, lens=85.0)
if name in getattr(lib, "FRAMES", {}): # a second view, from underneath: the frame the plate stands on
faz, fel, fmargin, hidden = lib.FRAMES[name]
for other in hidden:
bpy.data.objects[other].hide_render = True
M.shot(rig, cam, radius, faz, fel, out / f"{name}_frame.png", (800, 800), margin=fmargin, lens=85.0)
print("PART", name, "s", round(time.time() - t0, 1), "faces", sum(len(o.data.polygons) for o in bpy.data.objects if o.type == "MESH"))
for suffix, sizes in (("", {}), ("_var", getattr(lib, "VARIANTS", {}).get(name))):
if sizes is None:
continue
t0 = time.time()
for obj in list(bpy.data.objects):
bpy.data.objects.remove(obj, do_unlink=True)
M.FOLDED.clear()
az, el, margin, pitch = lib.VIEWS[name]
host = bpy.data.objects.new("Bench", None)
bpy.context.scene.collection.objects.link(host)
host.matrix_world = Matrix.Translation((0, 0, getattr(lib, "GROUND", {}).get(name, 5.0))) @ Matrix.Rotation(math.radians(pitch), 4, "X")
build = M.Build(name, host)
lib.PARTS[name](build, **sizes)
build.done()
M.update()
try:
M.shells_sound()
except SystemExit as unsound:
print("PART UNSOUND", name + suffix, unsound, flush=True)
rig, cam, centre, radius = M.stage_field(int(os.environ.get("MECH_SAMPLES", "32")))
M.shot(rig, cam, radius, az, el, out / f"{name}{suffix}.png", (800, 800), margin=margin, lens=85.0)
if not suffix and name in getattr(lib, "FRAMES", {}): # a second view, from underneath: the frame the plate stands on
faz, fel, fmargin, hidden = lib.FRAMES[name]
for other in hidden:
bpy.data.objects[other].hide_render = True
M.shot(rig, cam, radius, faz, fel, out / f"{name}_frame.png", (800, 800), margin=fmargin, lens=85.0)
print("PART", name + suffix, "s", round(time.time() - t0, 1), "faces", sum(len(o.data.polygons) for o in bpy.data.objects if o.type == "MESH"), flush=True)

View file

@ -48,6 +48,13 @@ def solve(name):
return {"height": H, "joints": joints, "ratios": {"rear": rear, "hero": hero}}
def cant(sk):
"""The leg's lean outward, in degrees, read off a solved skeleton: the angle from plumb of the line from hip to
ankle in the rear view. A mech whose feet stand wider than its hips has canted hips (mechlib.biped's hip_cant)."""
hip, ankle = sk["joints"]["hip"], sk["joints"]["ankle"]
return math.degrees(math.atan2(ankle[0] - hip[0], hip[1] - ankle[1]))
def lengths(r):
"""Segment lengths of one view's ratios, mean of the two sides, in figure heights."""
return {name: sum(math.dist(r[a + s], r[b + s]) for s in ("_l", "_r")) / 2 for name, a, b in SEGMENTS if a + "_l" in r and b + "_l" in r}