agent (cont.)

+0:58
  • read_file{"Path":"~/work/sortie/kit/lab/knightkit.py"}

    input

    {
      "Path": "~/work/sortie/kit/lab/knightkit.py"
    }

    result, 536 lines

    Showing lines 1-535 of 535
    1: """Sheets with compound curvature for the atelier direction board (kit/lab/atelier_board.py).
    2: 
    3: Round 1's plates are cones and cylinders of even thickness: shell() intersects two flat outlines, so
    4: it can only make flat and single curved faces. Knightly armour reads through domes, a curved profile
    5: down every plate, raised ridges, flutes and rolled rims. These helpers make them:
    6: 
    7:   Sheet     a plate t thick over a surface f(u, v): the outer face, the inner face set back along the
    8:             normals, closed round its edges. `disp` pushes the outer face out (ridges, flutes).
    9:   revolve   a surface of revolution round a vertical axis, elliptical in plan, through a profile of
    10:             (radius, z) points: the profile curves, so the plate is domed, not a cone
    11:   bead      a tube along a line of points: a rolled rim on a plate's edge, roped with `rope`
    12:   ridge, flutes   displacement profiles across u
    13: 
    14: Angles are degrees in plan, 0 is +X (outboard on the left), -90 the front (-Y), 90 the back.
    15: """
    16: import math
    17: 
    18: import bmesh
    19: from mathutils import Vector
    20: 
    21: 
    22: def lin(a, b, n):
    23:     """n + 1 values from a to b."""
    24:     return [a + (b - a) * i / n for i in range(n + 1)]
    25: 
    26: 
    27: def spline(pts):
    28:     """A Catmull-Rom curve through points (tuples), as a function of t in [0, 1]."""
    29:     P = [Vector(p) for p in pts]
    30:     n = len(P) - 1
    31: 
    32:     def at(t):
    33:         x = min(max(t, 0.0), 1.0) * n
    34:         i = min(int(x), n - 1)
    35:         s = x - i
    36:         p0, p1, p2, p3 = P[max(i - 1, 0)], P[i], P[i + 1], P[min(i + 2, n)]
    37:         return .5 * ((2 * p1) + (-p0 + p2) * s + (2 * p0 - 5 * p1 + 4 * p2 - p3) * s * s + (-p0 + 3 * p1 - 3 * p2 + p3) * s ** 3)
    38:     return at
    39: 
    40: 
    41: class Sheet:
    42:     """A plate t thick over f(u, v) on the grid us x vs. `inside` is a point on the plate's inner side
    43:     (default: the centroid of the surface, right for domes and shells round a body). `disp(u, v)`
    44:     moves the outer face out along the normal. `wrap` closes the sheet round u."""
    45: 
    46:     def __init__(self, f, us, vs, t, disp=None, inside=None, wrap=False):
    47:         self.us, self.vs, self.t, self.wrap = list(us), list(vs), t, wrap
    48:         nu, nv = len(self.us), len(self.vs)
    49:         S = [[Vector(f(u, v)) for v in self.vs] for u in self.us]
    50: 
    51:         def nrm(i, j):
    52:             if wrap:
    53:                 a, b = S[(i + 1) % nu][j], S[(i - 1) % nu][j]
    54:             else:
    55:                 a, b = S[min(i + 1, nu - 1)][j], S[max(i - 1, 0)][j]
    56:             c, d = S[i][min(j + 1, nv - 1)], S[i][max(j - 1, 0)]
    57:             n = (a - b).cross(c - d)
    58:             return n.normalized() if n.length > 1e-9 else None
    59:         N = [[nrm(i, j) for j in range(nv)] for i in range(nu)]
    60:         # a pole (a cap drawn from v = 0) has no normal of its own: it takes the mean of the next row's
    61:         for j in range(nv):
    62:             if any(N[i][j] is None for i in range(nu)):
    63:                 k = j + 1 if j + 1 < nv else j - 1
    64:                 m = sum((n for n in (N[i][k] for i in range(nu)) if n is not None), Vector())
    65:                 m = m.normalized() if m.length > 1e-9 else Vector((0, 0, 1))
    66:                 for i in range(nu):
    67:                     if N[i][j] is None:
    68:                         N[i][j] = m
    69:         c = Vector(inside) if inside is not None else sum((p for row in S for p in row), Vector()) / (nu * nv)
    70:         if sum(N[i][j].dot(S[i][j] - c) for i in range(nu) for j in range(nv)) < 0:
    71:             N = [[-n for n in row] for row in N]
    72:         if disp is not None:
    73:             S = [[S[i][j] + N[i][j] * disp(self.us[i], self.vs[j]) for j in range(nv)] for i in range(nu)]
    74:         self.O, self.N = S, N
    75:         self.I = [[S[i][j] - N[i][j] * t for j in range(nv)] for i in range(nu)]
    76: 
    77:     def bm(self):
    78:         bm = bmesh.new()
    79:         nu, nv = len(self.us), len(self.vs)
    80:         O = [[bm.verts.new(p) for p in row] for row in self.O]
    81:         I = [[bm.verts.new(p) for p in row] for row in self.I]
    82:         iu = range(nu) if self.wrap else range(nu - 1)
    83:         for i in iu:
    84:             k = (i + 1) % nu
    85:             for j in range(nv - 1):
    86:                 bm.faces.new((O[i][j], O[k][j], O[k][j + 1], O[i][j + 1]))
    87:                 bm.faces.new((I[i][j + 1], I[k][j + 1], I[k][j], I[i][j]))
    88:             bm.faces.new((O[i][0], I[i][0], I[k][0], O[k][0]))
    89:             bm.faces.new((O[k][-1], I[k][-1], I[i][-1], O[i][-1]))
    90:         if not self.wrap:
    91:             for j in range(nv - 1):
    92:                 bm.faces.new((O[0][j + 1], I[0][j + 1], I[0][j], O[0][j]))
    93:                 bm.faces.new((O[-1][j], I[-1][j], I[-1][j + 1], O[-1][j + 1]))
    94:         bmesh.ops.remove_doubles(bm, verts=bm.verts, dist=1e-6)  # closes a pole
    95:         bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
    96:         return bm
    97: 
    98:     def edge(self, side, at=.5, out=0.0):
    99:         """Points along one edge (u0, u1, v0, v1), `at` of the way through the thickness, pushed `out`
    100:         along the normal."""
    101:         nu, nv = len(self.us), len(self.vs)
    102:         idx = {"u0": [(0, j) for j in range(nv)], "u1": [(nu - 1, j) for j in range(nv)],
    103:                "v0": [(i, 0) for i in range(nu)], "v1": [(i, nv - 1) for i in range(nu)]}[side]
    104:         return [self.O[i][j] - self.N[i][j] * (self.t * at - out) for i, j in idx]
    105: 
    106:     def point(self, i, j, out=0.0):
    107:         return self.O[i][j] + self.N[i][j] * out
    108: 
    109: 
    110: def revolve(c, profile, kx=1.0, ky=1.0, steps=40):
    111:     """f(u, v) for a surface round a vertical axis through c = (x, y): u the plan angle in degrees, v in
    112:     [0, 1] along the profile, a list of (radius, z) points (or a function of v). kx and ky stretch the
    113:     plan into an ellipse. A profile that curves makes the plate domed."""
    114:     prof = profile if callable(profile) else spline(profile)
    115: 
    116:     def f(u, v):
    117:         r, z = prof(v)[:2]
    118:         a = math.radians(u)
    119:         return (c[0] + r * kx * math.cos(a), c[1] + r * ky * math.sin(a), z)
    120:     return f
    121: 
    122: 
    123: def tent(x, x0, w):
    124:     """1 at x0, falling linearly to 0 at x0 +- w: a ridge with a crease on its crest."""
    125:     return max(0.0, 1.0 - abs(x - x0) / w)
    126: 
    127: 
    128: def flutes(x, x0, x1, n, w=.5):
    129:     """n rounded flutes between x0 and x1, each `w` of its pitch wide, 0 between them."""
    130:     if not (x0 <= x <= x1):
    131:         return 0.0
    132:     s = (x - x0) / (x1 - x0) * n
    133:     f = s - math.floor(s)
    134:     d = abs(f - .5) / (w / 2)
    135:     return math.cos(min(d, 1.0) * math.pi / 2) ** 2 if d < 1 else 0.0
    136: 
    137: 
    138: def smooth(x, a, b):
    139:     """0 below a, 1 above b, smooth between."""
    140:     t = min(max((x - a) / (b - a), 0.0), 1.0)
    141:     return t * t * (3 - 2 * t)
    142: 
    143: 
    144: def bead(pts, r, n=None, rope=0.0, closed=False, pitch=None):
    145:     """A tube of radius r along points: a rolled rim. `rope` (0..1) twists three strands into it, a
    146:     roped rim, one turn every `pitch` metres."""
    147:     n = n or (12 if rope else 10)
    148:     pitch = pitch or r * 9
    149:     step = pitch / 9 if rope else r * 2.5
    150:     P0 = [Vector(p) for p in pts]
    151:     P = []
    152:     for i in range(len(P0) if closed else len(P0) - 1):
    153:         a, b = P0[i], P0[(i + 1) % len(P0)]
    154:         k = max(1, int((b - a).length / step + .999))
    155:         P += [a.lerp(b, j / k) for j in range(k)]
    156:     if not closed:
    157:         P.append(P0[-1])
    158:     m = len(P)
    159:     T = []
    160:     for i in range(m):
    161:         a = P[(i + 1) % m] if closed else P[min(i + 1, m - 1)]
    162:         b = P[(i - 1) % m] if closed else P[max(i - 1, 0)]
    163:         T.append((a - b).normalized())
    164:     up = Vector((0, 0, 1)) if abs(T[0].z) < .9 else Vector((1, 0, 0))
    165:     Nn = [(up - T[0] * up.dot(T[0])).normalized()]
    166:     for i in range(1, m):
    167:         v = Nn[-1] - T[i] * Nn[-1].dot(T[i])
    168:         Nn.append(v.normalized() if v.length > 1e-9 else Nn[-1])
    169:     bm = bmesh.new()
    170:     rings, s = [], 0.0
    171:     for i in range(m):
    172:         if i:
    173:             s += (P[i] - P[i - 1]).length
    174:         B = T[i].cross(Nn[i])
    175:         ring = []
    176:         for k in range(n):
    177:             q = 2 * math.pi * k / n
    178:             rr = r * (1 + rope * .2 * math.cos(3 * q - 2 * math.pi * s / pitch))
    179:             ring.append(bm.verts.new(P[i] + (Nn[i] * math.cos(q) + B * math.sin(q)) * rr))
    180:         rings.append(ring)
    181:     for i in range(m if closed else m - 1):
    182:         a, b = rings[i], rings[(i + 1) % m]
    183:         for k in range(n):
    184:             bm.faces.new((a[k], a[(k + 1) % n], b[(k + 1) % n], b[k]))
    185:     if not closed:
    186:         bm.faces.new(list(reversed(rings[0])))
    187:         bm.faces.new(rings[-1])
    188:     bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
    189:     return bm
    190: 
    191: 
    192: def rivets(pts, r=.06, n=6):
    193:     """Small domed studs at points [(position, normal)]."""
    194:     bm = bmesh.new()
    195:     for p, nn in pts:
    196:         p, nn = Vector(p), Vector(nn).normalized()
    197:         a = nn.orthogonal().normalized()
    198:         b = nn.cross(a)
    199:         base = [bm.verts.new(p + (a * math.cos(2 * math.pi * k / n) + b * math.sin(2 * math.pi * k / n)) * r - nn * r * .3) for k in range(n)]
    200:         mid = [bm.verts.new(p + (a * math.cos(2 * math.pi * k / n) + b * math.sin(2 * math.pi * k / n)) * r * .75 + nn * r * .35) for k in range(n)]
    201:         tip = bm.verts.new(p + nn * r * .6)
    202:         bm.faces.new(list(reversed(base)))
    203:         for k in range(n):
    204:             j = (k + 1) % n
    205:             bm.faces.new((base[k], base[j], mid[j], mid[k]))
    206:             bm.faces.new((mid[k], mid[j], tip))
    207:     bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
    208:     return bm
    209: 
    210: 
    211: def cap(c, axis, radii, up=(0, 0, 1)):
    212:     """f(u, v) for an ellipsoid round c with its pole along `axis`: u the angle round the axis in
    213:     degrees (0 toward `up`), v the angle from the pole in degrees. radii = (across up, across, along
    214:     the axis). Elbow and knee cops, fans and domes that face sideways."""
    215:     z = Vector(axis).normalized()
    216:     x = Vector(up) - z * Vector(up).dot(z)
    217:     x = x.normalized() if x.length > 1e-6 else z.orthogonal().normalized()
    218:     y = z.cross(x)
    219:     c = Vector(c)
    220:     ra, rb, rp = radii
    221: 
    222:     def f(u, v):
    223:         a, b = math.radians(u), math.radians(v)
    224:         return c + x * (ra * math.sin(b) * math.cos(a)) + y * (rb * math.sin(b) * math.sin(a)) + z * (rp * math.cos(b))
    225:     return f
    226: 
    227: 
    228: def put(P, name, sheet, role, jl, jr=None, bevel=.012):
    229:     """A sheet as a plate on a joint (mirrored onto jr)."""
    230:     P.solid(name, sheet.bm(), role, jl, jr, bevel=bevel)
    231: 
    232: 
    233: def rim(P, name, pts, r, jl, jr=None, role="trim", rope=0.0, closed=False):
    234:     """A rolled rim along points, in trim by default."""
    235:     P.solid(name, bead(pts, r, rope=rope, closed=closed), role, jl, jr, bevel=0)
    236: 
    237: 
    238: def curve(vals):
    239:     """A smooth function on [0, 1] through evenly spaced values."""
    240:     n = len(vals) - 1
    241:     s = spline([(i / n, v) for i, v in enumerate(vals)])
    242:     return lambda t: s(t)[1]
    243: 
    244: 
    245: def band(c, z0, z1, r, us, nv=6, kx=1.0, ky=1.0, t=.12, disp=None, wrap=False):
    246:     """A sheet round a vertical axis through c = (x, y) from height z0 to z1 (numbers or functions of
    247:     u). The radius r is a number, a pair (at z0, at z1), a list of evenly spaced values or a function
    248:     r(u, v), with v 0 at z0 and 1 at z1. Lames, tassets, greaves, sleeves."""
    249:     Z0 = z0 if callable(z0) else (lambda u: z0)
    250:     Z1 = z1 if callable(z1) else (lambda u: z1)
    251:     if callable(r):
    252:         R = r
    253:     elif isinstance(r, (int, float)):
    254:         R = lambda u, v: r
    255:     elif len(r) == 2:
    256:         R = lambda u, v: r[0] + (r[1] - r[0]) * v
    257:     else:
    258:         g = curve(r)
    259:         R = lambda u, v: g(v)
    260: 
    261:     def f(u, v):
    262:         a = math.radians(u)
    263:         rr = R(u, v)
    264:         return (c[0] + rr * kx * math.cos(a), c[1] + rr * ky * math.sin(a), Z0(u) + (Z1(u) - Z0(u)) * v)
    265:     um = us[len(us) // 2]
    266:     if wrap:
    267:         us = list(us)[:-1]  # a closed ring: the last angle is the first
    268:     return Sheet(f, us, lin(0, 1, nv), t, disp=disp, inside=(c[0], c[1], (Z0(um) + Z1(um)) / 2), wrap=wrap)
    269: 
    270: 
    271: def helm(P, J, g, extra=None, base=True):
    272:     """The atelier's helm (makers.atelier) with `extra(P, J)` adding parts on the head joint, all
    273:     seated low between the pauldrons as atelier.head does. base=False leaves the atelier helm out, for a
    274:     line that draws its own (its shell must be named head_helmet, which atelier.crown_z reads)."""
    275:     from mathutils import Matrix
    276: 
    277:     from makers import atelier
    278:     H = J["head"]
    279:     if base:
    280:         atelier._head(P, J, g)
    281:     if extra is not None:
    282:         extra(P, J)
    283:     m = Matrix.Translation((0, 0, -atelier.HEAD_DROP))
    284:     for o in H.children:
    285:         if o.type == "MESH":
    286:             for v in o.data.vertices:
    287:                 v.co = m @ v.co
    288: 
    289: 
    290: def horn(pts, r0, n=10, power=1.4, squash=1.0, up=(0, 0, 1)):
    291:     """A solid tapering from radius r0 at the first point to a sharp tip at the last, along a line of
    292:     points (bend it for a swept horn). `squash` flattens the section across `up`: a blade."""
    293:     P = [Vector(p) for p in pts]
    294:     m = len(P)
    295:     L = [0.0]
    296:     for i in range(1, m):
    297:         L.append(L[-1] + (P[i] - P[i - 1]).length)
    298:     bm = bmesh.new()
    299:     rings = []
    300:     for i in range(m):
    301:         t = (P[min(i + 1, m - 1)] - P[max(i - 1, 0)]).normalized()
    302:         a = Vector(up) - t * Vector(up).dot(t)
    303:         a = a.normalized() if a.length > 1e-6 else t.orthogonal().normalized()
    304:         b = t.cross(a)
    305:         r = r0 * max(1 - L[i] / L[-1], 0.0) ** power
    306:         if i == m - 1:
    307:             rings.append([bm.verts.new(P[i])])
    308:             break
    309:         rings.append([bm.verts.new(P[i] + (a * math.cos(2 * math.pi * k / n) + b * squash * math.sin(2 * math.pi * k / n)) * r) for k in range(n)])
    310:     for i in range(m - 2):
    311:         x, y = rings[i], rings[i + 1]
    312:         for k in range(n):
    313:             bm.faces.new((x[k], x[(k + 1) % n], y[(k + 1) % n], y[k]))
    314:     tip = rings[-1][0]
    315:     last = rings[-2]
    316:     for k in range(n):
    317:         bm.faces.new((last[k], last[(k + 1) % n], tip))
    318:     bm.faces.new(list(reversed(rings[0])))
    319:     bmesh.ops.recalc_face_normals(bm, faces=bm.faces)
    320:     return bm
    321: 
    322: 
    323: def shoulder_root(P, J, role="main"):
    324:     """Round 1's cover over the step from the chest to the shoulder joint (makers.atelier.shoulder)."""
    325:     from makers import atelier
    326:     S = (J["shoulder", "L"], J["shoulder", "R"])
    327:     P.solid("shoulder_root", atelier.sheet(atelier.rect(1.6, 2.0, 14.0, 15.05), [(-.8, 14.0), (.25, 14.0), (.25, 15.05), (-.5, 15.05), (-.8, 14.8)],
    328:                                            atelier.ring((1.8, -.1), (.3, .72), 180, 360)), role, *S)
    329: 
    330: 
    331: def strip(path, w, t, grow_f):
    332:     """A flat band of width w along a path on a surface: path(s) -> (u, z) for s in [0, 1], grow_f(u, z, out) ->
    333:     the surface point at plan angle u and height z pushed out by `out`."""
    334:     def f(s, k):
    335:         u, z = path(s)
    336:         return grow_f(u, z + k * w / 2, 0.0)
    337:     return Sheet(f, lin(0, 1, 16), lin(-1, 1, 2), t, inside=(0, 0, 13.6))
    338: 
    339: 
    340: def sabaton(P, J, lames=((.55, -3.35),), point=1.0, keel=0.0, rims="front", rope=0.0, role="main"):
    341:     """A sabaton arched over the frame's foot, in foot space (frame_std.place_foot fits it), plus the
    342:     atelier's heel spinner. `lames` are (heel end y, toe end y) spans, each laid over the next toward
    343:     the toe. `point` 1 narrows the toe to a point, 0 keeps it broad and round. `keel` raises a ridge down
    344:     the instep. `rims`: "front" rolls each lame's toe edge in trim, "all" rims the whole hem, None none."""
    345:     import frame_std
    346:     from makers import atelier
    347:     FT = (J["foot", "L"], J["foot", "R"])
    348:     fit = frame_std.place_foot
    349:     y_tip = min(b for _, b in lames)
    350:     top = curve([1.18, 1.04, .86, .7, .56, .44])  # heel end to toe, by (.55 - y) / (.55 - y_tip)
    351:     wid = curve([.54, .54, .52, .48, .42, .3])
    352: 
    353:     def f(a, y, grow):
    354:         h = (.55 - y) / (.55 - y_tip)
    355:         w = wid(h) * (1 - point * smooth(h, .7, 1.0) * .8) + grow
    356:         zt = top(h) + grow
    357:         q = math.radians(a)
    358:         s = max(math.sin(q), 0.0) ** .7
    359:         return (1.2 + w * math.cos(q), y, .3 + (zt - .3) * s)
    360:     for i, (y0, y1) in enumerate(lames):
    361:         grow = .05 * (len(lames) - 1 - i)
    362:         sh = Sheet(lambda a, y, grow=grow: f(a, y, grow), lin(-8, 188, 22), lin(y0, y1, 10), .1,
    363:                    disp=(lambda a, y: keel * tent(a, 90, 26)) if keel else None, inside=(1.2, (y0 + y1) / 2, .3))
    364:         P.solid(f"sabaton{i}", fit(sh.bm()), role, *FT, bevel=.01)
    365:         if rims == "front":
    366:             P.solid(f"sabaton_rim{i}", fit(bead(sh.edge("v1", out=.015), .045, rope=rope)), "trim", *FT, bevel=0)
    367:         elif rims == "all":
    368:             pts = sh.edge("u0", out=.015)[::-1] + sh.edge("v1", out=.015) + sh.edge("u1", out=.015)
    369:             P.solid(f"sabaton_rim{i}", fit(bead(pts, .05, rope=rope)), "trim", *FT, bevel=0)
    370:     atelier.spinner(P, J, "medium")
    371: 
    372: 
    373: # ---- shared by every line: layered plates, add-ons, joint covers ---------------------------------------------
    374: def by(g, light, medium, heavy):
    375:     return {"light": light, "medium": medium, "heavy": heavy}[g]
    376: 
    377: 
    378: def put2(P, name, bm, jl, jr, roles, bevel=.012):
    379:     """A plate on jl, mirrored onto jr, each side its own role: roles is one role or (left, right)."""
    380:     from lib import copy, mirror_x
    381:     rl, rr = (roles, roles) if isinstance(roles, str) else roles
    382:     if jr is None:
    383:         P.solid(name, bm, rl, jl, bevel=bevel)
    384:         return
    385:     P.solid(f"{name}.L", copy(bm), rl, jl, bevel=bevel)
    386:     P.solid(f"{name}.R", mirror_x(bm), rr, jr, bevel=bevel)
    387:     bm.free()
    388: 
    389: 
    390: def lames(P, name, c, top, n, h, step, r0, dr, us, jl, jr, roles, rim_role, ky=1.0, kx=1.0, flare=.06, rope=0.0, dip=None, t=.12):
    391:     """n lames stacked downward under a plate, each tucked under the hem of the one above (dr < 0), so every hem
    392:     and its rim shows. `dip(u)` sweeps every edge down where it is positive."""
    393:     for i in range(n):
    394:         za, zb = top - step * i, top - step * i - h
    395:         z0 = (lambda u, zb=zb, i=i: zb - dip(u) * (1 + .3 * i)) if dip else zb
    396:         z1 = (lambda u, za=za, i=i: za - dip(u) * (1 + .3 * i)) if dip else za
    397:         r = r0 + dr * i
    398:         s = band(c, z0, z1, [r + flare, r + flare * .5, r], us, nv=3, kx=kx, ky=ky, t=t)
    399:         put2(P, f"{name}{i}", s.bm(), jl, jr, roles)

    136 more lines not shown.

  • read_file{"Path":"~/work/sortie/kit/frame_std.py"}

    input

    {
      "Path": "~/work/sortie/kit/frame_std.py"
    }

    result, 436 lines

    Showing lines 1-435 of 435
    1: """The standard class inner frame (17.6 m), shared by every maker (docs/visual-language.md).
    2: 
    3: Dark roles only: frame for bones and blocks, joint for housings, cables and pistons, metal for the
    4: mount pad locks, the cockpit socket rim and the ankle pins, trim for the ring on every mount pad.
    5: Joint names and positions are the striker's (mech.joints), so poses, muzzles and harken mounts carry
    6: over. bend_knees stands the knees forward and the feet apart after the plates are on. Plates come
    7: from a maker family (kit/makers) and ride the same joints.
    8: 
    9: The frame shows at the sides and back of the neck, waist, shoulders, elbows, wrists, knees and ankles
    10: under every grade. The foot is a ball ankle in the shin's yoke, an arched sole and a hinged toe.
    11: Pistons at the hips, shoulders, elbows, knees and ankles, a cable run down every long bone. The chest
    12: carries the cockpit socket in front and the reactor drum behind it, visible through the open sides.
    13: Mount pads (one shape, `pad`) at the forearms, shoulders, backpack and hips, each with a mount.* empty.
    14: 
    15: Geometry is authored on the left (+X) in world rest pose coordinates and mirrored.
    16: """
    17: import math
    18: 
    19: import bpy
    20: from mathutils import Matrix, Vector
    21: 
    22: from lib import circle, cylinder, empty, loft, merge, mirror_x, octo, piston, rot, solid, transform, two_view
    23: from mech import gltf_dir, joints as striker_joints
    24: 
    25: HEIGHT = 17.6
    26: BEVEL = .04
    27: PAD = .72  # mount pad edge
    28: PAD_T = .08
    29: ROOF = 15.13  # the shoulder pad sits on the pauldron roof, the same height for every grade
    30: 
    31: 
    32: def box(x0, x1, y0, y1, z0, z1):
    33:     r = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)]
    34:     return loft([(z0, r), (z1, r)])
    35: 
    36: 
    37: def rod(p0, p1, r, n=6):
    38:     """A plain cylinder from p0 to p1."""
    39:     p0, p1 = Vector(p0), Vector(p1)
    40:     a = p1 - p0
    41:     m = Matrix.Translation(p0) @ Vector((0, 0, 1)).rotation_difference(a.normalized()).to_matrix().to_4x4()
    42:     return transform(loft([(0, circle(r, n)), (a.length, circle(r, n))]), m)
    43: 
    44: 
    45: def basis(at, normal, up):
    46:     """A matrix whose local +Z is `normal` and local +Y is `up`, placed at `at`."""
    47:     z = Vector(normal).normalized()
    48:     y = Vector(up)
    49:     y = (y - z * y.dot(z)).normalized()
    50:     x = y.cross(z)
    51:     m = Matrix((x, y, z)).transposed().to_4x4()
    52:     m.translation = Vector(at)
    53:     return m
    54: 
    55: 
    56: def joints(tag="frame_std"):
    57:     """The striker's 22 joint rig, exact names and positions, tagged with this frame's name."""
    58:     J = striker_joints()
    59:     J["frame"]["frame"] = tag
    60:     J["frame"]["height"] = HEIGHT
    61:     return J
    62: 
    63: 
    64: def lr(J, part):
    65:     return J[part, "L"], J[part, "R"]
    66: 
    67: 
    68: def pair(name, bm_left, role, jl, jr, **kw):
    69:     bm_right = mirror_x(bm_left)
    70:     return solid(f"{name}.L", bm_left, role, jl, **kw), solid(f"{name}.R", bm_right, role, jr, **kw)
    71: 
    72: 
    73: def cable(name, pts, parent_l, parent_r=None, r=.055):
    74:     """A cable run along a bone, inside a square duct through the points, a clamp at every inner point.
    75:     Seen from behind it reads as a covered run, not a loose hose."""
    76:     duct = merge(*[rod(a, b, r * 1.6, n=4) for a, b in zip(pts, pts[1:])])
    77:     clamps = merge(*[box(p[0] - .1, p[0] + .1, p[1] - .1, p[1] + .1, p[2] - .06, p[2] + .06) for p in pts[1:-1]]) if len(pts) > 2 else None
    78:     if parent_r is None:
    79:         solid(f"{name}", duct, "frame", parent_l, .01)
    80:         if clamps:
    81:             solid(f"{name}_clamp", clamps, "joint", parent_l)
    82:     else:
    83:         pair(name, duct, "frame", parent_l, parent_r, bevel=.01)
    84:         if clamps:
    85:             pair(f"{name}_clamp", clamps, "joint", parent_l, parent_r)
    86: 
    87: 
    88: def tube(name, rings, at, parents, collars=(), n=10):
    89:     """A long bone: a faceted tube through (height, radius) rings, a joint collar at each height in
    90:     `collars`."""
    91:     pair(name, loft([(z, circle(r, n, *at)) for z, r in rings]), "frame", *parents, bevel=.03)
    92:     radius = lambda z: next(r0 + (r1 - r0) * (z - z0) / (z1 - z0) for (z0, r0), (z1, r1) in zip(rings, rings[1:]) if z0 <= z <= z1)
    93:     if collars:
    94:         cs = [loft([(z - .08, circle(radius(z) + .06, n, *at)), (z + .08, circle(radius(z) + .06, n, *at))]) for z in collars]
    95:         pair(f"{name}_collar", merge(*cs), "joint", *parents, bevel=.015)
    96: 
    97: 
    98: def pad(name, parent, at, normal, up=(0, 0, 1)):
    99:     """The common pattern mount pad: a square plate with clipped corners, four bolt bosses and a lock
    100:     ring in the middle. Every maker builds to it, so it always reads the same. `at` is the centre of
    101:     the pad's back, `normal` the way it faces. A mount.<name> empty marks the face."""
    102:     m = basis(at, normal, up)
    103:     h = PAD / 2
    104:     plate = loft([(0, octo(PAD, PAD, .12)), (PAD_T, octo(PAD, PAD, .12))])
    105:     rim = loft([(PAD_T, octo(PAD * .62, PAD * .62, .06)), (PAD_T + .025, octo(PAD * .62, PAD * .62, .06))])
    106:     lock = merge(loft([(PAD_T, circle(.15, 10)), (PAD_T + .07, circle(.15, 10))]),
    107:                  loft([(PAD_T + .07, circle(.07, 8)), (PAD_T + .1, circle(.07, 8))]))
    108:     k = h - .1
    109:     bosses = merge(*[box(x - .045, x + .045, y - .045, y + .045, PAD_T, PAD_T + .05) for x in (-k, k) for y in (-k, k)])
    110:     solid(f"pad_{name}", transform(plate, m), "frame", parent, .015)
    111:     solid(f"pad_{name}_rim", transform(rim, m), "trim", parent)
    112:     solid(f"pad_{name}_lock", transform(lock, m), "metal", parent, .01)
    113:     solid(f"pad_{name}_bolts", transform(bosses, m), "joint", parent)
    114:     face = Vector(at) + Vector(normal).normalized() * (PAD_T + .1)
    115:     empty(f"mount.{name}", face, parent, dir=gltf_dir(normal), size=PAD)
    116: 
    117: 
    118: def mirror(p):
    119:     return (-p[0], p[1], p[2])
    120: 
    121: 
    122: # Pad sites on the left, mirrored on the right: (joint, centre of the pad back, normal, up).
    123: PADS = {
    124:     "forearm": ("forearm", (3.08, 0, 10.42), (1, 0, 0), (0, 0, 1)),
    125:     "shoulder": ("shoulder", (2.42, .12, ROOF), (0, 0, 1), (0, -1, 0)),
    126:     "hip": ("pelvis", (2.04, 0, 10.92), (1, 0, 0), (0, 0, 1)),
    127: }
    128: BACK_PAD = ((0, 1.56, 13.8), (0, 1, 0), (0, 0, 1))
    129: 
    130: 
    131: def build_pelvis(J):
    132:     P = J["pelvis"]
    133:     solid("pelvis_block", loft([(9.85, octo(1.1, .95, .25)), (10.35, octo(1.6, 1.25, .3)), (10.98, octo(1.5, 1.2, .3))]),
    134:           "frame", P, BEVEL)
    135:     # hip arms reach out over the thighs and carry the holster pads
    136:     pair("hip_arm", box(.6, 1.98, -.32, .32, 10.62, 11.04), "frame", P, P, bevel=BEVEL)
    137:     pair("hip_arm_web", box(.6, 1.0, -.25, .25, 10.2, 10.62), "frame", P, P, bevel=.02)
    138:     pair("hip_socket", cylinder(.5, .55, .8, 12, axis="x", at=(0, 10.55)), "joint", P, P, smooth=True)
    139:     for s, sx in (("L", 1), ("R", -1)):
    140:         j, at, nm, up = PADS["hip"]
    141:         pad(f"hip.{s}", P, (at[0] * sx, at[1], at[2]), (nm[0] * sx, nm[1], nm[2]), up)
    142: 
    143: 
    144: def build_waist(J):
    145:     W = J["waist"]
    146:     solid("spine", cylinder(.42, 10.9, 12.1, 12), "joint", W, smooth=True)
    147:     for i, z in enumerate((11.15, 11.5, 11.85)):
    148:         solid(f"spine_ring{i}", loft([(z - .07, octo(1.15, 1.0, .25)), (z + .07, octo(1.15, 1.0, .25))]), "frame", W, .02)
    149:     # two short rams either side of the spine: the waist twists and bends on them
    150:     pair("waist_ram", piston((.62, .1, 10.95), (.62, .1, 11.95), r=.1), "joint", W, W, smooth=True)
    151:     # the spine housing closes the back of the waist, ribbed so it still reads as the joint
    152:     solid("spine_housing", loft([(10.98, octo(.9, .34, .1, y=.56)), (11.98, octo(.9, .34, .1, y=.56))]), "frame", W, .02)
    153:     for i, z in enumerate((11.2, 11.48, 11.76)):
    154:         solid(f"spine_housing_rib{i}", box(-.5, .5, .7, .78, z - .05, z + .05), "joint", W, .01)
    155: 
    156: 
    157: def build_torso(J):
    158:     T = J["torso"]
    159:     solid("chest_base", loft([(11.95, octo(1.6, 1.3, .3)), (12.55, octo(2.5, 1.9, .4))]), "frame", T, BEVEL)
    160:     # cockpit block in front, the socket the pod sits in: a metal rim round a recessed hatch
    161:     solid("cockpit_block", box(-.88, .88, -1.04, -.15, 12.5, 14.95), "frame", T, BEVEL)
    162:     rim = [box(-.66, .66, -1.16, -.98, 14.3, 14.44), box(-.66, .66, -1.16, -.98, 12.98, 13.12),
    163:            box(-.66, -.52, -1.16, -.98, 12.98, 14.44), box(.52, .66, -1.16, -.98, 12.98, 14.44)]
    164:     solid("socket_rim", merge(*rim), "metal", T, .015)
    165:     solid("socket_hatch", box(-.52, .52, -1.08, -1.0, 13.12, 14.3), "joint", T, .01)
    166:     solid("socket_seam", box(-.015, .015, -1.1, -1.07, 13.16, 14.26), "frame", T)
    167:     # the reactor drum behind the cockpit, seen through the open chest sides
    168:     solid("reactor", cylinder(.62, -1.22, 1.22, 14, axis="x", at=(.35, 13.4)), "frame", T, smooth=True)
    169:     for x in (-.85, -.3, .3, .85):
    170:         solid(f"reactor_band{x:+.1f}", cylinder(.66, x - .06, x + .06, 14, axis="x", at=(.35, 13.4)), "joint", T, smooth=True)
    171:     pair("reactor_cap", cylinder(.44, 1.22, 1.27, 14, axis="x", at=(.35, 13.4)), "joint", T, T, smooth=True)
    172:     pair("reactor_glow", cylinder(.3, 1.26, 1.29, 14, axis="x", at=(.35, 13.4)), "glow_core", T, T, outline=False)
    173:     solid("spine_block", box(-.72, .72, .72, 1.12, 12.45, 14.95), "frame", T, BEVEL)
    174:     # back panels either side of the spine block close the torso, the reactor still shows at the sides
    175:     pair("back_panel", box(.72, 1.28, .86, 1.0, 12.5, 14.42), "frame", T, T, bevel=.02)
    176:     pair("back_panel_rib", box(.8, 1.2, .98, 1.04, 13.3, 13.4), "joint", T, T, bevel=.01)
    177:     # side posts tie the base to the shoulder girdle; the reactor shows between them
    178:     for y0, y1 in ((-.9, -.62), (.75, 1.02)):
    179:         pair(f"rib{y0:+.1f}", box(1.1, 1.32, y0, y1, 12.4, 14.5), "frame", T, T, bevel=.02)
    180:     solid("girdle", box(-1.55, 1.55, -.72, .9, 14.42, 15.02), "frame", T, BEVEL)
    181:     pair("girdle_cheek", box(1.3, 1.6, -.6, .6, 14.05, 14.42), "frame", T, T, bevel=.02)
    182:     solid("neck_base", loft([(15.0, octo(1.2, 1.1, .3)), (15.28, octo(.9, .85, .25))]), "frame", T, .02)
    183:     cable("chest_cable", [(1.22, -.95, 12.6), (1.38, -.98, 13.6), (1.42, -.8, 14.4)], T, T)
    184: 
    185: 
    186: def build_head(J):
    187:     N, H = J["neck"], J["head"]
    188:     solid("neck_column", cylinder(.3, 15.15, 16.05, 10), "joint", N, smooth=True)
    189:     for i, z in enumerate((15.42, 15.7)):
    190:         solid(f"neck_ring{i}", loft([(z - .05, octo(.78, .74, .18)), (z + .05, octo(.78, .74, .18))]), "frame", N, .015)
    191:     pair("neck_ram", piston((.32, .25, 15.2), (.3, .2, 15.95), r=.06), "joint", N, N, smooth=True)
    192:     # the bare head: a sensor block with one lens, the cradle every maker's helmet bolts over
    193:     solid("head_core", box(-.4, .4, -.42, .45, 15.95, 16.72), "frame", H, .03)
    194:     solid("head_lens_ring", cylinder(.16, -.47, -.42, 12, axis="y", at=(0, 16.4)), "joint", H, smooth=True)
    195:     solid("head_lens", cylinder(.11, -.49, -.46, 12, axis="y", at=(0, 16.4)), "glow_eye", H, outline=False)
    196: 
    197: 
    198: def build_arms(J):
    199:     S, UA, FA, HA = lr(J, "shoulder"), lr(J, "upperarm"), lr(J, "forearm"), lr(J, "hand")
    200:     pair("shoulder_housing", cylinder(.5, 1.5, 2.15, 14, axis="x", at=(0, 14.6)), "joint", *S, smooth=True)
    201:     pair("shoulder_block", box(2.1, 2.85, -.48, .48, 14.15, 15.1), "frame", *S, bevel=BEVEL)
    202:     # the shoulder pad sits on a pedestal that flares up to the pad's size, not a post
    203:     pair("shoulder_pedestal", loft([(15.0, octo(.56, .5, .1, x=2.42, y=.12)), (ROOF, octo(.68, .64, .14, x=2.42, y=.12))]), "frame", *S,
    204:          bevel=.02)
    205:     # shoulder rams from the chest corners up to the block, front and back
    206:     for k, y in (("f", -.62), ("b", .62)):
    207:         pair(f"shoulder_ram_{k}", piston((1.28, y, 13.1), (2.15, y * .8, 14.3), r=.11), "joint", *S, smooth=True)
    208:     pair("upperarm_swivel", cylinder(.42, 13.92, 14.32, 12, at=(2.45, 0)), "joint", *UA, smooth=True)
    209:     tube("upperarm_bone", [(12.35, .29), (13.95, .33)], (2.45, 0), UA, collars=(12.6, 13.7))
    210:     for k, (x0, x1) in (("i", (2.02, 2.16)), ("o", (2.74, 2.88))):
    211:         pair(f"elbow_fork_{k}", box(x0, x1, -.36, .36, 11.6, 12.55), "frame", *UA, bevel=.02)
    212:     cable("upperarm_cable", [(2.45, .4, 13.95), (2.45, .44, 13.1), (2.45, .4, 12.3)], *UA)
    213:     pair("elbow", cylinder(.42, 2.0, 2.9, 14, axis="x", at=(0, 11.95)), "joint", *FA, smooth=True)
    214:     tube("forearm_bone", [(9.88, .27), (11.7, .31)], (2.5, 0), FA, collars=(10.0, 11.5))
    215:     pair("elbow_ram", piston((2.5, .52, 12.55), (2.5, .42, 10.85), r=.09), "joint", *FA, smooth=True)
    216:     pair("pad_post", box(2.74, 3.08, -.2, .2, 10.2, 10.64), "frame", *FA, bevel=.02)
    217:     cable("forearm_cable", [(2.18, -.28, 11.6), (2.16, -.3, 10.8), (2.2, -.26, 10.0)], *FA)
    218:     for s, sx in (("L", 1), ("R", -1)):
    219:         j, at, nm, up = PADS["forearm"]
    220:         pad(f"forearm.{s}", J["forearm", s], (at[0] * sx, at[1], at[2]), (nm[0] * sx, nm[1], nm[2]), up)
    221:         j, at, nm, up = PADS["shoulder"]
    222:         pad(f"shoulder.{s}", J["shoulder", s], (at[0] * sx, at[1], at[2]), nm, up)
    223:     # bare hands: the frame's own
    224:     pair("wrist", cylinder(.28, 9.42, 9.86, 10, at=(2.5, 0)), "joint", *HA, smooth=True)
    225:     pair("palm", loft([(8.9, octo(.5, .82, .1, x=2.52)), (9.5, octo(.46, .8, .1, x=2.52))]), "frame", *HA, bevel=.02)
    226:     pair("fingers", loft([(8.75, octo(.42, .82, .13, x=2.27)), (9.35, octo(.44, .82, .13, x=2.27))]), "frame", *HA, bevel=.025)
    227:     pair("thumb", loft([(9.02, octo(.24, .24, .06, x=2.32, y=-.5)), (9.4, octo(.26, .26, .06, x=2.38, y=-.46))]), "frame", *HA,
    228:          bevel=.02)
    229:     pair("knuckles", box(2.62, 2.8, -.36, .36, 9.0, 9.42), "joint", *HA, bevel=.02)
    230: 
    231: 
    232: def build_legs(J):
    233:     TH, SH, FT = lr(J, "thigh"), lr(J, "shin"), lr(J, "foot")
    234:     pair("hip_ball", cylinder(.47, .8, 1.55, 12, axis="x", at=(0, 10.55)), "joint", *TH, smooth=True)
    235:     tube("thigh_bone", [(6.55, .42), (8.0, .5), (9.3, .54), (10.25, .48)], (1.16, 0), TH, collars=(7.0, 9.75))
    236:     for k, (x0, x1) in (("i", (.58, .72)), ("o", (1.68, 1.82))):
    237:         pair(f"knee_fork_{k}", box(x0, x1, -.4, .4, 5.75, 6.8), "frame", *TH, bevel=.02)
    238:     # hip rams: a long one down the back of the thigh, a short one at the front
    239:     pair("hip_ram_b", piston((1.15, .72, 10.45), (1.17, .7, 7.9), r=.13), "joint", *TH, smooth=True)
    240:     pair("hip_ram_f", piston((.8, -.68, 10.35), (.9, -.64, 9.15), r=.1), "joint", *TH, smooth=True)
    241:     cable("thigh_cable", [(.56, .3, 10.0), (.52, .34, 8.4), (.56, .3, 6.9)], *TH)
    242:     pair("knee", cylinder(.47, .7, 1.7, 14, axis="x", at=(0, 6.1)), "joint", *SH, smooth=True)
    243:     # slim under the knee, so the shin plate can be narrow there
    244:     tube("shin_bone", [(1.95, .36), (3.2, .46), (5.0, .36), (5.75, .42)], (1.2, .05), SH, collars=(2.4,))
    245:     pair("knee_ram", piston((1.2, .74, 7.35), (1.2, .8, 5.0), r=.11), "joint", *SH, smooth=True)
    246:     pair("ankle_ram", piston((1.2, .66, 3.2), (1.2, .8, 1.85), r=.08), "joint", *SH, smooth=True)
    247:     for k, (x0, x1) in (("i", (.7, .82)), ("o", (1.58, 1.7))):
    248:         pair(f"ankle_fork_{k}", box(x0, x1, -.26, .26, 1.34, 2.08), "frame", *SH, bevel=.02)
    249:     cable("shin_cable", [(.9, .36, 5.5), (.84, .42, 3.8), (.9, .36, 2.3)], *SH)
    250:     build_foot(J)
    251: 
    252: 
    253: # The foot is drawn at one size and then fitted: widened, shortened and turned out a touch about the
    254: # ankle. Every foot part, frame and plate, goes through place_foot().
    255: TURN = 6.0
    256: FOOT_SCALE = (1.45, .82)  # across and along
    257: ANKLE = (1.2, .1, 1.55)
    258: 
    259: 
    260: def place_foot(bm):
    261:     a = Vector((ANKLE[0], ANKLE[1], 0))
    262:     m = Matrix.Diagonal((FOOT_SCALE[0], FOOT_SCALE[1], 1, 1))
    263:     return transform(bm, rot("Z", TURN, about=a) @ Matrix.Translation(a) @ m @ Matrix.Translation(-a))
    264: 
    265: 
    266: def ball(r, at, n=12):
    267:     """A faceted sphere."""
    268:     rings = [(at[2] + r * math.cos(math.pi * i / 6), circle(max(r * math.sin(math.pi * i / 6), .01), n, at[0], at[1])) for i in range(6, -1, -1)]
    269:     return loft(rings)
    270: 
    271: 
    272: def build_foot(J):
    273:     """A foot that carries weight: a ball ankle in the shin's yoke, set in a cup on an A frame
    274:     pedestal, a sole with an arch between heel and ball, a toe block on a hinge. Toe longer than heel."""
    275:     FT = lr(J, "foot")
    276:     x, y, z = ANKLE
    277:     pair("ankle", ball(.36, ANKLE), "joint", *FT, smooth=True)
    278:     pair("ankle_pin", cylinder(.17, .62, 1.78, 10, axis="x", at=(y, z)), "metal", *FT, smooth=True)
    279:     pair("ankle_cup", place_foot(loft([(1.22, octo(.9, .86, .22, x=x, y=y)), (1.36, octo(.78, .76, .2, x=x, y=y))])), "joint", *FT, bevel=.015)
    280:     pair("ankle_pedestal", place_foot(two_view([(.84, 1.24), (1.56, 1.24), (1.64, .5), (.76, .5)],
    281:                                          [(-.3, 1.24), (.46, 1.24), (.9, .5), (-.8, .5)])), "frame", *FT, bevel=BEVEL)
    282:     # the rear foot: heel and arch on one sole, the hinge at the ball
    283:     plan = [(.82, 1.16), (1.58, 1.16), (1.72, .86), (1.74, -1.48), (.66, -1.48), (.68, .86)]
    284:     arch = [(-1.48, .3), (-1.48, 0), (-1.1, 0), (-.9, .14), (.3, .14), (.5, 0), (1.04, 0), (1.18, .14), (1.18, .3)]
    285:     pair("sole", place_foot(two_view([(.6, 0), (1.8, 0), (1.8, .3), (.6, .3)], arch, plan)), "joint", *FT, bevel=.02)
    286:     pair("foot_frame", place_foot(two_view([(.76, .29), (1.64, .29), (1.58, .62), (.82, .62)],
    287:                                      [(-1.44, .29), (1.08, .29), (.98, .64), (-1.38, .5)])), "frame", *FT, bevel=BEVEL)
    288:     pair("toe_hinge", place_foot(cylinder(.14, .76, 1.64, 10, axis="x", at=(-1.56, .26))), "joint", *FT, smooth=True)
    289:     toe_plan = [(.7, -1.62), (1.7, -1.62), (1.68, -2.3), (1.5, -2.58), (.9, -2.58), (.72, -2.3)]
    290:     pair("toe_frame", place_foot(two_view([(.6, .06), (1.8, .06), (1.8, .44), (.6, .44)],
    291:                                     [(-1.62, .06), (-2.5, .06), (-2.6, .16), (-2.48, .3), (-1.62, .44)], toe_plan)), "frame", *FT,
    292:          bevel=BEVEL)
    293:     pair("toe_sole", place_foot(two_view([(.6, 0), (1.8, 0), (1.8, .07), (.6, .07)], [(-1.62, 0), (-2.5, 0), (-2.5, .07), (-1.62, .07)],
    294:                                    toe_plan)), "joint", *FT, bevel=.015)
    295:     pair("heel_frame", place_foot(box(.82, 1.58, .56, 1.12, .28, .62)), "frame", *FT, bevel=.02)
    296: 
    297: 
    298: def build_backpack(J):
    299:     B = J["backpack"]
    300:     solid("back_mount", box(-.86, .86, 1.1, 1.56, 12.9, 14.72), "frame", B, BEVEL)
    301:     pad("backpack", B, *BACK_PAD)
    302:     for s, sx in (("L", 1), ("R", -1)):
    303:         x0, x1 = sorted((.48 * sx, .72 * sx))
    304:         solid(f"binder_arm.{s}", box(x0, x1, 1.3, 2.25, 14.58, 14.82), "frame", B, bevel=.02)
    305:         solid(f"binder_hinge.{s}", cylinder(.2, .9 * sx - .24, .9 * sx + .24, 12, axis="x", at=(2.25, 14.7)), "joint", J["binder", s],
    306:               smooth=True)
    307: 
    308: 
    309: KNEE_FORWARD = .42  # how far the knees stand forward of the hip to ankle line
    310: SPLAY = .4  # how far each foot stands out from under its hip: a slight A stance
    311: 
    312: 
    313: def bend_knees(J, forward=KNEE_FORWARD, splay=SPLAY):
    314:     """Stand the frame with its knees a little forward and its feet a little apart, so the leg is
    315:     not one straight post. Run after the plates are on. Everything under a thigh or shin moves along
    316:     y by an offset that runs from 0 at the hip to -forward at the knee and back to 0 at the ankle,
    317:     and outward by one that runs from 0 at the hip to `splay` at the ankle. The foot moves out whole.
    318:     Joints move with their parts. Joint names and the tree stay as they are."""
    319:     for s, sx in (("L", 1), ("R", -1)):
    320:         hip, knee, foot = J["thigh", s], J["shin", s], J["foot", s]
    321:         zh, zk, za = hip.matrix_world.translation.z, knee.matrix_world.translation.z, foot.matrix_world.translation.z
    322: 
    323:         def d(z):
    324:             out = sx * splay * (1.0 if z <= za else 0.0 if z >= zh else (zh - z) / (zh - za))
    325:             if z >= zh or z <= za:
    326:                 return Vector((out, 0, 0))
    327:             return Vector((out, -forward * ((zh - z) / (zh - zk) if z >= zk else (z - za) / (zk - za)), 0))
    328: 
    329:         order, stack = [], [hip]
    330:         while stack:
    331:             o = stack.pop(0)
    332:             order.append(o)
    333:             stack.extend(o.children)
    334:         keep = {foot} | set(foot.children_recursive)
    335:         world = {o: o.matrix_world.copy() for o in order}
    336:         for o in order:
    337:             if o in keep:
    338:                 world[o] = Matrix.Translation(d(za - 1)) @ world[o]
    339:                 continue
    340:             if o.type == "MESH":
    341:                 inv = world[o].inverted()
    342:                 for v in o.data.vertices:
    343:                     w = world[o] @ v.co
    344:                     v.co = inv @ (w + d(w.z))
    345:             else:
    346:                 world[o] = Matrix.Translation(d(world[o].translation.z)) @ world[o]
    347:         for o in order:
    348:             o.matrix_world = world[o]
    349:             bpy.context.view_layer.update()
    350: 
    351: 
    352: # The pattern builds' proportions, as fractions of the crown height (docs/study-proportions.md): the
    353: # knee joint, the crotch, and the crown itself in metres. The antenna stands above the crown.
    354: KNEE_AT = .39
    355: CROTCH_AT = .54
    356: CROWN = 16.9
    357: CROTCH_Z = 9.74  # the crotch's height on the striker rig, before proportion
    358: SHOULDER_OUT = .25  # how far the shoulders move out, the chest top widening to meet them
    359: KNEE_BAND = .55  # half height of the knee region that moves whole, so the knee block keeps its shape
    360: SHIN_FROM = 2.0  # the ankle and foot below this height stay as they are
    361: THIGH_TO = 9.55  # the hip and everything above it move whole
    362: 
    363: 
    364: def proportion(J, crown_z, knee=KNEE_AT, crotch=CROTCH_AT, crown=CROWN, shoulders=SHOULDER_OUT):
    365:     """Set the build's proportions on world positions, after the plates and bend_knees. `crown_z` is the
    366:     helmet top before this pass. The thigh is shortened and the body comes down onto it so the crotch
    367:     sits at `crotch` of the crown and the knee at `knee`: a long shin under a short thigh, the line
    368:     mech's leg. The knee region moves whole, the shin and thigh stretch or squeeze between it and the
    369:     ankle and hip. Everything not under a thigh moves down whole. The shoulders move out by
    370:     `shoulders`, the chest top widening with them. Then the whole frame is scaled so the crown lands at
    371:     `crown`. Joint names and the tree stay as they are."""
    372:     zk = J["shin", "L"].matrix_world.translation.z
    373:     d = (crotch * crown_z - CROTCH_Z) / (1 - crotch)  # the body's drop
    374:     zk2 = knee * (crown_z + d)
    375:     k = crown / (crown_z + d)
    376:     b = KNEE_BAND
    377: 
    378:     def lerp(z, a0, a1, b0, b1):
    379:         return b0 + (z - a0) * (b1 - b0) / (a1 - a0)
    380: 
    381:     def leg(z):
    382:         if z <= SHIN_FROM:
    383:             return z
    384:         if z <= zk - b:
    385:             return lerp(z, SHIN_FROM, zk - b, SHIN_FROM, zk2 - b)
    386:         if z <= zk + b:
    387:             return z + zk2 - zk
    388:         if z <= THIGH_TO:
    389:             return lerp(z, zk + b, THIGH_TO, zk2 + b, THIGH_TO + d)
    390:         return z + d
    391: 
    392:     def wide(x):
    393:         """The shoulders' move out at |x|: none inside the chest, whole past the shoulder joint."""
    394:         t = min(max((abs(x) - 1.25) / (2.05 - 1.25), 0.0), 1.0)
    395:         return math.copysign(shoulders * t * t * (3 - 2 * t), x)
    396: 
    397:     root = J["frame"]
    398:     legs = set()
    399:     for s in ("L", "R"):

    36 more lines not shown.