agent (cont.)

+1:26
  • read_file{"Path":"~/work/lowmarch/tools/outfit.py"}

    input

    {
      "Path": "~/work/lowmarch/tools/outfit.py"
    }

    result, 801 lines

    Showing lines 1-800 of 1272
    1: """Fantasy costume pieces, generated in code and fitted onto a VRoid body.
    2: 
    3: Coordinates are the model's (metres, y up, the character faces -z, its left is -x). Pieces are
    4: built once in the reference pose (the bust pose, arms down) and carry skin weights (J, W, jnames)
    5: so the renderer can pose them with the body through the skeleton: soft layers copy the weights of
    6: the body under them, hard parts ride one bone.
    7: 
    8: Kinds of piece (see docs/portrait-guide.md lesson 07 for the measurements behind the offsets):
    9: 
    10:   wrap      a garment shrink-wrapped onto a body region chosen by bones (tunic, trousers, boots,
    11:             gloves): seams welded, smoothed without shrinking, every vertex set at an offset
    12:   collar    a standing collar fitted to the neck by ray casts, rising toward the back
    13:   pauldron  three overlapping lames whose shape comes from ray casts to what they cover
    14:   drape     cloth (cape, tunic tails) settled by a small cloth simulation against the body
    15:   belt      a band around the waist on top of the tunic
    16:   trim      a band along a piece's edge (gold trim, piping), lifted off its surface
    17:   props     sword and hardware built from boxes, tubes and balls
    18: 
    19: A costume is a function of a Fit (body + bones in the reference pose) returning a list of pieces.
    20: """
    21: import math
    22: import os
    23: 
    24: import numpy as np
    25: from scipy.spatial import cKDTree
    26: 
    27: from fitting import (Surface, merge_surfaces, weld, compact, subdivide, shrink_wrap, flatten_hem, limb_hull,
    28:                      boundary_loops, vertex_normals, transfer_weights, rigid_weights, blend_weights, taubin)
    29: 
    30: 
    31: # ---- mesh helpers --------------------------------------------------------------
    32: def grid_mesh(P):
    33:     """P: (U, V, 3) grid of points -> (pos, tri)."""
    34:     U, V = P.shape[:2]
    35:     idx = np.arange(U * V).reshape(U, V)
    36:     a, b, c, d = idx[:-1, :-1], idx[1:, :-1], idx[1:, 1:], idx[:-1, 1:]
    37:     tri = np.concatenate([np.stack([a, b, c], -1).reshape(-1, 3), np.stack([a, c, d], -1).reshape(-1, 3)])
    38:     return P.reshape(-1, 3), tri
    39: 
    40: 
    41: def piece(name, role, pos, tri, nrm=None, outward_from=None, axis=None):
    42:     """outward_from: a point (or, with axis, a line) the normals should face away from, so the
    43:     renderer knows which side is the outside of a one-sided sheet."""
    44:     pos = np.asarray(pos, float)
    45:     tri = np.asarray(tri)
    46:     nrm = vertex_normals(pos, tri) if nrm is None else nrm
    47:     if outward_from is not None:
    48:         d = pos - np.asarray(outward_from, float)
    49:         if axis is not None:
    50:             a = np.asarray(axis, float) / np.linalg.norm(axis)
    51:             d -= np.outer(d @ a, a)
    52:         if (np.einsum("ij,ij->i", nrm, d) < 0).mean() > 0.5:
    53:             nrm = -nrm
    54:             tri = tri[:, ::-1]
    55:     return dict(mesh="outfit", material=f"OUTFIT_{name}", mi=-1, role=role, pos=pos,
    56:                 nrm=nrm, uv=np.zeros((len(pos), 2)), tri=tri)
    57: 
    58: 
    59: def thick_grid(P, thickness, outward_from, axis=None):
    60:     """A grid sheet given real thickness: outer face, inner face, and the four edges closed, so
    61:     rims read as solid and the inside never shows."""
    62:     pos, tri = grid_mesh(P)
    63:     n = vertex_normals(pos, tri)
    64:     d = pos - np.asarray(outward_from, float)
    65:     if axis is not None:
    66:         a = np.asarray(axis, float) / np.linalg.norm(axis)
    67:         d -= np.outer(d @ a, a)
    68:     if (np.einsum("ij,ij->i", n, d) < 0).mean() > 0.5:
    69:         n, tri = -n, tri[:, ::-1]
    70:     U, V = P.shape[:2]
    71:     inner = (pos - n * thickness).reshape(U, V, 3)
    72:     outer = pos.reshape(U, V, 3)
    73:     mid = outer.reshape(-1, 3).mean(0)
    74:     allp, allt, off = [], [], 0
    75:     parts = [(outer, tri, None), (inner, tri[:, ::-1], None)]
    76:     for edge in (lambda G: G[:, 0], lambda G: G[:, -1], lambda G: G[0, :], lambda G: G[-1, :]):
    77:         strip = np.stack([edge(outer), edge(inner)], 1)
    78:         p_, t_ = grid_mesh(strip)
    79:         nn = vertex_normals(p_, t_)
    80:         if (np.einsum("ij,ij->i", nn, p_ - mid) < 0).mean() > 0.5:
    81:             t_ = t_[:, ::-1]
    82:         parts.append((strip, t_, True))
    83:     for G, t_, _ in parts:
    84:         allp.append(G.reshape(-1, 3))
    85:         allt.append(t_ + off)
    86:         off += G.shape[0] * G.shape[1]
    87:     return np.concatenate(allp), np.concatenate(allt), outer
    88: 
    89: 
    90: def frame_axes(a, hint=(0, 1, 0)):
    91:     a = np.asarray(a, float) / np.linalg.norm(a)
    92:     b = np.cross(a, hint)
    93:     if np.linalg.norm(b) < 1e-6:
    94:         b = np.cross(a, (1, 0, 0))
    95:     b /= np.linalg.norm(b)
    96:     return a, b, np.cross(a, b)
    97: 
    98: 
    99: def box(name, role, centre, axes, half):
    100:     c = np.asarray(centre, float)
    101:     ax = [np.asarray(v, float) * h for v, h in zip(axes, half)]
    102:     corners = np.array([c + sx * ax[0] + sy * ax[1] + sz * ax[2]
    103:                         for sx in (-1, 1) for sy in (-1, 1) for sz in (-1, 1)])
    104:     quads = [(0, 1, 3, 2), (4, 6, 7, 5), (0, 4, 5, 1), (2, 3, 7, 6), (0, 2, 6, 4), (1, 5, 7, 3)]
    105:     pos, tri = [], []
    106:     for q in quads:
    107:         base = len(pos)
    108:         pos += [corners[i] for i in q]
    109:         tri += [(base, base + 1, base + 2), (base, base + 2, base + 3)]
    110:     return piece(name, role, np.array(pos), np.array(tri), outward_from=c)
    111: 
    112: 
    113: def tube(name, role, start, axis, length, r0, r1=None, seg=16, rows=2):
    114:     r1 = r0 if r1 is None else r1
    115:     a, b, c = frame_axes(axis)
    116:     ang = np.linspace(0, 2 * math.pi, seg, endpoint=False)
    117:     P = np.zeros((seg + 1, rows, 3))
    118:     for j, t in enumerate(np.linspace(0, 1, rows)):
    119:         r = r0 + (r1 - r0) * t
    120:         ring = np.asarray(start) + a * length * t + (np.outer(np.cos(ang), b) + np.outer(np.sin(ang), c)) * r
    121:         P[:seg, j] = ring
    122:         P[seg, j] = ring[0]
    123:     pos, tri = grid_mesh(P)
    124:     return piece(name, role, pos, tri, outward_from=np.asarray(start) + a * length / 2, axis=a)
    125: 
    126: 
    127: def ball(name, role, centre, r, seg=14, rows=8, squash=(1, 1, 1)):
    128:     th = np.linspace(0, math.pi, rows)
    129:     ph = np.linspace(0, 2 * math.pi, seg + 1)
    130:     P = np.zeros((seg + 1, rows, 3))
    131:     for j, t in enumerate(th):
    132:         P[:, j, 0] = np.sin(t) * np.cos(ph) * r * squash[0]
    133:         P[:, j, 1] = np.cos(t) * r * squash[1]
    134:         P[:, j, 2] = np.sin(t) * np.sin(ph) * r * squash[2]
    135:     P += np.asarray(centre)
    136:     pos, tri = grid_mesh(P)
    137:     return piece(name, role, pos, tri, outward_from=centre)
    138: 
    139: 
    140: def ribbon(name, role, curve, width=0.006, lift=0.002, normals=None, away=None, closed=False):
    141:     """A band along a 3D polyline, lifted off a surface. normals: the surface normal at each
    142:     point (the band lies flat on it); otherwise it faces away from `away`."""
    143:     C = np.asarray(curve, float)
    144:     N = None if normals is None else np.asarray(normals, float)
    145:     if closed:
    146:         C = np.concatenate([C, C[:1]])
    147:         N = None if N is None else np.concatenate([N, N[:1]])
    148:     t = np.gradient(C, axis=0)
    149:     t /= np.maximum(np.linalg.norm(t, axis=1, keepdims=True), 1e-9)
    150:     nrm = N if N is not None else C - np.asarray(away if away is not None else C.mean(0))
    151:     nrm = nrm - t * np.einsum("ij,ij->i", nrm, t)[:, None]
    152:     nrm /= np.maximum(np.linalg.norm(nrm, axis=1, keepdims=True), 1e-9)
    153:     side = np.cross(t, nrm)
    154:     P = np.stack([C - side * width / 2 + nrm * lift, C + side * width / 2 + nrm * lift], 1)
    155:     pos, tri = grid_mesh(P)
    156:     vn = np.repeat(nrm, 2, axis=0)
    157:     if (vertex_normals(pos, tri) * vn).sum(1).mean() < 0:
    158:         tri = tri[:, ::-1]
    159:     return piece(name, role, pos, tri, nrm=vn)
    160: 
    161: 
    162: # ---- body fit -----------------------------------------------------------------------
    163: class Fit:
    164:     """What a costume is built against: the body skin (welded, measurable) and the bones, all in
    165:     the reference pose, plus the skin weights so pieces can be bound to the skeleton."""
    166: 
    167:     def __init__(self, vrm, pose, prims, roles):
    168:         self._prims, self._roles = prims, roles
    169:         W = vrm.node_world(pose)
    170:         names = vrm.nodes_by_name()
    171:         self.world = {k: W[i].copy() for k, i in names.items() if k}
    172:         self.bone = {k: m[:3, 3].copy() for k, m in self.world.items()}
    173:         skin = [p for p, r in zip(prims, roles) if r == "body"]
    174:         self.body = skin[0]
    175:         self.pos = self.body["pos"]
    176:         self.J, self.W, self.jnames = self.body["J"], self.body["W"], self.body["jnames"]
    177:         self.tri = weld(self.pos, np.concatenate([p["tri"] for p in skin]))
    178:         self.surf = Surface(self.pos, self.tri)
    179:         self.skin = self.pos[np.unique(self.tri)]
    180:         # MakeHuman bodies (tools/makehuman.py) have real muscle relief; VRoid's limbs are smooth tubes
    181:         self.cloth_hull = vrm.j.get("asset", {}).get("generator", "").startswith("lowmarch makehuman") \
    182:             and not os.environ.get("LOWMARCH_NO_HULL")
    183: 
    184:     def head_surface(self):
    185:         """The head's skin (face and scalp), for charts over the skull (tools/hair.py)."""
    186:         from vrm import bone_weight
    187:         pos, tri, off = [], [], 0
    188:         for p, r in zip(self._prims, self._roles):
    189:             if r in ("face", "body") and "J" in p and len(p["tri"]):
    190:                 w = bone_weight(p, ("Head",))
    191:                 T = p["tri"][(w[p["tri"]] > 0.5).all(1)]
    192:                 if len(T):
    193:                     pos.append(p["pos"])
    194:                     tri.append(T + off)
    195:                     off += len(p["pos"])
    196:         return Surface(np.concatenate(pos), np.concatenate(tri))
    197: 
    198:     def weight(self, bones):
    199:         hit = np.array([any(b in n for b in bones) for n in self.jnames])
    200:         return (hit[self.J] * self.W).sum(1)
    201: 
    202:     def tris_for(self, bones, min_w=0.5, exclude=(), y_min=None, y_max=None):
    203:         w = self.weight(bones)
    204:         if exclude:
    205:             w = w - self.weight(exclude)
    206:         T = self.tri[(w[self.tri] >= min_w).all(1)]
    207:         tp = self.pos[T]
    208:         sel = np.ones(len(T), bool)
    209:         if y_min is not None:
    210:             sel &= tp[:, :, 1].min(1) > y_min
    211:         if y_max is not None:
    212:             sel &= tp[:, :, 1].max(1) < y_max
    213:         return T[sel]
    214: 
    215:     def bind(self, pc, allow=None, fallback=None, rigid=None, blend=None, surface=None):
    216:         """Attach skin weights to a piece: copied from the body under it (optionally limited to
    217:         some bones), or rigid on one bone / a fixed blend."""
    218:         if pc is None:
    219:             return None
    220:         n = len(pc["pos"])
    221:         if rigid or blend:
    222:             pc["J"], pc["W"] = rigid_weights(n, self.jnames, rigid, blend)
    223:         else:
    224:             pc["J"], pc["W"] = transfer_weights(pc["pos"], None, self.J, self.W, surface=surface or self.surf,
    225:                                                 allow=allow, jnames=self.jnames, fallback=fallback)
    226:         pc["jnames"] = self.jnames
    227:         return pc
    228: 
    229: 
    230: def without(pc, bones, max_w=0.3):
    231:     """A piece's triangles away from some bones, as (pos, tri) for merge_surfaces: a bodice's torso
    232:     without its sleeves. Casting a waist ring onto a garment with its sleeves in it catches the
    233:     hanging arms at the sides (the reference pose has the arms down beside the hips)."""
    234:     hit = np.array([any(b in n for b in bones) for n in pc["jnames"]])
    235:     w = (hit[pc["J"]] * pc["W"]).sum(1)
    236:     return pc["pos"], pc["tri"][(w[pc["tri"]] < max_w).all(1)]
    237: 
    238: 
    239: def inherit(child, parent):
    240:     """Trim and hardware take the weights of the nearest vertex of the piece they sit on."""
    241:     _, i = cKDTree(parent["pos"]).query(child["pos"])
    242:     child["J"], child["W"], child["jnames"] = parent["J"][i], parent["W"][i], parent["jnames"]
    243:     return child
    244: 
    245: 
    246: def near_normals(pc, pts):
    247:     return pc["nrm"][cKDTree(pc["pos"]).query(pts)[1]]
    248: 
    249: 
    250: # ---- garments ------------------------------------------------------------------------
    251: def wrap(fit, name, role, bones, offset, min_w=0.5, exclude=(), y_min=None, y_max=None, subdiv=0,
    252:          base=None, hems=(), smooth=15, cut=None, refloor=False, clamp=False):
    253:     """A garment shrink-wrapped onto the body region that follows `bones`. cut: (normal, d), keep only
    254:     the skin below that plane (n.p < d, give or take a centimetre; pair it with a hem on the same plane).
    255:     refloor: after the hems, push out whatever a hem pulled into the skin (a hem moves its edge straight
    256:     along the plane's normal, which sinks it into a sloping hip; off by default so finished costumes
    257:     don't drift). clamp: every vertex past a hem's plane goes onto it, not just the edge's (pass y_min
    258:     and y_max a few centimetres past the hems: large skin triangles crossing a hem line otherwise leave
    259:     notches as deep as a triangle)."""
    260:     T = fit.tris_for(bones, min_w, exclude, y_min, y_max)
    261:     if cut is not None:
    262:         n_ = np.asarray(cut[0], float) / np.linalg.norm(cut[0])
    263:         T = T[(fit.pos[T] @ n_).max(1) < cut[1] + 0.01]
    264:     if not len(T):
    265:         return None
    266:     pos, tri, used = compact(fit.pos, T)
    267:     levels = []
    268:     for _ in range(subdiv):
    269:         pos, tri, par = subdivide(pos, tri, with_parents=True)
    270:         levels.append(par)
    271:     out = shrink_wrap(pos, tri, base or fit.surf, offset, smooth=smooth)
    272:     for n, d in hems:
    273:         out = flatten_hem(out, tri, n, d)
    274:         if clamp:
    275:             n_ = np.asarray(n, float) / np.linalg.norm(n)
    276:             over = out @ n_ - d
    277:             out = out - np.outer(np.maximum(over, 0.0), n_)
    278:     if refloor and hems:
    279:         surf = base or fit.surf
    280:         d2, cp2, ti2 = surf.query(out)
    281:         low = d2 < offset * 0.75
    282:         out[low] = cp2[low] + surf.fn[ti2[low]] * offset * 0.75
    283:     pc = piece(name, role, out, tri)
    284:     # weights come from the exact skin each vertex grew from: copying from the nearest skin instead
    285:     # let the inside of one boot pick up the other leg's bones
    286:     pc["J"], pc["W"] = blend_weights(fit.J[used], fit.W[used], int(fit.J.max()) + 1, levels)
    287:     pc["jnames"] = fit.jnames
    288:     if getattr(fit, "cloth_hull", False):             # a body with muscle relief: sleeves span the hollows
    289:         hw = lambda b: (np.array([b == n for n in fit.jnames])[pc["J"]] * pc["W"]).sum(1)
    290:         axes = []
    291:         for sd in ("L", "R"):
    292:             for b0, b1 in (("UpperArm", "LowerArm"), ("LowerArm", "Hand"), ("UpperLeg", "LowerLeg"), ("LowerLeg", "Foot"),
    293:                            ("Foot", "ToeBase")):                  # (boots over the foot: no toes showing)
    294:                 n0, n1 = f"J_Bip_{sd}_{b0}", f"J_Bip_{sd}_{b1}"
    295:                 if n0 in fit.bone and n1 in fit.bone:
    296:                     m = hw(n0) + (hw(n1) if b0 == "Foot" else 0.0)    # the foot's segment takes the toes too
    297:                     axes.append((m >= 0.6, fit.bone[n0], fit.bone[n1], b0 == "Foot"))
    298:         pc["pos"] = limb_hull(pc["pos"], tri, axes)
    299:         pc["nrm"] = vertex_normals(pc["pos"], tri)
    300:     pc["loops"] = boundary_loops(tri)
    301:     return pc
    302: 
    303: 
    304: def loop_trim(name, role, garment, pick, width=0.008, lift=0.0015):
    305:     """Trim along one of a garment's open edges: the loop that scores highest under `pick`."""
    306:     loops = garment.get("loops") or []
    307:     if not loops:
    308:         return None
    309:     best = max(loops, key=lambda L: pick(garment["pos"][L]))
    310:     return inherit(ribbon(name, role, garment["pos"][best], width, lift, normals=garment["nrm"][best], closed=True), garment)
    311: 
    312: 
    313: def slice_line(pc, axis=0, value=0.0, keep=lambda p: True):
    314:     """Points where a plane (coordinate `axis` == value) cuts a piece, sorted top to bottom."""
    315:     P = pc["pos"][pc["tri"]]
    316:     s = P[:, :, axis] - value
    317:     out = []
    318:     for i, j in ((0, 1), (1, 2), (2, 0)):
    319:         a, b = s[:, i], s[:, j]
    320:         x = (a > 0) != (b > 0)
    321:         t = a[x] / (a[x] - b[x])
    322:         out.append(P[x, i] + (P[x, j] - P[x, i]) * t[:, None])
    323:     pts = np.concatenate(out)
    324:     pts = np.array([p for p in pts if keep(p)])
    325:     return pts[np.argsort(-pts[:, 1])] if len(pts) else pts
    326: 
    327: 
    328: def collar(fit, name, role, height_back=0.044, height_front=0.028, gap_deg=50, clear=(0.009, 0.015),
    329:            thickness=0.0035, seg=40, rows=6):
    330:     """A standing collar fitted to the neck: radius from ray casts to the neck skin plus clearance
    331:     (flaring toward the top), taller at the back, base lower at the front (the jugular notch)."""
    332:     nk = fit.bone["J_Bip_C_Neck"]
    333:     half = math.radians(180 - gap_deg / 2)
    334:     ang = np.linspace(-half, half, seg)                     # 0 = back (+z), +-pi = front (-z)
    335:     neck = Surface(fit.pos, fit.tris_for(("Neck", "UpperChest", "Head", "Shoulder"), min_w=0.3))
    336:     P = np.zeros((seg, rows, 3))
    337:     for i, a in enumerate(ang):
    338:         d = np.array([math.sin(a), 0, math.cos(a)])
    339:         front = (1 - math.cos(a)) / 2                       # 0 back .. 1 front
    340:         base_y = nk[1] - 0.010 - 0.012 * front
    341:         h = height_back + (height_front - height_back) * front
    342:         for j, t in enumerate(np.linspace(0, 1, rows)):
    343:             o = np.array([nk[0], base_y + h * t, nk[2]])
    344:             r = neck.cast(o, d, rmax=0.2, far=False)
    345:             r = 0.05 if np.isnan(r) else r
    346:             P[i, j] = o + d * (r + clear[0] + (clear[1] - clear[0]) * t)
    347:     pos, tri, outer = thick_grid(P, thickness, outward_from=nk, axis=[0, 1, 0])
    348:     pc = piece(name, role, pos, tri)
    349:     t = np.clip((pos[:, 1] - (nk[1] - 0.022)) / height_back, 0, 1)
    350:     fit.bind(pc, blend={"J_Bip_C_UpperChest": 0.5, "J_Bip_C_Neck": 0.5})
    351:     pc["W"][:, 0], pc["W"][:, 1] = 1 - 0.7 * t, 0.7 * t     # base on the chest, top mostly on the neck
    352:     return pc, outer[:, -1], (outer[0], outer[-1])
    353: 
    354: 
    355: def pauldron(fit, name, role, over, side="L", lames=((0, 62, 0.012, 0.016), (55, 78, 0.010, 0.013),
    356:              (72, 92, 0.008, 0.011)), spread=135, thickness=0.004, seg=30, rows=7):
    357:     """Overlapping lames over the shoulder. Each lame's shape comes from ray casts out of the
    358:     deltoid to the surface it covers (`over`: the tunic, plus the cape if it runs under), plus an
    359:     offset that grows toward the rim. Lower lames tuck under the one above. Open on the neck side."""
    360:     sh = fit.bone[f"J_Bip_{side}_UpperArm"]
    361:     el = fit.bone[f"J_Bip_{side}_LowerArm"]
    362:     down = (el - sh) / np.linalg.norm(el - sh)
    363:     up = -down
    364:     sx = -1 if side == "L" else 1
    365:     outw = np.array([sx, 0, 0.0]) - down * (np.array([sx, 0, 0.0]) @ down)
    366:     outw /= np.linalg.norm(outw)
    367:     fwd = np.cross(down, outw)
    368:     fwd = -fwd if fwd[2] > 0 else fwd
    369:     C = sh + down * 0.015
    370:     pole = up * math.cos(math.radians(28)) + outw * math.sin(math.radians(28))
    371:     pole /= np.linalg.norm(pole)
    372:     e1 = fwd - pole * (fwd @ pole)
    373:     e1 /= np.linalg.norm(e1)
    374:     e2 = np.cross(pole, e1)
    375:     e2 = -e2 if e2 @ outw < 0 else e2
    376:     ph = np.linspace(-math.radians(spread), math.radians(spread), seg)
    377:     pieces, rims = [], []
    378:     for k, (t0, t1, o0, o1) in enumerate(lames):
    379:         G = np.zeros((seg, rows, 3))
    380:         for j, th in enumerate(np.radians(np.linspace(t0, t1, rows))):
    381:             for i, p in enumerate(ph):
    382:                 d = pole * math.cos(th) + math.sin(th) * (e2 * math.cos(p) + e1 * math.sin(p))
    383:                 r = over.cast(C, d, rmax=0.25, far=True)
    384:                 r = 0.06 if np.isnan(r) else r
    385:                 G[i, j] = C + d * (r + o0 + (o1 - o0) * j / (rows - 1))
    386:         pos, tri, outer = thick_grid(G, thickness, outward_from=C)
    387:         pc = piece(f"{name}{k}", role, pos, tri)
    388:         if k == 0:
    389:             fit.bind(pc, blend={f"J_Bip_{side}_UpperArm": 0.7, f"J_Bip_{side}_Shoulder": 0.3})
    390:         else:
    391:             fit.bind(pc, rigid=f"J_Bip_{side}_UpperArm")
    392:         pieces.append(pc)
    393:         rims.append(outer[:, -1])
    394:     return pieces, rims
    395: 
    396: 
    397: def drape(P0, collide, clearance, pinned, steps=90, iters=10, gravity=0.0025, bend=0.25, closed=False):
    398:     """A small position-based cloth solve on a (U, V, 3) grid: gravity, stretch and bend
    399:     constraints taken from the starting shape, pinned points, and collision that keeps every

    401 more lines not shown.

  • read_file{"Path":"~/work/lowmarch/tools/shots/arm_shoot.py"}

    input

    {
      "Path": "~/work/lowmarch/tools/shots/arm_shoot.py"
    }

    result, 40 lines

    Showing lines 1-39 of 39
    1: """Shoot armory sheets from a patched copy of the built page with headless Chromium (as review/vroid-02/sheets.py).
    2: 
    3:   python3 arm_shoot.py SITE_DIR OUT_DIR NAME [NAME...]
    4: """
    5: import base64
    6: import os
    7: import re
    8: import socket
    9: import subprocess
    10: import sys
    11: import time
    12: 
    13: site, out, names = sys.argv[1], sys.argv[2], sys.argv[3:]
    14: os.makedirs(out, exist_ok=True)
    15: s = socket.socket()
    16: s.bind(("127.0.0.1", 0))
    17: port = s.getsockname()[1]
    18: s.close()
    19: server = subprocess.Popen([sys.executable, "-m", "http.server", str(port), "--bind", "127.0.0.1", "--directory", site],
    20:                           stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    21: try:
    22:     time.sleep(0.5)
    23:     for name in names:
    24:         t0 = time.time()
    25:         r = subprocess.run([os.environ.get("CHROMIUM", "/snap/bin/chromium"), *os.environ.get("CHROMIUM_FLAGS", "").split(),
    26:                             "--headless=new", "--use-angle=swiftshader", "--enable-unsafe-swiftshader",
    27:                             "--ignore-gpu-blocklist", "--window-size=1280,900", "--virtual-time-budget=600000",
    28:                             "--dump-dom", f"http://127.0.0.1:{port}/index.html?sheet={name}&rows={os.environ.get('ROWS', '0,1')}&scale=2{os.environ.get('EXTRA', '')}"],
    29:                            capture_output=True, text=True, timeout=900)
    30:         m = re.search(r'id="sheetOut"[^>]*>[redacted: data-URI prefix]([A-Za-z0-9+/=]+)<', r.stdout)
    31:         if not m:
    32:             err = re.search(r'id="sheetOut"[^>]*>([^<]*)<', r.stdout)
    33:             print(name, "FAILED", err.group(1)[:300] if err else r.stderr[-800:])
    34:             continue
    35:         p = os.path.join(out, f"painted_{name}.png")
    36:         open(p, "wb").write(base64.b64decode(m.group(1)))
    37:         print(name, p, f"{time.time() - t0:.0f}s")
    38: finally:
    39:     server.terminate()