A 3D model pipeline, pushed by Gemini 4 Carbon
agent (cont.)
+5:32read_file{"EndLine":250,"Path":"~/work/lowmarch/tools/plates.py","StartLine":1}
input
{ "EndLine": 250, "Path": "~/work/lowmarch/tools/plates.py", "StartLine": 1 }result, 251 lines
Showing lines 1-250 of 487 1: """Plates drawn as outlines: the armour kit's second generation (portrait guide, lesson 13). 2: 3: The first kit builds plate as bands (limb_lames, pauldron lames) or shrink-wraps (the cuirass): fine 4: for stacked lames, but it can't draw a shape. Here a plate is drawn like a pattern piece laid on a 5: dress form. 6: 7: A chart wraps a body region in two coordinates: 8: TorsoChart u = degrees round the body (0 front, +90 the character's right, 180 back), v = height (m) 9: LimbChart u = degrees round a bone (0 = `front`), v = fraction along it (0 at the joint) 10: point(u, v) is on the surface the chart covers: a ray out of the chart's axis, at a radius taken from 11: a field of ray casts that is filled and smoothed (and, as a shell, kept from following hollows), so 12: plates come out as shells rather than mouldings of the skin. 13: 14: A plate is the region between two edge curves over a range of u, bottom(u) and top(u), so its outline 15: is exactly the mesh boundary (no jagged clipping) and a pointed waist, a scooped neckline or a pointed 16: cuff is one function each. It sits `offset` off the chart, is domed by `crown`, given thickness, and 17: carries per-vertex plate data for the painted renderer: 18: plate = (1, distance to the outline in metres, gold border width in metres, height in the plate 0..1) 19: from which the shader paints the border, an engraved line inside it, and a top-to-bottom gradient 20: so a flat plate doesn't read as one flat value. 21: """ 22: import math 23: 24: import numpy as np 25: from scipy.ndimage import gaussian_filter 26: from scipy.spatial import cKDTree 27: 28: 29: def _fill_nan(R, wrap_u=True): 30: """Fill missing radii (rays that hit nothing) from their neighbours round u, then along v.""" 31: R = R.copy() 32: nu, nv = R.shape 33: idx = np.arange(nu) 34: for j in range(nv): 35: col = R[:, j] 36: ok = np.isfinite(col) 37: if ok.sum() >= 2: 38: if wrap_u: 39: xs = np.concatenate([idx[ok] - nu, idx[ok], idx[ok] + nu]) 40: R[:, j] = np.interp(idx, xs, np.tile(col[ok], 3)) 41: else: 42: R[:, j] = np.interp(idx, idx[ok], col[ok]) 43: good = np.isfinite(R).all(0) 44: if not good.any(): 45: raise ValueError("chart: no ray hit the surface") 46: for j in range(nv): 47: if not good[j]: 48: k = np.nonzero(good)[0] 49: R[:, j] = R[:, k[np.argmin(np.abs(k - j))]] 50: return R 51: 52: 53: class _Chart: 54: """Shared: a radius field R[u, v] over a grid, sampled bilinearly (u wraps).""" 55: 56: def _setup(self, R, smooth, shell, wrap_u): 57: R = _fill_nan(R, wrap_u) 58: mode = ("wrap" if wrap_u else "nearest", "nearest") 59: if shell: # bridge hollows (between the breasts, the spine) 60: R = np.maximum(R, gaussian_filter(R, (smooth[0] * 3, smooth[1] * 3), mode=mode)) 61: self.R = gaussian_filter(R, smooth, mode=mode) 62: 63: def radius(self, u, v): 64: u, v = np.broadcast_arrays(np.asarray(u, float), np.asarray(v, float)) 65: fu = (u - self.u0) / self.du 66: fv = np.clip((v - self.v0) / self.dv, 0, self.R.shape[1] - 1.000001) 67: nu = self.R.shape[0] 68: if self.wrap: 69: fu = np.mod(fu, nu) 70: else: 71: fu = np.clip(fu, 0, nu - 1.000001) 72: i0 = np.floor(fu).astype(int) 73: i1 = (i0 + 1) % nu if self.wrap else np.minimum(i0 + 1, nu - 1) 74: j0 = np.floor(fv).astype(int) 75: j1 = np.minimum(j0 + 1, self.R.shape[1] - 1) 76: a, b = fu - i0, fv - j0 77: R = self.R 78: return ((R[i0, j0] * (1 - a) + R[i1, j0] * a) * (1 - b) + (R[i0, j1] * (1 - a) + R[i1, j1] * a) * b) 79: 80: def point(self, u, v, off=0.0): 81: o, d = self.ray(u, v) 82: return o + d * (self.radius(u, v) + off)[..., None] 83: 84: def normal(self, u, v, eu=1.0, ev=None): 85: """The chart surface's outward normal (finite differences of point()).""" 86: ev = self.ev if ev is None else ev 87: pu = self.point(np.asarray(u) + eu, v) - self.point(np.asarray(u) - eu, v) 88: pv = self.point(u, np.asarray(v) + ev) - self.point(u, np.asarray(v) - ev) 89: n = np.cross(pv, pu) 90: _, d = self.ray(u, v) 91: n = np.where((np.einsum("...i,...i->...", n, d) < 0)[..., None], -n, n) 92: return n / np.maximum(np.linalg.norm(n, axis=-1, keepdims=True), 1e-12) 93: 94: 95: class TorsoChart(_Chart): 96: """u = degrees round the vertical axis through (cx, cz) (0 = front, -z; +90 = the character's 97: right, +x), v = height in metres. `over`: the Surface the plates sit on.""" 98: 99: 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): 100: self.cx, self.cz, self.wrap = cx, cz, True 101: self.u0, self.du, self.v0, self.dv, self.ev = -180.0, du, y0, dv, dv * 0.5 102: us = np.arange(-180.0, 180.0, du) 103: vs = np.arange(y0, y1 + dv * 0.5, dv) 104: R = np.full((len(us), len(vs)), np.nan) 105: for i, u in enumerate(us): 106: d = np.array([math.sin(math.radians(u)), 0.0, -math.cos(math.radians(u))]) 107: for j, v in enumerate(vs): 108: R[i, j] = over.cast(np.array([cx, v, cz]), d, rmax=rmax, far=True) 109: self._setup(R, smooth, shell, True) 110: 111: def ray(self, u, v): 112: u, v = np.broadcast_arrays(np.asarray(u, float), np.asarray(v, float)) 113: ur = np.radians(u) 114: d = np.stack([np.sin(ur), np.zeros_like(ur), -np.cos(ur)], -1) 115: o = np.stack([np.full_like(u, self.cx), v, np.full_like(u, self.cz)], -1) 116: return o, d 117: 118: def metric(self, u, v): 119: """(arc length round the body, height) in metres: distances along the surface for trim.""" 120: return np.stack([np.radians(u) * self.radius(u, v), np.asarray(v, float) + 0 * np.asarray(u, float)], -1) 121: 122: def centre(self, v): 123: return np.array([self.cx, v, self.cz]) 124: 125: 126: class ConeChart(TorsoChart): 127: """A TorsoChart whose radius is a function r(u, v) instead of ray casts: a skirt's cone, a 128: plate standing off a skirt. r_fn takes and returns arrays.""" 129: 130: def __init__(self, r_fn, cx=0.0, cz=0.0, ev=0.005): 131: self.cx, self.cz, self.r_fn, self.ev, self.wrap = cx, cz, r_fn, ev, True 132: 133: def radius(self, u, v): 134: u, v = np.broadcast_arrays(np.asarray(u, float), np.asarray(v, float)) 135: return np.asarray(self.r_fn(u, v), float) + 0 * u 136: 137: 138: class LimbChart(_Chart): 139: """u = degrees round the bone from a to b (0 = toward `front`, +90 = toward front x axis, i.e. 140: the right-handed turn about the bone), v = fraction along it (0 at a, 1 at b; -0.2..1.2 covered).""" 141: 142: def __init__(self, over, a, b, front=(0, 0, -1), du=6.0, dv=0.025, smooth=(1.2, 1.2), shell=True, rmax=0.14, 143: v_range=(-0.2, 1.2)): 144: self.a, self.b = np.asarray(a, float), np.asarray(b, float) 145: ax = self.b - self.a 146: self.L = float(np.linalg.norm(ax)) 147: self.ax = ax / self.L 148: f = np.asarray(front, float) - self.ax * (np.asarray(front, float) @ self.ax) 149: self.f = f / np.linalg.norm(f) 150: self.s = np.cross(self.ax, self.f) 151: self.wrap = True 152: self.u0, self.du, self.v0, self.dv, self.ev = -180.0, du, v_range[0], dv, dv * 0.5 153: us = np.arange(-180.0, 180.0, du) 154: vs = np.arange(v_range[0], v_range[1] + dv * 0.5, dv) 155: R = np.full((len(us), len(vs)), np.nan) 156: for i, u in enumerate(us): 157: ur = math.radians(u) 158: d = self.f * math.cos(ur) + self.s * math.sin(ur) 159: for j, v in enumerate(vs): 160: R[i, j] = over.cast(self.a + self.ax * self.L * v, d, rmax=rmax, far=True) 161: self._setup(R, smooth, shell, True) 162: 163: def ray(self, u, v): 164: u, v = np.broadcast_arrays(np.asarray(u, float), np.asarray(v, float)) 165: ur = np.radians(u) 166: d = np.cos(ur)[..., None] * self.f + np.sin(ur)[..., None] * self.s 167: o = self.a + self.ax * (self.L * v)[..., None] 168: return o, d 169: 170: def metric(self, u, v): 171: return np.stack([np.radians(u) * self.radius(u, v), np.asarray(v, float) * self.L + 0 * np.asarray(u, float)], -1) 172: 173: def centre(self, v): 174: return self.a + self.ax * self.L * v 175: 176: 177: def _thick(G, n, thickness, data, uv): 178: """A grid shell (outer face G, inner face G - n*thickness, the four edges closed) with per-vertex 179: plate data and decal coordinates: the inner face copies the outer, edge walls sit at the outline 180: (distance 0).""" 181: U, V = G.shape[:2] 182: idx = np.arange(U * V).reshape(U, V) 183: a, b, c, d = idx[:-1, :-1], idx[1:, :-1], idx[1:, 1:], idx[:-1, 1:] 184: tri = np.concatenate([np.stack([a, b, c], -1).reshape(-1, 3), np.stack([a, c, d], -1).reshape(-1, 3)]) 185: th = np.asarray(thickness, float) 186: outer, inner = G.reshape(-1, 3), (G - n * (th[..., None] if th.ndim else th)).reshape(-1, 3) 187: fn = np.cross(outer[tri[:, 1]] - outer[tri[:, 0]], outer[tri[:, 2]] - outer[tri[:, 0]]) 188: if (np.einsum("ij,ij->i", fn, n.reshape(-1, 3)[tri[:, 0]]) < 0).mean() > 0.5: 189: tri = tri[:, ::-1] # the outer face winds outward (along the chart normal) 190: mid = (outer.mean(0) + inner.mean(0)) / 2 191: D, UV = data.reshape(-1, 4), uv.reshape(-1, 2) 192: pos, tris, dat, uvs = [outer, inner], [tri, tri[:, ::-1] + U * V], [D, D], [UV, UV] 193: off = 2 * U * V 194: for e in (idx[:, 0], idx[:, -1], idx[0, :], idx[-1, :]): 195: m = len(e) 196: P = np.concatenate([outer[e], inner[e]]) 197: k = np.arange(m - 1) 198: t = np.concatenate([np.stack([k, k + 1, m + k + 1], 1), np.stack([k, m + k + 1, m + k], 1)]) 199: wn = np.cross(P[t[:, 1]] - P[t[:, 0]], P[t[:, 2]] - P[t[:, 0]]) 200: if (np.einsum("ij,ij->i", wn, P[t[:, 0]] - mid) < 0).mean() > 0.5: 201: t = t[:, ::-1] # edge walls face away from the plate's middle 202: pos.append(P) 203: tris.append(t + off) 204: dd = np.concatenate([D[e], D[e]]) 205: dd[:, 1] = 0.0 206: dat.append(dd) 207: uvs.append(np.concatenate([UV[e], UV[e]])) 208: off += 2 * m 209: return np.concatenate(pos), np.concatenate(tris), np.concatenate(dat), np.concatenate(uvs) 210: 211: 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 214: # colour), G = groove (a dark recessed line), B = gold inlay. The painted renderer reads it per pixel. 215: CHANNEL = {"paint": 0, "groove": 1, "gold": 2} 216: 217: 218: class Canvas: 219: """Draw shapes given in (s, t) in 0..1 (t up) at w x h pixels, supersampled for clean edges.""" 220: 221: def __init__(self, w, h, ss=3): 222: from PIL import Image, ImageDraw 223: self.w, self.h, self.ss = int(w), int(h), ss 224: self.layers = [Image.new("L", (self.w * ss, self.h * ss), 0) for _ in range(3)] 225: self.draw = [ImageDraw.Draw(im) for im in self.layers] 226: 227: def _xy(self, st): 228: st = np.atleast_2d(np.asarray(st, float)) 229: return [(float(s * self.w * self.ss), float((1 - t) * self.h * self.ss)) for s, t in st] 230: 231: def poly(self, st, ch): 232: self.draw[CHANNEL[ch]].polygon(self._xy(st), fill=255) 233: 234: def line(self, st, width_px, ch): 235: xy = self._xy(st) 236: w = max(1, int(round(width_px * self.ss))) 237: self.draw[CHANNEL[ch]].line(xy, fill=255, width=w, joint="curve") 238: r = w / 2 239: for x, y in (xy[0], xy[-1]): # round caps 240: self.draw[CHANNEL[ch]].ellipse((x - r, y - r, x + r, y + r), fill=255) 241: 242: def dot(self, st, rx_px, ry_px, ch): 243: (x, y), = self._xy(st) 244: 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), 245: fill=255) 246: 247: def array(self): 248: from PIL import Image 249: chans = [np.asarray(im.resize((self.w, self.h), Image.LANCZOS)) for im in self.layers] 250: return np.dstack(chans + [np.full((self.h, self.w), 255, np.uint8)]).astype(np.uint8)
agent
+5:51reasoning
Examining the Python files for relevant code related to the environment generation, particularly focusing on how objects like cages are created and placed within the world. Also, investigating specific lines within the plates module for possible cage generation logic. A quick shell command will be used to list the cage object within the specified directory to check for consistency with the code.
read_file{"EndLine":487,"Path":"~/work/lowmarch/tools/plates.py","StartLine":251}
input
{ "EndLine": 487, "Path": "~/work/lowmarch/tools/plates.py", "StartLine": 251 }result, 238 lines
Showing lines 251-487 of 487 251: 252: 253: def _seg_distance(P, A, B): 254: """Distance from points P (N,2) to segments A->B (M,2): (N,) minimum.""" 255: d = B - A 256: L2 = np.maximum((d * d).sum(1), 1e-18) 257: t = np.clip(((P[:, None] - A[None]) * d[None]).sum(-1) / L2[None], 0, 1) 258: Q = A[None] + t[..., None] * d[None] 259: return np.linalg.norm(P[:, None] - Q, axis=-1).min(1) 260: 261: 262: def outline_plate(name, role, chart, u0, u1, bottom, top, offset=0.012, crown=0.0, flare=None, thickness=0.003, 263: nu=48, nv=18, trim=0.0, roll=0.0026, roll_edges=("bottom", "top", "left", "right"), 264: roll_role=None, rivets=None, rivet_role="gold", seams=(), groove=(0.004, 0.0025), 265: panel_crown=0.0, studs=(), stud_r=0.004, stud_role=None, facets=None, decal=(), decal_px=1400, 266: pattern=None): 267: """A plate between bottom(u) and top(u) over u in [u0, u1] on `chart`. 268: offset: off the chart surface; crown: extra rise in the middle of the plate (0 at the outline); 269: flare(u, v, s, t) -> extra offset (s across, t up, both 0..1), e.g. a cuff belling out at one end; 270: thickness: metres, or thickness(u, v, s, t) per point (a beard filled down to the face); 271: trim: gold border width painted by the renderer (0 = none); roll: rolled-edge tube radius along 272: `roll_edges` (0 = none); rivets: (spacing, inset, radius) studs inside the outline (rivet_role). 273: seams: polylines [(u, v), ...] dividing the plate into panels: each panel domes by panel_crown, 274: the seams sink into grooves (width, depth) and are painted as dark grooves; 275: studs: (u, v) points (seam junctions) given domed studs of radius stud_r; 276: facets: u angles where the plate turns a corner: flat between them (a TorsoChart's horizontal rows); 277: decal: shapes in chart coordinates painted on the plate (see Canvas): 278: ("poly", [(u, v), ...], channel) / ("line", [(u, v), ...], width_m, channel) / ("dot", (u, v), r_m, channel) 279: channels: "paint" (the character's motif colour), "groove", "gold". 280: Returns (plate piece, [extra pieces: rolls, rivets, studs]); bind them all before export.""" 281: from outfit import piece, pipe, ball 282: U = np.linspace(u0, u1, nu) 283: S = np.linspace(0, 1, nu) 284: T = np.linspace(0, 1, nv) 285: vb = np.array([bottom(u) for u in U]) 286: vt = np.array([top(u) for u in U]) 287: uu = np.repeat(U[:, None], nv, 1) 288: vv = vb[:, None] + (vt - vb)[:, None] * T[None, :] 289: n = chart.normal(uu, vv) 290: lift = np.full(uu.shape, float(offset)) 291: if crown: 292: lift += crown * np.sqrt(np.clip(np.sin(np.pi * S)[:, None] * np.sin(np.pi * T)[None, :], 0, 1)) 293: if flare is not None: 294: lift += np.array([[flare(U[i], vv[i, j], S[i], T[j]) for j in range(nv)] for i in range(nu)]) 295: if seams: # panels dome between seams that sink into grooves 296: M = chart.metric(uu, vv).reshape(-1, 2) 297: segs = [(chart.metric(np.array([a[0], b[0]]), np.array([a[1], b[1]]))) for L in seams for a, b in zip(L[:-1], L[1:])] 298: A = np.array([sg[0] for sg in segs]) 299: Bv = np.array([sg[1] for sg in segs]) 300: dseam = _seg_distance(M, A, Bv).reshape(uu.shape) 301: gw, gd = groove 302: lift += panel_crown * (1 - np.exp(-dseam / 0.025)) - gd * np.clip(1 - dseam / gw, 0, 1) ** 2 303: G = chart.point(uu, vv) + n * lift[..., None] 304: if facets is not None: # flat faces between the facet angles, row by row 305: for j in range(nv): 306: cu = np.array(facets, float) 307: cv = np.interp(cu, U, vv[:, j]) 308: cl = np.interp(cu, U, lift[:, j]) 309: CP = chart.point(cu, cv) + chart.normal(cu, cv) * cl[:, None] 310: # circumscribe: push each corner out so the flat faces stay outside the curved surface 311: # (a chord across a 45-degree face would otherwise sink about 8% of the radius into it) 312: half = np.radians(np.maximum(np.diff(cu, prepend=cu[0]), np.diff(cu, append=cu[-1])) / 2) 313: o_ = np.stack([np.full(len(cu), chart.cx), cv, np.full(len(cu), chart.cz)], 1) 314: rad = CP - o_ 315: rad[:, 1] = 0 316: CP = CP + rad * (1 / np.cos(half) - 1)[:, None] 317: for i in range(nu): 318: k = int(np.clip(np.searchsorted(cu, U[i]) - 1, 0, len(cu) - 2)) 319: o, d = chart.ray(U[i], vv[i, j]) 320: o, d = np.asarray(o, float), np.asarray(d, float) 321: a, b = CP[k], CP[k + 1] 322: # intersect the level ray with the chord a-b (in the horizontal plane) 323: e = b - a 324: den = d[0] * e[2] - d[2] * e[0] 325: if abs(den) < 1e-9: 326: continue 327: t = ((a[0] - o[0]) * e[2] - (a[2] - o[2]) * e[0]) / den 328: G[i, j, 0], G[i, j, 2] = o[0] + d[0] * t, o[2] + d[2] * t 329: # distance to the outline, measured on the plate (dense samples of its four edges) 330: edge = np.concatenate([G[:, 0], G[:, -1], G[0, :], G[-1, :]]) 331: dense = np.array([edge[k] + (edge[k + 1] - edge[k]) * t for k in range(len(edge) - 1) 332: for t in (0.0, 0.25, 0.5, 0.75)]) 333: dist, _ = cKDTree(dense).query(G.reshape(-1, 3)) 334: data = np.stack([np.ones(nu * nv), dist, np.full(nu * nv, float(trim)), np.tile(T, nu)], 1).reshape(nu, nv, 4) 335: # decal coordinates: (u, v) mapped linearly onto the plate's bounding square 336: vmin, vmax = float(vv.min()), float(vv.max()) 337: 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) 338: uv = to_st(uu, vv) 339: if callable(thickness): # per point, e.g. a solid mass down to the surface 340: thickness = np.array([[thickness(U[i], vv[i, j], S[i], T[j]) for j in range(nv)] for i in range(nu)]) 341: pos, tri, dat, uvs = _thick(G, n, thickness, data, uv) 342: pc = piece(name, role, pos, tri) 343: pc["plate"] = dat 344: if pattern is not None: # a repeating texture (mail rings): (image, metres per repeat) 345: img, period = pattern 346: mid_u, mid_v = (u0 + u1) / 2, (vmin + vmax) / 2 347: wm = abs(np.radians(u1 - u0)) * float(chart.radius(mid_u, mid_v)) 348: hm = (vmax - vmin) * (1 if isinstance(chart, TorsoChart) else chart.L) 349: pc["decal"] = img 350: pc["uv"] = uvs * np.array([wm / period, hm / period * img.shape[1] / img.shape[0]]) 351: elif seams or decal: 352: mid_u, mid_v = (u0 + u1) / 2, (vmin + vmax) / 2 353: wm = abs(np.radians(u1 - u0)) * float(chart.radius(mid_u, mid_v)) # metres across and up 354: hm = (vmax - vmin) * (1 if isinstance(chart, TorsoChart) else chart.L) 355: px_m = decal_px 356: cv_ = Canvas(min(1024, max(64, wm * px_m)), min(1024, max(64, hm * px_m))) 357: sx, sy = cv_.w / max(wm, 1e-6), cv_.h / max(hm, 1e-6) # pixels per metre across and up 358: for L in seams: 359: cv_.line(to_st(*np.array(L, float).T), groove[0] * 0.7 * sx, "groove") 360: for sh in decal: 361: if sh[0] == "poly": 362: cv_.poly(to_st(*np.array(sh[1], float).T), sh[2]) 363: elif sh[0] == "line": 364: cv_.line(to_st(*np.array(sh[1], float).T), sh[2] * sx, sh[3]) 365: elif sh[0] == "dot": 366: cv_.dot(to_st(*sh[1]), sh[2] * sx, sh[2] * sy, sh[3]) 367: pc["decal"] = cv_.array() 368: pc["uv"] = uvs 369: extras = [] 370: lines = {"bottom": G[:, 0], "top": G[:, -1], "left": G[0, :], "right": G[-1, :]} 371: if roll: 372: for k, e in enumerate(roll_edges): 373: L = lines[e] + (n[:, 0] if e == "bottom" else n[:, -1] if e == "top" else n[0] if e == "left" else n[-1]) * roll * 0.4 374: if np.ptp(L, axis=0).max() < 1e-4: 375: continue 376: extras.append(pipe(f"{name}_roll{k}", roll_role or role, L, r=roll, seg=7)) 377: if rivets: 378: spacing, inset, rr = rivets 379: ring = np.concatenate([G[:, 0], G[-1, 1:], G[::-1, -1][1:], G[0, ::-1][1:]]) 380: ring_n = np.concatenate([n[:, 0], n[-1, 1:], n[::-1, -1][1:], n[0, ::-1][1:]]) 381: mid = G.reshape(-1, 3).mean(0) 382: seglen = np.linalg.norm(np.diff(ring, axis=0), axis=1) 383: at = np.concatenate([[0], np.cumsum(seglen)]) 384: for k, s_ in enumerate(np.arange(spacing / 2, at[-1], spacing)): 385: i = min(np.searchsorted(at, s_) - 1, len(ring) - 2) 386: p_ = ring[i] + (ring[i + 1] - ring[i]) * ((s_ - at[i]) / max(seglen[i], 1e-9)) 387: q = p_ + (mid - p_) / max(np.linalg.norm(mid - p_), 1e-9) * inset 388: extras.append(ball(f"{name}_rivet{k}", rivet_role, q + ring_n[i] * rr * 0.3, rr, seg=8, rows=5)) 389: for k, (su, sv) in enumerate(studs): # domed studs at seam junctions, on the plate's surface 390: i = int(np.argmin(np.abs(U - su))) 391: j = int(np.argmin(np.abs(vv[i] - sv))) 392: o, d = chart.ray(su, sv) 393: p_ = chart.point(su, sv) + chart.normal(su, sv) * (lift[i, j] + stud_r * 0.2) 394: extras.append(ball(f"{name}_stud{k}", stud_role or role, p_, stud_r, seg=10, rows=6, squash=(1, 1, 1))) 395: return pc, extras 396: 397: 398: def stiffen(pc, fit, bone="J_Bip_C_Hips", share=0.6): 399: """Move `share` of every vertex's weight onto one bone: a stiff garment (a starched overskirt, a 400: plate hanging from the belt) that the legs only partly drag.""" 401: n, nj = len(pc["J"]), len(fit.jnames) 402: dense = np.zeros((n, nj)) 403: np.add.at(dense, (np.repeat(np.arange(n), pc["J"].shape[1]), pc["J"].ravel()), pc["W"].ravel()) 404: dense *= 1 - share 405: dense[:, fit.jnames.index(bone)] += share 406: top = np.argsort(-dense, 1)[:, :4] 407: W = np.take_along_axis(dense, top, 1) 408: pc["J"], pc["W"] = top.astype(np.int64), W / np.maximum(W.sum(1, keepdims=True), 1e-12) 409: pc["jnames"] = fit.jnames 410: return pc 411: 412: 413: def _ear_clip(P): 414: """Triangles (index triples into P) filling a simple polygon P (n, 2), either winding.""" 415: P = np.asarray(P, float) 416: n = len(P) 417: area = 0.5 * np.sum(P[:, 0] * np.roll(P[:, 1], -1) - np.roll(P[:, 0], -1) * P[:, 1]) 418: idx = list(range(n)) if area > 0 else list(range(n))[::-1] 419: tri = [] 420: 421: def inside(p, a, b, c): 422: d1 = (p[0] - b[0]) * (a[1] - b[1]) - (a[0] - b[0]) * (p[1] - b[1]) 423: d2 = (p[0] - c[0]) * (b[1] - c[1]) - (b[0] - c[0]) * (p[1] - c[1]) 424: d3 = (p[0] - a[0]) * (c[1] - a[1]) - (c[0] - a[0]) * (p[1] - a[1]) 425: return not ((d1 < 0 or d2 < 0 or d3 < 0) and (d1 > 0 or d2 > 0 or d3 > 0)) 426: guard = 0 427: while len(idx) > 3 and guard < 10 * n: 428: guard += 1 429: for k in range(len(idx)): 430: i0, i1, i2 = idx[k - 1], idx[k], idx[(k + 1) % len(idx)] 431: a, b, c = P[i0], P[i1], P[i2] 432: if (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]) <= 1e-12: 433: continue # reflex corner 434: if any(inside(P[j], a, b, c) for j in idx if j not in (i0, i1, i2)): 435: continue 436: tri.append((i0, i1, i2)) 437: idx.pop(k) 438: break 439: if len(idx) == 3: 440: tri.append(tuple(idx)) 441: return np.array(tri, int) 442: 443: 444: def flat_piece(name, role, outline, origin, ex, ey, thickness=0.002, decal=(), px=4000): 445: """A flat convex shape (outline: (x, y) points in metres, in order) on the plane origin + x ex + y ey, 446: given thickness along ex x ey, with an optional decal in the same (x, y) coordinates.""" 447: from outfit import piece 448: O, ex, ey = (np.asarray(a, float) for a in (origin, ex, ey)) 449: nz = np.cross(ex, ey) 450: nz /= np.linalg.norm(nz) 451: P2 = np.asarray(outline, float) 452: c2 = P2.mean(0) 453: m = len(P2) 454: lo, hi = P2.min(0), P2.max(0) 455: span = np.maximum(hi - lo, 1e-6) 456: pts = np.vstack([c2, P2]) 457: top = O + pts[:, :1] * ex + pts[:, 1:] * ey + nz * thickness / 2 458: bot = top - nz * thickness 459: k = np.arange(m) 460: fan = 1 + _ear_clip(P2) # any simple outline, concave too (an axe's crescent) 461: nn = m + 1 462: wall = np.concatenate([np.stack([1 + k, 1 + (k + 1) % m, nn + 1 + (k + 1) % m], 1), 463: np.stack([1 + k, nn + 1 + (k + 1) % m, nn + 1 + k], 1)]) 464: tri = np.concatenate([fan, fan[:, ::-1] + nn, wall]) 465: pos = np.concatenate([top, bot]) 466: if np.cross(pos[tri[0, 1]] - pos[tri[0, 0]], pos[tri[0, 2]] - pos[tri[0, 0]]) @ nz < 0: 467: tri = np.concatenate([fan[:, ::-1], fan + nn, wall[:, ::-1]]) 468: pc = piece(name, role, pos, tri) 469: if decal: 470: cv = Canvas(min(1024, max(32, span[0] * px)), min(1024, max(32, span[1] * px))) 471: st = lambda xy: (np.atleast_2d(np.asarray(xy, float)) - lo) / span 472: for sh in decal: 473: if sh[0] == "poly": 474: cv.poly(st(sh[1]), sh[2]) 475: elif sh[0] == "line": 476: cv.line(st(sh[1]), sh[2] * cv.w / span[0], sh[3]) 477: pc["decal"] = cv.array() 478: pc["uv"] = np.concatenate([st(pts), st(pts)]) 479: return pc 480: 481: 482: def taper(pc, n_along, n_round, scale): 483: """Scale a pipe's cross-section along its length (scale: one factor per centreline point).""" 484: P = pc["pos"].reshape(n_along, n_round, 3) 485: C = P.mean(1, keepdims=True) 486: pc["pos"] = (C + (P - C) * np.asarray(scale, float)[:, None, None]).reshape(-1, 3) 487: return pcread_file{"EndLine":250,"Path":"~/work/lowmarch/tools/rig.py","StartLine":1}
input
{ "EndLine": 250, "Path": "~/work/lowmarch/tools/rig.py", "StartLine": 1 }result, 191 lines
Showing lines 1-190 of 190 1: """Small rig tools for authoring poses on a VRoid skeleton: rotate a bone in world space, two-bone 2: leg and arm IK, aiming a held prop (the sword) at a direction, and gripping a sword so its blade 3: runs through a given point. 4: 5: Poses here are the same dicts as tools/poses.py (bone name -> 3x3 or 4x4 adjustment in the bone's 6: own frame). Everything is solved in model space (VRoid: the character faces -z, y up). 7: """ 8: import numpy as np 9: 10: from poses import as4 11: 12: 13: def rot_between(a, b): 14: a = np.asarray(a, float) / np.linalg.norm(a) 15: b = np.asarray(b, float) / np.linalg.norm(b) 16: v, c = np.cross(a, b), float(np.dot(a, b)) 17: if c < -0.999999: 18: axis = np.cross(a, [1, 0, 0]) if abs(a[0]) < 0.9 else np.cross(a, [0, 1, 0]) 19: axis /= np.linalg.norm(axis) 20: return 2 * np.outer(axis, axis) - np.eye(3) 21: vx = np.array([[0, -v[2], v[1]], [v[2], 0, -v[0]], [-v[1], v[0], 0]]) 22: return np.eye(3) + vx + vx @ vx / (1 + c) 23: 24: 25: class Rig: 26: def __init__(self, vrm, shape=None, ortho=False): 27: """ortho: rotate bones through the parent's pure rotation (exact with scaled bones, see 28: rotate_world). Off by default so clips authored before it (Aldric's, frozen) stay identical.""" 29: import vroid_portrait as vp 30: self.v = vrm 31: self.shape = dict(vp.NEUTRAL, **(shape or {})) 32: self.names = vrm.nodes_by_name() 33: self._bp = vp.bone_pose 34: self.ortho = ortho 35: self._par = vrm.parents() 36: 37: def world(self, pose): 38: return self.v.node_world(self._bp(self.v, self.shape, pose)) 39: 40: def pos(self, pose, bone): 41: return self.world(pose)[self.names[bone]][:3, 3] 42: 43: def rotate_world(self, pose, bone, R): 44: """Pre-multiply the bone's world rotation by R (about its joint) by editing its local pose. 45: With proportion scales on the skeleton the bone's world matrix is not a rotation; the 46: default (legacy) form then leaks shear into the pose and an iterated solve can diverge. 47: ortho mode conjugates by the pure rotation of the frame the adjustment lives in.""" 48: W = self.world(pose) 49: i = self.names[bone] 50: cur = W[i][:3, :3] 51: adj_old = as4(pose.get(bone, np.eye(3))) 52: if self.ortho: 53: par = self._par.get(i) 54: base = (W[par] if par is not None else np.eye(4)) @ self.v.local_matrix(i, None) 55: u, _, vt = np.linalg.svd(base[:3, :3]) 56: Q = u @ vt # nearest rotation 57: out = dict(pose) 58: a = adj_old.copy() 59: a[:3, :3] = Q.T @ R @ Q @ adj_old[:3, :3] 60: out[bone] = a 61: return out 62: base = cur @ np.linalg.inv(adj_old[:3, :3]) # world rotation without this bone's adjustment 63: new_rot = np.linalg.inv(base) @ (R @ cur) 64: out = dict(pose) 65: a = adj_old.copy() 66: a[:3, :3] = new_rot 67: out[bone] = a 68: return out 69: 70: def leg_ik(self, pose, side, target, pole=(0, 0, -1)): 71: """Bend the leg so the ankle lands on `target`, knee toward `pole` (forward).""" 72: up, lo, ft = f"J_Bip_{side}_UpperLeg", f"J_Bip_{side}_LowerLeg", f"J_Bip_{side}_Foot" 73: H, K, A = self.pos(pose, up), self.pos(pose, lo), self.pos(pose, ft) 74: l1, l2 = np.linalg.norm(K - H), np.linalg.norm(A - K) 75: T = np.asarray(target, float) 76: d = np.clip(np.linalg.norm(T - H), 1e-4, l1 + l2 - 1e-4) 77: u = (T - H) / np.linalg.norm(T - H) 78: w = np.asarray(pole, float) - u * np.dot(pole, u) 79: w /= np.linalg.norm(w) 80: ca = np.clip((l1 * l1 + d * d - l2 * l2) / (2 * l1 * d), -1, 1) 81: K2 = H + l1 * (ca * u + np.sqrt(1 - ca * ca) * w) 82: pose = self.rotate_world(pose, up, rot_between(K - H, K2 - H)) 83: K, A = self.pos(pose, lo), self.pos(pose, ft) 84: return self.rotate_world(pose, lo, rot_between(A - K, H + u * d - K)) 85: 86: def plant_feet(self, pose, reference): 87: """Keep both ankles where they are in `reference` (feet stay on the ground while the hips move).""" 88: for side in "LR": 89: pose = self.leg_ik(pose, side, self.pos(reference, f"J_Bip_{side}_Foot")) 90: return pose 91: 92: def aim(self, pose, bone, local_dir, target_dir): 93: """Turn `bone` so its local direction (e.g. the sword blade, hand -z) points along target_dir.""" 94: W = self.world(pose)[self.names[bone]][:3, :3] 95: cur = W @ np.asarray(local_dir, float) 96: return self.rotate_world(pose, bone, rot_between(cur, target_dir)) 97: 98: def arm_ik(self, pose, side, target, pole): 99: """Bend the arm so the wrist lands on `target`, elbow toward `pole`.""" 100: up, lo, hd = f"J_Bip_{side}_UpperArm", f"J_Bip_{side}_LowerArm", f"J_Bip_{side}_Hand" 101: S, E, W = self.pos(pose, up), self.pos(pose, lo), self.pos(pose, hd) 102: l1, l2 = np.linalg.norm(E - S), np.linalg.norm(W - E) 103: T = np.asarray(target, float) 104: d = np.clip(np.linalg.norm(T - S), abs(l1 - l2) + 1e-3, l1 + l2 - 1e-4) 105: u = (T - S) / np.linalg.norm(T - S) 106: w = np.asarray(pole, float) - u * np.dot(pole, u) 107: w /= np.linalg.norm(w) 108: ca = np.clip((l1 * l1 + d * d - l2 * l2) / (2 * l1 * d), -1, 1) 109: E2 = S + l1 * (ca * u + np.sqrt(1 - ca * ca) * w) 110: pose = self.rotate_world(pose, up, rot_between(E - S, E2 - S)) 111: E, W = self.pos(pose, lo), self.pos(pose, hd) 112: return self.rotate_world(pose, lo, rot_between(W - E, S + u * d - E)) 113: 114: def held(self, pose, bone, ref_pose, point): 115: """Where a point attached to `bone` (given in the reference pose, model space) is in `pose`.""" 116: i = self.names[bone] 117: M = self.world(pose)[i] @ np.linalg.inv(self.world(ref_pose)[i]) 118: return M[:3, :3] @ np.asarray(point, float) + M[:3, 3] 119: 120: def grip(self, pose, side, ref_pose, fist_ref, fist_target, blade_dir, pole, local_blade=(0, 0, -1), iters=14): 121: """Put the fist (a point on the hand, from the reference pose) on `fist_target` with the hand's 122: `local_blade` axis along `blade_dir`. An analytic arm IK gets close (elbow toward `pole`); 123: then cyclic corrections that measure the real fist after every step (aim the hand, swing 124: the forearm, swing the upper arm) finish it, which converges even when proportion scales 125: shear the arm and the analytic solve alone undershoots.""" 126: hd, lo, up = f"J_Bip_{side}_Hand", f"J_Bip_{side}_LowerArm", f"J_Bip_{side}_UpperArm" 127: T = np.asarray(fist_target, float) 128: D = np.asarray(blade_dir, float) / np.linalg.norm(blade_dir) 129: wrist = T - (self.held(pose, hd, ref_pose, fist_ref) - self.pos(pose, hd)) 130: pose = self.arm_ik(pose, side, wrist, pole) 131: for _ in range(iters): 132: for _ in range(2): 133: M = self.world(pose)[self.names[hd]][:3, :3] 134: pose = self.rotate_world(pose, hd, rot_between(M @ np.asarray(local_blade, float), D)) 135: for bone in (lo, up): 136: j = self.pos(pose, bone) 137: f = self.held(pose, hd, ref_pose, fist_ref) 138: if np.linalg.norm(f - j) > 1e-4 and np.linalg.norm(T - j) > 1e-4: 139: pose = self.rotate_world(pose, bone, rot_between(f - j, T - j)) 140: miss = np.linalg.norm(T - self.held(pose, hd, ref_pose, fist_ref)) 141: M = self.world(pose)[self.names[hd]][:3, :3] 142: bd = M @ np.asarray(local_blade, float) 143: if miss < 2e-3 and np.dot(bd / np.linalg.norm(bd), D) > 0.9995: 144: break 145: for _ in range(2): # the blade direction is what reads; finish on it 146: M = self.world(pose)[self.names[hd]][:3, :3] 147: pose = self.rotate_world(pose, hd, rot_between(M @ np.asarray(local_blade, float), D)) 148: return pose 149: 150: 151: def grip_points(vrm, shape, ref_pose, fingers=("Index", "Middle", "Ring", "Little")): 152: """Where each fist closes: the centre of the hole the curled fingers make (poses.fist), in model 153: space in `ref_pose` (the hand doesn't move when the fingers curl, so a weapon built there and bound 154: to the hand sits in the fist whenever the fingers are curled). Each finger's joints and fingertip 155: (the last segment again, bent by its own joint) are fitted with a circle in the plane across the 156: hole (the hand's local z runs through it, palm to fingertips in x and y); the hole's centre is the 157: mean of the fingers' circle centres. A fixed offset from the wrist, tuned on one hand, missed on 158: larger or differently made hands (the shaft ran over the knuckles, the fingers closed under it). 159: Returns {side: dict(point, axis, radius)}: radius is the finger-centreline circle's (the shaft's 160: radius plus a finger's half-thickness fits).""" 161: import vroid_portrait as vp 162: import poses as P 163: sh = dict(vp.NEUTRAL, **(shape or {})) 164: names = vrm.nodes_by_name() 165: out = {} 166: for side in "LR": 167: sx = 1.0 if side == "R" else -1.0 168: W = vrm.node_world(vp.bone_pose(vrm, sh, P.merge(ref_pose, P.fist(side)))) 169: H = W[names[f"J_Bip_{side}_Hand"]] 170: R = H[:3, :3] / np.linalg.norm(H[:3, :3], axis=0) 171: o, e1, e2, ax = H[:3, 3], R[:, 0] * sx, R[:, 1], R[:, 2] 172: cs, axial, rads = [], [], [] 173: for f in fingers: 174: ks = [names.get(f"J_Bip_{side}_{f}{k}") for k in (1, 2, 3)] 175: if any(k is None for k in ks): 176: continue 177: js = [W[k][:3, 3] for k in ks] 178: M3 = W[ks[2]][:3, :3] / np.linalg.norm(W[ks[2]][:3, :3], axis=0) 179: pts = js + [js[2] + M3 @ np.array([sx, 0.0, 0.0]) * 0.85 * np.linalg.norm(js[2] - js[1])] 180: Q = np.array([[(p - o) @ e1, (p - o) @ e2] for p in pts]) 181: A = np.c_[2 * Q, np.ones(len(Q))] # algebraic circle fit 182: b = (Q ** 2).sum(1) 183: cx, cy, c0 = np.linalg.lstsq(A, b, rcond=None)[0] 184: cs.append((cx, cy)) 185: rads.append(float(np.sqrt(c0 + cx * cx + cy * cy))) 186: axial.append(float((js[0] - o) @ ax)) 187: c = np.mean(cs, 0) 188: out[side] = dict(point=o + c[0] * e1 + c[1] * e2 + np.mean(axial) * ax, axis=ax, radius=float(np.mean(rads)), 189: centres=[o + x * e1 + y * e2 + a * ax for (x, y), a in zip(cs, axial)]) 190: return outread_file{"EndLine":250,"Path":"~/work/lowmarch/tools/gear.py","StartLine":1}
input
{ "EndLine": 250, "Path": "~/work/lowmarch/tools/gear.py", "StartLine": 1 }result, 251 lines
Showing lines 1-250 of 984 1: """Gear for generic units (the enemy soldiers): helmets, hoods and coifs, quilted coats, mail, 2: riveted vests, shields and weapons, built on the plate kit (plates.py) and the head chart (hair.py). 3: Each function returns pieces bound to the skeleton; a class costume (mobs.py) combines them. 4: 5: Builds and faces for generic units are presets of the body's shape controls (BUILDS, FACES), so the 6: same costume dresses a slim young soldier or a huge brute. 7: """ 8: import math 9: 10: import numpy as np 11: 12: import outfit as O 13: from fitting import Surface 14: from plates import TorsoChart, LimbChart, ConeChart, outline_plate, stiffen, flat_piece, taper, Canvas 15: from hair import head_chart 16: 17: # ---- builds and faces: presets of vroid_portrait's shape controls ------------------------------------ 18: BUILDS = { 19: "slim": dict(chest=0.95, torso=0.94, arms=0.94, legs=0.94, neck=0.95), 20: "average": dict(), 21: "athletic": dict(chest=1.06, arms=1.07, legs=1.04, neck=1.08, shoulder_w=0.010), 22: "stocky": dict(chest=1.18, torso=1.24, arms=1.18, legs=1.16, neck=1.28, shoulder_w=0.018, leg_len=0.95, height=0.97), 23: "huge": dict(chest=1.34, torso=1.32, arms=1.40, legs=1.32, neck=1.55, hands=1.22, shoulder_w=0.042, height=1.12, 24: head=0.92), 25: } 26: FACES = { # 3D-strength values (the sculpt moves anatomical points by millimetres per unit) 27: "bare": dict(), # no sculpt here: the head is sculpted in its own file (tools/heads.py, the armory) 28: "young": dict(face_len=-0.04, jaw=-0.4, chin_len=-0.5, eye=1.04), 29: "plain": dict(face_len=0.05, jaw=0.6, brow_ridge=0.6, eye=0.95, rest={"Fcl_BRW_Angry": 0.3}), 30: "veteran": dict(face_len=0.14, jaw=1.4, chin_w=1.2, chin_len=1.0, cheek=-1.0, brow_ridge=1.6, nose=1.4, eye=0.88, 31: age_lines=0.8, iris=0.82, blush=0.0, mouth=1.1, 32: rest={"Fcl_EYE_Angry": 0.6, "Fcl_EYE_Close": 0.12, "Fcl_EYE_Joy": 0.22, "Fcl_BRW_Angry": 0.65, 33: "Fcl_MTH_Down": 0.35}), 34: "brute": dict(face_len=0.10, jaw=2.6, chin_w=2.2, chin_len=0.8, cheek=1.2, brow_ridge=2.4, nose=0.8, nose_w=2.2, 35: eye=0.86, mouth=1.25, rest={"Fcl_EYE_Close": 0.28, "Fcl_BRW_Angry": 0.75}), 36: "gaunt": dict(face_len=0.18, jaw=0.3, chin_len=1.2, cheek=-1.6, nose=1.8, eye=0.88, 37: rest={"Fcl_BRW_Angry": 0.5, "Fcl_EYE_Close": 0.25}), 38: "round": dict(face_len=-0.03, jaw=1.0, chin_w=1.2, cheek=1.6, eye=0.93, mouth=1.08), 39: "soft": dict(face_len=0.02, jaw=-0.2, cheek=0.4, eye=1.0), 40: "stern": dict(face_len=0.07, jaw=0.6, chin_len=0.5, brow_ridge=0.8, eye=0.92, rest={"Fcl_BRW_Angry": 0.55}), 41: } 42: 43: 44: def shape(build="average", face="plain", **extra): 45: """A shape dict for the cast: a build and a face combined (later keys win).""" 46: out = dict(BUILDS[build]) 47: f = dict(FACES[face]) 48: extra = dict(extra) 49: rest = {**out.pop("rest", {}), **f.pop("rest", {}), **extra.pop("rest", {})} 50: out.update(f) 51: out.update(extra) 52: if rest: 53: out["rest"] = rest 54: return out 55: 56: 57: def _bind(fit, pcs, bone): 58: for pc in pcs: 59: fit.bind(pc, rigid=bone) 60: return pcs 61: 62: 63: def _group(pcs, g): 64: for pc in pcs: 65: pc["group"] = g 66: return pcs 67: 68: 69: # ---- heads: helmets, coifs and hoods on the chart over the skull ---------------------------------------- 70: def helmet(fit, kind="kettle", role="steel", lift=0.030, name="helmet", rivets=True, trim_role=None): 71: """A helmet on the skull chart. 72: kettle: a rounded bowl to just above the brows and ears, a wide brim sloping down. 73: nasal: a taller bowl with a band at the rim and a nose guard down to the nose's tip. 74: sallet: a bowl coming low over the forehead, sweeping into a long flared tail at the back. 75: close: a bowl to the jaw all round, a face plate with an eye slit and breaths (a bucket helm).""" 76: ch = head_chart(fit) 77: out = [] 78: if kind == "kettle": 79: rim = lambda u: float(np.interp(abs(u), [0, 60, 100, 180], [74, 80, 86, 92])) 80: elif kind == "nasal": 81: rim = lambda u: float(np.interp(abs(u), [0, 60, 100, 180], [72, 82, 92, 100])) 82: elif kind == "sallet": 83: rim = lambda u: float(np.interp(abs(u), [0, 50, 90, 140, 180], [78, 86, 104, 124, 130])) 84: else: # close 85: rim = lambda u: float(np.interp(abs(u), [0, 60, 100, 180], [136, 134, 126, 122])) 86: fl = None 87: if kind == "sallet": # the tail flares out over the nape 88: fl = lambda u, v, s, t: 0.030 * max(0.0, (abs(u) - 110) / 70) * (1 - t) ** 1.6 89: seams = [] 90: if kind in ("nasal", "kettle"): # a raised comb from front to back 91: seams = [[(0, 4), (0, rim(0) - 4)], [(180, 4), (180, rim(180) - 4)]] 92: deco = [] 93: if kind == "close": # the eye slit and the breaths 94: deco.append(("line", [(-44, 97), (44, 97)], 0.008, "groove")) 95: for u in (-24, -16, -8, 8, 16, 24): 96: deco.append(("line", [(u, 112), (u, 122)], 0.003, "groove")) 97: bowl, ex = outline_plate(f"{name}", role, ch, -180, 180, rim, lambda u: 0.0, offset=lift, 98: flare=fl, thickness=0.004, nu=72, nv=22, roll=0.003, roll_edges=("bottom",), 99: roll_role=trim_role or role, seams=seams, groove=(0.006, -0.004), panel_crown=0.0, 100: decal=deco, decal_px=1200) 101: out += [bowl] + ex 102: if kind == "kettle": # the brim: out and down from the rim, all round 103: U = np.linspace(-180, 180, 73) 104: rimP = np.array([ch.point(u, rim(u), off=lift) for u in U]) 105: d = rimP - ch.c 106: d[:, 1] = 0 107: d /= np.linalg.norm(d, axis=1, keepdims=True) 108: G = np.stack([rimP + d * 0.058 * t - np.array([0, 0.022 * t * t, 0]) for t in np.linspace(0, 1, 5)], 1) 109: pos, tri, outer = O.thick_grid(G, 0.004, outward_from=ch.c - np.array([0, 0.4, 0])) 110: brim = O.piece(f"{name}_brim", role, pos, tri) 111: out += [brim, O.pipe(f"{name}_brim_roll", trim_role or role, outer[:, -1], r=0.003, seg=6)] 112: if kind == "nasal": # the nose guard and a riveted band 113: guard, gx = outline_plate(f"{name}_nasal", role, ch, -5, 5, lambda u: 104.0, lambda u: rim(0) - 8, 114: offset=lift + 0.006, thickness=0.004, nu=8, nv=12, roll=0) 115: out += [guard] 116: band, bx = outline_plate(f"{name}_band", role, ch, -180, 180, lambda u: rim(u), lambda u: rim(u) - 9, 117: offset=lift + 0.003, thickness=0.003, nu=72, nv=4, roll=0, 118: rivets=(0.035, 0.009, 0.0035) if rivets else None, rivet_role=role) 119: out += [band] + bx 120: _bind(fit, out, "J_Bip_C_Head") 121: return _group(out, "helmet") 122: 123: 124: def coif(fit, role="mail", name="coif", lift=0.017, face=True): 125: """A hood worn under a helmet (padded or mail): over the skull and down to the jaw, the face left 126: open (face=False closes it to a slit-less cap), and a short cape over the shoulders.""" 127: ch = head_chart(fit) 128: if face: 129: # down over the nape at the back: the study's soldiers show no hair there (a cut hair edge read 130: # as a sawtooth under the brim) 131: bottom = lambda u: float(np.interp(abs(u), [0, 34, 52, 80, 120, 180], [58, 64, 132, 142, 150, 156])) 132: else: 133: bottom = lambda u: 146.0 134: pc, _ = outline_plate(name, role, ch, -180, 180, bottom, lambda u: 0.0, offset=lift, thickness=0.004, 135: nu=72, nv=24, roll=0) 136: _bind(fit, [pc], "J_Bip_C_Head") 137: return _group([pc], "helmet") 138: 139: 140: def hood(fit, role="cloth", name="hood", lift=0.022, peak=0.03): 141: """A cloth hood: roomy over the head, open around the face, a peak at the back of the crown.""" 142: ch = head_chart(fit) 143: bottom = lambda u: float(np.interp(abs(u), [0, 30, 50, 80, 180], [52, 58, 128, 142, 148])) 144: fl = lambda u, v, s, t: peak * math.exp(-((abs(u) - 180) / 40) ** 2) * math.exp(-((v - 30) / 25) ** 2) 145: pc, _ = outline_plate(name, role, ch, -180, 180, bottom, lambda u: 0.0, offset=lift, flare=fl, thickness=0.004, 146: nu=72, nv=24, roll=0) 147: _bind(fit, [pc], "J_Bip_C_Head") 148: return _group([pc], "hood") 149: 150: 151: def mail_pattern(w, h, ring_px=7, hem=None): 152: """A decal of mail rings (dark ring edges in the groove channel), rows offset like real mail.""" 153: cv = Canvas(w, h, ss=2) 154: r = ring_px / 2 155: for j, yy in enumerate(np.arange(r, h, ring_px * 0.62)): 156: for xx in np.arange(r + (j % 2) * r, w, ring_px): 157: s, t = xx / w, 1 - yy / h 158: th = np.linspace(0, 2 * np.pi, 10) 159: cv.line(np.stack([s + np.cos(th) * r / w, t + np.sin(th) * r / h], 1), 0.9, "groove") 160: return cv.array() 161: 162: 163: # ---- the torso: quilted coats, mail, riveted vests ------------------------------------------------------- 164: def quilted(fit, under, name="gambeson", role="padding", y_neck=None, y_hem=None, flare=0.08, split=10.0, 165: stitch=16.0, sleeves=True, sleeve_end=0.92): 166: """A padded coat quilted in vertical channels (each channel puffs between stitched seams): a body 167: from the neck to `y_hem` (below the hips it becomes a skirt over a cone, split at the front), and 168: sleeves quilted along the arm. `under`: the Surface it sits on (the shirt).""" 169: B = fit.bone 170: nk, hips = B["J_Bip_C_Neck"], B["J_Bip_C_Hips"] 171: y_neck = nk[1] - 0.03 if y_neck is None else y_neck 172: y_hem = hips[1] - 0.22 if y_hem is None else y_hem 173: cz = float(hips[2]) 174: y_waist = hips[1] + 0.06 175: tc = TorsoChart(under, y_waist - 0.04, y_neck + 0.03, cz=cz, du=3.0, dv=0.008) 176: out = [] 177: us = np.arange(-180 + stitch, 180, stitch) 178: seams = [[(u, y_waist), (u, y_neck)] for u in us] 179: 180: def neck_top(u): # lower at the front: a round neckline 181: return y_neck - 0.035 * max(0.0, 1 - abs(u) / 70) ** 1.5 182: body, _ = outline_plate(name, role, tc, -178, 178, lambda u: y_waist, neck_top, offset=0.008, thickness=0.006, 183: nu=120, nv=26, roll=0.004, roll_edges=("top",), seams=seams, groove=(0.004, 0.004), 184: panel_crown=0.006, decal_px=700) 185: fit.bind(body, allow=("Spine", "Chest", "UpperChest", "Bust", "Hips", "Neck", "Shoulder"), fallback="J_Bip_C_Chest") 186: out.append(body) 187: # the skirt: a cone from the waist down, split at the front 188: r0 = lambda u: float(tc.radius(u, y_waist)) + 0.010 189: r0m = float(np.mean([r0(u) for u in range(-180, 180, 15)])) 190: cone = ConeChart(lambda u, v: np.vectorize(r0)(u) + flare * np.clip((y_waist - v) / (y_waist - y_hem), 0, 1.2) ** 1.2, 191: cz=cz) 192: sk_seams = [[(u, y_hem), (u, y_waist)] for u in us if abs(u) > split + 4] 193: skirt, _ = outline_plate(f"{name}_skirt", role, cone, split, 360 - split, lambda u: y_hem, lambda u: y_waist + 0.012, 194: offset=0.002, thickness=0.006, nu=110, nv=18, roll=0.004, roll_edges=("bottom", "left", "right"), 195: seams=[[((u % 360), a), ((u % 360), b)] for (u, a), (_, b) in sk_seams], 196: groove=(0.004, 0.004), panel_crown=0.006, decal_px=600) 197: fit.bind(skirt, allow=("Hips", "UpperLeg"), fallback="J_Bip_C_Hips") 198: stiffen(skirt, fit, share=0.55) 199: out.append(skirt) 200: if sleeves: 201: for side in ("L", "R"): 202: for seg, (a, b, v0, v1) in enumerate(((f"J_Bip_{side}_UpperArm", f"J_Bip_{side}_LowerArm", -0.05, 1.02), 203: (f"J_Bip_{side}_LowerArm", f"J_Bip_{side}_Hand", -0.02, sleeve_end))): 204: arm = O.limb_surface(fit, (a.replace("J_Bip_", ""), b.replace("J_Bip_", "")), side) 205: lc = LimbChart(arm, B[a], B[b], front=(0, 0, -1)) 206: sl_seams = [[(u, v0), (u, v1)] for u in range(-150, 180, 30)] 207: sl, _ = outline_plate(f"{name}_sleeve_{side}{seg}", role, lc, -180, 180, lambda u, v1=v1: v1, 208: lambda u, v0=v0: v0, offset=0.010, thickness=0.005, nu=48, nv=14, roll=0, 209: seams=sl_seams, groove=(0.005, 0.003), panel_crown=0.004, decal_px=700) 210: fit.bind(sl, allow=(a.replace("J_Bip_", ""), b.replace("J_Bip_", "")), fallback=a) 211: out.append(sl) 212: return _group(out, "padding") 213: 214: 215: def mail_shirt(fit, under, name="hauberk", role="mail", y_top=None, y_hem=None, sleeve=0.55, flare=0.05): 216: """A mail shirt over the coat: body to `y_hem`, short sleeves, rings painted as a decal, the hem 217: scalloped into a ragged edge.""" 218: B = fit.bone 219: nk, hips = B["J_Bip_C_Neck"], B["J_Bip_C_Hips"] 220: y_top = nk[1] - 0.05 if y_top is None else y_top 221: y_hem = hips[1] - 0.12 if y_hem is None else y_hem 222: cz = float(hips[2]) 223: y_waist = hips[1] + 0.06 224: tc = TorsoChart(under, y_waist - 0.04, y_top + 0.03, cz=cz, du=3.0, dv=0.008) 225: rings = (mail_pattern(256, 128), 0.12) # one tile of rings covers 12 cm 226: body, _ = outline_plate(name, role, tc, -178, 178, lambda u: y_waist, lambda u: y_top - 0.02 * max(0, 1 - abs(u) / 60), 227: offset=0.006, thickness=0.004, nu=96, nv=20, roll=0, pattern=rings) 228: out = [body] 229: r0 = lambda u: float(tc.radius(u, y_waist)) + 0.010 230: cone = ConeChart(lambda u, v: np.vectorize(r0)(u) + flare * np.clip((y_waist - v) / (y_waist - y_hem), 0, 1.2), cz=cz) 231: hem = lambda u: y_hem + 0.006 * abs(math.sin(math.radians(u) * 18)) # small scallops: a ragged mail edge 232: skirt, _ = outline_plate(f"{name}_skirt", role, cone, -178, 178, hem, lambda u: y_waist + 0.01, offset=0.004, 233: thickness=0.004, nu=120, nv=10, roll=0, pattern=rings) 234: out.append(skirt) 235: fit.bind(body, allow=("Spine", "Chest", "UpperChest", "Bust", "Hips", "Neck", "Shoulder"), fallback="J_Bip_C_Chest") 236: fit.bind(skirt, allow=("Hips", "UpperLeg"), fallback="J_Bip_C_Hips") 237: stiffen(skirt, fit, share=0.5) 238: for side in ("L", "R"): 239: a, b = f"J_Bip_{side}_UpperArm", f"J_Bip_{side}_LowerArm" 240: arm = O.limb_surface(fit, (f"{side}_UpperArm",), side) 241: lc = LimbChart(arm, B[a], B[b], front=(0, 0, -1)) 242: sl, _ = outline_plate(f"{name}_sleeve_{side}", role, lc, -180, 180, lambda u: sleeve, lambda u: -0.08, 243: offset=0.018, thickness=0.004, nu=40, nv=8, roll=0, pattern=rings) 244: fit.bind(sl, allow=(f"{side}_UpperArm", f"{side}_Shoulder"), fallback=a) 245: out.append(sl) 246: return _group(out, "mail") 247: 248: 249: def riveted_vest(fit, under, name="brigandine", role="leather", rivet_role="steel", y_top=None, y_bottom=None): 250: """A coat of plates: cloth-covered plates held by rows of rivets, front and back, open at the sides."""read_file{"EndLine":200,"Path":"~/work/lowmarch/tools/terrain.py","StartLine":1}
input
{ "EndLine": 200, "Path": "~/work/lowmarch/tools/terrain.py", "StartLine": 1 }result, 78 lines
Showing lines 1-77 of 77 1: """Battle-scene terrain built in code: the ground a unit stands on in the side-view battle. 2: 3: Pieces use the same primitive dicts as outfit.py, with `world=True` so the renderer keeps them 4: fixed while the character turns. Model coordinates: metres, y up, ground at y = 0. 5: """ 6: import math 7: 8: import numpy as np 9: 10: from outfit import grid_mesh, piece, ball 11: 12: 13: def _noise(x, z, seed): 14: rng = np.random.default_rng(seed) 15: out = np.zeros_like(x) 16: for k in range(5): 17: fx, fz, ph = rng.uniform(1.5, 6.0), rng.uniform(1.5, 6.0), rng.uniform(0, 2 * math.pi, 2) 18: out += np.sin(x * fx + ph[0]) * np.cos(z * fz + ph[1]) / (k + 1) 19: return out 20: 21: 22: def plains(width=4.2, depth=1.8, thick=0.25, seed=3, tufts=26, stones=5): 23: """A raised plains platform: grassy top with gentle bumps, an earth bank on the sides, grass 24: tufts and a few stones.""" 25: out = [] 26: nx, nz = 60, 26 27: xs = np.linspace(-width / 2, width / 2, nx) 28: zs = np.linspace(-depth / 2, depth / 2, nz) 29: X, Z = np.meshgrid(xs, zs, indexing="ij") 30: Y = 0.012 * _noise(X, Z, seed) - 0.004 31: # keep it flat where the unit stands 32: Y *= np.clip(np.hypot(X / 0.5, Z / 0.4) - 0.6, 0, 1) 33: top = np.stack([X, Y, Z], -1) 34: pos, tri = grid_mesh(top) 35: out.append(piece("ground", "grass", pos, tri, outward_from=[0, -5, 0])) 36: # earth bank on the four sides 37: def bank(edge, name): 38: lo = edge.copy() 39: lo[:, 1] = -thick 40: lo[:, 0] *= 1.02 41: lo[:, 2] *= 1.02 42: P = np.stack([edge, lo], 1) 43: p_, t_ = grid_mesh(P) 44: return piece(name, "dirt", p_, t_, outward_from=[0, -thick / 2, 0]) 45: out.append(bank(top[:, 0], "bank_back")) 46: out.append(bank(top[:, -1], "bank_front")) 47: out.append(bank(top[0, :], "bank_left")) 48: out.append(bank(top[-1, :], "bank_right")) 49: rng = np.random.default_rng(seed + 1) 50: for i in range(tufts): 51: x, z = rng.uniform(-width / 2 * 0.95, width / 2 * 0.95), rng.uniform(-depth / 2 * 0.9, depth / 2 * 0.9) 52: if abs(x) < 0.45 and abs(z) < 0.35: 53: continue 54: h = rng.uniform(0.04, 0.09) 55: blades = [] 56: for b in range(5): 57: a = rng.uniform(0, 2 * math.pi) 58: lean = np.array([math.cos(a), 0, math.sin(a)]) * rng.uniform(0.01, 0.03) 59: base = np.array([x, 0.0, z]) + lean * 0.4 60: tip = base + np.array([0, h, 0]) + lean 61: w = np.array([-math.sin(a), 0, math.cos(a)]) * 0.007 62: blades.append(np.array([base - w, base + w, tip])) 63: pos = np.concatenate(blades) 64: tri = np.arange(len(pos)).reshape(-1, 3) 65: out.append(piece(f"tuft{i}", "grass", pos, tri, outward_from=[x, -1, z])) 66: for i in range(stones): 67: x, z = rng.uniform(-width / 2 * 0.9, width / 2 * 0.9), rng.uniform(-depth / 2 * 0.8, depth / 2 * 0.8) 68: if abs(x) < 0.5 and abs(z) < 0.4: 69: continue 70: r = rng.uniform(0.04, 0.09) 71: out.append(ball(f"stone{i}", "stone", [x, r * 0.35, z], r, squash=(1.0, 0.55, 0.8))) 72: for p in out: 73: p["world"] = True 74: return out 75: 76: 77: TERRAIN = {"plains": plains}