A 3D model pipeline, pushed by GPT-6.2-Astra
agent (cont.)
+2:15exec_commandsed -n '458,505p' review/vroid-02/index.html
command
sed -n '458,505p' review/vroid-02/index.html sed -n '1,115p' tools/plates.py sed -n '95,120p' tools/vroid_portrait.py sed -n '163,231p' tools/outfit.py rg -n 'Canvas|decal' tools/plates.py date -u && ls -l ~/context/sortie-node_modules/three/build | head
result, 289 lines
Script completed Wall time 0.1 seconds Output: } else if (uKind == 2) { // hair: four even bands, hard strand highlights float strand = dot(tex.rgb, vec3(1.0 / 3.0)); vec3 c0 = tone(uBase, 0.72, 0.07, 1.10, 0.45), c1 = tone(uBase, 0.72, 0.035, 1.05, 0.68); vec3 c2 = tone(uBase, 0.56, 0.02, 0.92, 1.10), c3 = tone(uBase, 0.56, 0.03, 0.55, 1.42); float l = lit + (strand - 0.6) * 0.12; col = mix(c0, c1, st(l, 0.40)); col = mix(col, uBase, st(l, 0.56)); col = mix(col, c2, st(l, 0.84)); float sp = dot(n, normalize(uKey + v)) + (strand - 0.6) * 0.18; col = mix(col, c3, st(sp, 0.90) * (1.0 - st(sp, 0.985))); } else if (uKind == 3 || uKind == 4) { // steel, gold bool plate = vPlate.x > 0.5; float e = vPlate.y, w = vPlate.z; bool gilt = uKind == 4 || (plate && w > 0.0 && e < w); // an outline plate's gold border col = metal(gilt, gilt && uKind == 3 ? uGold : uBase, n, v, lit, plate ? vPlate.w : -1.0); if (plate && w > 0.0) { // engraved lines: one inside the border, one on its seam float aa = fwidth(e) * 1.2 + 1e-5; float l1 = 1.0 - smoothstep(0.0010, 0.0010 + aa, abs(e - (w + 0.0050))); float l2 = 1.0 - smoothstep(0.0006, 0.0006 + aa, abs(e - w)); col = mix(col, col * 0.42, max(l1, l2 * 0.8)); } } else if (uKind == 7) { // iris float l = dot(tex.rgb, vec3(1.0 / 3.0)); col = l < 0.3 ? mix(uEye[0], uEye[1], l / 0.3) : mix(uEye[1], uEye[2], clamp((l - 0.3) / 0.6, 0.0, 1.0)); } else if (uKind == 8) { col = tex.rgb; } else if (uKind == 10) { // the open mouth: VRoid's map read as three parts, float lum = dot(tex.rgb, vec3(1.0 / 3.0)); // teeth (white), tongue (its light pink) and the col = mix(vec3(0.36, 0.11, 0.14), vec3(0.78, 0.38, 0.42), smoothstep(0.53, 0.58, tex.g)); // dark inside col = mix(col, vec3(0.98, 0.96, 0.95), smoothstep(0.80, 0.86, lum)); } else { col = uFlat; } if (vPlate.x > 0.5 && vPlate.z > 0.0 && uKind != 3 && uKind != 4) { // a cloth outline piece's gold border, float e = vPlate.y, w = vPlate.z, aa = fwidth(e) * 1.2 + 1e-5; // and a fine gold line inside it float band = 1.0 - smoothstep(w - aa, w, e); float l1 = 1.0 - smoothstep(0.0006, 0.0006 + aa, abs(e - (w + 0.0040))); col = mix(col, metal(true, uGold, n, v, lit, -1.0), max(band, l1 * 0.9)); } if (uDecal == 1) { // a design in the piece's own coordinates: vec3 dm = tex.rgb; // R paint, G groove, B gold inlay float pm = smoothstep(0.3, 0.7, dm.r), gm = smoothstep(0.3, 0.7, dm.g), au = smoothstep(0.3, 0.7, dm.b); if (au > 0.0) col = mix(col, metal(true, uGold, n, v, lit, -1.0), au); if (pm > 0.0) { vec3 pc = mix(tone(uMotif, 0.70, 0.05, 1.10, 0.62), uMotif, st(lit, 0.42)); col = mix(col, mix(pc, tone(uMotif, 0.56, 0.03, 0.8, 1.25), st(lit, 0.92)), pm); } if (gm > 0.0) col = mix(col, col * 0.30, gm); } if (vEdge > 0.5) { // the cloth's border band vec3 gd = tone(uBand, 0.20, 0.03, 1.0, 0.72); col = mix(gd, uBand, st(lit, 0.45)); col = mix(col, tone(uBand, 0.16, 0.03, 0.5, 1.45), st(lit, 0.85)); """Plates drawn as outlines: the armour kit's second generation (portrait guide, lesson 13). The first kit builds plate as bands (limb_lames, pauldron lames) or shrink-wraps (the cuirass): fine for stacked lames, but it can't draw a shape. Here a plate is drawn like a pattern piece laid on a dress form. A chart wraps a body region in two coordinates: TorsoChart u = degrees round the body (0 front, +90 the character's right, 180 back), v = height (m) LimbChart u = degrees round a bone (0 = `front`), v = fraction along it (0 at the joint) point(u, v) is on the surface the chart covers: a ray out of the chart's axis, at a radius taken from a field of ray casts that is filled and smoothed (and, as a shell, kept from following hollows), so plates come out as shells rather than mouldings of the skin. A plate is the region between two edge curves over a range of u, bottom(u) and top(u), so its outline is exactly the mesh boundary (no jagged clipping) and a pointed waist, a scooped neckline or a pointed cuff is one function each. It sits `offset` off the chart, is domed by `crown`, given thickness, and carries per-vertex plate data for the painted renderer: plate = (1, distance to the outline in metres, gold border width in metres, height in the plate 0..1) from which the shader paints the border, an engraved line inside it, and a top-to-bottom gradient so a flat plate doesn't read as one flat value. """ import math import numpy as np from scipy.ndimage import gaussian_filter from scipy.spatial import cKDTree def _fill_nan(R, wrap_u=True): """Fill missing radii (rays that hit nothing) from their neighbours round u, then along v.""" R = R.copy() nu, nv = R.shape idx = np.arange(nu) for j in range(nv): col = R[:, j] ok = np.isfinite(col) if ok.sum() >= 2: if wrap_u: xs = np.concatenate([idx[ok] - nu, idx[ok], idx[ok] + nu]) R[:, j] = np.interp(idx, xs, np.tile(col[ok], 3)) else: R[:, j] = np.interp(idx, idx[ok], col[ok]) good = np.isfinite(R).all(0) if not good.any(): raise ValueError("chart: no ray hit the surface") for j in range(nv): if not good[j]: k = np.nonzero(good)[0] R[:, j] = R[:, k[np.argmin(np.abs(k - j))]] return R class _Chart: """Shared: a radius field R[u, v] over a grid, sampled bilinearly (u wraps).""" def _setup(self, R, smooth, shell, wrap_u): R = _fill_nan(R, wrap_u) mode = ("wrap" if wrap_u else "nearest", "nearest") if shell: # bridge hollows (between the breasts, the spine) R = np.maximum(R, gaussian_filter(R, (smooth[0] * 3, smooth[1] * 3), mode=mode)) self.R = gaussian_filter(R, smooth, mode=mode) def radius(self, u, v): u, v = np.broadcast_arrays(np.asarray(u, float), np.asarray(v, float)) fu = (u - self.u0) / self.du fv = np.clip((v - self.v0) / self.dv, 0, self.R.shape[1] - 1.000001) nu = self.R.shape[0] if self.wrap: fu = np.mod(fu, nu) else: fu = np.clip(fu, 0, nu - 1.000001) i0 = np.floor(fu).astype(int) i1 = (i0 + 1) % nu if self.wrap else np.minimum(i0 + 1, nu - 1) j0 = np.floor(fv).astype(int) j1 = np.minimum(j0 + 1, self.R.shape[1] - 1) a, b = fu - i0, fv - j0 R = self.R return ((R[i0, j0] * (1 - a) + R[i1, j0] * a) * (1 - b) + (R[i0, j1] * (1 - a) + R[i1, j1] * a) * b) def point(self, u, v, off=0.0): o, d = self.ray(u, v) return o + d * (self.radius(u, v) + off)[..., None] def normal(self, u, v, eu=1.0, ev=None): """The chart surface's outward normal (finite differences of point()).""" ev = self.ev if ev is None else ev pu = self.point(np.asarray(u) + eu, v) - self.point(np.asarray(u) - eu, v) pv = self.point(u, np.asarray(v) + ev) - self.point(u, np.asarray(v) - ev) n = np.cross(pv, pu) _, d = self.ray(u, v) n = np.where((np.einsum("...i,...i->...", n, d) < 0)[..., None], -n, n) return n / np.maximum(np.linalg.norm(n, axis=-1, keepdims=True), 1e-12) class TorsoChart(_Chart): """u = degrees round the vertical axis through (cx, cz) (0 = front, -z; +90 = the character's right, +x), v = height in metres. `over`: the Surface the plates sit on.""" def __init__(self, over, y0, y1, cx=0.0, cz=0.0, du=3.0, dv=0.01, smooth=(1.5, 1.2), shell=True, rmax=0.4): self.cx, self.cz, self.wrap = cx, cz, True self.u0, self.du, self.v0, self.dv, self.ev = -180.0, du, y0, dv, dv * 0.5 us = np.arange(-180.0, 180.0, du) vs = np.arange(y0, y1 + dv * 0.5, dv) R = np.full((len(us), len(vs)), np.nan) for i, u in enumerate(us): d = np.array([math.sin(math.radians(u)), 0.0, -math.cos(math.radians(u))]) for j, v in enumerate(vs): R[i, j] = over.cast(np.array([cx, v, cz]), d, rmax=rmax, far=True) self._setup(R, smooth, shell, True) def ray(self, u, v): u, v = np.broadcast_arrays(np.asarray(u, float), np.asarray(v, float)) ur = np.radians(u) d = np.stack([np.sin(ur), np.zeros_like(ur), -np.cos(ur)], -1) o = np.stack([np.full_like(u, self.cx), v, np.full_like(u, self.cz)], -1) def repose(v, prims, ref, target): """Move prims built in the `ref` pose to the `target` pose: each bone's change W_target(j) @ W_ref(j)^-1, blended by the skin weights (bones missing from this skeleton, like another model's hair bones, follow the head).""" names = v.nodes_by_name() Wr, Wt = v.node_world(ref), v.node_world(target) cache = {} def delta(nm): if nm not in cache: i = names.get(nm, names["J_Bip_C_Head"]) cache[nm] = Wt[i] @ np.linalg.inv(Wr[i]) return cache[nm] for p in prims: if "J" not in p: continue D = np.stack([delta(nm) for nm in p["jnames"]]) # (nj,4,4) M = (D[p["J"]] * p["W"][:, :, None, None]).sum(1) # (N,4,4) p["pos"] = np.einsum("nij,nj->ni", M[:, :3, :3], p["pos"]) + M[:, :3, 3] n = np.einsum("nij,nj->ni", M[:, :3, :3], p["nrm"]) p["nrm"] = n / np.maximum(np.linalg.norm(n, axis=1, keepdims=True), 1e-12) def reduce_blocks(char, depth, pid, role, h, w): """Majority vote over each SSxSS block, weighted by PRIORITY so thin features survive. Returns class Fit: """What a costume is built against: the body skin (welded, measurable) and the bones, all in the reference pose, plus the skin weights so pieces can be bound to the skeleton.""" def __init__(self, vrm, pose, prims, roles): self._prims, self._roles = prims, roles W = vrm.node_world(pose) names = vrm.nodes_by_name() self.world = {k: W[i].copy() for k, i in names.items() if k} self.bone = {k: m[:3, 3].copy() for k, m in self.world.items()} skin = [p for p, r in zip(prims, roles) if r == "body"] self.body = skin[0] self.pos = self.body["pos"] self.J, self.W, self.jnames = self.body["J"], self.body["W"], self.body["jnames"] self.tri = weld(self.pos, np.concatenate([p["tri"] for p in skin])) self.surf = Surface(self.pos, self.tri) self.skin = self.pos[np.unique(self.tri)] # MakeHuman bodies (tools/makehuman.py) have real muscle relief; VRoid's limbs are smooth tubes self.cloth_hull = vrm.j.get("asset", {}).get("generator", "").startswith("lowmarch makehuman") \ and not os.environ.get("LOWMARCH_NO_HULL") def head_surface(self): """The head's skin (face and scalp), for charts over the skull (tools/hair.py).""" from vrm import bone_weight pos, tri, off = [], [], 0 for p, r in zip(self._prims, self._roles): if r in ("face", "body") and "J" in p and len(p["tri"]): w = bone_weight(p, ("Head",)) T = p["tri"][(w[p["tri"]] > 0.5).all(1)] if len(T): pos.append(p["pos"]) tri.append(T + off) off += len(p["pos"]) return Surface(np.concatenate(pos), np.concatenate(tri)) def weight(self, bones): hit = np.array([any(b in n for b in bones) for n in self.jnames]) return (hit[self.J] * self.W).sum(1) def tris_for(self, bones, min_w=0.5, exclude=(), y_min=None, y_max=None): w = self.weight(bones) if exclude: w = w - self.weight(exclude) T = self.tri[(w[self.tri] >= min_w).all(1)] tp = self.pos[T] sel = np.ones(len(T), bool) if y_min is not None: sel &= tp[:, :, 1].min(1) > y_min if y_max is not None: sel &= tp[:, :, 1].max(1) < y_max return T[sel] def bind(self, pc, allow=None, fallback=None, rigid=None, blend=None, surface=None): """Attach skin weights to a piece: copied from the body under it (optionally limited to some bones), or rigid on one bone / a fixed blend.""" if pc is None: return None n = len(pc["pos"]) if rigid or blend: pc["J"], pc["W"] = rigid_weights(n, self.jnames, rigid, blend) else: pc["J"], pc["W"] = transfer_weights(pc["pos"], None, self.J, self.W, surface=surface or self.surf, allow=allow, jnames=self.jnames, fallback=fallback) pc["jnames"] = self.jnames return pc def without(pc, bones, max_w=0.3): """A piece's triangles away from some bones, as (pos, tri) for merge_surfaces: a bodice's torso 179: plate data and decal coordinates: the inner face copies the outer, edge walls sit at the outline 212:# ---- decals: designs drawn in a piece's own surface coordinates ----------------------------------- 213:# A decal is an RGB texture over the piece's (s, t) square (t up): R = paint (the character's motif 218:class Canvas: 265: panel_crown=0.0, studs=(), stud_r=0.004, stud_role=None, facets=None, decal=(), decal_px=1400, 277: decal: shapes in chart coordinates painted on the plate (see Canvas): 335: # decal coordinates: (u, v) mapped linearly onto the plate's bounding square 349: pc["decal"] = img 351: elif seams or decal: 355: px_m = decal_px 356: cv_ = Canvas(min(1024, max(64, wm * px_m)), min(1024, max(64, hm * px_m))) 360: for sh in decal: 367: pc["decal"] = cv_.array() 444:def flat_piece(name, role, outline, origin, ex, ey, thickness=0.002, decal=(), px=4000): 446: given thickness along ex x ey, with an optional decal in the same (x, y) coordinates.""" 469: if decal: 470: cv = Canvas(min(1024, max(32, span[0] * px)), min(1024, max(32, span[1] * px))) 472: for sh in decal: 477: pc["decal"] = cv.array() Tue Nov 17 22:46:28 UTC 2026 total 6568 -rw------- 1 runner runner 631 Oct 24 21:58 three.cjs -rw------- 1 runner runner 1458113 Oct 24 21:58 three.core.js -rw------- 1 runner runner 662772 Oct 24 21:58 three.module.js -rw------- 1 runner runner 36854 Oct 24 21:58 three.tsl.js -rw------- 1 runner runner 2284850 Oct 24 21:58 three.webgpu.js -rw------- 1 runner runner 2276209 Oct 24 21:58 three.webgpu.nodes.jsexec_commandsed -n '213,261p;334,352p' tools/plates.py
command
sed -n '213,261p;334,352p' tools/plates.py sed -n '210,239p' tools/vroid_portrait.py sed -n '89,135p' tools/rig.py rg -n 'def grip_points|scipy|/tmp/|mkdir|cache' tools/fitting.py tools/rig.py | head -55 cat .envrc du -sh ~/out
result, 155 lines
Script completed Wall time 0.1 seconds Output: # A decal is an RGB texture over the piece's (s, t) square (t up): R = paint (the character's motif # colour), G = groove (a dark recessed line), B = gold inlay. The painted renderer reads it per pixel. CHANNEL = {"paint": 0, "groove": 1, "gold": 2} class Canvas: """Draw shapes given in (s, t) in 0..1 (t up) at w x h pixels, supersampled for clean edges.""" def __init__(self, w, h, ss=3): from PIL import Image, ImageDraw self.w, self.h, self.ss = int(w), int(h), ss self.layers = [Image.new("L", (self.w * ss, self.h * ss), 0) for _ in range(3)] self.draw = [ImageDraw.Draw(im) for im in self.layers] def _xy(self, st): st = np.atleast_2d(np.asarray(st, float)) return [(float(s * self.w * self.ss), float((1 - t) * self.h * self.ss)) for s, t in st] def poly(self, st, ch): self.draw[CHANNEL[ch]].polygon(self._xy(st), fill=255) def line(self, st, width_px, ch): xy = self._xy(st) w = max(1, int(round(width_px * self.ss))) self.draw[CHANNEL[ch]].line(xy, fill=255, width=w, joint="curve") r = w / 2 for x, y in (xy[0], xy[-1]): # round caps self.draw[CHANNEL[ch]].ellipse((x - r, y - r, x + r, y + r), fill=255) def dot(self, st, rx_px, ry_px, ch): (x, y), = self._xy(st) self.draw[CHANNEL[ch]].ellipse((x - rx_px * self.ss, y - ry_px * self.ss, x + rx_px * self.ss, y + ry_px * self.ss), fill=255) def array(self): from PIL import Image chans = [np.asarray(im.resize((self.w, self.h), Image.LANCZOS)) for im in self.layers] return np.dstack(chans + [np.full((self.h, self.w), 255, np.uint8)]).astype(np.uint8) def _seg_distance(P, A, B): """Distance from points P (N,2) to segments A->B (M,2): (N,) minimum.""" d = B - A L2 = np.maximum((d * d).sum(1), 1e-18) t = np.clip(((P[:, None] - A[None]) * d[None]).sum(-1) / L2[None], 0, 1) Q = A[None] + t[..., None] * d[None] return np.linalg.norm(P[:, None] - Q, axis=-1).min(1) data = np.stack([np.ones(nu * nv), dist, np.full(nu * nv, float(trim)), np.tile(T, nu)], 1).reshape(nu, nv, 4) # decal coordinates: (u, v) mapped linearly onto the plate's bounding square vmin, vmax = float(vv.min()), float(vv.max()) to_st = lambda u, v: np.stack([(np.asarray(u, float) - u0) / (u1 - u0), (np.asarray(v, float) - vmin) / max(vmax - vmin, 1e-9)], -1) uv = to_st(uu, vv) if callable(thickness): # per point, e.g. a solid mass down to the surface thickness = np.array([[thickness(U[i], vv[i, j], S[i], T[j]) for j in range(nv)] for i in range(nu)]) pos, tri, dat, uvs = _thick(G, n, thickness, data, uv) pc = piece(name, role, pos, tri) pc["plate"] = dat if pattern is not None: # a repeating texture (mail rings): (image, metres per repeat) img, period = pattern mid_u, mid_v = (u0 + u1) / 2, (vmin + vmax) / 2 wm = abs(np.radians(u1 - u0)) * float(chart.radius(mid_u, mid_v)) hm = (vmax - vmin) * (1 if isinstance(chart, TorsoChart) else chart.L) pc["decal"] = img pc["uv"] = uvs * np.array([wm / period, hm / period * img.shape[1] / img.shape[0]]) elif seams or decal: mid_u, mid_v = (u0 + u1) / 2, (vmin + vmax) / 2 def as4(r): r = np.asarray(r, float) if r.shape == (4, 4): return r m = np.eye(4) m[:3, :3] = r return m pose = {k: as4(r) for k, r in base_pose.items()} for i, n in enumerate(nodes): nm = n.get("name") if not nm: continue mine = own_of(i) par = own_of(parent[i]) if i in parent else np.ones(3) adj = mine / par if np.allclose(adj, 1): continue pose[nm] = pose.get(nm, np.eye(4)) @ np.diag(list(adj) + [1.0]) if sh["shoulder_w"]: # wider shoulders by moving the arm joints out (no shear, unlike for side, sx in (("L", -1.0), ("R", 1.0)): # `shoulders`, which scales the clavicle and skews a turned arm) mv = np.eye(4) mv[0, 3] = sx * sh["shoulder_w"] nm = f"J_Bip_{side}_UpperArm" pose[nm] = mv @ pose.get(nm, np.eye(4)) if sh.get("curl"): # relaxed hands (degrees per finger joint) wherever the pose for side, sg in (("L", 1.0), ("R", -1.0)): # leaves the fingers alone: an open hand reads as a paddle for f in ("Index", "Middle", "Ring", "Little"): for j, kf in ((1, 0.6), (2, 1.0), (3, 0.8)): nm = f"J_Bip_{side}_{f}{j}" pose = self.leg_ik(pose, side, self.pos(reference, f"J_Bip_{side}_Foot")) return pose def aim(self, pose, bone, local_dir, target_dir): """Turn `bone` so its local direction (e.g. the sword blade, hand -z) points along target_dir.""" W = self.world(pose)[self.names[bone]][:3, :3] cur = W @ np.asarray(local_dir, float) return self.rotate_world(pose, bone, rot_between(cur, target_dir)) def arm_ik(self, pose, side, target, pole): """Bend the arm so the wrist lands on `target`, elbow toward `pole`.""" up, lo, hd = f"J_Bip_{side}_UpperArm", f"J_Bip_{side}_LowerArm", f"J_Bip_{side}_Hand" S, E, W = self.pos(pose, up), self.pos(pose, lo), self.pos(pose, hd) l1, l2 = np.linalg.norm(E - S), np.linalg.norm(W - E) T = np.asarray(target, float) d = np.clip(np.linalg.norm(T - S), abs(l1 - l2) + 1e-3, l1 + l2 - 1e-4) u = (T - S) / np.linalg.norm(T - S) w = np.asarray(pole, float) - u * np.dot(pole, u) w /= np.linalg.norm(w) ca = np.clip((l1 * l1 + d * d - l2 * l2) / (2 * l1 * d), -1, 1) E2 = S + l1 * (ca * u + np.sqrt(1 - ca * ca) * w) pose = self.rotate_world(pose, up, rot_between(E - S, E2 - S)) E, W = self.pos(pose, lo), self.pos(pose, hd) return self.rotate_world(pose, lo, rot_between(W - E, S + u * d - E)) def held(self, pose, bone, ref_pose, point): """Where a point attached to `bone` (given in the reference pose, model space) is in `pose`.""" i = self.names[bone] M = self.world(pose)[i] @ np.linalg.inv(self.world(ref_pose)[i]) return M[:3, :3] @ np.asarray(point, float) + M[:3, 3] def grip(self, pose, side, ref_pose, fist_ref, fist_target, blade_dir, pole, local_blade=(0, 0, -1), iters=14): """Put the fist (a point on the hand, from the reference pose) on `fist_target` with the hand's `local_blade` axis along `blade_dir`. An analytic arm IK gets close (elbow toward `pole`); then cyclic corrections that measure the real fist after every step (aim the hand, swing the forearm, swing the upper arm) finish it, which converges even when proportion scales shear the arm and the analytic solve alone undershoots.""" hd, lo, up = f"J_Bip_{side}_Hand", f"J_Bip_{side}_LowerArm", f"J_Bip_{side}_UpperArm" T = np.asarray(fist_target, float) D = np.asarray(blade_dir, float) / np.linalg.norm(blade_dir) wrist = T - (self.held(pose, hd, ref_pose, fist_ref) - self.pos(pose, hd)) pose = self.arm_ik(pose, side, wrist, pole) for _ in range(iters): for _ in range(2): M = self.world(pose)[self.names[hd]][:3, :3] pose = self.rotate_world(pose, hd, rot_between(M @ np.asarray(local_blade, float), D)) for bone in (lo, up): tools/rig.py:151:def grip_points(vrm, shape, ref_pose, fingers=("Index", "Middle", "Ring", "Little")): tools/fitting.py:12:from scipy import sparse tools/fitting.py:13:from scipy.spatial import cKDTree tools/fitting.py:210: from scipy.spatial import ConvexHull export GH_CONFIG_DIR="$HOME/.config/gh-personal" 4.0K ~/outexec_commandhead -87 tools/rig.py
command
head -87 tools/rig.py sed -n '55,82p' tools/gear.py rg -n '^def (vertex|.*normal)' tools/{outfit,fitting,vrm}.py cat tools/session/smoke_spec.json | head -47 sed -n '1030,1064p' tools/vroid_portrait.py df -h .result, 207 lines
Script completed Wall time 0.1 seconds Output: """Small rig tools for authoring poses on a VRoid skeleton: rotate a bone in world space, two-bone leg and arm IK, aiming a held prop (the sword) at a direction, and gripping a sword so its blade runs through a given point. Poses here are the same dicts as tools/poses.py (bone name -> 3x3 or 4x4 adjustment in the bone's own frame). Everything is solved in model space (VRoid: the character faces -z, y up). """ import numpy as np from poses import as4 def rot_between(a, b): a = np.asarray(a, float) / np.linalg.norm(a) b = np.asarray(b, float) / np.linalg.norm(b) v, c = np.cross(a, b), float(np.dot(a, b)) if c < -0.999999: axis = np.cross(a, [1, 0, 0]) if abs(a[0]) < 0.9 else np.cross(a, [0, 1, 0]) axis /= np.linalg.norm(axis) return 2 * np.outer(axis, axis) - np.eye(3) vx = np.array([[0, -v[2], v[1]], [v[2], 0, -v[0]], [-v[1], v[0], 0]]) return np.eye(3) + vx + vx @ vx / (1 + c) class Rig: def __init__(self, vrm, shape=None, ortho=False): """ortho: rotate bones through the parent's pure rotation (exact with scaled bones, see rotate_world). Off by default so clips authored before it (Aldric's, frozen) stay identical.""" import vroid_portrait as vp self.v = vrm self.shape = dict(vp.NEUTRAL, **(shape or {})) self.names = vrm.nodes_by_name() self._bp = vp.bone_pose self.ortho = ortho self._par = vrm.parents() def world(self, pose): return self.v.node_world(self._bp(self.v, self.shape, pose)) def pos(self, pose, bone): return self.world(pose)[self.names[bone]][:3, 3] def rotate_world(self, pose, bone, R): """Pre-multiply the bone's world rotation by R (about its joint) by editing its local pose. With proportion scales on the skeleton the bone's world matrix is not a rotation; the default (legacy) form then leaks shear into the pose and an iterated solve can diverge. ortho mode conjugates by the pure rotation of the frame the adjustment lives in.""" W = self.world(pose) i = self.names[bone] cur = W[i][:3, :3] adj_old = as4(pose.get(bone, np.eye(3))) if self.ortho: par = self._par.get(i) base = (W[par] if par is not None else np.eye(4)) @ self.v.local_matrix(i, None) u, _, vt = np.linalg.svd(base[:3, :3]) Q = u @ vt # nearest rotation out = dict(pose) a = adj_old.copy() a[:3, :3] = Q.T @ R @ Q @ adj_old[:3, :3] out[bone] = a return out base = cur @ np.linalg.inv(adj_old[:3, :3]) # world rotation without this bone's adjustment new_rot = np.linalg.inv(base) @ (R @ cur) out = dict(pose) a = adj_old.copy() a[:3, :3] = new_rot out[bone] = a return out def leg_ik(self, pose, side, target, pole=(0, 0, -1)): """Bend the leg so the ankle lands on `target`, knee toward `pole` (forward).""" up, lo, ft = f"J_Bip_{side}_UpperLeg", f"J_Bip_{side}_LowerLeg", f"J_Bip_{side}_Foot" H, K, A = self.pos(pose, up), self.pos(pose, lo), self.pos(pose, ft) l1, l2 = np.linalg.norm(K - H), np.linalg.norm(A - K) T = np.asarray(target, float) d = np.clip(np.linalg.norm(T - H), 1e-4, l1 + l2 - 1e-4) u = (T - H) / np.linalg.norm(T - H) w = np.asarray(pole, float) - u * np.dot(pole, u) w /= np.linalg.norm(w) ca = np.clip((l1 * l1 + d * d - l2 * l2) / (2 * l1 * d), -1, 1) K2 = H + l1 * (ca * u + np.sqrt(1 - ca * ca) * w) pose = self.rotate_world(pose, up, rot_between(K - H, K2 - H)) K, A = self.pos(pose, lo), self.pos(pose, ft) return self.rotate_world(pose, lo, rot_between(A - K, H + u * d - K)) def plant_feet(self, pose, reference): """Keep both ankles where they are in `reference` (feet stay on the ground while the hips move).""" def _bind(fit, pcs, bone): for pc in pcs: fit.bind(pc, rigid=bone) return pcs def _group(pcs, g): for pc in pcs: pc["group"] = g return pcs # ---- heads: helmets, coifs and hoods on the chart over the skull ---------------------------------------- def helmet(fit, kind="kettle", role="steel", lift=0.030, name="helmet", rivets=True, trim_role=None): """A helmet on the skull chart. kettle: a rounded bowl to just above the brows and ears, a wide brim sloping down. nasal: a taller bowl with a band at the rim and a nose guard down to the nose's tip. sallet: a bowl coming low over the forehead, sweeping into a long flared tail at the back. close: a bowl to the jaw all round, a face plate with an eye slit and breaths (a bucket helm).""" ch = head_chart(fit) out = [] if kind == "kettle": rim = lambda u: float(np.interp(abs(u), [0, 60, 100, 180], [74, 80, 86, 92])) elif kind == "nasal": rim = lambda u: float(np.interp(abs(u), [0, 60, 100, 180], [72, 82, 92, 100])) elif kind == "sallet": tools/outfit.py:140:def ribbon(name, role, curve, width=0.006, lift=0.002, normals=None, away=None, closed=False): tools/outfit.py:246:def near_normals(pc, pts): tools/outfit.py:626:def dome(name, role, centre, normal, up, r, depth, thickness=0.003, seg=20, rows=6, scallop=0.0): tools/fitting.py:182:def vertex_normals(pos, tri): { "_note": "A test of the kit only, not a design: grey figure, placeholder blocks. tools/session/smoke.sh uses it.", "figure": "arm_f_slender", "frame": { "w": 960, "h": 540, "camera": { "kind": "ortho", "yaw": 25, "pitch": 4, "figure_h": 0.55, "figure_x": 0.5 } }, "look": { "hide": [] }, "options": [ { "label": "A" }, { "label": "B", "look": { "hide": [ "hair" ] }, "blocks": [ { "kind": "ball", "at": "J_Bip_C_Head", "c": [ 0, 0.1, -0.01 ], "r": [ 0.115, 0.115, 0.125 ], "colour": "#55555e", "shade": "#3e3e46" }, { "kind": "tube", self.roles.append(rl) if pose is not target_pose and any(not np.allclose(pose.get(k_, np.eye(4)), target_pose.get(k_, np.eye(4))) for k_ in set(pose) | set(target_pose)): repose(self.v, [p for p in self.prims if not p.get("world")], pose, target_pose) names = self.v.nodes_by_name() Wn = self.v.node_world() self.eye = (Wn[names["J_Adj_L_FaceEye"]][:3, 3] + Wn[names["J_Adj_R_FaceEye"]][:3, 3]) / 2 self.chin_y = self.lm["chin"][1] self.tex = {} for k, p in enumerate(self.prims): if self.roles[k] in ("line", "brow", "iris", "highlight", "white", "hair", "mouth"): src = self._hair_v if (hair_from and "_HAIR" in p["material"]) else self.v t = src.material_texture(p["mi"]) if t is not None and self.roles[k] == "line": # VRoid's upper lid is a thick graded band over the iris; keep its dark core only t = t.copy() t[..., 3] = np.where(t[..., :3].mean(-1) < LID_CORE, t[..., 3], 0) if t is not None: self.tex[k] = t # painted face marks (lip line, nose) from the face texture, grown so they survive the vote from scipy.ndimage import binary_dilation, label self.marks = {} self.mouth_pts = None self.mouth_curve = None for k, p in enumerate(self.prims): if self.roles[k] != "face": continue t = self.v.material_texture(p["mi"]) if t is None: continue th, tw = t.shape[:2] vv, uu = np.mgrid[0:th, 0:tw] vv, uu = (vv + 0.5) / th, (uu + 0.5) / tw win = ((uu > MARK_WINDOW["u"][0]) & (uu < MARK_WINDOW["u"][1]) & (vv > MARK_WINDOW["v"][0]) & (vv < MARK_WINDOW["v"][1])) Filesystem Size Used Avail Use% Mounted on /dev/sdd 1007G 540G 417G 57% ~exec_commandmkdir -p review/high-water review/out/high-water
command
mkdir -p review/high-water review/out/high-water cat > review/high-water/figure.py <<'PY' """Pose a cached armory body in the existing caster kit for the high-water study.""" import json import sys from pathlib import Path import numpy as np HERE = Path(__file__).resolve().parent ROOT = HERE.parents[1] CACHE = ROOT / "review/out/high-water" sys.path[:0] = [str(ROOT / "tools"), str(ROOT / "art/cast")] import cage from cast import CAST import export_glb import gear import mobs import outfit import poses import rig import vroid_portrait as vp from fitting import vertex_normals from plates import Canvas from vrm import VRM def hem_pattern(): """A woven border of alternating crests, each with a brass drop in its hollow.""" cloth = Canvas(1024, 384) for k in range(14): x = k / 14 crest = [(0, .078), (.21, .13), (.44, .21), (.63, .22), (.76, .186), (.62, .187), (.51, .162), (.52, .142), (.62, .131), (.78, .142), (1, .177), (1, .148), (.78, .112), (.56, .103), (.39, .117), (.29, .107), (0, .055)] cloth.poly([(x + u / 14, v) for u, v in crest], "paint") cloth.dot((x + .79 / 14, .184), 2.3, 2.3, "gold") for v in (.035, .046, .245): cloth.line([(0, v), (1, v)], 1.6, "gold") return cloth.array() def costume(fit): pieces = mobs.witch(fit) # Recut the stock cone. A higher front gives the forward boot room and the # slack runs behind the wearer. Use the angle before moving the hem for UVs. skirt = next(p for p in pieces if p["material"] == "OUTFIT_robe_skirt") pos = skirt["pos"] angle = np.mod(np.arctan2(pos[:, 0], -(pos[:, 2] - fit.bone["J_Bip_C_Hips"][2])), 2 * np.pi) t = skirt["plate"][:, 3] fall = (1 - t) ** 1.6 front = (1 + np.cos(angle)) / 2 fold = (.010 * np.cos(9 * angle + t) + .008 * np.sin(5 * angle - t)) * fall pos[:, 0] += np.sin(angle) * fold - .025 * fall pos[:, 2] += (.175 - .09 * front) * fall - np.cos(angle) * fold pos[:, 1] += (.12 + .16 * front + .024 * np.cos(5 * angle)) * fall skirt["uv"] = np.column_stack([angle / (2 * np.pi), t]) skirt["decal"] = hem_pattern() skirt["nrm"] = vertex_normals(pos, skirt["tri"]) skirt["role"] = "tidecoat" for p in pieces: if p["material"].startswith("OUTFIT_hat"): if p["material"] == "OUTFIT_hat": pos = p["pos"] tip = np.clip((pos[:, 1] - pos[:, 1].min()) / .32, 0, 1) pos[:, 2] += .20 * tip ** 2 pos[:, 1] -= .115 * tip ** 2 p["nrm"] = vertex_normals(pos, p["tri"]) if p["role"] == "signature": p["role"] = "tidecoat" # Marks on the part of the sounding staff that goes into the water. grip, axis, _, _, _ = gear._hand_frame(fit) for i in range(9): length = .030 if i % 3 == 0 else .014 mark = outfit.tube(f"staff_mark_{i}", "heraldry", grip + axis * (-.72 + .065*i), axis, length, .0162, .0162) pieces.append(fit.bind(mark, rigid="J_Bip_R_Hand")) return pieces def make_pose(model, shape): ref = vp.BUST_POSE skeleton = rig.Rig(model, shape, ortho=True) pose = poses.merge(poses.BATTLE_IDLE, { "J_Bip_C_Hips": poses.move(dy=-.043), "J_Bip_C_Spine": poses.rot((1, 0, 0), -9), "J_Bip_C_Head": poses.rot((0, 1, 0), 9) @ poses.rot((1, 0, 0), -5), "J_Bip_L_UpperArm": poses.rot((0, 1, 0), 25), "J_Bip_L_LowerArm": poses.rot((0, 1, 0), -16), }) for side, dz in (("L", -.17), ("R", .135)): foot = skeleton.pos(ref, f"J_Bip_{side}_Foot") pose = skeleton.leg_ik(pose, side, foot + [0, .015 if side == "R" else 0, dz]) hand = rig.grip_points(model, shape, ref)["R"]["point"] shoulder = skeleton.pos(pose, "J_Bip_R_UpperArm") # Wrist extended ahead of her as she takes a sounding. The staff points # back toward her at the top, planting its foot away from her front boot. return skeleton.grip(pose, "R", ref, hand, shoulder + [.085, -.27, -.39], [-.045, 1, .38], [.95, -.65, .4]) def main(): CACHE.mkdir(parents=True, exist_ok=True) name = "arm_f_strong" cast = CAST[name] path = cage.path_for(name, cast["cage"]) model = VRM(path) shape = dict(vp.NEUTRAL, **cast["shape"]) pose = make_pose(model, shape) actor = vp.Portrait(path, shape=shape, pose=pose, costume=costume, morphs={"Fcl_EYE_Halfclose": .14}) actor.paint = dict(signature="#ad5239", tidecoat="#34575b", doublet="#393c49", hair="#ead4aa", skin="#e4b48e", boot="#514343", glove="#553e39", wood=dict(kind="leather", base="#65503d"), gold="#c3985c", heraldry="#e2bd85", motif="#ccbf95") palette = dict(vp.PALETTE, **cast["colors"]) export_glb.export_skinned(actor, palette, CACHE / "figure.glb") info = export_glb.scene_info(actor, palette) (CACHE / "camera.json").write_text(json.dumps({"characters": [{"name": "figure", "info": info}]})) if __name__ == "__main__": main() PY OPENBLAS_NUM_THREADS=1 python3 review/high-water/figure.py > review/out/high-water/build.log 2>&1result, 4 lines
Script completed Wall time 0.4 seconds Output: {"chunk_id":"897ada","wall_time_seconds":0.251089768,"session_id":73191,"original_token_count":0,"output":""}exec_commandcat review/out/high-water/build.log
command
cat review/out/high-water/build.log sed -n '1709,1745p' review/vroid-02/index.html sed -n '145,182p' tools/rig.py env | rg 'PLAYWRIGHT|TMPDIR|CHROM'
result, 4 lines
Script completed Wall time 0.1 seconds Output: {"chunk_id":"bf3f38","wall_time_seconds":0.00000369,"exit_code":0,"original_token_count":957,"output":" const steps = Math.max(1, Math.round(dt / (1 / 120)));\n for (let s = 0; s < steps; s++) { simT += dt / steps; cloths.forEach(c => c.step(dt / steps, simT)); }\n cloths.forEach(c => c.write());\n }\n render();\n placeTags();\n }\n requestAnimationFrame(frame);\n}\n\nif (!LINEUP.order.length) $(\"lineupBtn\").hidden = true;\n// a check for scripts (?springprobe): after a few seconds of the motion, each body's widest spring-bone swing (degrees)\nif (params.has(\"springprobe\")) setTimeout(() => {\n document.title = \"springs \" + JSON.stringify(Object.fromEntries(active().map(c => [c.name, +(c.springMax || 0).toFixed(1)])));\n}, 4000);\nif (SHEET) {\n runSheet(SHEET).catch(e => { console.error(e); $(\"sheetOut\").textContent = \"error: \" + e; document.title = \"sheet failed\"; });\n} else {\n if (window.innerWidth > 1100) setPanel(true);\n loadChecks();\n const v0 = params.get(\"view\"), w0 = params.get(\"who\"), m0 = params.get(\"mode\");\n if (w0 && charDef(w0)) state.who = w0;\n if (m0 === \"3d\") document.querySelector('[data-mode=\"3d\"]').click();\n const views = ARMORY_PAGE ? [\"battle\", \"bust\", \"compare\"] : NO_DUEL ? [\"battle\", \"bust\", \"lineup\"] : [\"duel\", \"battle\", \"bust\", \"lineup\"];\n await setView(views.includes(v0) ? v0 : ARMORY_PAGE ? \"compare\" : NO_DUEL ? \"lineup\" : \"duel\", params.get(\"clip\") || undefined);\n if (params.has(\"yaw\")) setYaw(+params.get(\"yaw\") || 0); // ?yaw=180: open turned (the backs)\n requestAnimationFrame(frame);\n}\n</script>\n for _ in range(2): # the blade direction is what reads; finish on it\n M = self.world(pose)[self.names[hd]][:3, :3]\n pose = self.rotate_world(pose, hd, rot_between(M @ np.asarray(local_blade, float), D))\n return pose\n\n\ndef grip_points(vrm, shape, ref_pose, fingers=(\"Index\", \"Middle\", \"Ring\", \"Little\")):\n \"\"\"Where each fist closes: the centre of the hole the curled fingers make (poses.fist), in model\n space in `ref_pose` (the hand doesn't move when the fingers curl, so a weapon built there and bound\n to the hand sits in the fist whenever the fingers are curled). Each finger's joints and fingertip\n (the last segment again, bent by its own joint) are fitted with a circle in the plane across the\n hole (the hand's local z runs through it, palm to fingertips in x and y); the hole's centre is the\n mean of the fingers' circle centres. A fixed offset from the wrist, tuned on one hand, missed on\n larger or differently made hands (the shaft ran over the knuckles, the fingers closed under it).\n Returns {side: dict(point, axis, radius)}: radius is the finger-centreline circle's (the shaft's\n radius plus a finger's half-thickness fits).\"\"\"\n import vroid_portrait as vp\n import poses as P\n sh = dict(vp.NEUTRAL, **(shape or {}))\n names = vrm.nodes_by_name()\n out = {}\n for side in \"LR\":\n sx = 1.0 if side == \"R\" else -1.0\n W = vrm.node_world(vp.bone_pose(vrm, sh, P.merge(ref_pose, P.fist(side))))\n H = W[names[f\"J_Bip_{side}_Hand\"]]\n R = H[:3, :3] / np.linalg.norm(H[:3, :3], axis=0)\n o, e1, e2, ax = H[:3, 3], R[:, 0] * sx, R[:, 1], R[:, 2]\n cs, axial, rads = [], [], []\n for f in fingers:\n ks = [names.get(f\"J_Bip_{side}_{f}{k}\") for k in (1, 2, 3)]\n if any(k is None for k in ks):\n continue\n js = [W[k][:3, 3] for k in ks]\n M3 = W[ks[2]][:3, :3] / np.linalg.norm(W[ks[2]][:3, :3], axis=0)\n pts = js + [js[2] + M3 @ np.array([sx, 0.0, 0.0]) * 0.85 * np.linalg.norm(js[2] - js[1])]\n Q = np.array([[(p - o) @ e1, (p - o) @ e2] for p in pts])\n A = np.c_[2 * Q, np.ones(len(Q))] # algebraic circle fit\n b = (Q ** 2).sum(1)\nPLAYWRIGHT_BROWSERS_PATH=/opt/ms-playwright\n"}exec_commandcat > review/high-water/shoot.cjs <<'JS'
command
cat > review/high-water/shoot.cjs <<'JS' // Read the project viewer directly so its colour, depth and outline passes stay together. // Playwright serves all inputs from disk. Chromium never needs a network connection. const fs = require("node:fs/promises"); const path = require("node:path"); const os = require("node:os"); const root = path.resolve(__dirname, "../.."); const cache = path.join(root, "review/out/high-water"); const packages = process.env.LOWMARCH_NODE_MODULES || path.join(os.homedir(), "context/sortie-node_modules"); const three = path.join(packages, "three"); const { chromium } = require(path.join(packages, "playwright")); async function main() { const profile = path.join(cache, "browser"); await fs.mkdir(profile, { recursive: true }); process.env.TMPDIR = profile; const viewer = await fs.readFile(path.join(root, "review/vroid-02/index.html"), "utf8"); const ending = viewer.indexOf("if (!LINEUP.order.length)"); if (ending === -1) throw new Error("Cannot find the viewer entry point"); const shot = await fs.readFile(path.join(__dirname, "shot.js"), "utf8"); const html = viewer.slice(0, ending).replaceAll("https://cdn.jsdelivr.net/npm/three@0.160.0/", "/three/") + shot + "\n</script>"; const binary = await fs.readFile(path.join(cache, "figure.glb")); const browser = await chromium.launch({ headless: true, args: ["--use-angle=swiftshader", "--enable-unsafe-swiftshader"] }); try { const page = await browser.newPage(); const errors = []; page.on("pageerror", e => errors.push(String(e))); page.on("console", msg => { if (msg.type() === "error") errors.push(msg.text()); }); await page.route("**/*", async route => { const url = new URL(route.request().url()); if (url.origin !== "http://lowmarch.local") return route.abort(); const p = url.pathname; if (p === "/") return route.fulfill({ body: html, contentType: "text/html" }); if (p === "/figure.glb.json") return route.fulfill({ json: {glb: binary.toString("base64")} }); if (p === "/camera.json") return route.fulfill({ path: path.join(cache, "camera.json") }); if (p.startsWith("/three/") && p.endsWith(".js")) { return route.fulfill({ path: path.join(three, p.slice(7)), contentType: "text/javascript" }); } return route.abort(); }); await page.goto("http://lowmarch.local/?sheet=figure"); if (errors.length) throw new Error(errors.join("\n")); const png = await page.evaluate(() => window.studyPNG); if (!png || errors.length) throw new Error(errors.join("\n") || "No painted frame"); await fs.writeFile(path.join(cache, "figure.png"), Buffer.from(png.split(",")[1], "base64")); } finally { await browser.close(); } } main().catch(err => { console.error(err); process.exitCode = 1; }); JS cat > review/high-water/shot.js <<'JS' // Runs as the final lines of the review viewer's module in headless Chromium. state.view = "battle"; state.cloth = false; const actor = await loadCharacter("figure"); stage.add(actor.turn); actor.turn.rotation.y = THREE.MathUtils.degToRad(57); const height = 2.36, width = 2.65, middle = .99; R.setPixelRatio(1); R.setSize(1590, 1416, false); camera.left = -.43 * width; camera.right = .57 * width; camera.top = height / 2; camera.bottom = -height / 2; camera.position.set(0, middle + .40, 5.5); camera.lookAt(0, middle, 0); camera.updateProjectionMatrix(); render(); window.studyPNG = R.domElement.toDataURL("image/png"); JS ls -lah review/out/high-water cat review/out/high-water/build.logresult, 4 lines
Script completed Wall time 0.1 seconds Output: {"chunk_id":"f2c188","wall_time_seconds":0.00000437,"exit_code":0,"original_token_count":69,"output":"total 4.4M\ndrwx------ 2 runner runner 4.0K Nov 17 22:48 .\ndrwx------ 3 runner runner 4.0K Nov 17 22:47 ..\n-rw------- 1 runner runner 0 Nov 17 22:47 build.log\n-rw------- 1 runner runner 9.9K Nov 17 22:48 camera.json\n-rw------- 1 runner runner 4.4M Nov 17 22:48 figure.glb\n"}exec_commandnode review/high-water/shoot.cjs && python3 - <<'PY'
command
node review/high-water/shoot.cjs && python3 - <<'PY' from PIL import Image from pathlib import Path d=Path('review/out/high-water') im=Image.open(d/'figure.png'); print(im.getbbox()) bg=Image.new('RGB',im.size,'#e3cead'); bg.paste(im,mask=im.getchannel('A')); bg.thumbnail((720,720)); bg.save(d/'check.jpg') PYresult, 4 lines
Script completed Wall time 0.1 seconds Output: {"chunk_id":"81450a","wall_time_seconds":0.000006461,"exit_code":1,"original_token_count":283,"output":"node:internal/modules/cjs/loader:1386\n throw err;\n ^\n\nError: Cannot find module 'playwright-core'\nRequire stack:\n- ~/context/sortie-node_modules/playwright/index.js\n- ~/work/lowmarch/review/high-water/shoot.cjs\n at Function._resolveFilename (node:internal/modules/cjs/loader:1383:15)\n at defaultResolveImpl (node:internal/modules/cjs/loader:1025:19)\n at resolveForCJSWithHooks (node:internal/modules/cjs/loader:1030:22)\n at Function._load (node:internal/modules/cjs/loader:1192:37)\n at TracingChannel.traceSync (node:diagnostics_channel:328:14)\n at wrapModuleLoad (node:internal/modules/cjs/loader:237:24)\n at Module.require (node:internal/modules/cjs/loader:1463:12)\n at require (node:internal/modules/helpers:147:16)\n at Object.<anonymous> (~/context/sortie-node_modules/playwright/index.js:17:18)\n at Module._compile (node:internal/modules/cjs/loader:1706:14) {\n code: 'MODULE_NOT_FOUND',\n requireStack: [\n '~/context/sortie-node_modules/playwright/index.js',\n '~/work/lowmarch/review/high-water/shoot.cjs'\n ]\n}\n\nNode.js v22.21.1\n"}exec_commandsed -i 's/const { chromium } = require(path.join(packages, "playwright"));/const { chromium } = require(path.join(packages, "playwright-core"));/' review/high-water/shoot.cjs
command
sed -i 's/const { chromium } = require(path.join(packages, "playwright"));/const { chromium } = require(path.join(packages, "playwright-core"));/' review/high-water/shoot.cjs node review/high-water/shoot.cjs && python3 - <<'PY' from PIL import Image from pathlib import Path d=Path('review/out/high-water') im=Image.open(d/'figure.png'); print(im.getbbox()) bg=Image.new('RGB',im.size,'#e3cead'); bg.paste(im,mask=im.getchannel('A')); bg.thumbnail((720,720)); bg.save(d/'check.jpg') PYresult, 4 lines
Script completed Wall time 0.4 seconds Output: {"chunk_id":"12f9b4","wall_time_seconds":0.250571836,"session_id":84483,"original_token_count":0,"output":""}write_stdinpoll session 84483
input
text(await tools.write_stdin({session_id:84483,chars:"",yield_time_ms:1200,max_output_tokens:950}))result, 4 lines
Script completed Wall time 0.0 seconds Output: {"chunk_id":"3b25be","wall_time_seconds":0.0000033,"exit_code":1,"original_token_count":79,"output":"Error: Failed to load resource: net::ERR_FAILED\n at main (~/work/lowmarch/review/high-water/shoot.cjs:42:30)\n at runNextTicks (node:internal/process/task_queues:65:5)\n at process.processImmediate (node:internal/timers:453:9)\n at process.callbackTrampoline (node:internal/async_hooks:130:17)\n"}exec_commandsed -i 's/errors.push(msg.text())/errors.push(msg.text() + " " + JSON.stringify(msg.location()))/' review/high-water/shoot.cjs
command
sed -i 's/errors.push(msg.text())/errors.push(msg.text() + " " + JSON.stringify(msg.location()))/' review/high-water/shoot.cjs rg -n 'https?://|url\(' review/vroid-02/index.html | cut -c1-200 | head -35 node review/high-water/shoot.cjsresult, 4 lines
Script completed Wall time 0.5 seconds Output: {"chunk_id":"cdd6c8","wall_time_seconds":0.300584727,"session_id":24269,"original_token_count":129,"output":"4:<link rel=\"preconnect\" href=\"https://fonts.googleapis.com\">\n5:<link rel=\"preconnect\" href=\"https://fonts.gstatic.com\" crossorigin>\n6:<link href=\"https://fonts.googleapis.com/css2?family=Alegreya+Sans:ital,wght@0,400;0,500;0,700;1,400&family=Pixelify+Sans:wght@500;700&family=Silkscreen&display=swap\" rel=\"stylesheet\">\n219:{ \"imports\": { \"three\": \"https://cdn.jsdelivr.net/npm/three@0.160.0/build/three.module.js\",\n220: \"three/addons/\": \"https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/\" } }\n"}exec_commandsed -i 's/viewer.slice(0, ending).replaceAll/viewer.slice(0, ending).replace(\/<link [^>]+>\/g, "").replaceAll/' review/high-water/shoot.cjs
command
sed -i 's/viewer.slice(0, ending).replaceAll/viewer.slice(0, ending).replace(\/<link [^>]+>\/g, "").replaceAll/' review/high-water/shoot.cjs node review/high-water/shoot.cjs && python3 - <<'PY' from PIL import Image from pathlib import Path d=Path('review/out/high-water') im=Image.open(d/'figure.png'); print(im.getbbox()) bg=Image.new('RGB',im.size,'#e3cead'); bg.paste(im,mask=im.getchannel('A')); bg.thumbnail((720,720)); bg.save(d/'check.jpg') PYresult, 4 lines
Script completed Wall time 0.4 seconds Output: {"chunk_id":"c78f2a","wall_time_seconds":0.251088738,"session_id":9202,"original_token_count":0,"output":""}write_stdinpoll session 9202
input
text(await tools.write_stdin({session_id:9202,chars:"",yield_time_ms:2000,max_output_tokens:1000}))result, 4 lines
Script completed Wall time 0.0 seconds Output: {"chunk_id":"be9125","wall_time_seconds":0.00000298,"exit_code":1,"original_token_count":25,"output":"Error: No painted frame\n at main (~/work/lowmarch/review/high-water/shoot.cjs:44:38)\n"}exec_commandsed -i '/const png = await page.evaluate/i\ await page.waitForFunction(() => !!window.studyPNG, null, { timeout: 45000 }).catch(e => { throw new Error(errors.join("\\n") || e.message); });' review/high-water/shoot.cjs
command
sed -i '/const png = await page.evaluate/i\ await page.waitForFunction(() => !!window.studyPNG, null, { timeout: 45000 }).catch(e => { throw new Error(errors.join("\\n") || e.message); });' review/high-water/shoot.cjs node review/high-water/shoot.cjs && python3 - <<'PY' from PIL import Image from pathlib import Path d=Path('review/out/high-water') im=Image.open(d/'figure.png'); print(im.getbbox()) bg=Image.new('RGB',im.size,'#e3cead'); bg.paste(im,mask=im.getchannel('A')); bg.thumbnail((720,720)); bg.save(d/'check.jpg') PYresult, 4 lines
Script completed Wall time 0.4 seconds Output: {"chunk_id":"1cc569","wall_time_seconds":0.251266894,"session_id":16637,"original_token_count":0,"output":""}exec_commandls -la review/out/high-water
command
ls -la review/out/high-water rg -n 'new ResizeObserver|CAM\.duel|loadChecks\(' review/vroid-02/index.htmlresult, 4 lines
Script completed Wall time 0.0 seconds Output: {"chunk_id":"2dd247","wall_time_seconds":0.0000054,"exit_code":0,"original_token_count":211,"output":"total 4948\ndrwx------ 3 runner runner 4096 Nov 17 22:49 .\ndrwx------ 3 runner runner 4096 Nov 17 22:47 ..\ndrwx------ 2 runner runner 4096 Nov 17 22:49 browser\n-rw------- 1 runner runner 0 Nov 17 22:47 build.log\n-rw------- 1 runner runner 10049 Nov 17 22:48 camera.json\n-rw------- 1 runner runner 22399 Nov 17 22:49 check.jpg\n-rw------- 1 runner runner 4521464 Nov 17 22:48 figure.glb\n-rw------- 1 runner runner 493114 Nov 17 22:49 figure.png\n907:const CAM_VIEW = () => state.view === \"duel\" || ROW_VIEW() ? CAM.duel.cam : charDef(state.who).cams[state.view];\n908:const activeNames = () => state.view === \"duel\" ? [CAM.duel.order.player, CAM.duel.order.opponent]\n1356: const pl = CAM.duel.place[c.name];\n1600:async function loadChecks() {\n1691:new ResizeObserver(() => size()).observe(stageEl);\n1728: loadChecks();\n"}view_image~/work/lowmarch/review/out/high-water/check.jpg
input
image((await tools.view_image({path:"~/work/lowmarch/review/out/high-water/check.jpg"})).image_url)result, 4 lines
Script completed Wall time 0.0 seconds Output:
exec_commandpython3 - <<'PY'
command
python3 - <<'PY' from PIL import Image from pathlib import Path d=Path('review/out/high-water') im=Image.open(d/'figure.png'); print(im.getbbox()); a=Image.new('RGB',im.size,'#e3cead');a.paste(im,mask=im.getchannel('A')); a.crop((560,240,950,570)).save(d/'detail.png') PYresult, 4 lines
Script completed Wall time 0.1 seconds Output: {"chunk_id":"a73ff1","wall_time_seconds":0.000004591,"exit_code":0,"original_token_count":6,"output":"(435, 53, 981, 1346)\n"}
