A 3D model pipeline, pushed by Gemini 4 Argon
agent (cont.)
+13:42read_file{"EndLine":850,"Path":"~/work/lowmarch/review/vroid-02/index.html","StartLine":600}
input
{ "EndLine": 850, "Path": "~/work/lowmarch/review/vroid-02/index.html", "StartLine": 600 }result, 252 lines
Showing lines 600-850 of 1737 600: float hair = 0.0; 601: for (int s = 1; s <= 4; s++) { vec4 a = texture2D(tInfo, uv + vec2(0.0, float(s)) * uSil * px); int ra = rid(a); if (a.a > 0.5 && (ra == 3 || ra == 11)) hair = 1.0; } 602: col = mix(col, col * vec3(0.84, 0.74, 0.76), 0.75 * hair); 603: } 604: } 605: gl_FragColor = vec4(col, 1.0); 606: }`; 607: 608: const compCam = new THREE.Camera(); 609: function compPass(fs, uniforms) { 610: const mat = new THREE.ShaderMaterial({ uniforms, vertexShader: `void main() { gl_Position = vec4(position.xy, 0.0, 1.0); }`, 611: fragmentShader: fs, transparent: true }); 612: const s = new THREE.Scene(); s.add(new THREE.Mesh(new THREE.PlaneGeometry(2, 2), mat)); 613: return { mat, scene: s }; 614: } 615: 616: // ---- the renderer --------------------------------------------------------------------------------------------------- 617: const stageEl = $("stage"); 618: const R = new THREE.WebGLRenderer({ antialias: false, alpha: true, preserveDrawingBuffer: !!SHEET }); 619: R.setClearColor(0x000000, 0); 620: R.outputColorSpace = THREE.LinearSRGBColorSpace; 621: stageEl.appendChild(R.domElement); 622: const paint = compPass(PAINT_COMP, { tColor: { value: null }, tInfo: { value: null }, tDepth: { value: null }, uRes: { value: new THREE.Vector2() }, 623: uNear: { value: 0.1 }, uFar: { value: 40 }, uGap: { value: 0.012 }, uSil: { value: 2 }, uInner: { value: 1 }, uPpm: { value: 1000 } }); 624: const ctl = new OrbitControls(camera, R.domElement); 625: ctl.enableDamping = true; ctl.zoomToCursor = true; ctl.screenSpacePanning = true; 626: ctl.minZoom = 0.3; ctl.maxZoom = 12; 627: let freeLook = false; 628: ctl.addEventListener("start", () => { freeLook = true; }); 629: R.domElement.addEventListener("dblclick", focusAt); 630: const targets = { rt: null, rtInfo: null, key: "" }; 631: function targetsFor(w, h) { 632: const key = `${w}x${h}`; 633: if (targets.key === key) return; 634: [targets.rt, targets.rtInfo].forEach(t => t && t.dispose()); 635: const o = { minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter }; 636: targets.rt = new THREE.WebGLRenderTarget(w, h, o); 637: targets.rtInfo = new THREE.WebGLRenderTarget(w, h, { ...o, depthTexture: new THREE.DepthTexture(w, h) }); 638: targets.key = key; 639: } 640: 641: // ---- cloth ------------------------------------------------------------------------------------------------------- 642: // The skinned cape/tails stay hidden and provide the pinned row (they follow the animated body); 643: // a plain display mesh in world space shows the simulated cloth. Colliders ride the bones. 644: const _v = new THREE.Vector3(), _a = new THREE.Vector3(), _ab = new THREE.Vector3(), _cp = new THREE.Vector3(); 645: const _A = new THREE.Vector3(), _B = new THREE.Vector3(); 646: class Cloth { 647: constructor(skinned, U, V, trims, capsules, bone, closed = false, hemOnly = false) { 648: this.skinned = skinned; this.U = U; this.V = V; this.trims = trims; this.closed = closed; this.hemOnly = hemOnly; 649: this.n = skinned.geometry.attributes.position.count; 650: this.caps = capsules.map(c => ({ a: bone(c.bones[0]), b: bone(c.bones[1]), r: c.r + 0.006 })).filter(c => c.a && c.b); 651: this.x = new Float32Array(this.n * 3); this.prev = new Float32Array(this.n * 3); 652: const idx = (i, j) => i * V + j, links = [], bends = [], edge = new Float32Array(this.n); 653: for (let i = 0; i < U; i++) for (let j = 0; j < V; j++) { 654: // a closed cloth (a skirt) wraps around: the last column links back to the first 655: if (i + 1 < U || closed) links.push([idx(i, j), idx((i + 1) % U, j)]); 656: if (j + 1 < V) links.push([idx(i, j), idx(i, j + 1)]); 657: if (i + 2 < U || closed) bends.push([idx(i, j), idx((i + 2) % U, j)]); 658: if (j + 2 < V) bends.push([idx(i, j), idx(i, j + 2)]); 659: edge[idx(i, j)] = ((j === 0 && !hemOnly) || j === V - 1 || (!closed && trims.length > 1 && (i === 0 || i === U - 1))) ? 1 : 0; 660: } 661: const src = skinned.geometry.attributes.position, r = src.array; 662: const len = ([a, b]) => Math.hypot(r[3*a] - r[3*b], r[3*a+1] - r[3*b+1], r[3*a+2] - r[3*b+2]); 663: this.links = links.map(l => [l[0], l[1], len(l)]); 664: this.bends = bends.map(l => [l[0], l[1], len(l)]); 665: this.pinned = new Uint8Array(this.n); for (let i = 0; i < U; i++) this.pinned[idx(i, 0)] = 1; 666: const g = new THREE.BufferGeometry(); 667: g.setAttribute("position", new THREE.BufferAttribute(new Float32Array(this.n * 3), 3).setUsage(THREE.DynamicDrawUsage)); 668: g.setAttribute("normal", new THREE.BufferAttribute(new Float32Array(this.n * 3), 3)); 669: g.setAttribute("uv", skinned.geometry.attributes.uv || new THREE.BufferAttribute(new Float32Array(this.n * 2), 2)); 670: g.setAttribute("edge", new THREE.BufferAttribute(edge, 1)); 671: g.setIndex(skinned.geometry.index); 672: this.display = new THREE.Mesh(g, skinned.material); 673: this.display.userData = { ...skinned.userData, cloth: true }; 674: this.display.frustumCulled = false; 675: this.lines = new THREE.LineSegments(new THREE.BufferGeometry(), null); 676: this.lines.frustumCulled = false; 677: } 678: rest(k, out) { this.skinned.getVertexPosition(k, out); return out.applyMatrix4(this.skinned.matrixWorld); } 679: reset(lift) { 680: for (let k = 0; k < this.n; k++) { 681: this.rest(k, _v); 682: if (lift && !this.pinned[k]) { const j = k % this.V; _v.y += 0.0035 * j * j; } 683: this.x[3*k] = this.prev[3*k] = _v.x; this.x[3*k+1] = this.prev[3*k+1] = _v.y; this.x[3*k+2] = this.prev[3*k+2] = _v.z; 684: } 685: } 686: step(dt, t) { 687: const x = this.x, pv = this.prev, pin = this.pinned; 688: const g = -9.8 * dt * dt, damp = 0.985; 689: const gust = state.wind ? (0.9 + 0.6 * Math.sin(t * 1.7) + 0.3 * Math.sin(t * 4.3)) * dt * dt * 4.0 : 0; 690: for (let k = 0; k < this.n; k++) { 691: if (pin[k]) continue; 692: for (let c = 0; c < 3; c++) { 693: const i = 3*k + c, v = (x[i] - pv[i]) * damp; 694: pv[i] = x[i]; x[i] += v + (c === 1 ? g : 0) + (c === 0 ? gust : 0) + (c === 2 ? gust * 0.4 : 0); 695: } 696: } 697: const pins = []; 698: for (let k = 0; k < this.n; k++) if (pin[k]) pins.push([k, this.rest(k, new THREE.Vector3())]); 699: const caps = this.caps.map(c => ({ a: c.a.getWorldPosition(new THREE.Vector3()), b: c.b.getWorldPosition(new THREE.Vector3()), r: c.r })); 700: // a closed skirt's axis: the middle of its pinned waist row. Inside a leg collider, its cloth is 701: // always pushed away from this axis; pushed to the nearest side, a leg stepping wide drags the 702: // fabric in between the legs 703: const axis = new THREE.Vector3(); 704: if (this.closed) { for (const [, w] of pins) axis.add(w); axis.multiplyScalar(1 / Math.max(1, pins.length)); } 705: const solve = (L, stiff) => { 706: for (const [ia, ib, R] of L) { 707: const a = 3 * ia, b = 3 * ib; 708: const dx = x[b] - x[a], dy = x[b+1] - x[a+1], dz = x[b+2] - x[a+2]; 709: const d = Math.hypot(dx, dy, dz) || 1e-9, f = (d - R) / d * stiff; 710: const wa = pin[ia] ? 0 : 1, wb = pin[ib] ? 0 : 1, s = wa + wb; 711: if (!s) continue; 712: const ka = f * wa / s, kb = f * wb / s; 713: x[a] += dx * ka; x[a+1] += dy * ka; x[a+2] += dz * ka; 714: x[b] -= dx * kb; x[b+1] -= dy * kb; x[b+2] -= dz * kb; 715: } 716: }; 717: const touch = this.touch || (this.touch = new Uint8Array(this.n)); touch.fill(0); 718: for (let it = 0; it < 10; it++) { 719: for (const [k, w] of pins) { x[3*k] = w.x; x[3*k+1] = w.y; x[3*k+2] = w.z; } 720: solve(this.links, 1.0); 721: solve(this.bends, 0.2); 722: for (let k = 0; k < this.n; k++) { 723: if (pin[k]) continue; 724: _v.set(x[3*k], x[3*k+1], x[3*k+2]); 725: let jumped = false; 726: for (const c of caps) { 727: _ab.subVectors(c.b, c.a); 728: const tt = THREE.MathUtils.clamp(_a.subVectors(_v, c.a).dot(_ab) / _ab.lengthSq(), 0, 1); 729: _cp.copy(c.a).addScaledVector(_ab, tt); 730: const d = _v.distanceTo(_cp); 731: if (d < c.r && d > 1e-6) { 732: if (this.closed) { 733: _A.set(_v.x - axis.x, 0, _v.z - axis.z); // outward, horizontally 734: _B.set(_v.x - _cp.x, 0, _v.z - _cp.z); 735: if (_A.lengthSq() > 1e-8 && _B.dot(_A) < 0) { // the nearest way out is inward: go round 736: _A.normalize(); _v.set(_cp.x + _A.x * c.r, _v.y, _cp.z + _A.z * c.r); jumped = true; continue; 737: } 738: } 739: _v.sub(_cp).multiplyScalar(c.r / d).add(_cp); 740: } 741: } 742: // inelastic contact: most of a push-out doesn't turn into velocity, so a limb moving into the 743: // cloth carries it instead of flinging it 744: const px = _v.x - x[3*k], py = _v.y - x[3*k+1], pz = _v.z - x[3*k+2]; 745: if (jumped) { pv[3*k] = _v.x; pv[3*k+1] = _v.y; pv[3*k+2] = _v.z; } // a jump round a leg carries no speed 746: else if (px * px + py * py + pz * pz > 1e-12) { 747: pv[3*k] += px * 0.8; pv[3*k+1] += py * 0.8; pv[3*k+2] += pz * 0.8; 748: touch[k] = 1; 749: } 750: x[3*k] = _v.x; x[3*k+1] = _v.y; x[3*k+2] = _v.z; 751: } 752: } 753: // friction, once per step: cloth touching a limb keeps 40% of its speed, so a stepping knee 754: // carries a skirt forward instead of the fabric sliding off round the leg 755: for (let k = 0; k < this.n; k++) if (touch[k]) for (let c = 0; c < 3; c++) { const i = 3*k + c; pv[i] = x[i] - (x[i] - pv[i]) * 0.4; } 756: } 757: write() { 758: const p = this.display.geometry.attributes.position; 759: p.array.set(this.x); p.needsUpdate = true; 760: this.display.geometry.computeVertexNormals(); this.display.geometry.computeBoundingSphere(); 761: const pts = [], idx = (i, j) => i * this.V + j, X = this.x; 762: const seg = (a, b) => pts.push(X[3*a], X[3*a+1], X[3*a+2], X[3*b], X[3*b+1], X[3*b+2]); 763: const U = this.U, last = this.closed ? U : U - 1; 764: for (let i = 0; i < last; i++) { if (!this.hemOnly) seg(idx(i, 0), idx((i + 1) % U, 0)); seg(idx(i, this.V - 1), idx((i + 1) % U, this.V - 1)); } 765: if (this.trims.length > 1 && !this.closed) for (let j = 0; j + 1 < this.V; j++) { seg(idx(0, j), idx(0, j + 1)); seg(idx(this.U - 1, j), idx(this.U - 1, j + 1)); } 766: const g = this.lines.geometry; 767: g.setAttribute("position", new THREE.Float32BufferAttribute(pts, 3)); g.computeBoundingSphere(); 768: } 769: } 770: 771: // A long skirt is posed, not simulated: each column hangs from its waist point at its rest shape; 772: // anything that would sit inside a leg is pushed straight out along its column, and everything below 773: // a contact hangs from it, so the skirt tents over a stepping knee. Column lengths are kept (the hem 774: // rises as it tents) and the pushes are smoothed round the skirt and over time. A free cloth tube 775: // against moving leg colliders slid off the knee, jumped round the legs or drifted, whatever the 776: // friction; this can't end up between the legs. 777: class SkirtRig extends Cloth { 778: constructor(skinned, U, V, trims, capsules, bone, hemOnly) { 779: super(skinned, U, V, trims, capsules, bone, true, hemOnly); 780: const src = skinned.geometry.attributes.position, idx = (i, j) => i * V + j; 781: const P = k => new THREE.Vector3(src.getX(k), src.getY(k), src.getZ(k)); 782: const C = new THREE.Vector3(); for (let i = 0; i < U; i++) C.add(P(idx(i, 0))); C.multiplyScalar(1 / U); 783: this.r0 = new Float32Array(U * V); this.h0 = new Float32Array(U * V); this.t0 = new Float32Array(U * V); 784: this.push = new Float32Array(U * V); 785: for (let i = 0; i < U; i++) { 786: const W = P(idx(i, 0)), d = new THREE.Vector3(W.x - C.x, 0, W.z - C.z).normalize(), t = new THREE.Vector3(-d.z, 0, d.x); 787: for (let j = 0; j < V; j++) { 788: const o = P(idx(i, j)).sub(W); 789: this.r0[idx(i, j)] = o.dot(d); this.h0[idx(i, j)] = o.y; this.t0[idx(i, j)] = o.dot(t); 790: } 791: } 792: } 793: pose(dt, instant) { 794: const U = this.U, V = this.V, X = this.x, idx = (i, j) => i * V + j; 795: const W = [], C = new THREE.Vector3(); 796: for (let i = 0; i < U; i++) { W.push(this.rest(idx(i, 0), new THREE.Vector3())); C.add(W[i]); } 797: C.multiplyScalar(1 / U); 798: const caps = this.caps.map(c => ({ a: c.a.getWorldPosition(new THREE.Vector3()), b: c.b.getWorldPosition(new THREE.Vector3()), r: c.r + 0.012 })); 799: const target = new Float32Array(U * V), p = new THREE.Vector3(), cp = new THREE.Vector3(), ab = new THREE.Vector3(), ap = new THREE.Vector3(); 800: for (let i = 0; i < U; i++) { 801: const d = new THREE.Vector3(W[i].x - C.x, 0, W[i].z - C.z).normalize(), t = new THREE.Vector3(-d.z, 0, d.x); 802: let carry = 0; 803: for (let j = 1; j < V; j++) { 804: const k = idx(i, j); 805: let need = carry; // below a contact the cloth hangs from it 806: for (let it = 0; it < 6; it++) { 807: p.copy(W[i]).addScaledVector(d, this.r0[k] + need).addScaledVector(t, this.t0[k]); p.y += this.h0[k]; 808: let worst = 0; 809: for (const c of caps) { 810: ab.subVectors(c.b, c.a); const tt = THREE.MathUtils.clamp(ap.subVectors(p, c.a).dot(ab) / ab.lengthSq(), 0, 1); 811: cp.copy(c.a).addScaledVector(ab, tt); 812: const dx = p.x - cp.x, dz = p.z - cp.z, dist = Math.hypot(dx, p.y - cp.y, dz); 813: if (dist < c.r) worst = Math.max(worst, c.r - dist); 814: } 815: if (worst < 1e-4) break; 816: need += worst * 1.15; 817: } 818: target[k] = carry = need; 819: } 820: } 821: for (let pass = 0; pass < 2; pass++) // smooth round the skirt 822: for (let j = 1; j < V; j++) { 823: const row = []; 824: for (let i = 0; i < U; i++) row.push((target[idx((i + U - 1) % U, j)] + 2 * target[idx(i, j)] + target[idx((i + 1) % U, j)]) / 4); 825: for (let i = 0; i < U; i++) target[idx(i, j)] = Math.max(row[i], target[idx(i, j)] * 0.6); 826: } 827: const ease = instant ? 1 : Math.min(1, dt * 9); 828: for (let k = 0; k < U * V; k++) this.push[k] += (target[k] - this.push[k]) * ease; 829: for (let i = 0; i < U; i++) { 830: const d = new THREE.Vector3(W[i].x - C.x, 0, W[i].z - C.z).normalize(), t = new THREE.Vector3(-d.z, 0, d.x); 831: let prev = W[i].clone(), pr = 0, ph = 0, pt = 0; 832: X[3 * idx(i, 0)] = prev.x; X[3 * idx(i, 0) + 1] = prev.y; X[3 * idx(i, 0) + 2] = prev.z; 833: for (let j = 1; j < V; j++) { 834: const k = idx(i, j), r = this.r0[k] + this.push[k], h0 = this.h0[k], tt = this.t0[k]; 835: // keep the rest length of this segment: what the push adds outward comes off the drop 836: const L = Math.hypot(this.r0[k] - this.r0[k - 1], h0 - this.h0[k - 1], tt - this.t0[k - 1]); 837: const dr = r - pr, dtan = tt - pt, dh = -Math.sqrt(Math.max(L * L - dr * dr - dtan * dtan, 1e-6)); 838: const h = ph + (j === 1 ? Math.min(dh, h0) : dh); 839: const q = W[i].clone().addScaledVector(d, r).addScaledVector(t, tt); q.y += h; 840: X[3 * k] = q.x; X[3 * k + 1] = q.y; X[3 * k + 2] = q.z; 841: pr = r; ph = h; pt = tt; 842: } 843: } 844: this.prev.set(X); 845: } 846: reset() { this.push.fill(0); this.pose(0, true); } 847: step(dt) { this.pose(dt, false); } 848: } 849: 850: // ---- materials per mesh ----------------------------------------------------------------------------------------------read_file{"EndLine":1737,"Path":"~/work/lowmarch/review/vroid-02/index.html","StartLine":1400}
input
{ "EndLine": 1737, "Path": "~/work/lowmarch/review/vroid-02/index.html", "StartLine": 1400 }result, 339 lines
Showing lines 1400-1737 of 1737 1400: targetsFor(buf.x, buf.y); 1401: cloths.forEach(c => c.lines3d.visible = false); 1402: meshes.forEach(o => { o.material = o.userData.mats.painted; o.material.uniforms.uPass.value = 0; }); 1403: const G = GRADE[state.view === "bust" ? "bust" : "battle"]; // stage grade, shared by the characters and the stage 1404: for (const o of meshes) { const mu = o.material.uniforms; mu.uAmbient.value.set(...G.ambient); mu.uKeyCol.value.set(...G.key); mu.uRimCol.value.set(...G.rim); } 1405: // the info pass (roles, ids, depth) first: the colour pass reads it for cast shadows 1406: meshes.forEach(o => { // unbound while it is drawn: reading it now would be a feedback loop 1407: const mu = o.material.uniforms; mu.uPass.value = 1; mu.uCastOn.value = 0; mu.tCastInfo.value = null; mu.tCastDepth.value = null; 1408: }); 1409: R.setRenderTarget(targets.rtInfo); R.clear(); R.render(scene, camera); 1410: const ppmBuf = buf.y / (camera.top - camera.bottom) * camera.zoom; 1411: for (const o of meshes) { 1412: const mu = o.material.uniforms; 1413: mu.uPass.value = 0; mu.uCastOn.value = 1; mu.tCastInfo.value = targets.rtInfo.texture; mu.tCastDepth.value = targets.rtInfo.depthTexture; 1414: mu.uCastRes.value.set(buf.x, buf.y); mu.uCastNear.value = camera.near; mu.uCastFar.value = camera.far; mu.uCastPpm.value = ppmBuf; 1415: } 1416: R.setRenderTarget(targets.rt); R.clear(); R.render(scene, camera); 1417: const u = paint.mat.uniforms; 1418: u.tColor.value = targets.rt.texture; u.tInfo.value = targets.rtInfo.texture; u.tDepth.value = targets.rtInfo.depthTexture; 1419: u.uRes.value.set(buf.x, buf.y); u.uNear.value = camera.near; u.uFar.value = camera.far; 1420: // line weight follows the figure's size on screen (study: ~0.4% of its height) 1421: const ppm = buf.y / (camera.top - camera.bottom) * camera.zoom, dpr = R.getPixelRatio(); 1422: u.uSil.value = THREE.MathUtils.clamp(1.75 * ppm * 0.0042, dpr, 2.6 * dpr); 1423: u.uInner.value = Math.max(dpr * 0.75, u.uSil.value * 0.55); 1424: u.uPpm.value = ppm; 1425: R.setRenderTarget(null); R.clear(); R.render(paint.scene, compCam); 1426: } 1427: 1428: // ---- check sheets ---------------------------------------------------------------------------------------------------- 1429: // ?sheet=<name> poses one character through every check view; ?sheet=duel shows the bind. Each tile 1430: // is posed, its cloth settled at that angle, rendered by the same painted renderer as the page, and 1431: // drawn into one image, which lands in #sheetOut as a PNG data URL (a headless browser reads it). 1432: const ARMS_YAWS = [0, 45, 90, 135, 180, 270]; 1433: const CHAR_ROWS = [ 1434: // arms down, as character design sheets are drawn: the row to compare against references 1435: { label: "Reference pose", tiles: [0, 30, 90, 180, 270, 330].map(y => ({ clip: "ref", t: 0, yaw: y, pitch: 0, hide: ["sword", "weapon"], label: `${y}°` })) }, 1436: { label: "Head", tiles: [0, 30, 90, 150, 180, 270].map(y => ({ clip: "ref", t: 0, yaw: y, pitch: 4, focus: "J_Bip_C_Head", dy: 0.03, 1437: size: 0.42, hide: ["sword", "weapon"], label: `${y}°` })) }, 1438: { label: "Arms out", tiles: ARMS_YAWS.map(y => ({ clip: "apose", t: 0, yaw: y, label: `${y}°` })) }, 1439: { label: "Idle", tiles: ARMS_YAWS.map(y => ({ clip: "idle", t: 0, yaw: y, label: `${y}°` })) }, 1440: // the idle loop through time from one side (the camera holds still: the body's rise and sink shows) 1441: { label: "Idle loop", tiles: [0, 0.4, 0.8, 1.0, 1.3, 1.6].map(t => ({ clip: "idle", t, yaw: 300, label: `${t.toFixed(1)} s` })) }, 1442: { label: "Attack", tiles: [[0.32, "wind-up"], [0.56, "slash"], [0.68, "follow-through"]].flatMap(([t, n]) => 1443: [60, 300].map(y => ({ clip: "attack", t, yaw: y, label: `${n}, ${y}°` }))) }, 1444: { label: "Close-ups", tiles: [ 1445: { clip: "apose", t: 0, yaw: 0, focus: "J_Bip_C_Hips", dy: 0.10, size: 0.62, label: "waist, front" }, 1446: { clip: "apose", t: 0, yaw: 90, focus: "J_Bip_C_Hips", dy: 0.10, size: 0.62, label: "waist, side" }, 1447: { clip: "apose", t: 0, yaw: 180, focus: "J_Bip_C_Hips", dy: 0.10, size: 0.62, label: "waist, back" }, 1448: { clip: "idle", t: 0, yaw: 60, focus: "J_Bip_R_Hand", dy: 0, size: 0.45, label: "right wrist" }, 1449: { clip: "idle", t: 0, yaw: 300, focus: "J_Bip_L_Hand", dy: 0, size: 0.45, label: "left wrist" }, 1450: { clip: "idle", t: 0, yaw: 30, focus: "J_Bip_L_Foot", dy: 0.02, size: 0.5, label: "feet" }] }, 1451: // where a head meets its neck (grafted heads): from below the jaw, the side and behind, and mid-attack 1452: // when the head turns on the neck 1453: { label: "Neck and collar", tiles: [ 1454: ...[[0, -10, "front, from below"], [60, -10, "three-quarter"], [120, -4, "behind the ear"], [180, 0, "nape"]].map(([y, p, n]) => 1455: ({ clip: "ref", t: 0, yaw: y, pitch: p, focus: "J_Bip_C_Neck", dy: 0.03, size: 0.30, hide: ["sword", "weapon"], label: n })), 1456: { clip: "attack", t: 0.32, yaw: 60, focus: "J_Bip_C_Neck", dy: 0.03, size: 0.34, label: "wind-up, 60°" }, 1457: { clip: "attack", t: 0.56, yaw: 300, focus: "J_Bip_C_Neck", dy: 0.03, size: 0.34, label: "slash, 300°" }] }, 1458: ]; 1459: // the armory (bodies, heads and hair to assemble from): the T-pose round, the head close, the joins 1460: const ARMORY_ROWS = [ 1461: { label: "T-pose", tiles: [0, 45, 90, 135, 180, 270].map(y => ({ clip: "ref", t: 0, yaw: y, pitch: 0, label: `${y}°` })) }, 1462: { label: "Head", tiles: [0, 30, 90, 150, 180, 270].map(y => ({ clip: "ref", t: 0, yaw: y, pitch: 4, focus: "J_Bip_C_Head", dy: 0.03, 1463: size: 0.42, label: `${y}°` })) }, 1464: { label: "Joins", tiles: [ 1465: ...[[0, -10, "neck, front"], [120, -4, "neck, behind the ear"]].map(([y, p, n]) => 1466: ({ clip: "ref", t: 0, yaw: y, pitch: p, focus: "J_Bip_C_Neck", dy: 0.03, size: 0.30, label: n })), 1467: { clip: "ref", t: 0, yaw: 0, focus: "J_Bip_L_UpperArm", dy: 0, size: 0.40, label: "shoulder, front" }, 1468: { clip: "ref", t: 0, yaw: 180, focus: "J_Bip_C_Hips", dy: -0.12, size: 0.55, label: "hips and thighs, back" }, 1469: { clip: "ref", t: 0, yaw: 0, focus: "J_Bip_C_Hips", dy: -0.12, size: 0.55, label: "hips and thighs, front" }, 1470: { clip: "ref", t: 0, yaw: 30, focus: "J_Bip_L_Foot", dy: 0.02, size: 0.5, label: "feet" }] }, 1471: ]; 1472: const DUEL_YAWS = [0, 40, 90, 320]; 1473: const LINEUP_ROWS = [ 1474: { label: "Lineup", tiles: [0, 30].map(y => ({ clip: "ref", t: 0, yaw: y, pitch: 0, hide: ["sword", "weapon"], label: `${y}°, reference pose` })) }, 1475: { label: "Lineup", tiles: [90, 180].map(y => ({ clip: "ref", t: 0, yaw: y, pitch: 0, hide: ["sword", "weapon"], label: `${y}°, reference pose` })) }, 1476: { label: "Lineup", tiles: [20, 300].map(y => ({ clip: "idle", t: 0, yaw: y, label: `${y}°, idle` })) }, 1477: // faces with helmets and hoods off: the face structures underneath, one close-up each 1478: { label: "Faces (helmets and hoods off)", tw: 300, th: 340, tiles: LINEUP.order.map((n, i) => ({ clip: "ref", t: 0, yaw: 20, 1479: pitch: 0, hide: ["sword", "weapon", "helmet", "hood", "shield"], focusChar: i, size: 0.40, 1480: label: (charDef(n) || {}).label || n })) }, 1481: { label: "Faces (helmets on)", tw: 300, th: 340, tiles: LINEUP.order.map((n, i) => ({ clip: "ref", t: 0, yaw: 20, 1482: pitch: 0, hide: ["sword", "weapon", "shield"], focusChar: i, size: 0.40, label: (charDef(n) || {}).label || n })) }, 1483: ]; 1484: const DUEL_ROWS = [0, 0.8, 1.6].map(t => ({ label: `Clash ${t.toFixed(1)} s`, tiles: DUEL_YAWS.map(y => ({ clip: "clash", t, yaw: y, label: `${y}°` })) })) 1485: .concat([{ label: "The bind, close", tiles: [0, 90, 180, 300].map(y => ({ clip: "clash", t: 0, yaw: y, focusBind: true, size: 0.95, label: `${y}°` })) }]); 1486: 1487: function holdPose(clip, t) { 1488: for (const c of active()) { 1489: if (c.skeleton) c.skeleton.pose(); 1490: c.mixer.stopAllAction(); c.blend = null; c.clip = clip; 1491: if (clip === "ref") continue; // the reference (bind) pose itself 1492: const a = c.actions[clip] || c.actions.idle; 1493: a.reset(); a.setEffectiveWeight(1); a.play(); a.time = t; c.mixer.update(0); 1494: } 1495: scene.updateMatrixWorld(true); 1496: } 1497: function settleCloth() { 1498: const cs = active(); 1499: cs.forEach(c => c.cloths.forEach(cl => cl.reset(false))); 1500: for (let s = 0; s < 150; s++) cs.forEach(c => c.cloths.forEach(cl => cl.step(1 / 120, s / 120))); 1501: cs.forEach(c => c.cloths.forEach(cl => cl.write())); 1502: } 1503: function frameAt(centre, h, tw, th, pitch) { 1504: const w = h * tw / th, a = THREE.MathUtils.degToRad(pitch); 1505: camera.left = -w / 2; camera.right = w / 2; camera.top = h / 2; camera.bottom = -h / 2; camera.zoom = 1; 1506: camera.updateProjectionMatrix(); 1507: camera.position.copy(centre).add(new THREE.Vector3(0, Math.sin(a), Math.cos(a)).multiplyScalar(15)); 1508: camera.up.set(0, 1, 0); camera.lookAt(centre); ctl.target.copy(centre); 1509: } 1510: async function runSheet(kind) { 1511: document.body.classList.add("sheet"); 1512: const lineup = kind === "lineup", duel = kind === "duel" || lineup; 1513: if (!duel) state.who = kind; 1514: if (params.get("mode") === "3d") state.mode = "3d"; // ?mode=3d: the plain 3D renderer (tells a geometry fault from a shading one) 1515: await setView(lineup ? "lineup" : duel ? "duel" : "battle"); 1516: if ((!duel || lineup) && ground) { scene.remove(ground.root); } 1517: applyMaterials(); 1518: // ?rows=0,3 keeps some rows, ?scale=3 renders them larger (for side-by-sides against a reference) 1519: const keep = (params.get("rows") || "").split(",").filter(Boolean).map(Number); 1520: const scale = Math.max(1, Math.min(4, +(params.get("scale") || 1))); 1521: const rows = (lineup ? LINEUP_ROWS : duel ? DUEL_ROWS : PAGE && PAGE.armory ? ARMORY_ROWS : [...CHAR_ROWS]) 1522: .filter((r, i) => !keep.length || keep.includes(i)); 1523: if (!duel && !keep.length) { 1524: try { 1525: const chk = (await (await fetch("checks.json")).json())[kind]; 1526: const seen = new Set(), tiles = []; 1527: for (const it of chk.through) { 1528: const [limb] = it.hits[0], key = `${it.clip}@${it.t}`; 1529: if (seen.has(key) || tiles.length >= 6) continue; 1530: seen.add(key); 1531: for (const y of [60, 300]) tiles.push({ clip: it.clip, t: it.t, yaw: y, focus: `J_Bip_${limb.slice(0, 2)}LowerArm`, dy: 0, size: 0.75, 1532: label: `${it.clip} ${it.t} s, ${y}°` }); 1533: } 1534: // garments through plate: a close-up framed on the plate (two angles), reference pose first 1535: for (const it of (chk.layers ? chk.layers.items : [])) { 1536: const [, plate] = it.hits[0], key = `${it.clip}@${it.t}:${plate}`; 1537: if (seen.has(key) || tiles.length >= 10) continue; 1538: seen.add(key); 1539: const clip = it.clip === "reference pose" ? "ref" : it.clip; 1540: for (const y of [30, 330]) tiles.push({ clip, t: it.t, yaw: y, focusMesh: `OUTFIT_${plate}`, size: 0.5, 1541: label: `${plate}, ${it.clip === "reference pose" ? "as built" : it.clip + " " + it.t + " s"}, ${y}°` }); 1542: } 1543: if (tiles.length) rows.push({ label: "Flagged by the checks", tiles: tiles.slice(0, 6) }); 1544: if (tiles.length > 6) rows.push({ label: "Flagged by the checks (more)", tiles: tiles.slice(6, 12) }); 1545: } catch (e) { /* no checks: no row */ } 1546: } 1547: // the lineup's tiles shrink to stay under WebGL's largest drawing size (8192 here): past it they came out black 1548: const lw0 = Math.round(FIGURE.lineup.w / 2.5 * 480), lk = Math.min(1, 8000 / (lw0 * scale)), lw = Math.round(lw0 * lk); 1549: const tw = (lineup ? lw : duel ? 520 : 300) * scale, th = (duel ? 420 : lineup ? Math.round(520 * lk) : 520) * scale, 1550: lab = 22, rowHead = 30, gap = 6; 1551: const rw = r => (r.tw || tw / scale) * scale, rh = r => (r.th || th / scale) * scale; 1552: const cv = document.createElement("canvas"); 1553: cv.width = Math.max(...rows.map(r => r.tiles.length * (rw(r) + gap))) + gap; 1554: cv.height = rows.reduce((a, r) => a + rowHead + rh(r) + lab + gap, 0) + gap; 1555: const ctx = cv.getContext("2d"); 1556: ctx.fillStyle = "#100e18"; ctx.fillRect(0, 0, cv.width, cv.height); 1557: R.setPixelRatio(1); 1558: let y0 = gap; 1559: for (const row of rows) { 1560: const tw_ = rw(row), th_ = rh(row); 1561: R.setSize(tw_, th_, false); 1562: ctx.fillStyle = "#e9e6f2"; ctx.font = "bold 18px sans-serif"; 1563: ctx.fillText(`${lineup ? "Enemies" : duel ? "Duel" : charDef(kind).label} · ${row.label}`, gap + 2, y0 + 21); 1564: y0 += rowHead; 1565: row.tiles.forEach((tile, k) => { 1566: setYaw(tile.yaw); 1567: state.hidden = new Set(tile.hide || []); applyMaterials(); 1568: holdPose(tile.clip, tile.t); 1569: settleCloth(); 1570: let centre, h = tile.size || (lineup ? 2.5 : duel ? 2.3 : 2.05), pitch = tile.pitch ?? 8; 1571: if (tile.focusBind) { 1572: const hs = active().map(c => c.root.getObjectByName("J_Bip_R_Hand").getWorldPosition(new THREE.Vector3())); 1573: centre = hs[0].clone().add(hs[1]).multiplyScalar(0.5).add(new THREE.Vector3(0, 0.12, 0)); pitch = 4; 1574: } else if (tile.focusChar != null) { // one unit's head in the lineup 1575: centre = active()[tile.focusChar].root.getObjectByName("J_Bip_C_Head").getWorldPosition(new THREE.Vector3()); 1576: centre.y += 0.05; pitch = tile.pitch ?? 0; 1577: } else if (tile.focusMesh) { 1578: const m = active()[0].meshes.find(o => o.userData.material === tile.focusMesh); 1579: centre = m ? new THREE.Box3().setFromObject(m, true).getCenter(new THREE.Vector3()) : new THREE.Vector3(0, 1, 0); pitch = 4; 1580: } else if (tile.focus) { 1581: centre = active()[0].root.getObjectByName(tile.focus).getWorldPosition(new THREE.Vector3()); centre.y += tile.dy; pitch = tile.pitch ?? 4; 1582: } else { 1583: // follow the hips across the ground (a lunge steps out of a fixed frame) 1584: const p = duel ? new THREE.Vector3(0, 0, 0) : active()[0].root.getObjectByName("J_Bip_C_Hips").getWorldPosition(new THREE.Vector3()); 1585: centre = new THREE.Vector3(p.x, h / 2 - 0.06, p.z); 1586: } 1587: frameAt(centre, h, tw_, th_, pitch); 1588: render(); 1589: const x = gap + k * (tw_ + gap); 1590: ctx.drawImage(R.domElement, x, y0, tw_, th_); 1591: ctx.fillStyle = "#9c98b5"; ctx.font = "14px sans-serif"; ctx.fillText(tile.label, x + 4, y0 + th_ + 16); 1592: }); 1593: y0 += th_ + lab + gap; 1594: } 1595: $("sheetOut").textContent = cv.toDataURL("image/png"); 1596: document.title = "sheet ready"; 1597: } 1598: 1599: // ---- panel: checks and sheets ------------------------------------------------------------------------------------------ 1600: async function loadChecks() { 1601: const box = $("checks"); 1602: try { 1603: const chk = await (await fetch("checks.json")).json(); 1604: box.classList.remove("muted"); box.innerHTML = ""; 1605: for (const c of CAM.characters) { 1606: const r = chk[c.name]; if (!r) continue; 1607: const d = document.createElement("div"); d.className = "check"; 1608: const bad = r.through.length > 0 || (r.props || []).some(x => x.verdict === "FAIL"); 1609: d.innerHTML = `<span class="sum ${bad ? "bad" : "ok"}"></span>`; 1610: d.querySelector(".sum").textContent = r.summary.replace(/^\w+:/, `${c.label}:`); 1611: const lay = r.layers; 1612: if (lay) { 1613: const ls = document.createElement("span"); ls.className = `sum ${lay.items.length ? "bad" : "ok"}`; 1614: ls.textContent = lay.summary.replace(/^\w+:/, `${c.label}:`); d.appendChild(ls); 1615: } 1616: // the armory's girths against real people of the body's height and waist (tools/anthro.py) list apart 1617: const props = (r.props || []).filter(x => x.verdict !== "real" && x.verdict !== "face"), 1618: real = (r.props || []).filter(x => x.verdict === "real"), face = (r.props || []).filter(x => x.verdict === "face"); 1619: for (const [list, title] of [[r.through, "Arms through the body"], [r.touching, "Arms resting on the body"], 1620: [lay ? lay.items : [], "Garments through plate"], [props, "Proportions out of range"], 1621: [real, "Girths past most real people of this height and waist"], 1622: [face, "The face against the study's paintings (reported, not held)"]]) { 1623: if (!list.length) continue; 1624: const det = document.createElement("details"); 1625: det.innerHTML = `<summary>${title} (${list.length})</summary><ul></ul>`; 1626: list.forEach(l => { const li = document.createElement("li"); li.textContent = l.text.replace(/^\w+, /, "").replace(/^Real bodies: /, ""); det.querySelector("ul").appendChild(li); }); 1627: d.appendChild(det); 1628: } 1629: box.appendChild(d); 1630: } 1631: } catch (e) { box.textContent = "No checks in this build."; } 1632: try { 1633: const sh = await (await fetch("sheets.json")).json(); 1634: const box2 = $("sheets"); 1635: sh.forEach(s => { 1636: const a = document.createElement("a"); a.href = s.file; a.target = "_blank"; a.rel = "noopener"; 1637: a.innerHTML = `<img alt="" loading="lazy"><span></span>`; 1638: a.querySelector("img").src = s.file; a.querySelector("img").alt = `Check sheet: ${s.label}.`; 1639: a.querySelector("span").textContent = s.label; 1640: box2.appendChild(a); 1641: }); 1642: } catch (e) { $("sheets").textContent = "No sheets in this build."; } 1643: } 1644: 1645: // ---- wiring ------------------------------------------------------------------------------------------------------------ 1646: const panelEl = $("panel"); 1647: function setPanel(open) { 1648: panelEl.hidden = !open; $("panelBtn").setAttribute("aria-expanded", String(open)); 1649: requestAnimationFrame(size); 1650: } 1651: $("panelBtn").addEventListener("click", () => setPanel(panelEl.hidden)); 1652: $("panelClose").addEventListener("click", () => setPanel(false)); 1653: document.addEventListener("keydown", e => { if (e.key === "Escape" && !panelEl.hidden && window.innerWidth <= 900) setPanel(false); }); 1654: document.querySelectorAll("[data-view]").forEach(b => b.addEventListener("click", () => setView(b.dataset.view))); 1655: document.querySelectorAll("[data-pose]").forEach(b => { 1656: b.setAttribute("aria-pressed", String(b.dataset.pose === state.pose)); 1657: b.addEventListener("click", () => { 1658: state.pose = b.dataset.pose; 1659: document.querySelectorAll("[data-pose]").forEach(x => x.setAttribute("aria-pressed", String(x === b))); 1660: if (state.view === "compare") { compareChanged(); } // room and frame follow the pose 1661: }); 1662: }); 1663: document.querySelectorAll("[data-motion]").forEach(b => { 1664: b.setAttribute("aria-pressed", String(b.dataset.motion === state.motion)); 1665: b.addEventListener("click", () => { 1666: state.motion = b.dataset.motion; 1667: document.querySelectorAll("[data-motion]").forEach(x => x.setAttribute("aria-pressed", String(x === b))); 1668: }); 1669: }); 1670: document.querySelectorAll("[data-mode]").forEach(b => b.addEventListener("click", () => { 1671: state.mode = b.dataset.mode; 1672: document.querySelectorAll("[data-mode]").forEach(x => x.setAttribute("aria-pressed", String(x === b))); 1673: })); 1674: document.querySelectorAll("[data-clip]").forEach(b => b.addEventListener("click", async () => { 1675: const want = b.dataset.clip, view = CLIP_VIEW[want]; 1676: if (state.view === "lineup" && view === "battle") { setClip(want); return; } 1677: if (state.view !== view) await setView(view, want); 1678: else setClip(want, want === "clash" ? "idle" : null); 1679: })); 1680: const toggle = (id, key, after) => $(id).addEventListener("click", e => { state[key] = !state[key]; e.currentTarget.setAttribute("aria-pressed", String(state[key])); after && after(); }); 1681: toggle("cloth", "cloth", () => { applyMaterials(); active().forEach(c => c.cloths.forEach(cl => { cl.reset(false); cl.write(); })); }); 1682: toggle("wind", "wind"); 1683: toggle("physics", "physics"); 1684: toggle("xray", "xray", applyMaterials); 1685: toggle("stepped", "stepped"); 1686: $("shade").addEventListener("click", e => { state.toon = !state.toon; e.currentTarget.setAttribute("aria-pressed", String(state.toon)); e.currentTarget.textContent = state.toon ? "3D: toon" : "3D: clay"; applyMaterials(); }); 1687: $("resetCloth").addEventListener("click", () => { state.cloth = true; $("cloth").setAttribute("aria-pressed", "true"); applyMaterials(); active().forEach(c => c.cloths.forEach(cl => cl.reset(true))); }); 1688: $("reset").addEventListener("click", matchCamera); 1689: $("yaw").addEventListener("input", e => setYaw(+e.target.value)); 1690: $("play").addEventListener("click", e => { state.playing = !state.playing; e.currentTarget.setAttribute("aria-pressed", String(state.playing)); }); 1691: new ResizeObserver(() => size()).observe(stageEl); 1692: 1693: let last = performance.now(), simT = 0; 1694: const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches; 1695: function frame(now) { 1696: const dt = Math.min(0.05, Math.max(0.001, (now - last) / 1000)); last = now; 1697: ctl.update(); 1698: const cs = active(); 1699: if (cs.length) { 1700: if (state.playing) setYaw(state.yaw + dt * (reduceMotion ? 20 : 70)); 1701: animate(dt); 1702: scene.updateMatrixWorld(true); 1703: if (state.physics && !SHEET) { // spring bones at a fixed 120 Hz, as the cloth 1704: const steps = Math.max(1, Math.round(dt / (1 / 120))); 1705: for (const c of cs) if (c.springs && c.springs.length) for (let s = 0; s < steps; s++) stepSprings(c, dt / steps); 1706: } 1707: const cloths = cs.flatMap(c => c.cloths); 1708: if (state.cloth && cloths.length) { 1709: const steps = Math.max(1, Math.round(dt / (1 / 120))); 1710: for (let s = 0; s < steps; s++) { simT += dt / steps; cloths.forEach(c => c.step(dt / steps, simT)); } 1711: cloths.forEach(c => c.write()); 1712: } 1713: render(); 1714: placeTags(); 1715: } 1716: requestAnimationFrame(frame); 1717: } 1718: 1719: if (!LINEUP.order.length) $("lineupBtn").hidden = true; 1720: // a check for scripts (?springprobe): after a few seconds of the motion, each body's widest spring-bone swing (degrees) 1721: if (params.has("springprobe")) setTimeout(() => { 1722: document.title = "springs " + JSON.stringify(Object.fromEntries(active().map(c => [c.name, +(c.springMax || 0).toFixed(1)]))); 1723: }, 4000); 1724: if (SHEET) { 1725: runSheet(SHEET).catch(e => { console.error(e); $("sheetOut").textContent = "error: " + e; document.title = "sheet failed"; }); 1726: } else { 1727: if (window.innerWidth > 1100) setPanel(true); 1728: loadChecks(); 1729: const v0 = params.get("view"), w0 = params.get("who"), m0 = params.get("mode"); 1730: if (w0 && charDef(w0)) state.who = w0; 1731: if (m0 === "3d") document.querySelector('[data-mode="3d"]').click(); 1732: const views = ARMORY_PAGE ? ["battle", "bust", "compare"] : NO_DUEL ? ["battle", "bust", "lineup"] : ["duel", "battle", "bust", "lineup"]; 1733: await setView(views.includes(v0) ? v0 : ARMORY_PAGE ? "compare" : NO_DUEL ? "lineup" : "duel", params.get("clip") || undefined); 1734: if (params.has("yaw")) setYaw(+params.get("yaw") || 0); // ?yaw=180: open turned (the backs) 1735: requestAnimationFrame(frame); 1736: } 1737: </script>read_file{"EndLine":1405,"Path":"~/work/lowmarch/review/vroid-02/index.html","StartLine":1150}
input
{ "EndLine": 1405, "Path": "~/work/lowmarch/review/vroid-02/index.html", "StartLine": 1150 }result, 257 lines
Showing lines 1150-1405 of 1737 1150: c.springMax = Math.max(c.springMax || 0, THREE.MathUtils.radToDeg(2 * Math.acos(Math.min(1, Math.abs(b.quaternion.dot(j.rest)))))); 1151: } 1152: } 1153: // side by side: each model gets room to turn in place in the current pose (its posed skin's reach round its own 1154: // axis), and the frame fits the row and the tallest reach (raised hands) 1155: const COMPARE = { frame: { w: 2.0, top: 1.6, bottom: -1.3 }, room: [] }; 1156: function layoutCompare() { 1157: const cs = active(), gap = 0.15, rooms = [], p = v3(), m4 = new THREE.Matrix4(); 1158: let top = 0; 1159: for (const c of cs) { 1160: c.skeleton && c.skeleton.pose(); applyPose(c); c.root.updateMatrixWorld(true); c.skeleton && c.skeleton.update(); 1161: const inv = c.root.matrixWorld.clone().invert(); 1162: let r = 0; 1163: for (const m of c.meshes) { 1164: const pos = m.geometry.attributes.position, step = Math.max(1, Math.floor(pos.count / 6000)); 1165: m4.multiplyMatrices(inv, m.matrixWorld); 1166: for (let i = 0; i < pos.count; i += step) { 1167: m.getVertexPosition(i, p).applyMatrix4(m4); 1168: r = Math.max(r, Math.hypot(p.x, p.z)); top = Math.max(top, p.y); 1169: } 1170: } 1171: rooms.push(r + 0.04); 1172: } 1173: const total = rooms.reduce((a, r) => a + 2 * r + gap, -gap); 1174: let x = -total / 2; 1175: cs.forEach((c, i) => { c.turn.position.set(x + rooms[i], 0, 0); x += 2 * rooms[i] + gap; }); 1176: COMPARE.room = rooms; 1177: COMPARE.frame = { w: Math.max(2.0, total + 0.2), top: Math.max(1.0, top - 1.0 + 0.1), bottom: -1.32 }; 1178: } 1179: function placeTags() { // the names under the feet 1180: const box = $("tags"); 1181: if (state.view !== "compare" || SHEET) { if (box.childElementCount) box.textContent = ""; return; } 1182: const cs = active(); 1183: if (box.childElementCount !== cs.length) { box.textContent = ""; cs.forEach(() => box.appendChild(document.createElement("span"))); } 1184: const W = stageEl.clientWidth, H = stageEl.clientHeight, mpp = (camera.right - camera.left) / camera.zoom / Math.max(1, W); 1185: cs.forEach((c, i) => { 1186: const el = box.children[i], label = charDef(c.name).label; 1187: if (el.textContent !== label) el.textContent = label; 1188: const p = c.turn.getWorldPosition(v3()); p.y = -0.03; p.project(camera); 1189: el.style.left = `${(p.x + 1) / 2 * W}px`; el.style.top = `${(1 - p.y) / 2 * H + 6}px`; 1190: el.style.maxWidth = `${Math.max(70, 2 * (COMPARE.room[i] || 0.5) / mpp - 10)}px`; 1191: }); 1192: } 1193: function compareChanged() { // the comparison is in the link, to share it 1194: const u = new URL(location.href); 1195: u.searchParams.set("view", "compare"); u.searchParams.set("compare", state.compare.join(",")); u.searchParams.set("pose", state.pose); 1196: try { history.replaceState(null, "", u); } catch (e) { /* a sandboxed page may refuse: the view still changes */ } 1197: setView("compare"); 1198: } 1199: 1200: // ---- sizing and camera --------------------------------------------------------------------------------------------- 1201: // The game camera's frame (its pixel size, scale and pivot) is fitted into the window between the two 1202: // bars, then the window's extra width or height is shown around it. 1203: function insets() { 1204: if (SHEET) return { top: 0, bottom: 0 }; 1205: const k = state.view === "compare" ? 1.0 : 0.8; // compare's bar is tall (the picker): raised hands mustn't hide under it 1206: return { top: document.querySelector(".hud.top").offsetHeight * k, bottom: document.querySelector(".hud.bottom").offsetHeight * 0.8 }; 1207: } 1208: let frameRef = null; // the game frame, metres from the orbit target 1209: function fitFrustum() { 1210: if (!frameRef) return; 1211: const W = stageEl.clientWidth || 1, H = stageEl.clientHeight || 1, ins = insets(); 1212: const f = frameRef, fw = (f.right - f.left) * 1.04, fh = (f.top - f.bottom) * 1.04; 1213: const s = Math.max(fw / W, fh / Math.max(60, H - ins.top - ins.bottom)); // metres per pixel 1214: const cx = (f.left + f.right) / 2, cy = (f.top + f.bottom) / 2; 1215: const top = cy + (H / 2 + (ins.top - ins.bottom) / 2) * s; // the frame's centre sits midway between the bars 1216: camera.left = cx - W * s / 2; camera.right = cx + W * s / 2; camera.top = top; camera.bottom = top - H * s; 1217: camera.updateProjectionMatrix(); 1218: } 1219: function size() { 1220: const w = stageEl.clientWidth, h = stageEl.clientHeight; 1221: if (!SHEET) { R.setPixelRatio(Math.min(2, window.devicePixelRatio || 1)); R.setSize(w, h, false); } 1222: fitFrustum(); 1223: } 1224: // The default framing: the portrait keeps the game's bust crop; battle and duel frame the figures 1225: // (head to feet, both fighters) rather than the whole ground strip, so they fill the window. 1226: const FIGURE = { duel: { w: 2.9, top: 1.28, bottom: -1.18 }, battle: { w: 1.5, top: 1.24, bottom: -1.14 }, 1227: get lineup() { return { w: Math.max(2.0, LINEUP.order.length * LINEUP.spacing + 0.4), top: 1.60, bottom: -1.16 }; }, 1228: get compare() { return COMPARE.frame; } }; 1229: function matchCamera() { 1230: // orbit around the middle of the body (the feet in battle would send zooms into the ground) 1231: const v = CAM_VIEW(), ppm = v.px_per_m, p = v.pivot, a = THREE.MathUtils.degToRad(v.pitch); 1232: const lift = state.view === "bust" ? 0.0 : 1.0; 1233: const target = new THREE.Vector3(p[0], p[1] + lift, p[2]); 1234: const tx = v.pivot_px[0], ty = v.pivot_px[1] - lift * Math.cos(a) * ppm, F = FIGURE[state.view]; 1235: frameRef = F ? { left: -F.w / 2, right: F.w / 2, top: F.top, bottom: F.bottom } 1236: : { left: -tx / ppm, right: (v.w - tx) / ppm, top: ty / ppm, bottom: -(v.h - ty) / ppm }; 1237: camera.zoom = 1; fitFrustum(); 1238: camera.position.copy(target).add(new THREE.Vector3(0, Math.sin(a), Math.cos(a)).multiplyScalar(15)); 1239: camera.up.set(0, 1, 0); camera.lookAt(target); 1240: ctl.target.copy(target); ctl.update(); 1241: freeLook = false; 1242: } 1243: // double-click: orbit around the spot under the cursor 1244: const ray = new THREE.Raycaster(); 1245: function focusAt(e) { 1246: const rect = R.domElement.getBoundingClientRect(); 1247: const ndc = new THREE.Vector2(((e.clientX - rect.left) / rect.width) * 2 - 1, -((e.clientY - rect.top) / rect.height) * 2 + 1); 1248: ray.setFromCamera(ndc, camera); 1249: const hit = ray.intersectObjects(allMeshes().filter(o => o.visible), false)[0]; 1250: if (!hit) return; 1251: const shift = hit.point.clone().sub(ctl.target); 1252: ctl.target.add(shift); camera.position.add(shift); ctl.update(); 1253: freeLook = true; 1254: } 1255: function setYaw(y) { 1256: state.yaw = ((y % 360) + 360) % 360; 1257: $("yaw").value = Math.round(state.yaw); $("yawOut").textContent = `${Math.round(state.yaw)}°`; 1258: const r = -THREE.MathUtils.degToRad(state.yaw); 1259: if (state.view === "duel") stage.rotation.y = r; 1260: else if (ROW_VIEW()) active().forEach(c => c.turn.rotation.y = r); 1261: else { const c = chars.get(state.who); if (c) c.turn.rotation.y = r; } 1262: } 1263: 1264: // ---- controls -------------------------------------------------------------------------------------------------------- 1265: function buildParts() { 1266: const box = $("parts"); box.innerHTML = ""; 1267: const groups = [...new Set(active().flatMap(c => c.groups)), ...(state.view !== "bust" ? ["terrain"] : [])]; 1268: groups.forEach(g => { 1269: const l = document.createElement("label"); l.className = "chip"; 1270: l.innerHTML = `<input type="checkbox" ${state.hidden.has(g) ? "" : "checked"}> ${GROUP_LABELS[g] || g}`; 1271: l.querySelector("input").addEventListener("change", e => { e.target.checked ? state.hidden.delete(g) : state.hidden.add(g); applyMaterials(); }); 1272: box.appendChild(l); 1273: }); 1274: } 1275: function groupedSelect(label, skip, onPick) { // every model in its group, as one dropdown 1276: const sel = document.createElement("select"); 1277: sel.className = "btn"; sel.setAttribute("aria-label", label); 1278: const first = document.createElement("option"); first.value = ""; first.textContent = label; sel.appendChild(first); 1279: [...new Set(CAM.characters.map(c => c.group || "Other"))].forEach(g => { 1280: const og = document.createElement("optgroup"); og.label = g; 1281: CAM.characters.filter(c => (c.group || "Other") === g && !skip.includes(c.name)).forEach(c => { 1282: const o = document.createElement("option"); o.value = c.name; o.textContent = c.label; og.appendChild(o); 1283: }); 1284: if (og.children.length) sel.appendChild(og); 1285: }); 1286: sel.addEventListener("change", () => sel.value && onPick(sel.value)); 1287: return sel; 1288: } 1289: function buildWho() { 1290: const box = $("who"); box.innerHTML = ""; 1291: if (state.view === "compare") { // the models being compared, left to right, and one to add 1292: const wrap = document.createElement("span"); wrap.className = "pick"; 1293: state.compare.forEach(n => { 1294: const b = document.createElement("button"), label = charDef(n).label; 1295: b.type = "button"; b.className = "btn"; b.disabled = state.compare.length <= 1; 1296: b.setAttribute("aria-label", `Remove ${label} from the comparison`); b.title = "Remove from the comparison"; 1297: b.append(label, Object.assign(document.createElement("b"), { textContent: "✕" })); 1298: b.addEventListener("click", () => { state.compare = state.compare.filter(x => x !== n); compareChanged(); }); 1299: wrap.appendChild(b); 1300: }); 1301: if (state.compare.length < MAX_COMPARE) 1302: wrap.appendChild(groupedSelect("Add a model…", state.compare, n => { state.compare = [...state.compare, n]; compareChanged(); })); 1303: box.appendChild(wrap); 1304: return; 1305: } 1306: if (CAM.characters.some(c => c.group)) { // a long roster in groups (camera.json "group"): one dropdown 1307: const sel = document.createElement("select"); 1308: sel.className = "btn"; sel.setAttribute("aria-label", "Character"); 1309: const order = [...new Set(CAM.characters.map(c => c.group || "Other"))]; 1310: order.forEach(g => { 1311: const og = document.createElement("optgroup"); og.label = g; 1312: CAM.characters.filter(c => (c.group || "Other") === g).forEach(c => { 1313: const o = document.createElement("option"); o.value = c.name; o.textContent = c.label; 1314: o.selected = state.who === c.name; og.appendChild(o); 1315: }); 1316: sel.appendChild(og); 1317: }); 1318: sel.addEventListener("change", () => { state.who = sel.value; setView(state.view === "duel" ? "battle" : state.view); }); 1319: box.appendChild(sel); 1320: return; 1321: } 1322: CAM.characters.forEach(c => { 1323: const b = document.createElement("button"); 1324: b.type = "button"; b.className = "btn"; b.textContent = c.label; 1325: b.setAttribute("aria-pressed", String((state.view === "battle" || state.view === "bust") && state.who === c.name)); 1326: b.addEventListener("click", () => { state.who = c.name; setView(state.view === "duel" ? "battle" : state.view); }); 1327: box.appendChild(b); 1328: }); 1329: } 1330: 1331: async function setView(view, clip) { 1332: const changed = view !== state.view; 1333: state.view = view; 1334: document.querySelectorAll("[data-view]").forEach(b => b.setAttribute("aria-pressed", String(b.dataset.view === view))); 1335: buildWho(); 1336: statusEl.hidden = false; statusEl.textContent = view === "duel" ? "Loading both fighters…" : "Loading the model…"; 1337: try { 1338: const cs = await Promise.all(activeNames().map(loadCharacter)); 1339: const g = view !== "bust" && !ROW_VIEW() ? await loadGround() : null; // a row of models stands on nothing 1340: for (const c of chars.values()) { c.turn.removeFromParent(); scene.remove(c.world); } 1341: if (ground) scene.remove(ground.root); 1342: if (g) scene.add(g.root); 1343: const v = CAM_VIEW(), lead = cs[0].info; 1344: paint.mat.uniforms.uGap.value = lead.depth_gap; 1345: stage.rotation.y = 0; 1346: for (const c of cs) { 1347: scene.add(c.world); 1348: c.turn.rotation.set(0, 0, 0); 1349: if (view === "lineup") { 1350: const i = LINEUP.order.indexOf(c.name); 1351: stage.add(c.turn); 1352: c.turn.position.set(lineupX(i), 0, 0); c.holder.position.set(0, 0, 0); 1353: } else if (view === "compare") { // placed by layoutCompare, once all are in 1354: stage.add(c.turn); c.holder.position.set(0, 0, 0); 1355: } else if (view === "duel") { 1356: const pl = CAM.duel.place[c.name]; 1357: stage.add(c.turn); 1358: c.turn.position.set(...pl.pos); c.turn.rotation.y = THREE.MathUtils.degToRad(pl.yaw); c.holder.position.set(0, 0, 0); 1359: } else { 1360: scene.add(c.turn); 1361: c.turn.position.set(v.pivot[0], 0, v.pivot[2]); c.holder.position.set(-v.pivot[0], 0, -v.pivot[2]); 1362: } 1363: } 1364: statusEl.hidden = true; 1365: if (view === "compare") layoutCompare(); 1366: buildParts(); applyMaterials(); size(); matchCamera(); 1367: setYaw(changed || view === "duel" ? VIEW_YAW[view] : state.yaw); 1368: const want = clip || (view === "duel" ? "clash" : (CLIP_VIEW[state.clip] === "battle" ? state.clip : "idle")); 1369: if (view === "duel") setClip("clash", SHEET ? null : "idle"); else if (view === "battle") setClip(want); 1370: else if (view === "lineup") setClip(clip && CLIP_VIEW[clip] === "battle" ? clip : "idle"); else setClip("idle"); 1371: animate(0); 1372: scene.updateMatrixWorld(true); cs.forEach(c => c.cloths.forEach(cl => { cl.reset(false); cl.write(); })); 1373: } catch (e) { console.error(e); statusEl.textContent = "The model didn't load."; } 1374: } 1375: 1376: // ---- rendering ------------------------------------------------------------------------------------------------------- 1377: function applySkin(meshes) { 1378: // the picked tone on every skin material (face, body, shadow cards); the built tone is kept to go back to 1379: const tone = state.skin && PAGE && PAGE.skins ? PAGE.skins.find(s => s.name === state.skin) : null; 1380: for (const o of meshes) { 1381: const m = o.userData.mats && o.userData.mats.painted, u = m && m.uniforms; 1382: if (!u || !u.uSkinRamp || u.uKind.value !== 1) continue; 1383: if (!o.userData.builtSkin) o.userData.builtSkin = [u.uSkinRamp.value, u.uSkinL.value.clone(), u.uSkinS.value.clone(), u.uSkinC.value.clone()]; 1384: if (tone) { u.uSkinRamp.value = 1; u.uSkinL.value.copy(hex(tone.ramp[0])); u.uSkinS.value.copy(hex(tone.ramp[1])); u.uSkinC.value.copy(hex(tone.ramp[2])); } 1385: else { const b = o.userData.builtSkin; u.uSkinRamp.value = b[0]; u.uSkinL.value.copy(b[1]); u.uSkinS.value.copy(b[2]); u.uSkinC.value.copy(b[3]); } 1386: } 1387: } 1388: function render() { 1389: const meshes = allMeshes(), cs = active(); 1390: applySkin(meshes); 1391: const cloths = cs.flatMap(c => c.cloths); 1392: if (state.mode === "3d") { 1393: meshes.forEach(o => o.material = o.userData.mat3d); 1394: cloths.forEach(c => c.lines3d.visible = trimsShown(c)); 1395: sun.position.copy(camera.position).add(new THREE.Vector3(-3, 4, 0)); sun.target.position.copy(ctl.target); sun.target.updateMatrixWorld(); 1396: R.setRenderTarget(null); R.setClearColor(0x191626, 1); R.clear(); R.render(scene, camera); R.setClearColor(0x000000, 0); 1397: return; 1398: } 1399: const buf = R.getDrawingBufferSize(new THREE.Vector2()); 1400: targetsFor(buf.x, buf.y); 1401: cloths.forEach(c => c.lines3d.visible = false); 1402: meshes.forEach(o => { o.material = o.userData.mats.painted; o.material.uniforms.uPass.value = 0; }); 1403: const G = GRADE[state.view === "bust" ? "bust" : "battle"]; // stage grade, shared by the characters and the stage 1404: for (const o of meshes) { const mu = o.material.uniforms; mu.uAmbient.value.set(...G.ambient); mu.uKeyCol.value.set(...G.key); mu.uRimCol.value.set(...G.rim); } 1405: // the info pass (roles, ids, depth) first: the colour pass reads it for cast shadows