<!DOCTYPE html>
<html lang="pt-BR">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
<style>
:root { color-scheme: light; }
html, body { margin: 0; padding: 0; height: 100%; }
[hidden] { display: none !important; }
</style>
<title>Boneco 3D</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@500;700&family=Inter:wght@400;500&display=swap">
<style>
/* Layout: cena 3D em tela cheia; estado no topo, legenda dos muros à esquerda, controles embaixo. */
:root {
--sky: #bcd4e6;
--ink: #15212c;
--ink-soft: #4a5a68;
--panel: rgba(250, 252, 253, .88);
--line: rgba(21, 33, 44, .16);
--accent: #e0793a;
--font-display: 'Space Grotesk', 'Segoe UI', system-ui, sans-serif;
--font-body: 'Inter', 'Segoe UI', system-ui, sans-serif;
color-scheme: light;
}
html, body { height: 100%; }
body { background: var(--sky); color: var(--ink); font-family: var(--font-body); overflow: hidden; }
#stage { position: relative; width: 100%; height: 100%; overflow: hidden; touch-action: none; user-select: none; -webkit-user-select: none; }
#view { display: block; width: 100%; height: 100%; outline: none; }
.hud { position: absolute; pointer-events: none; z-index: 2; }
.ui { pointer-events: auto; }
.top {
top: 12px;
left: max(16px, env(safe-area-inset-left, 0px));
right: max(16px, env(safe-area-inset-right, 0px));
display: flex; justify-content: space-between; align-items: flex-start; gap: 12px;
}
.pill {
display: inline-flex; align-items: center; gap: 10px;
padding: 9px 14px; border-radius: 10px;
background: var(--panel); border: 1px solid var(--line);
font: 500 14px/1 var(--font-body);
}
.pill strong { font-family: var(--font-display); font-weight: 700; font-size: 15px; }
.num { font-variant-numeric: tabular-nums; color: var(--ink-soft); min-width: 7ch; text-align: right; }
.btn {
padding: 9px 14px; border-radius: 10px; cursor: pointer;
background: var(--panel); border: 1px solid var(--line); color: var(--ink);
font: 500 13px/1 var(--font-body);
}
.btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.legend {
top: 62px; left: max(16px, env(safe-area-inset-left, 0px));
margin: 0; padding: 10px 12px; list-style: none;
display: flex; flex-direction: column; gap: 7px;
background: var(--panel); border: 1px solid var(--line); border-radius: 10px;
font: 400 12px/1.2 var(--font-body);
}
.legend li { display: flex; align-items: center; gap: 8px; }
.sw { width: 12px; height: 12px; border-radius: 3px; border: 1px solid rgba(0, 0, 0, .2); flex: none; }
.keys {
left: max(16px, env(safe-area-inset-left, 0px)); bottom: 14px;
max-width: calc(100% - 32px);
margin: 0; padding: 10px 12px; list-style: none;
display: flex; flex-wrap: wrap; gap: 6px 16px;
background: var(--panel); border: 1px solid var(--line); border-radius: 10px;
font: 400 12px/1.2 var(--font-body);
}
.keys li { display: flex; align-items: center; gap: 6px; }
kbd {
font: 700 11px/1 var(--font-display); padding: 3px 6px; background: #fff;
border: 1px solid var(--line); border-bottom-width: 2px; border-radius: 5px;
}
.pad {
right: max(16px, env(safe-area-inset-right, 0px)); bottom: 22px;
display: none; align-items: flex-end; gap: 14px;
}
.pad .col { display: flex; flex-direction: column; gap: 10px; }
.act {
width: 74px; height: 74px; border-radius: 50%; cursor: pointer;
background: var(--panel); border: 1px solid var(--line); color: var(--ink);
font: 700 13px/1 var(--font-display); letter-spacing: .04em; text-transform: uppercase;
}
.act.sm { width: 62px; height: 62px; font-size: 10.5px; }
.act.jump { width: 88px; height: 88px; background: var(--accent); border-color: rgba(0, 0, 0, .2); }
.act.jump.on, .act.sm.on { transform: scale(.94); }
.act[aria-pressed="true"] { background: var(--ink); color: #fff; }
.stick {
position: absolute; width: 110px; height: 110px; border-radius: 50%; z-index: 2; pointer-events: none;
background: rgba(21, 33, 44, .14); border: 2px solid rgba(21, 33, 44, .3);
}
.knob { position: absolute; left: 32px; top: 32px; width: 46px; height: 46px; border-radius: 50%; background: rgba(21, 33, 44, .62); }
@media (pointer: coarse) {
.pad { display: flex; }
.keys, .legend { display: none; }
}
@media (max-width: 560px) { .legend { display: none; } }
</style>
</head>
<body>
<div id="stage">
<canvas id="view" tabindex="0" aria-label="Cena 3D com o boneco e as paredes de teste"></canvas>
<div class="hud top">
<div class="pill" role="status"><strong id="status">Parado</strong><span class="num" id="speed">0,0 m/s</span></div>
<button class="ui btn" id="btnReset" type="button">Reiniciar</button>
</div>
<ul class="hud legend" aria-label="Obstáculos de teste">
<li><span class="sw" style="background:#e08a4a"></span>0,6 m · pule por cima</li>
<li><span class="sw" style="background:#d6b04a"></span>1,0 m · mureta: pule ou se abrigue</li>
<li><span class="sw" style="background:#4aa8a0"></span>0,4 m · degrau</li>
<li><span class="sw" style="background:#6f9bc4"></span>1,3 m · suba na borda, abrigo agachado</li>
<li><span class="sw" style="background:#8f7fb3"></span>2,2 m · bloco para escalar</li>
<li><span class="sw" style="background:#e4e1da"></span>3 m · escale ou cole nela</li>
</ul>
<ul class="hud keys" aria-label="Controles">
<li><kbd>W</kbd><kbd>A</kbd><kbd>S</kbd><kbd>D</kbd> andar</li>
<li><kbd>Shift</kbd> correr</li>
<li><kbd>C</kbd> agachar · correndo: deslizar</li>
<li><kbd>F</kbd> mergulho em qualquer direção · deitado: <kbd>Espaço</kbd> levanta</li>
<li><kbd>E</kbd> abrigar-se / soltar</li>
<li><kbd>Espaço</kbd> pular, vencer mureta, escalar</li>
<li><kbd>Q</kbd> trocar ombro</li>
<li>Mouse: câmera (<kbd>Esc</kbd> solta)</li>
<li><kbd>R</kbd> reiniciar</li>
</ul>
<div class="hud pad ui">
<div class="col">
<button class="ui act sm" id="btnRun" type="button" aria-pressed="false">Correr</button>
<button class="ui act sm" id="btnCrouch" type="button" aria-pressed="false">Agachar</button>
<button class="ui act sm" id="btnCover" type="button">Abrigo</button>
<button class="ui act sm" id="btnDive" type="button">Mergulho</button>
</div>
<button class="ui act jump" id="btnJump" type="button">Pular</button>
</div>
<div class="stick" id="stick" hidden><div class="knob" id="knob"></div></div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script>
(function () {
'use strict';
const stage = document.getElementById('stage');
const canvas = document.getElementById('view');
const statusEl = document.getElementById('status');
const speedEl = document.getElementById('speed');
const stickEl = document.getElementById('stick');
const knobEl = document.getElementById('knob');
const btnJump = document.getElementById('btnJump');
const btnRun = document.getElementById('btnRun');
const btnCrouch = document.getElementById('btnCrouch');
const btnCover = document.getElementById('btnCover');
const btnReset = document.getElementById('btnReset');
const btnDive = document.getElementById('btnDive');
if (typeof THREE === 'undefined') { statusEl.textContent = 'O motor 3D não carregou'; return; }
let renderer;
try {
renderer = new THREE.WebGLRenderer({ canvas: canvas, antialias: true });
} catch (err) { statusEl.textContent = 'Este navegador não abriu o WebGL'; return; }
/* ---------- utilidades e medidas (metros) ---------- */
const TAU = Math.PI * 2;
const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
const lerp = (a, b, t) => a + (b - a) * t;
const damp = (rate, dt) => 1 - Math.exp(-rate * dt);
const smooth = (a, b, x) => { const t = clamp((x - a) / (b - a), 0, 1); return t * t * (3 - 2 * t); };
const angDiff = (a, b) => { let d = (b - a) % TAU; if (d > Math.PI) d -= TAU; if (d < -Math.PI) d += TAU; return d; };
const WALK = 2.3, RUN = 5.8, CROUCH = 1.2, JUMP_V = 6.6, GRAVITY = 19;
const STEP = 0.3, R = 0.48, HIP_Y = 1.005, REACH = 1.75, VAULT_MAX = 1.2, CLIMB_MAX = 3.6;
const CLIMB_DIST = 0.26, COVER_LOW_DIST = 0.22, COVER_HIGH_DIST = 0.15;
const UP_LEN = 0.29, FORE_LEN = 0.31, THIGH_LEN = 0.45, SHIN_LEN = 0.43;
/* ---------- esqueleto: rotações XYZ do three.js e cinemática inversa ---------- */
const rotX = (a) => { const c = Math.cos(a), s = Math.sin(a); return [1, 0, 0, 0, c, -s, 0, s, c]; };
const rotY = (a) => { const c = Math.cos(a), s = Math.sin(a); return [c, 0, s, 0, 1, 0, -s, 0, c]; };
const rotZ = (a) => { const c = Math.cos(a), s = Math.sin(a); return [c, -s, 0, s, c, 0, 0, 0, 1]; };
const mmul = (a, b) => {
const r = new Array(9);
for (let i = 0; i < 3; i++) for (let j = 0; j < 3; j++) r[i * 3 + j] = a[i * 3] * b[j] + a[i * 3 + 1] * b[3 + j] + a[i * 3 + 2] * b[6 + j];
return r;
};
const mvec = (m, v) => [m[0] * v[0] + m[1] * v[1] + m[2] * v[2], m[3] * v[0] + m[4] * v[1] + m[5] * v[2], m[6] * v[0] + m[7] * v[1] + m[8] * v[2]];
const mtvec = (m, v) => [m[0] * v[0] + m[3] * v[1] + m[6] * v[2], m[1] * v[0] + m[4] * v[1] + m[7] * v[2], m[2] * v[0] + m[5] * v[1] + m[8] * v[2]];
// Membro de dois ossos: ombro/quadril com rotação X·Z e articulação (cotovelo/joelho) em X.
// Dado o vetor do pivô até o alvo, devolve [rotZ, rotX, dobra]. sign = -1 braços, +1 pernas.
function solveLimb(vx, vy, vz, L1, L2, sign) {
let d = Math.hypot(vx, vy, vz);
const dMax = L1 + L2 - 0.004;
const dMin = Math.sqrt(L1 * L1 + L2 * L2 + 2 * L1 * L2 * Math.cos(2.45));
if (d > dMax) { const k = dMax / d; vx *= k; vy *= k; vz *= k; d = dMax; }
else if (d < dMin && d > 1e-6) { const k = dMin / d; vx *= k; vy *= k; vz *= k; d = dMin; }
const ce = clamp((d * d - L1 * L1 - L2 * L2) / (2 * L1 * L2), -1, 1);
const e = sign * Math.acos(ce);
const qy = -(L1 + L2 * Math.cos(e)), qz = -L2 * Math.sin(e);
const a = Math.asin(clamp(-vx / qy, -1, 1));
const b = Math.atan2(vz, vy) - Math.atan2(qz, qy * Math.cos(a));
return [a, Math.atan2(Math.sin(b), Math.cos(b)), e];
}
// Posição do fim do membro, no referencial do pivô (inverso de solveLimb).
function limbEnd(a, b, e, L1, L2) {
return mvec(mmul(rotX(b), rotZ(a)), [0, -(L1 + L2 * Math.cos(e)), -L2 * Math.sin(e)]);
}
/* ---------- cena ---------- */
renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
renderer.shadowMap.enabled = true;
renderer.shadowMap.type = THREE.PCFSoftShadowMap;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0xbcd4e6);
scene.fog = new THREE.Fog(0xbcd4e6, 38, 110);
const camera = new THREE.PerspectiveCamera(62, 1, 0.1, 200);
scene.add(new THREE.HemisphereLight(0xffffff, 0x6c8a78, 0.65));
const sun = new THREE.DirectionalLight(0xffffff, 0.5);
sun.castShadow = true;
sun.shadow.mapSize.set(2048, 2048);
sun.shadow.camera.left = -22; sun.shadow.camera.right = 22;
sun.shadow.camera.top = 22; sun.shadow.camera.bottom = -22;
sun.shadow.camera.near = 1; sun.shadow.camera.far = 70;
sun.shadow.bias = -0.0006;
scene.add(sun); scene.add(sun.target);
// Chão: cada quadradinho tem 1 m por 1 m, para ler as distâncias.
function groundTexture() {
const c = document.createElement('canvas');
c.width = c.height = 256;
const g = c.getContext('2d');
g.fillStyle = '#93ab9e'; g.fillRect(0, 0, 256, 256);
g.fillStyle = '#869f92'; g.fillRect(0, 0, 128, 128); g.fillRect(128, 128, 128, 128);
g.strokeStyle = 'rgba(255,255,255,.4)'; g.lineWidth = 2; g.strokeRect(1, 1, 254, 254);
const t = new THREE.CanvasTexture(c);
t.wrapS = t.wrapT = THREE.RepeatWrapping;
t.repeat.set(60, 60);
t.anisotropy = Math.min(8, renderer.capabilities.getMaxAnisotropy());
return t;
}
const ground = new THREE.Mesh(new THREE.PlaneGeometry(120, 120), new THREE.MeshStandardMaterial({ map: groundTexture(), roughness: 1 }));
ground.rotation.x = -Math.PI / 2;
ground.receiveShadow = true;
scene.add(ground);
/* ---------- obstáculos de teste ---------- */
const solids = [];
const wallMeshes = [];
function addBox(x, z, w, d, h, color) {
const geo = new THREE.BoxGeometry(w, h, d);
const mesh = new THREE.Mesh(geo, new THREE.MeshStandardMaterial({ color: color, roughness: 0.9 }));
mesh.position.set(x, h / 2, z);
mesh.castShadow = true; mesh.receiveShadow = true;
const edges = new THREE.LineSegments(new THREE.EdgesGeometry(geo), new THREE.LineBasicMaterial({ color: 0x15212c, transparent: true, opacity: 0.28 }));
mesh.add(edges);
scene.add(mesh);
mesh.updateMatrixWorld(true);
wallMeshes.push(mesh);
solids.push({ minX: x - w / 2, maxX: x + w / 2, minZ: z - d / 2, maxZ: z + d / 2, top: h });
}
const CONCRETE = 0xe4e1da;
addBox(0, 9, 16, 0.5, 3, CONCRETE); // parede alta no fundo
addBox(-7.75, 5.5, 0.5, 7, 3, CONCRETE); // parede lateral, forma um canto
addBox(8.5, -1, 0.5, 14, 3, CONCRETE); // parede alta à direita
addBox(5, 3, 5, 0.5, 0.6, 0xe08a4a); // mureta de 0,6 m
addBox(-3, 3, 4, 0.5, 1.0, 0xd6b04a); // mureta de 1,0 m
addBox(-4, -3, 6, 0.5, 1.3, 0x6f9bc4); // muro de 1,3 m
addBox(3, -6, 3, 3, 0.4, 0x4aa8a0); // degrau de 0,4 m
addBox(-9, -6, 1.2, 1.2, 3, CONCRETE); // pilar
addBox(-1, -10, 4, 2, 2.2, 0x8f7fb3); // bloco de 2,2 m
/* ---------- boneco: só blocos, todo cinza ---------- */
const gray = (c) => new THREE.MeshStandardMaterial({ color: c, roughness: 0.75, flatShading: true });
const mat = {
torso: gray(0x8a9097), limb: gray(0xa4a9af), joint: gray(0x6a7077),
head: gray(0xbcc1c6), dark: gray(0x4b5056), shoe: gray(0x585e65)
};
function box(w, h, d, m) {
const mesh = new THREE.Mesh(new THREE.BoxGeometry(w, h, d), m);
mesh.castShadow = true; mesh.receiveShadow = true; return mesh;
}
function boxHang(w, h, d, m) { // pivô no topo da peça
const g = new THREE.BoxGeometry(w, h, d);
g.translate(0, -h / 2, 0);
const mesh = new THREE.Mesh(g, m);
mesh.castShadow = true; mesh.receiveShadow = true; return mesh;
}
function pivot(parent, x, y, z) {
const g = new THREE.Group();
g.position.set(x, y, z);
parent.add(g); return g;
}
function at(mesh, parent, x, y, z) { mesh.position.set(x, y, z); parent.add(mesh); return mesh; }
const root = new THREE.Group(); scene.add(root);
const hips = pivot(root, 0, HIP_Y, 0);
at(box(0.36, 0.18, 0.22, mat.torso), hips, 0, 0.03, 0);
const spine = pivot(hips, 0, 0.1, 0);
at(box(0.3, 0.16, 0.2, mat.dark), spine, 0, 0.08, 0);
const chest = at(box(0.44, 0.3, 0.25, mat.torso), spine, 0, 0.31, 0);
const neck = pivot(spine, 0, 0.47, 0);
at(box(0.08, 0.08, 0.08, mat.joint), neck, 0, 0.04, 0);
at(box(0.2, 0.23, 0.22, mat.head), neck, 0, 0.2, 0);
at(box(0.2, 0.05, 0.03, mat.dark), neck, 0, 0.21, 0.115); // faixa que mostra a frente
const arms = [], legs = [];
[1, -1].forEach(function (side) {
const sh = pivot(spine, side * 0.28, 0.4, 0);
sh.add(box(0.11, 0.11, 0.11, mat.joint));
sh.add(boxHang(0.095, UP_LEN, 0.095, mat.limb));
const el = pivot(sh, 0, -UP_LEN, 0);
el.add(box(0.085, 0.085, 0.085, mat.joint));
el.add(boxHang(0.08, 0.27, 0.08, mat.limb));
at(box(0.09, 0.1, 0.07, mat.dark), el, 0, -FORE_LEN, 0);
arms.push({ sh: sh, el: el, side: side });
const hp = pivot(hips, side * 0.1, -0.06, 0);
hp.add(box(0.12, 0.12, 0.12, mat.joint));
hp.add(boxHang(0.14, THIGH_LEN, 0.15, mat.limb));
const kn = pivot(hp, 0, -THIGH_LEN, 0);
kn.add(box(0.1, 0.1, 0.1, mat.joint));
kn.add(boxHang(0.115, SHIN_LEN, 0.12, mat.limb));
const an = pivot(kn, 0, -SHIN_LEN, 0);
at(box(0.12, 0.07, 0.27, mat.shoe), an, 0, -0.04, 0.065);
legs.push({ hp: hp, kn: kn, an: an, side: side });
});
/* ---------- estado ---------- */
const P = { x: 0, y: 0, z: 0, vx: 0, vy: 0, vz: 0, yaw: 0, grounded: true };
// modos: move, vault (pular mureta), mantle (subir na borda), climb (escalar), cover (abrigo)
const S = {
mode: 'move', t: 0, dur: 1, crouch: false, info: null, solid: null, low: false,
along: 0, along0: 0, latSign: 1, dist: 0, alongVel: 0, upV: 0, hop: 0, awayT: 0, dirLocal: 1, coverSide: 1, deepT: 1,
sx: 0, sz: 0, sy: 0, ex: 0, ez: 0, ey: 0, arc: 0, over: true, vtype: 'speed', hand: 0, vSpeed: 0, yawOff: 0,
rollSign: 1, faceT: 0, faceYaw: 0,
slideV: 0, slideV0: 0, diveDir: [0, 1], diveYaw: 0, diveKind: 0, diveSide: 1, lyRx: 1.5, lyTw: 0, gT: 0, gDur: 1, gProne: true, gCrouch: false
};
const cam = {
yaw: 0, pitch: 0.24, side: 1, shoulder: 0.65, tx: 0, tz: 0, ty: 1.5, dist: 3.4, fov: 62, roll: 0,
shake: 0, punch: 0, dip: 0, dipV: 0, lastLook: -9, swapT: 0, lockUntil: 0
};
const A = {
phase: 0, cPhase: 0, sPhase: 0, speedS: 0, gaitS: 0, runT: 0, airT: 0, cr: 0, deep: 0, cm: 0,
wh: 0, ws: 0, wsSign: 1, wsAng: 0.38, pl: 0, mV: 0, mM: 0, mC: 0, mK: 0, kLow: 0, vt: 0, mt: 0,
land: 0, landImpact: 0, jPos: 0, jVel: 0, airSide: 0, accS: 0, prevSp: 0, yr: 0,
mS: 0, mD: 0, mP: 0, mG: 0, tw: 0, dv: 0, pc: 0, pa: 0, snapW: 0, snap: null,
ikA: [0, 0], ikL: [0, 0],
ikAT: [{ x: 0, y: 0, z: 0 }, { x: 0, y: 0, z: 0 }], ikLT: [{ x: 0, y: 0, z: 0 }, { x: 0, y: 0, z: 0 }]
};
const lastPose = { hipRX: 0, hipY: 0, hipRY: 0, hipRZ: 0, spX: 0, spY: 0, spZ: 0, shx: [0, 0], shz: [0, 0], elx: [0, 0], th: [0, 0], thz: [0, 0], kn: [0, 0], yaw: 0 };
const keys = {};
const act = { cover: false, crouch: false, swap: false, dive: false };
const stick = { id: null, ox: 0, oy: 0, x: 0, y: 0 };
const look = { id: null, x: 0, y: 0 };
let jumpBuf = 0, coyote = 0, runToggle = false, portrait = false;
let locked = false, mouseDrag = false;
let hudLabel = '', hudTimer = 0, time = 0;
function resetPlayer() {
P.x = 0; P.y = 0; P.z = 0; P.vx = P.vy = P.vz = 0; P.yaw = 0; P.grounded = true;
S.mode = 'move'; S.crouch = false; S.alongVel = 0; S.upV = 0; S.hop = 0; S.faceT = 0; S.yawOff = 0;
cam.yaw = 0; cam.pitch = 0.24; cam.tx = 0; cam.tz = 0; cam.ty = 1.5; cam.shake = 0; cam.punch = 0; cam.dip = 0; cam.dipV = 0;
A.phase = 0; A.speedS = 0; A.gaitS = 0; A.runT = 0; A.airT = 0; A.cr = 0; A.deep = 0; A.cm = 0; A.wh = 0; A.ws = 0; A.pl = 0;
A.mV = A.mM = A.mC = A.mK = 0; A.land = 0; A.landImpact = 0; A.jPos = 0; A.jVel = 0;
A.ikA[0] = A.ikA[1] = A.ikL[0] = A.ikL[1] = 0;
A.mS = A.mD = A.mP = A.mG = 0; A.snapW = 0; S.slideV = 0; act.dive = false;
}
/* ---------- entrada ---------- */
const STICK_R = 50;
function readInput() {
let ix = 0, iz = 0, mag = 0;
if (keys.KeyD || keys.ArrowRight) ix += 1;
if (keys.KeyA || keys.ArrowLeft) ix -= 1;
if (keys.KeyW || keys.ArrowUp) iz += 1;
if (keys.KeyS || keys.ArrowDown) iz -= 1;
if (ix || iz) { const l = Math.hypot(ix, iz); ix /= l; iz /= l; mag = 1; }
if (stick.id !== null) {
const m = Math.hypot(stick.x, stick.y);
if (m > 0.12) { ix = stick.x / m; iz = stick.y / m; mag = clamp((m - 0.12) / 0.78, 0, 1); }
else { ix = iz = 0; mag = 0; }
}
return { ix: ix, iz: iz, mag: mag, run: !!(keys.ShiftLeft || keys.ShiftRight || runToggle) };
}
window.addEventListener('keydown', function (e) {
if (e.code === 'Space' || e.code.indexOf('Arrow') === 0) e.preventDefault();
if (e.repeat) return;
keys[e.code] = true;
if (e.code === 'Space') jumpBuf = 0.14;
if (e.code === 'KeyR') resetPlayer();
if (e.code === 'KeyE') act.cover = true;
if (e.code === 'KeyC') act.crouch = true;
if (e.code === 'KeyQ') act.swap = true;
if (e.code === 'KeyF') act.dive = true;
});
window.addEventListener('keyup', function (e) { keys[e.code] = false; });
window.addEventListener('blur', function () { for (const k in keys) keys[k] = false; });
document.addEventListener('pointerlockchange', function () { locked = document.pointerLockElement === canvas; });
function lookBy(dx, dy, sens) {
cam.yaw -= dx * sens;
cam.pitch = clamp(cam.pitch + dy * sens, -0.4, 1.15);
cam.lastLook = time;
}
stage.addEventListener('pointerdown', function (e) {
if (e.target.closest && e.target.closest('.ui')) return;
try { canvas.focus({ preventScroll: true }); } catch (err) { /* sem foco */ }
if (e.pointerType === 'mouse') {
if (e.button !== 0) return;
mouseDrag = true;
try { stage.setPointerCapture(e.pointerId); } catch (err) { /* sem captura */ }
try {
const r = canvas.requestPointerLock && canvas.requestPointerLock();
if (r && r.catch) r.catch(function () {});
} catch (err) { /* sem trava de ponteiro */ }
return;
}
const rect = stage.getBoundingClientRect();
if (e.clientX - rect.left < rect.width * 0.5 && stick.id === null) {
stick.id = e.pointerId; stick.ox = e.clientX; stick.oy = e.clientY; stick.x = stick.y = 0;
stickEl.style.left = (e.clientX - rect.left - 55) + 'px';
stickEl.style.top = (e.clientY - rect.top - 55) + 'px';
knobEl.style.transform = 'translate(0px,0px)';
stickEl.hidden = false;
} else if (look.id === null) {
look.id = e.pointerId; look.x = e.clientX; look.y = e.clientY;
} else return;
try { stage.setPointerCapture(e.pointerId); } catch (err) { /* sem captura */ }
});
stage.addEventListener('pointermove', function (e) {
if (e.pointerType === 'mouse') {
if (locked || mouseDrag) lookBy(e.movementX || 0, e.movementY || 0, 0.0026);
return;
}
if (e.pointerId === stick.id) {
const dx = e.clientX - stick.ox, dy = e.clientY - stick.oy;
const m = Math.hypot(dx, dy), k = m > STICK_R ? STICK_R / m : 1;
stick.x = dx * k / STICK_R; stick.y = -dy * k / STICK_R;
knobEl.style.transform = 'translate(' + (dx * k) + 'px,' + (dy * k) + 'px)';
} else if (e.pointerId === look.id) {
lookBy(e.clientX - look.x, e.clientY - look.y, 0.0058);
look.x = e.clientX; look.y = e.clientY;
}
});
function endPointer(e) {
if (e.pointerType === 'mouse') { mouseDrag = false; return; }
if (e.pointerId === stick.id) { stick.id = null; stick.x = stick.y = 0; stickEl.hidden = true; }
if (e.pointerId === look.id) look.id = null;
}
stage.addEventListener('pointerup', endPointer);
stage.addEventListener('pointercancel', endPointer);
function hold(btn, fn) {
btn.addEventListener('pointerdown', function (e) { e.preventDefault(); fn(); btn.classList.add('on'); });
['pointerup', 'pointerleave', 'pointercancel'].forEach(function (t) {
btn.addEventListener(t, function () { btn.classList.remove('on'); });
});
}
hold(btnJump, function () { jumpBuf = 0.15; });
hold(btnCover, function () { act.cover = true; });
hold(btnDive, function () { act.dive = true; });
btnRun.addEventListener('click', function () {
runToggle = !runToggle;
btnRun.setAttribute('aria-pressed', runToggle ? 'true' : 'false');
});
btnCrouch.addEventListener('click', function () { act.crouch = true; });
btnReset.addEventListener('click', function () { resetPlayer(); btnReset.blur(); });
/* ---------- geometria dos obstáculos ---------- */
function floorAt(x, z, y) {
let f = 0;
for (const s of solids) {
if (s.top <= y + STEP + 0.001 && s.top > f && x > s.minX - 0.15 && x < s.maxX + 0.15 && z > s.minZ - 0.15 && z < s.maxZ + 0.15) f = s.top;
}
return f;
}
function spotFree(x, z, y) {
for (const s of solids) {
if (s.top <= y + STEP) continue;
const cx = clamp(x, s.minX, s.maxX), cz = clamp(z, s.minZ, s.maxZ);
if (Math.hypot(x - cx, z - cz) < R - 0.05) return false;
}
return true;
}
// Descreve a face do obstáculo voltada para o ponto (x, z): normal, tangente e extensão.
function faceInfo(s, x, z) {
const ex = x < s.minX ? x - s.minX : (x > s.maxX ? x - s.maxX : 0);
const ez = z < s.minZ ? z - s.minZ : (z > s.maxZ ? z - s.maxZ : 0);
let nx = 0, nz = 0;
if (ex === 0 && ez === 0) {
const l = x - s.minX, r = s.maxX - x, b = z - s.minZ, f = s.maxZ - z, m = Math.min(l, r, b, f);
if (m === l) nx = -1; else if (m === r) nx = 1; else if (m === b) nz = -1; else nz = 1;
} else if (Math.abs(ex) >= Math.abs(ez)) nx = ex > 0 ? 1 : -1;
else nz = ez > 0 ? 1 : -1;
const tx = -nz, tz = nx;
let face, t0, t1, thick;
if (nx !== 0) {
face = nx > 0 ? s.maxX : s.minX; thick = s.maxX - s.minX;
if (tz > 0) { t0 = s.minZ; t1 = s.maxZ; } else { t0 = -s.maxZ; t1 = -s.minZ; }
} else {
face = nz > 0 ? s.maxZ : s.minZ; thick = s.maxZ - s.minZ;
if (tx > 0) { t0 = s.minX; t1 = s.maxX; } else { t0 = -s.maxX; t1 = -s.minX; }
}
return { nx: nx, nz: nz, tx: tx, tz: tz, t0: t0, t1: t1, thick: thick, ox: nx !== 0 ? face : 0, oz: nx !== 0 ? 0 : face };
}
function facePos(info, along, dist) {
return [info.ox + info.tx * along + info.nx * dist, info.oz + info.tz * along + info.nz * dist];
}
const alongOf = (info, x, z) => x * info.tx + z * info.tz;
const distOf = (info, x, z) => (x - info.ox) * info.nx + (z - info.oz) * info.nz;
const clampAlong = (info, a, m) => {
const lo = info.t0 + m, hi = info.t1 - m;
return lo > hi ? (info.t0 + info.t1) / 2 : clamp(a, lo, hi);
};
const localXSign = (info, yaw) => (Math.cos(yaw) * info.tx - Math.sin(yaw) * info.tz) >= 0 ? 1 : -1;
// Empurra o boneco para fora das paredes (círculo contra caixa). Devolve a pior batida.
function resolveWalls() {
let inward = 0, hnx = 0, hnz = 0, hs = null;
for (let pass = 0; pass < 2; pass++) {
for (const s of solids) {
if (s.top <= P.y + STEP) continue;
const cx = clamp(P.x, s.minX, s.maxX), cz = clamp(P.z, s.minZ, s.maxZ);
let nx = P.x - cx, nz = P.z - cz, depth;
const d2 = nx * nx + nz * nz;
if (d2 >= R * R) continue;
if (d2 > 1e-8) {
const d = Math.sqrt(d2); nx /= d; nz /= d; depth = R - d;
} else {
const l = P.x - s.minX, r = s.maxX - P.x, b = P.z - s.minZ, f = s.maxZ - P.z, m = Math.min(l, r, b, f);
if (m === l) { nx = -1; nz = 0; depth = l + R; }
else if (m === r) { nx = 1; nz = 0; depth = r + R; }
else if (m === b) { nx = 0; nz = -1; depth = b + R; }
else { nx = 0; nz = 1; depth = f + R; }
}
P.x += nx * depth; P.z += nz * depth;
const vn = P.vx * nx + P.vz * nz;
if (vn < 0) {
P.vx -= vn * nx; P.vz -= vn * nz;
if (-vn > inward) { inward = -vn; hnx = nx; hnz = nz; hs = s; }
}
}
}
return { inward: inward, nx: hnx, nz: hnz, s: hs };
}
/* ---------- ações: pular mureta, subir na borda, escalar, abrigo ---------- */
function findAhead(dirx, dirz) { // obstáculo logo à frente do boneco
for (const d of [0.55, 0.85, 1.1]) {
const x = P.x + dirx * d, z = P.z + dirz * d;
for (const s of solids) {
if (s.top > P.y + STEP && x > s.minX - 0.05 && x < s.maxX + 0.05 && z > s.minZ - 0.05 && z < s.maxZ + 0.05) return s;
}
}
return null;
}
// Dois estilos, como nos jogos de ação: salto rápido com uma mão (em corrida) e salto seguro com as duas.
function startVault(s, info) {
const spd = Math.hypot(P.vx, P.vz);
const along = clampAlong(info, alongOf(info, P.x, P.z), 0.15);
const over = info.thick <= 1.5;
let end;
if (over) {
end = facePos(info, along, -(info.thick + 0.5));
const ey = floorAt(end[0], end[1], 0);
if (!spotFree(end[0], end[1], ey)) return false;
S.ey = ey;
} else {
end = facePos(info, along, -Math.min(info.thick / 2, 0.6));
S.ey = s.top;
}
S.vtype = (over && spd > 3.3) ? 'speed' : 'safety';
S.mode = 'vault'; S.t = 0; S.info = info; S.solid = s; S.over = over; S.vSpeed = spd;
S.dur = !over ? 0.6 : (S.vtype === 'speed' ? 0.52 : 0.72);
S.along0 = along; S.latSign = localXSign(info, P.yaw);
S.hand = Math.random() < 0.5 ? 0 : 1;
S.sx = P.x; S.sz = P.z; S.sy = P.y; S.ex = end[0]; S.ez = end[1];
S.arc = over ? (s.top - Math.min(P.y, S.ey)) + 0.18 : 0.25 + 0.4 * (s.top - P.y);
S.rollSign = Math.random() < 0.5 ? 1 : -1; S.yawOff = 0;
S.crouch = false;
P.vx = P.vz = P.vy = 0; coyote = 0; jumpBuf = 0;
cam.punch += 4;
return true;
}
function startMantle(s, info) {
S.mode = 'mantle'; S.t = 0; S.dur = 1.05; S.info = info; S.solid = s;
S.along0 = clampAlong(info, alongOf(info, P.x, P.z), 0.2);
S.latSign = localXSign(info, Math.atan2(-info.nx, -info.nz));
const end = facePos(info, S.along0, -Math.min(info.thick / 2, 0.4));
S.sx = P.x; S.sz = P.z; S.sy = P.y; S.ex = end[0]; S.ez = end[1]; S.ey = s.top;
S.crouch = false; S.upV = 0; S.hop = 0;
P.vx = P.vz = P.vy = 0; jumpBuf = 0;
}
function startClimb(s, info) {
const fromGround = P.grounded;
S.mode = 'climb'; S.info = info; S.solid = s; S.upV = 0; S.alongVel = 0; S.crouch = false;
S.along = clampAlong(info, alongOf(info, P.x, P.z), 0.2);
S.dist = distOf(info, P.x, P.z);
S.hop = fromGround ? 3.0 : 0; // salto curto para alcançar a primeira pegada
P.vx = P.vz = P.vy = 0; P.grounded = false; coyote = 0; jumpBuf = 0;
cam.punch += 2; cam.shake += 0.02;
}
function wallJump() {
const info = S.info;
S.mode = 'move';
P.vy = 6.4; P.vx = info.nx * 3.6; P.vz = info.nz * 3.6; P.grounded = false;
S.faceT = 0.4; S.faceYaw = Math.atan2(info.nx, info.nz);
A.airSide = 0; coyote = 0; jumpBuf = 0;
cam.punch += 4; cam.shake += 0.03;
}
function releaseWall(push) {
const info = S.info;
S.mode = 'move';
P.vx = info.nx * push; P.vz = info.nz * push; P.vy = 0; P.grounded = false;
}
function tryCover() {
let best = null, bestD = 1.05;
for (const s of solids) {
if (s.top < 0.45 || s.top > P.y + CLIMB_MAX) continue;
const cx = clamp(P.x, s.minX, s.maxX), cz = clamp(P.z, s.minZ, s.maxZ);
const d = Math.hypot(P.x - cx, P.z - cz);
if (d > 1e-6 && d < bestD) { bestD = d; best = s; }
}
if (!best) return false;
const info = faceInfo(best, P.x, P.z);
const spd = Math.hypot(P.vx, P.vz);
S.mode = 'cover'; S.info = info; S.solid = best; S.low = best.top < 1.5;
S.deepT = best.top >= 0.9 ? 1 : 0.7;
S.along = clampAlong(info, alongOf(info, P.x, P.z), 0.3);
S.dist = distOf(info, P.x, P.z);
S.alongVel = 0; S.awayT = 0; S.crouch = false;
P.vx = P.vz = P.vy = 0;
A.jVel -= Math.min(4, spd * 0.8); // entrando correndo: o tronco bate de costas na parede
cam.shake += 0.008 + Math.min(0.03, spd * 0.005);
return true;
}
function exitCover() {
const info = S.info;
S.mode = 'move';
P.vx = info.nx * 1.2; P.vz = info.nz * 1.2;
}
/* ---------- cinemática direta (posição dos 13 pontos do corpo a partir da pose atual) ---------- */
const mT = (m) => [m[0], m[3], m[6], m[1], m[4], m[7], m[2], m[5], m[8]];
function eulerXYZ(m) { // ordem XYZ, igual ao three.js
const y = Math.asin(clamp(m[2], -1, 1));
if (Math.abs(m[2]) < 0.9999999) return [Math.atan2(-m[5], m[8]), y, Math.atan2(-m[1], m[0])];
return [Math.atan2(m[7], m[4]), y, 0];
}
// pontos: 0-1 quadris, 2-3 ombros, 4 cabeça, 5-6 cotovelos, 7-8 mãos, 9-10 joelhos, 11-12 tornozelos
function fkPoints() {
const L = lastPose, Rr = rotY(L.yaw);
const Mh = mmul(Rr, mmul(rotX(L.hipRX), mmul(rotY(L.hipRY), rotZ(L.hipRZ))));
const Ms = mmul(Mh, mmul(rotX(L.spX), mmul(rotY(L.spY), rotZ(L.spZ))));
const c0 = [P.x, P.y + L.hipY, P.z];
const add = (a, m, v) => { const r = mvec(m, v); return [a[0] + r[0], a[1] + r[1], a[2] + r[2]]; };
const so = add(c0, Mh, [0, 0.1, 0]);
const pts = new Array(13);
for (let i = 0; i < 2; i++) {
const sd = i === 0 ? 1 : -1;
const hj = add(c0, Mh, [sd * 0.1, -0.06, 0]);
const Mt = mmul(Mh, mmul(rotX(L.th[i]), rotZ(L.thz[i])));
const kn = add(hj, Mt, [0, -THIGH_LEN, 0]);
const ft = add(kn, mmul(Mt, rotX(L.kn[i])), [0, -SHIN_LEN, 0]);
const sh = add(so, Ms, [sd * 0.28, 0.4, 0]);
const Mu = mmul(Ms, mmul(rotX(L.shx[i]), rotZ(L.shz[i])));
const el = add(sh, Mu, [0, -UP_LEN, 0]);
const hd = add(el, mmul(Mu, rotX(L.elx[i])), [0, -FORE_LEN, 0]);
pts[i] = hj; pts[2 + i] = sh; pts[5 + i] = el; pts[7 + i] = hd; pts[9 + i] = kn; pts[11 + i] = ft;
}
pts[4] = add(so, Ms, [0, 0.71, 0]);
return pts;
}
/* ---------- ragdoll: pontos com gravidade, distâncias fixas e colisão com chão e paredes ---------- */
const RG = { p: [], q: [], t: 0, acc: 0, Mh: null, Mc: null, c0: null, vals: null };
const RG_R = [0.1, 0.1, 0.08, 0.08, 0.13, 0.07, 0.07, 0.07, 0.07, 0.08, 0.08, 0.07, 0.07];
const RG_C = (function () {
const loc = [[0.1, -0.06, 0], [-0.1, -0.06, 0], [0.28, 0.5, 0], [-0.28, 0.5, 0], [0, 0.81, 0]];
const dd = (a, b) => Math.hypot(loc[a][0] - loc[b][0], loc[a][1] - loc[b][1], loc[a][2] - loc[b][2]);
const c = [];
[[0, 1], [2, 3], [0, 2], [1, 3], [0, 3], [1, 2], [4, 2], [4, 3], [4, 0], [4, 1]].forEach(function (e) { c.push([e[0], e[1], dd(e[0], e[1])]); });
c.push([2, 5, UP_LEN], [5, 7, FORE_LEN], [3, 6, UP_LEN], [6, 8, FORE_LEN], [0, 9, THIGH_LEN], [9, 11, SHIN_LEN], [1, 10, THIGH_LEN], [10, 12, SHIN_LEN]);
return c;
})();
const v3sub = (a, b) => [a[0] - b[0], a[1] - b[1], a[2] - b[2]];
const v3nrm = (v) => { const l = Math.hypot(v[0], v[1], v[2]) || 1; return [v[0] / l, v[1] / l, v[2] / l]; };
const v3cross = (a, b) => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
const v3dot = (a, b) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
const v3mid = (a, b) => [(a[0] + b[0]) / 2, (a[1] + b[1]) / 2, (a[2] + b[2]) / 2];
function frameOf(xv, upv) {
const x = v3nrm(xv), d = v3dot(upv, x);
const y = v3nrm([upv[0] - x[0] * d, upv[1] - x[1] * d, upv[2] - x[2] * d]);
const z = v3cross(x, y);
return [x[0], y[0], z[0], x[1], y[1], z[1], x[2], y[2], z[2]];
}
function startRagdoll(vx, vy, vz) {
const pts = fkPoints();
RG.p = pts.map((a) => a.slice());
RG.q = pts.map((a) => [a[0] - vx / 120, a[1] - vy / 120, a[2] - vz / 120]);
RG.t = 0; RG.acc = 0;
S.mode = 'ragdoll'; S.crouch = false;
P.vx = P.vy = P.vz = 0; P.grounded = false; jumpBuf = 0;
cam.shake += 0.07; cam.punch -= 3; cam.dipV -= 2;
}
function ragSub(h) {
const p = RG.p, q = RG.q;
const late = RG.t > 2.6 ? 0.94 : 0.996;
const mh = v3mid(p[0], p[1]), ms = v3mid(p[2], p[3]);
const xa = v3nrm(v3sub(p[2], p[3])), ya = v3nrm(v3sub(ms, mh));
const fw = v3cross(xa, ya);
for (let i = 0; i < 13; i++) {
const a = p[i], b = q[i];
let ax = 0, ay = -14, az = 0;
if (i === 9 || i === 10) { ax += fw[0] * 6; ay += fw[1] * 6; az += fw[2] * 6; } // joelhos dobram para a frente
if (i === 5 || i === 6) { ax -= fw[0] * 5; ay -= fw[1] * 5; az -= fw[2] * 5; } // cotovelos para trás
let dx = (a[0] - b[0]) * late + ax * h * h, dy = (a[1] - b[1]) * late + ay * h * h, dz = (a[2] - b[2]) * late + az * h * h;
const dl = Math.hypot(dx, dy, dz);
if (dl > 0.25) { const k = 0.25 / dl; dx *= k; dy *= k; dz *= k; }
b[0] = a[0]; b[1] = a[1]; b[2] = a[2];
a[0] += dx; a[1] += dy; a[2] += dz;
}
for (let it = 0; it < 6; it++) {
for (const c of RG_C) {
const a = p[c[0]], b = p[c[1]];
let dx = b[0] - a[0], dy = b[1] - a[1], dz = b[2] - a[2];
const d = Math.hypot(dx, dy, dz) || 1e-6, f = (d - c[2]) / d * 0.5;
dx *= f; dy *= f; dz *= f;
a[0] += dx; a[1] += dy; a[2] += dz; b[0] -= dx; b[1] -= dy; b[2] -= dz;
}
[[2, 7, 0.24], [3, 8, 0.24], [0, 11, 0.32], [1, 12, 0.32]].forEach(function (c) { // limites: braço e perna não dobram demais
const a = p[c[0]], b = p[c[1]];
let dx = b[0] - a[0], dy = b[1] - a[1], dz = b[2] - a[2];
const d = Math.hypot(dx, dy, dz) || 1e-6;
if (d < c[2]) {
const f = (d - c[2]) / d * 0.5; dx *= f; dy *= f; dz *= f;
a[0] += dx; a[1] += dy; a[2] += dz; b[0] -= dx; b[1] -= dy; b[2] -= dz;
}
});
for (let i = 0; i < 13; i++) {
const a = p[i], b = q[i], r = RG_R[i];
if (a[1] < r) {
const vy = a[1] - b[1];
a[1] = r; b[1] = r + Math.min(0, vy) * 0.12;
b[0] += (a[0] - b[0]) * 0.25; b[2] += (a[2] - b[2]) * 0.25;
}
for (const s of solids) {
if (a[0] > s.minX - r && a[0] < s.maxX + r && a[2] > s.minZ - r && a[2] < s.maxZ + r && a[1] < s.top + r) {
const l = a[0] - (s.minX - r), rr = (s.maxX + r) - a[0], bk = a[2] - (s.minZ - r), fr = (s.maxZ + r) - a[2], tp = (s.top + r) - a[1];
const mn = Math.min(l, rr, bk, fr, tp);
if (mn === tp) { a[1] = s.top + r; b[1] = a[1]; b[0] += (a[0] - b[0]) * 0.25; b[2] += (a[2] - b[2]) * 0.25; }
else if (mn === l) { a[0] = s.minX - r; b[0] = a[0]; }
else if (mn === rr) { a[0] = s.maxX + r; b[0] = a[0]; }
else if (mn === bk) { a[2] = s.minZ - r; b[2] = a[2]; }
else { a[2] = s.maxZ + r; b[2] = a[2]; }
}
}
}
}
}
function stepRagdoll(dt) {
RG.t += dt; RG.acc = Math.min(RG.acc + dt, 0.05);
while (RG.acc >= 1 / 120) { ragSub(1 / 120); RG.acc -= 1 / 120; }
const c = v3mid(RG.p[0], RG.p[1]);
P.x = c[0]; P.z = c[2]; P.y = c[1] - 1.0;
if (RG.t >= 4) endRagdoll();
}
// Liga os pontos ao esqueleto de blocos: cada osso aponta do ombro ao cotovelo, etc.
function applyRagdoll() {
const p = RG.p;
const mh = v3mid(p[0], p[1]), ms = v3mid(p[2], p[3]);
const up = v3sub(ms, mh);
const Mh = frameOf(v3sub(p[0], p[1]), up);
const hd = v3sub(p[4], ms);
const Mc = frameOf(v3sub(p[2], p[3]), [up[0] + hd[0] * 0.6, up[1] + hd[1] * 0.6, up[2] + hd[2] * 0.6]);
const c0 = [mh[0] + Mh[1] * 0.06, mh[1] + Mh[4] * 0.06, mh[2] + Mh[7] * 0.06];
RG.Mh = Mh; RG.Mc = Mc; RG.c0 = c0;
const v = { shx: [0, 0], shz: [0, 0], elx: [0, 0], elz: [0, 0], th: [0, 0], thz: [0, 0], kn: [0, 0], knz: [0, 0] };
const eh = eulerXYZ(Mh), es = eulerXYZ(mmul(mT(Mh), Mc));
hips.position.set(c0[0], c0[1], c0[2]);
hips.rotation.set(eh[0], eh[1], eh[2]);
spine.rotation.set(es[0], es[1], es[2]);
const nb = [c0[0] + Mh[1] * 0.1 + Mc[1] * 0.47, c0[1] + Mh[4] * 0.1 + Mc[4] * 0.47, c0[2] + Mh[7] * 0.1 + Mc[7] * 0.47];
const nl = mtvec(Mc, v3nrm(v3sub(p[4], nb)));
const na = -Math.asin(clamp(nl[0], -1, 1)), nbx = Math.atan2(nl[2], nl[1]);
neck.rotation.set(nbx, 0, na);
const hang = (M, d) => { const l = mtvec(M, v3nrm(d)); const a = Math.asin(clamp(l[0], -1, 1)); return [Math.atan2(-l[2], -l[1]), a]; };
for (let i = 0; i < 2; i++) {
const u = hang(Mc, v3sub(p[5 + i], p[2 + i]));
arms[i].sh.rotation.set(u[0], 0, u[1]);
const Mu = mmul(Mc, mmul(rotX(u[0]), rotZ(u[1])));
const f = hang(Mu, v3sub(p[7 + i], p[5 + i]));
arms[i].el.rotation.set(f[0], 0, f[1]);
const t = hang(Mh, v3sub(p[9 + i], p[i]));
legs[i].hp.rotation.set(t[0], 0, t[1]);
const Mt = mmul(Mh, mmul(rotX(t[0]), rotZ(t[1])));
const s = hang(Mt, v3sub(p[11 + i], p[9 + i]));
legs[i].kn.rotation.set(s[0], 0, s[1]);
legs[i].an.rotation.set(0, 0, 0);
v.shx[i] = u[0]; v.shz[i] = u[1]; v.elx[i] = f[0]; v.elz[i] = f[1];
v.th[i] = t[0]; v.thz[i] = t[1]; v.kn[i] = s[0]; v.knz[i] = s[1];
}
v.neX = nbx; v.neZ = na; v.sp = es;
RG.vals = v;
}
function endRagdoll() {
const Mc = RG.Mc, Mh = RG.Mh, c0 = RG.c0, v = RG.vals;
const prone = Mc[5] < 0;
const hx = Mc[1], hz = Mc[7];
const yaw = Math.hypot(hx, hz) > 0.25 ? (prone ? Math.atan2(hx, hz) : Math.atan2(-hx, -hz)) : cam.yaw;
P.x = c0[0]; P.z = c0[2]; P.yaw = yaw; P.vx = P.vy = P.vz = 0;
P.y = floorAt(P.x, P.z, c0[1]); P.grounded = true;
const eh = eulerXYZ(mmul(rotY(-yaw), Mh));
A.snap = {
hipRX: eh[0], hipRY: eh[1], hipRZ: eh[2], hipY: Math.max(0.14, c0[1] - P.y),
spX: v.sp[0], spY: v.sp[1], spZ: v.sp[2], neX: v.neX, neZ: v.neZ,
shx: v.shx, shz: v.shz, elx: v.elx, elz: v.elz, th: v.th, thz: v.thz, kn: v.kn, knz: v.knz
};
A.snapW = 1;
startGetup(prone, 2.2, false);
}
/* ---------- levantar do chão (de bruços ou de costas) ---------- */
const GU_PRONE = [
{ t: 0, rx: 1.5, sp: -0.1, th: 0.05, kn: 0.1, shx: -2.3, shz: 0.4, elx: -1.8, ne: -0.8 },
{ t: 0.3, rx: 1.2, sp: -0.1, th: 0, kn: 0.1, shx: -1.2, shz: 0.2, elx: -0.1, ne: -0.7 },
{ t: 0.58, rx: 0.7, sp: 0.15, th: -1.3, kn: 2.3, shx: -1.0, shz: 0.15, elx: -0.4, ne: -0.4 },
{ t: 0.8, rx: 0.2, sp: 0.35, th: -1.4, kn: 2.6, shx: -0.9, shz: 0.15, elx: -1.2, ne: -0.3 },
{ t: 1, rx: 0, sp: 0.04, th: 0, kn: 0.05, shx: 0, shz: 0.09, elx: -0.12, ne: 0 }
];
const GU_SUPINE = [
{ t: 0, rx: -1.5, sp: 0.05, th: 0.05, kn: 0.05, shx: 0.1, shz: 0.35, elx: -0.2, ne: 0.4 },
{ t: 0.3, rx: -0.55, sp: 0.3, th: -1.0, kn: 0.05, shx: -0.95, shz: 0.2, elx: -0.3, ne: -0.2 },
{ t: 0.58, rx: -0.1, sp: 0.45, th: -1.5, kn: 2.3, shx: -1.0, shz: 0.15, elx: -0.6, ne: -0.3 },
GU_PRONE[3], GU_PRONE[4]
];
function getupKey(t, prone) {
const K = prone ? GU_PRONE : GU_SUPINE;
t = clamp(t, 0, 1);
let i = 0;
while (i < K.length - 2 && t > K[i + 1].t) i++;
const a = K[i], b = K[i + 1], lin = clamp((t - a.t) / (b.t - a.t), 0, 1);
const u = lerp(lin, smooth(0, 1, lin), 0.7), o = {};
for (const k in a) if (k !== 't') o[k] = lerp(a[k], b[k], u);
return o;
}
function startGetup(prone, dur, crouch) {
S.mode = 'getup'; S.gT = 0; S.gDur = dur; S.gProne = prone; S.gCrouch = crouch;
P.vx = P.vz = P.vy = 0; S.crouch = false; jumpBuf = 0;
}
function stepGetup(dt) {
S.gT += dt;
resolveWalls();
if (S.gT >= S.gDur) { S.mode = 'move'; S.crouch = S.gCrouch; P.grounded = true; }
}
/* ---------- deslizar no chão, mergulho e rastejar (Omnimovement) ---------- */
function startSlide() {
const sp = Math.hypot(P.vx, P.vz) || 1;
S.mode = 'slide'; S.t = 0; S.slideV0 = Math.max(sp, 5.5) * 1.12; S.slideV = S.slideV0;
S.diveDir = [P.vx / sp, P.vz / sp]; S.crouch = false;
cam.punch += 3; cam.dipV -= 1.5; cam.shake += 0.01;
}
function endSlide(toCrouch) {
S.mode = 'move'; S.crouch = toCrouch;
P.vx = S.diveDir[0] * Math.min(S.slideV, 2.4); P.vz = S.diveDir[1] * Math.min(S.slideV, 2.4);
}
function stepSlide(dt, inp, dx, dz) {
S.t += dt;
if (act.crouch) { act.crouch = false; endSlide(true); return; } // agachar cancela o deslize
if (inp.mag > 0.1) { // dá para curvar um pouco durante o deslize
const cur = Math.atan2(S.diveDir[0], S.diveDir[1]), want = Math.atan2(dx, dz);
const na = cur + clamp(angDiff(cur, want), -1.1 * dt, 1.1 * dt);
S.diveDir = [Math.sin(na), Math.cos(na)];
}
S.slideV = S.slideV0 * Math.exp(-1.25 * S.t);
P.vx = S.diveDir[0] * S.slideV; P.vz = S.diveDir[1] * S.slideV;
P.x += P.vx * dt; P.z += P.vz * dt;
const hit = resolveWalls();
P.yaw += angDiff(P.yaw, Math.atan2(S.diveDir[0], S.diveDir[1])) * damp(12, dt);
const fl = floorAt(P.x, P.z, P.y);
if (P.y > fl + 0.02) { S.mode = 'move'; P.grounded = false; return; }
P.y = fl; P.grounded = true;
if (jumpBuf > 0) {
jumpBuf = 0; S.mode = 'move'; P.vy = JUMP_V * 0.85; P.grounded = false; cam.punch += 3; return;
}
if (hit.inward > 1.5) { cam.shake += 0.02; endSlide(true); return; }
if (S.slideV < 1.8 || S.t > 1.2) endSlide(true);
}
function startDive(inp, dx, dz) {
const has = inp.mag > 0.1;
const ddx = has ? dx : Math.sin(cam.yaw), ddz = has ? dz : Math.cos(cam.yaw);
const a = angDiff(cam.yaw, Math.atan2(ddx, ddz)); // direção do mergulho em relação a onde se olha
S.diveKind = (!has || Math.abs(a) < 0.8) ? 0 : (Math.abs(a) > 2.35 ? 1 : 2); // 0 frente, 1 costas, 2 lado
S.diveSide = a >= 0 ? 1 : -1;
S.mode = 'dive'; S.t = 0; S.crouch = false;
P.vx = ddx * 6.8; P.vz = ddz * 6.8; P.vy = 5.2; P.grounded = false;
S.diveYaw = cam.yaw; S.diveDir = [ddx, ddz];
coyote = 0; jumpBuf = 0;
cam.punch += 5; cam.shake += 0.02;
}
function stepDive(dt) {
S.t += dt;
P.vy -= 15 * dt;
P.x += P.vx * dt; P.z += P.vz * dt;
const hit = resolveWalls();
if (hit.inward > 3.5) {
P.vx += hit.nx * hit.inward * 0.35; P.vz += hit.nz * hit.inward * 0.35;
startRagdoll(P.vx, P.vy, P.vz); return;
}
P.y += P.vy * dt;
S.diveYaw = cam.yaw; // o corpo olha para onde a câmera olha, qualquer que seja a direção do mergulho
P.yaw += angDiff(P.yaw, S.diveYaw) * damp(20, dt);
const fl = floorAt(P.x, P.z, P.y);
if (P.vy <= 0 && P.y <= fl + 0.0005) {
P.y = fl; P.vy = 0; P.grounded = true;
S.mode = 'prone'; S.t = 0; S.slideV = Math.hypot(P.vx, P.vz) * 0.9;
S.lyRx = S.diveKind === 1 ? -1.5 : 1.5; // de costas se mergulhou para trás
S.lyTw = S.diveKind === 2 ? -S.diveSide * 1.4 : 0; // de lado se mergulhou de lado
A.landImpact = Math.max(A.landImpact, 0.25); cam.shake += 0.03; cam.dipV -= 2.5;
}
}
function stepProne(dt, inp, dx, dz) {
S.t += dt;
if (S.slideV > 0.45) { // escorregando de peito depois do mergulho
S.slideV *= Math.exp(-3.0 * dt);
P.vx = S.diveDir[0] * S.slideV; P.vz = S.diveDir[1] * S.slideV;
P.yaw += angDiff(P.yaw, cam.yaw) * damp(14, dt);
} else { // rasteja em qualquer direção e gira livre
S.slideV = 0;
const sp = 1.05 * inp.mag;
P.vx += (dx * sp - P.vx) * damp(10, dt); P.vz += (dz * sp - P.vz) * damp(10, dt);
P.yaw += angDiff(P.yaw, cam.yaw) * damp(9, dt);
S.lyTw += (0 - S.lyTw) * damp(2.5, dt); // se estava de lado, rola para a barriga
}
P.x += P.vx * dt; P.z += P.vz * dt;
resolveWalls();
P.y = floorAt(P.x, P.z, P.y); P.grounded = true; P.vy = 0;
if (S.t > 0.45 && S.slideV < 2) {
if (jumpBuf > 0) { jumpBuf = 0; startGetup(S.lyRx > 0, 0.95, false); return; }
if (act.crouch) { act.crouch = false; startGetup(S.lyRx > 0, 0.8, true); return; }
}
if (act.dive && S.t > 0.45 && S.slideV < 2) { act.dive = false; startDive(inp, dx, dz); }
}
/* ---------- um passo em cada modo ---------- */
function stepVault(dt) {
S.t += dt / S.dur;
const t = clamp(S.t, 0, 1), speed = S.vtype === 'speed';
const u = speed ? t : smooth(0, 1, t); // o salto rápido mantém o embalo
P.x = lerp(S.sx, S.ex, u); P.z = lerp(S.sz, S.ez, u);
P.y = lerp(S.sy, S.ey, smooth(0, 1, t)) + S.arc * Math.sin(Math.PI * t);
P.vx = P.vz = P.vy = 0;
const yt = Math.atan2(-S.info.nx, -S.info.nz);
P.yaw += angDiff(P.yaw, yt) * damp(16, dt);
S.yawOff = speed ? -(S.hand === 0 ? 1 : -1) * 0.45 * Math.sin(Math.PI * t) : 0;
if (S.t >= 1) {
P.x = S.ex; P.z = S.ez; P.y = S.ey; P.grounded = true;
const carry = speed ? Math.max(S.vSpeed, 3.8) : 2.2;
P.vx = -S.info.nx * carry; P.vz = -S.info.nz * carry;
S.mode = 'move'; S.yawOff = 0;
A.landImpact = Math.max(A.landImpact, speed ? 0.18 : 0.26);
cam.shake += 0.012; cam.dipV -= 0.8;
}
}
function stepMantle(dt) {
S.t += dt / S.dur;
const m = clamp(S.t, 0, 1);
const yA = Math.max(S.sy, S.ey - 1.2); // peito na altura da borda
P.y = m < 0.4 ? lerp(S.sy, yA, smooth(0, 0.4, m)) : lerp(yA, S.ey, smooth(0.4, 1, m));
const u = smooth(0.42, 1, m);
P.x = lerp(S.sx, S.ex, u); P.z = lerp(S.sz, S.ez, u);
P.vx = P.vz = P.vy = 0;
const yt = Math.atan2(-S.info.nx, -S.info.nz);
P.yaw += angDiff(P.yaw, yt) * damp(16, dt);
if (S.t >= 1) {
P.x = S.ex; P.z = S.ez; P.y = S.ey; P.grounded = true;
S.mode = 'move';
A.landImpact = Math.max(A.landImpact, 0.3);
cam.shake += 0.02; cam.dipV -= 1.2; cam.punch += 2;
}
}
function stepClimb(dt, inp, dx, dz) {
const info = S.info, s = S.solid;
const into = -(dx * info.nx + dz * info.nz) * inp.mag;
const lat = (dx * info.tx + dz * info.tz) * inp.mag;
S.upV += ((into > 0.3 ? 1.6 * into : (into < -0.3 ? 2.2 * into : 0)) - S.upV) * damp(12, dt);
S.alongVel += (lat * 1.2 - S.alongVel) * damp(12, dt);
P.y = Math.max(0, P.y + (S.upV + S.hop) * dt);
S.hop *= Math.exp(-6 * dt);
S.along = clampAlong(info, S.along + S.alongVel * dt, 0.2);
S.dist += (CLIMB_DIST - S.dist) * damp(12, dt);
const pos = facePos(info, S.along, S.dist);
P.x = pos[0]; P.z = pos[1];
P.vx = P.vz = P.vy = 0;
const yt = Math.atan2(-info.nx, -info.nz);
P.yaw += angDiff(P.yaw, yt) * damp(14, dt);
if (jumpBuf > 0) { wallJump(); return; }
if (act.cover || act.crouch) { act.cover = act.crouch = false; releaseWall(0.6); return; }
if (P.y <= 0.001 && S.upV < -0.1) { S.mode = 'move'; P.grounded = true; P.y = 0; return; }
if (s.top - P.y <= REACH && into > 0.2) startMantle(s, info);
}
function stepCover(dt, inp, dx, dz) {
const info = S.info, s = S.solid;
const sp = S.low ? 1.4 : 1.9;
const along = dx * info.tx + dz * info.tz;
const away = dx * info.nx + dz * info.nz;
S.alongVel += (along * inp.mag * sp - S.alongVel) * damp(14, dt);
S.along = clampAlong(info, S.along + S.alongVel * dt, 0.3);
const mv = smooth(0.15, 0.7, Math.abs(S.alongVel) / sp);
// mureta: de costas para ela parado; ao andar vira de lado e anda agachado rente ao muro.
// parede alta: costas coladas, passo lateral.
const yawBack = Math.atan2(info.nx, info.nz);
let yt = yawBack;
if (S.low) {
const dirT = S.alongVel >= 0 ? 1 : -1;
yt = yawBack + angDiff(yawBack, Math.atan2(info.tx * dirT, info.tz * dirT)) * mv;
}
P.yaw += angDiff(P.yaw, yt) * damp(10, dt);
S.dist += ((S.low ? lerp(COVER_LOW_DIST, 0.34, mv) : COVER_HIGH_DIST) - S.dist) * damp(12, dt);
const pos = facePos(info, S.along, S.dist);
P.x = pos[0]; P.z = pos[1];
P.vx = P.vz = P.vy = 0;
if (Math.abs(S.alongVel) > 0.15) {
const lx = Math.cos(yawBack), lz = -Math.sin(yawBack);
S.dirLocal = (info.tx * lx + info.tz * lz) * S.alongVel >= 0 ? 1 : -1;
const rxv = -Math.cos(cam.yaw), rzv = Math.sin(cam.yaw);
S.coverSide = (info.tx * rxv + info.tz * rzv) * S.alongVel >= 0 ? 1 : -1;
}
if (jumpBuf > 0) {
jumpBuf = 0;
const rise = s.top - P.y;
if (S.low && rise <= VAULT_MAX && startVault(s, info)) return;
if (S.low && rise <= CLIMB_MAX) { startClimb(s, info); return; }
exitCover(); return;
}
if (act.cover) { act.cover = false; exitCover(); return; }
if (inp.mag > 0.1 && away > 0.7) { S.awayT += dt; if (S.awayT > 0.25) exitCover(); }
else S.awayT = 0;
}
function stepMove(dt, inp, dx, dz) {
const ctrl = !!keys.ControlLeft;
if (act.dive) { act.dive = false; if (P.grounded) { startDive(inp, dx, dz); return; } }
if (act.crouch) {
act.crouch = false;
if (P.grounded) {
if (Math.hypot(P.vx, P.vz) > 3.9 && inp.mag > 0.1) { startSlide(); return; }
S.crouch = !S.crouch;
}
}
if (inp.run && inp.mag > 0.1 && !ctrl) S.crouch = false;
btnCrouch.setAttribute('aria-pressed', S.crouch ? 'true' : 'false');
const crouchNow = S.crouch || ctrl;
if (act.cover) { act.cover = false; if (P.grounded && tryCover()) return; }
const hasDir = inp.mag > 0.1;
const fdx = hasDir ? dx : Math.sin(P.yaw), fdz = hasDir ? dz : Math.cos(P.yaw);
// pular mureta / escalar, quando há obstáculo na frente
coyote = P.grounded ? 0.1 : coyote - dt;
if (jumpBuf > 0 && P.grounded) {
const s = findAhead(fdx, fdz);
if (s) {
const info = faceInfo(s, P.x, P.z);
const headOn = (fdx * -info.nx + fdz * -info.nz) > 0.5;
const rise = s.top - P.y;
if (headOn && rise <= VAULT_MAX && startVault(s, info)) return;
if (headOn && rise > VAULT_MAX && rise <= CLIMB_MAX) { startClimb(s, info); return; }
}
}
const target = inp.mag * (crouchNow ? CROUCH : (inp.run ? RUN : WALK));
let ddx = dx * target - P.vx, ddz = dz * target - P.vz;
const dl = Math.hypot(ddx, ddz);
const acc = P.grounded ? (inp.mag > 0 ? 24 : 32) : 6;
const maxd = acc * dt;
if (dl > maxd) { ddx *= maxd / dl; ddz *= maxd / dl; }
P.vx += ddx; P.vz += ddz;
// pulo comum (com tolerância de apertar um pouco antes ou depois do chão)
jumpBuf = Math.max(0, jumpBuf - dt);
if (jumpBuf > 0 && coyote > 0) {
P.vy = JUMP_V; P.grounded = false; coyote = 0; jumpBuf = 0; S.crouch = false;
A.airSide = Math.sin(A.phase) >= 0 ? 0 : 1;
cam.punch += 3;
}
const wasGrounded = P.grounded;
P.vy -= GRAVITY * dt;
P.x += P.vx * dt; P.z += P.vz * dt;
const hit = resolveWalls();
if (hit.inward > 2) { // bateu de frente: tronco balança e quica um pouco
A.jVel += hit.inward * 1.1;
P.vx += hit.nx * hit.inward * 0.08;
P.vz += hit.nz * hit.inward * 0.08;
cam.shake += Math.min(0.05, hit.inward * 0.008);
cam.punch -= Math.min(2, hit.inward * 0.3);
}
// bateu de cara numa parede alta demais para alcançar a quina: ragdoll
if (!wasGrounded && hit.s && hit.inward > 3.0 && hit.s.top - P.y > 2.4) {
P.vx += hit.nx * hit.inward * 0.35; P.vz += hit.nz * hit.inward * 0.35;
startRagdoll(P.vx, Math.min(P.vy, 0), P.vz); return;
}
// pulou contra a parede: agarra a borda ou fica pendurado nela
if (!wasGrounded && hit.s && hit.inward > 1.0) {
const rise = hit.s.top - P.y;
if (rise > 0.5 && rise <= 2.4) { // alcança a quina: se segura, sem ragdoll
const info = faceInfo(hit.s, P.x, P.z);
if (rise <= REACH) startMantle(hit.s, info); else startClimb(hit.s, info);
cam.shake += 0.025;
return;
}
}
P.y += P.vy * dt;
const fl = floorAt(P.x, P.z, P.y);
if (P.vy <= 0 && P.y <= fl + 0.0005 && !wasGrounded && P.vy < -10) { // queda de lugar alto: ragdoll
P.y = fl; startRagdoll(P.vx, P.vy, P.vz); return;
}
if (P.vy <= 0 && P.y <= fl + 0.0005) {
if (!wasGrounded && P.vy < -2.5) {
const imp = clamp((-P.vy - 2) / 8, 0, 1);
A.landImpact = Math.max(A.landImpact, imp);
cam.dipV -= 4 * imp; cam.shake += 0.012 + 0.05 * imp; cam.punch -= 3 * imp;
}
P.y = fl; P.vy = 0; P.grounded = true;
} else {
P.grounded = false;
}
P.x = clamp(P.x, -55, 55); P.z = clamp(P.z, -55, 55);
// para onde o boneco olha
if (S.faceT > 0) {
S.faceT -= dt;
P.yaw += angDiff(P.yaw, S.faceYaw) * damp(18, dt);
} else if (hasDir) {
P.yaw += angDiff(P.yaw, Math.atan2(dx, dz)) * damp(P.grounded ? 14 : 6, dt);
}
}
/* ---------- contexto de parede para a pose ---------- */
function wallContext(inp, dx, dz) {
const c = { wallHead: 0, wallSide: 0, wallSign: 1, reach: 0.38, plant: 0, wall: null };
let best = null, bestD = 1e9, bestS = null;
for (const s of solids) {
if (s.top <= P.y + STEP) continue;
const cx = clamp(P.x, s.minX, s.maxX), cz = clamp(P.z, s.minZ, s.maxZ);
const nx = P.x - cx, nz = P.z - cz, d = Math.hypot(nx, nz);
if (d > 1e-6 && d < R + 0.7 && d < bestD) { bestD = d; best = { nx: nx / d, nz: nz / d }; bestS = s; }
}
if (!best) return c;
const gap = bestD - R;
const fx = Math.sin(P.yaw), fz = Math.cos(P.yaw);
const xx = Math.cos(P.yaw), xz = -Math.sin(P.yaw);
const toX = -best.nx, toZ = -best.nz; // direção da parede
const front = toX * fx + toZ * fz;
const sideDot = toX * xx + toZ * xz;
const pushing = inp.mag > 0.1 && (dx * toX + dz * toZ) > 0.35;
c.wallHead = pushing ? smooth(0.4, 0.8, front) * smooth(0.6, 0.05, gap) : 0;
c.wallSide = smooth(0.35, 0.75, Math.abs(sideDot)) * (1 - c.wallHead) * clamp(A.speedS / 1.0, 0, 1) * smooth(0.5, 0.05, gap);
c.wallSign = sideDot >= 0 ? 1 : -1;
c.reach = clamp(Math.asin(clamp((bestD - 0.285) / 0.52, 0.2, 1)), 0.2, 1.1);
c.plant = (!P.grounded && front > 0.6 && gap < 0.3) ? 1 : 0;
c.wall = { info: faceInfo(bestS, P.x, P.z), s: bestS, gap: gap };
return c;
}
/* ---------- alvos das mãos e dos pés (em coordenadas do mundo) ---------- */
function buildIK(c) {
const T = { arm: [null, null], leg: [null, null] };
const yawV = c.yawVis;
const cx = Math.cos(yawV), sx = -Math.sin(yawV); // eixo x local do boneco
const fx = Math.sin(yawV), fz = Math.cos(yawV); // frente do boneco
const sideOf = (i) => (i === 0 ? 1 : -1);
if (S.mode === 'move' && c.wall) {
const w = c.wall;
if (c.wallHead > 0.02) {
// empurrando de frente: as duas mãos espalmadas na parede, na altura do peito
for (let i = 0; i < 2; i++) {
const side = sideOf(i);
const al = clamp(alongOf(w.info, P.x + cx * side * 0.2, P.z + sx * side * 0.2), w.info.t0 + 0.1, w.info.t1 - 0.1);
const p = facePos(w.info, al, 0.045);
T.arm[i] = { x: p[0], y: P.y + 1.3 - 0.3 * A.cr, z: p[1], w: c.wallHead };
}
} else if (c.wallSide > 0.02) {
// passando rente: a mão do lado da parede encosta e acompanha
const i = c.wallSign > 0 ? 0 : 1, side = c.wallSign;
const al = clamp(alongOf(w.info, P.x + cx * side * 0.25 + fx * 0.12, P.z + sx * side * 0.25 + fz * 0.12), w.info.t0 + 0.1, w.info.t1 - 0.1);
const p = facePos(w.info, al, 0.045);
T.arm[i] = { x: p[0], y: P.y + 1.0 - 0.25 * A.cr, z: p[1], w: c.wallSide };
}
} else if (S.mode === 'vault') {
const m = clamp(S.t, 0, 1), info = S.info, s = S.solid, speed = S.vtype === 'speed';
const wPlant = smooth(0.1, 0.28, m) * (1 - smooth(speed ? 0.68 : 0.8, speed ? 0.8 : 0.92, m));
for (let i = 0; i < 2; i++) {
if (speed && i !== S.hand) continue;
const al = clampAlong(info, S.along0 + S.latSign * sideOf(i) * 0.2, 0.05);
const p = facePos(info, al, -Math.min(info.thick / 2, 0.3));
T.arm[i] = { x: p[0], y: s.top + 0.04, z: p[1], w: wPlant };
}
} else if (S.mode === 'mantle') {
const m = clamp(S.t, 0, 1), info = S.info, s = S.solid;
const wHand = smooth(0, 0.1, m) * (1 - smooth(0.75, 0.92, m));
for (let i = 0; i < 2; i++) {
const al = clampAlong(info, S.along0 + S.latSign * sideOf(i) * 0.2, 0.05);
const p = facePos(info, al, -0.12);
T.arm[i] = { x: p[0], y: s.top + 0.04, z: p[1], w: wHand };
}
// perna de apoio na parede o tempo todo; a outra sobe para a borda na segunda metade
const wallFoot = facePos(info, clampAlong(info, S.along0 - S.latSign * 0.12, 0.05), 0.2);
T.leg[1] = { x: wallFoot[0], y: P.y + 0.2, z: wallFoot[1], w: 1 - smooth(0.4, 0.62, m) };
if (m < 0.45) {
const f0 = facePos(info, clampAlong(info, S.along0 + S.latSign * 0.12, 0.05), 0.2);
T.leg[0] = { x: f0[0], y: P.y + 0.12, z: f0[1], w: 1 - smooth(0.3, 0.45, m) };
} else {
const f0 = facePos(info, clampAlong(info, S.along0 + S.latSign * 0.1, 0.05), -0.25);
T.leg[0] = { x: f0[0], y: s.top + 0.135, z: f0[1], w: smooth(0.45, 0.58, m) * (1 - smooth(0.88, 0.98, m)) };
}
} else if (S.mode === 'climb') {
const info = S.info, s = S.solid, cp = A.cPhase;
const ls = (cx * info.tx + sx * info.tz) >= 0 ? 1 : -1;
const av = 0.05 + 0.28 * clamp(Math.abs(S.upV) / 1.2, 0, 1);
const al = 0.22 * clamp(Math.abs(S.alongVel) / 0.9, 0, 1);
const dir = S.alongVel >= 0 ? 1 : -1;
for (let i = 0; i < 2; i++) {
const side = sideOf(i), q = cp + i * Math.PI;
const hy = Math.min(P.y + 1.78 + av * Math.sin(q), s.top - 0.04);
const p = facePos(info, clampAlong(info, S.along + ls * side * 0.22 + dir * al * Math.sin(q), 0.05), 0.04);
T.arm[i] = { x: p[0], y: hy, z: p[1], w: 1 };
const lift = Math.max(0, -Math.sin(q)); // pé do mesmo lado sobe quando a mão desce
const f = facePos(info, clampAlong(info, S.along + ls * side * 0.13, 0.05), 0.2);
T.leg[i] = { x: f[0], y: P.y + 0.14 + (0.08 + 0.25 * clamp(Math.abs(S.upV) / 1.2, 0, 1)) * lift, z: f[1], w: 1 };
}
} else if (S.mode === 'cover') {
// no abrigo as mãos se seguram na parede: espalmadas ao lado do corpo; ao andar, as mãos se revezam deslizando
const info = S.info, s = S.solid;
const mvw = S.low ? smooth(0.15, 0.7, Math.abs(S.alongVel) / 1.4) : 0;
const ls = cx * info.tx + sx * info.tz;
const dirT = S.alongVel >= 0 ? 1 : -1;
const hy = S.low ? Math.min(s.top - 0.12, P.y + 0.72) : P.y + 1.0;
const near = ((-info.nx) * cx + (-info.nz) * sx) >= 0 ? 0 : 1;
const moving = clamp(Math.abs(S.alongVel) / 1.4, 0, 1);
for (let i = 0; i < 2; i++) {
const side = sideOf(i);
let al = S.along + ls * side * 0.3 + dirT * 0.1 * Math.sin(A.sPhase + i * Math.PI) * moving, w = 1;
if (S.low && mvw > 0.01) {
if (i === near) al = lerp(al, S.along + dirT * 0.15, mvw); else w = 1 - mvw;
}
const p = facePos(info, clampAlong(info, al, 0.05), 0.045);
T.arm[i] = { x: p[0], y: hy, z: p[1], w: w };
}
}
return T;
}
/* ---------- animação do corpo ---------- */
function pose(dt, c, T) {
const k = (r) => damp(r, dt);
const inCover = S.mode === 'cover';
const gaitOn = S.mode === 'move' || (inCover && S.low);
const sp = inCover ? Math.abs(S.alongVel) : Math.hypot(P.vx, P.vz);
A.accS += (((sp - A.prevSp) / Math.max(dt, 1e-3)) - A.accS) * k(8);
A.prevSp = sp;
A.yr += (c.yawRate - A.yr) * k(10);
A.speedS += (sp - A.speedS) * k(14);
const crT = ((S.mode === 'move' && (S.crouch || keys.ControlLeft)) || (inCover && S.low)) ? 1 : 0;
A.cr += (crT - A.cr) * k(10);
A.deep += (((inCover && S.low) ? S.deepT : 0) - A.deep) * k(8);
A.cm += (((inCover && S.low) ? smooth(0.15, 0.7, Math.abs(S.alongVel) / 1.4) : 0) - A.cm) * k(12);
A.runT += ((S.mode === 'move' ? smooth(2.6, 5.4, A.speedS) : 0) - A.runT) * k(7);
A.airT += (((P.grounded || S.mode !== 'move') ? 0 : 1) - A.airT) * k(16);
A.wh += (c.wallHead - A.wh) * k(12);
A.ws += (c.wallSide - A.ws) * k(12);
A.pl += (c.plant - A.pl) * k(14);
A.mV += ((S.mode === 'vault' ? 1 : 0) - A.mV) * k(S.mode === 'vault' ? 22 : 12);
A.mM += ((S.mode === 'mantle' ? 1 : 0) - A.mM) * k(S.mode === 'mantle' ? 22 : 12);
A.mC += ((S.mode === 'climb' ? 1 : 0) - A.mC) * k(S.mode === 'climb' ? 16 : 12);
A.mK += ((inCover ? 1 : 0) - A.mK) * k(inCover ? 14 : 12);
A.mS += ((S.mode === 'slide' ? 1 : 0) - A.mS) * k(S.mode === 'slide' ? 16 : 9);
A.mD += ((S.mode === 'dive' ? 1 : 0) - A.mD) * k(S.mode === 'dive' ? 18 : 16);
A.mP += ((S.mode === 'prone' ? 1 : 0) - A.mP) * k(S.mode === 'prone' ? 14 : 12);
A.mG += ((S.mode === 'getup' ? 1 : 0) - A.mG) * k(S.mode === 'getup' ? 30 : 12);
A.snapW *= Math.exp(-4.5 * dt);
A.tw += (S.lyTw - A.tw) * k(7);
if (S.mode === 'dive') A.dv = smooth(0, 0.28, S.t); else if (A.mD < 0.05) A.dv = 0;
if (S.mode === 'prone') {
const spd = S.slideV > 0.45 ? 0 : Math.hypot(P.vx, P.vz);
const hy0 = P.yaw + (S.lyRx < 0 ? Math.PI : 0); // direção da cabeça
const dirS = (P.vx * Math.sin(hy0) + P.vz * Math.cos(hy0)) >= -0.05 ? 1 : -1;
A.pc += dt * TAU * spd / 0.95 * dirS;
A.pa += (clamp(spd / 1.05, 0, 1) - A.pa) * k(10);
} else A.pa += (0 - A.pa) * k(10);
if (S.mode === 'vault') A.vt = S.t;
if (S.mode === 'mantle') A.mt = S.t;
if (c.wallSide > 0.05) { A.wsSign = c.wallSign; A.wsAng = c.reach; }
if (inCover) A.kLow += ((S.low ? 1 : 0) - A.kLow) * k(10);
A.gaitS += ((gaitOn ? clamp(A.speedS / lerp(2.0, 1.1, A.cr), 0, 1) : 0) - A.gaitS) * k(14);
const gait = A.gaitS, run = A.runT, air = A.airT, wh = A.wh, ws = A.ws, pl = A.pl, lp = A.land, cr = A.cr;
if (gaitOn && (P.grounded || inCover)) A.phase = (A.phase + dt * TAU * A.speedS / lerp(lerp(1.5, 3.1, run), 1.15, cr)) % TAU;
if (S.mode === 'climb') A.cPhase += (Math.abs(S.upV) + 0.6 * Math.abs(S.alongVel)) * dt / 0.55 * Math.PI;
if (inCover) A.sPhase += Math.abs(S.alongVel) * dt / 0.7 * TAU;
A.landImpact *= Math.exp(-9 * dt);
A.land += (A.landImpact - A.land) * k(28);
A.jVel += (-140 * A.jPos - 11 * A.jVel) * dt; // mola do tronco (batidas)
A.jPos = clamp(A.jPos + A.jVel * dt, -0.45, 0.55);
const ph = A.phase;
const amp = lerp(0.5, 0.92, run) * gait * (1 - 0.5 * cr);
const kb = lerp(0.75, 1.65, run) * gait * (1 - 0.35 * cr);
const kMin = lerp(0.06, 0.25, run) * gait + 0.04;
const armA = lerp(0.55, 1.0, run) * gait * (1 - 0.4 * cr);
const elb = lerp(0.25, 1.5, run) * gait + 0.12;
const lean = lerp(0.05, 0.24, run) * gait;
const twist = lerp(0.12, 0.28, run) * gait;
const riseT = clamp((P.vy + 2) / 7, 0, 1);
const idleW = (1 - gait) * (1 - air) * (1 - A.mV) * (1 - A.mM) * (1 - A.mC) * (1 - A.mK) * (1 - A.mS) * (1 - A.mD) * (1 - A.mP) * (1 - A.mG);
const crTh = lerp(-0.95, -1.4, A.deep), crKn = lerp(1.9, 2.6, A.deep); // agachado normal e agachado fundo
const th = [0, 0], kn = [0, 0], thz = [0, 0], shx = [0, 0], shz = [0, 0], elx = [0, 0];
let hipRX = 0, neZ = 0;
const elz = [0, 0], knz = [0, 0];
for (let i = 0; i < 2; i++) {
const side = i === 0 ? 1 : -1;
const p = ph + i * Math.PI;
// no chão (andando, correndo, agachado)
const gTh = -amp * Math.sin(p) + crTh * cr;
const gKn = kMin + kb * Math.max(0, Math.cos(p - 0.35)) + crKn * cr;
const gSh = armA * Math.sin(p) - 0.4 * cr;
const gEl = -elb - 0.5 * cr;
const gShz = side * (0.09 + 0.05 * run);
// no ar
const front = i === A.airSide;
const aTh = front ? lerp(-0.45, -1.05, riseT) : lerp(0.3, 0.15, riseT);
const aKn = front ? lerp(0.45, 1.35, riseT) : lerp(0.7, 1.25, riseT);
const aSh = lerp(-0.35, -2.3, riseT);
const aShz = side * lerp(1.0, 0.4, riseT);
th[i] = lerp(gTh, aTh, air);
kn[i] = lerp(gKn, aKn, air);
shx[i] = lerp(gSh, aSh, air);
elx[i] = lerp(gEl, -0.45, air);
shz[i] = lerp(gShz, aShz, air);
// aterrissagem: joelhos absorvem
th[i] -= 0.75 * lp; kn[i] += 1.3 * lp; shx[i] -= 0.5 * lp;
// quase parado: respiração nos ombros
shx[i] += 0.02 * Math.sin(time * 1.7 + i) * idleW;
}
let spX = lerp(lean + 0.025 * Math.sin(2 * ph) * gait + lerp(0.3, 0.12, A.deep) * cr, 0.12, air) + 0.1 * wh + A.jPos + 0.32 * lp;
// acelerando inclina para a frente, freando inclina para trás
spX += clamp(A.accS / 24, -1, 1) * 0.18 * (1 - air) * (A.mV + A.mM + A.mC + A.mK > 0.2 ? 0 : 1);
let spY = 0.9 * twist * Math.sin(ph);
let spZ = 0.03 * Math.sin(ph) * gait;
spZ -= clamp(A.yr * A.speedS * 0.006, -0.25, 0.25) * (1 - air); // inclina para dentro da curva
let hipRY = -0.5 * twist * Math.sin(ph);
let hipRZ = 0.03 * Math.sin(time * 0.6) * idleW + 0.05 * Math.sin(ph) * gait * (1 - cr) * (1 - air); // troca de peso parado
let neX = 0;
let neY = 0.3 * Math.sin(time * 0.35) * Math.sin(time * 0.13 + 1) * idleW - (spY + hipRY) * 0.8 * gait; // olha em volta
// pernas apoiadas na parede durante o pulo
for (let i = 0; i < 2; i++) {
th[i] = lerp(th[i], i === 0 ? -1.2 : -1.0, pl);
kn[i] = lerp(kn[i], i === 0 ? 0.95 : 0.8, pl);
shx[i] = lerp(shx[i], -1.0, pl);
elx[i] = lerp(elx[i], -0.7, pl);
}
spX = lerp(spX, -0.05, pl);
// empurrando a parede de frente / passando rente (as mãos vão por cinemática inversa)
for (let i = 0; i < 2; i++) {
const side = i === 0 ? 1 : -1;
th[i] = lerp(th[i], i === 0 ? -0.38 : 0.32, wh);
kn[i] = lerp(kn[i], i === 0 ? 0.3 : 0.12, wh);
shx[i] = lerp(shx[i], -0.95 + 0.06 * Math.sin(time * 9 + i * 2), wh);
elx[i] = lerp(elx[i], -1.45, wh);
shz[i] = lerp(shz[i], side * 0.2, wh);
if (side === A.wsSign) {
shz[i] = lerp(shz[i], side * A.wsAng, ws);
elx[i] = lerp(elx[i], -0.3, ws);
shx[i] = lerp(shx[i], -0.2, ws);
}
}
spZ += -A.wsSign * 0.1 * ws;
// pular mureta
let vaultT = 0;
if (A.mV > 0.01) {
const vt = A.vt, w = A.mV, spd = S.vtype === 'speed', sgn = S.hand === 0 ? 1 : -1;
const hW = smooth(0.08, 0.3, vt) * (1 - smooth(0.7, 0.92, vt)) * w; // braços para o apoio
const tW = smooth(0.2, 0.42, vt) * (1 - smooth(0.62, 0.88, vt)) * w; // pernas recolhidas e jogadas de lado
vaultT = tW;
for (let i = 0; i < 2; i++) {
const side = i === 0 ? 1 : -1;
const planted = spd ? (i === S.hand) : true;
shx[i] = lerp(shx[i], planted ? -1.2 : 0.35, hW);
elx[i] = lerp(elx[i], planted ? -0.3 : -0.5, hW);
shz[i] = lerp(shz[i], side * (planted ? 0.15 : 0.7), hW);
const lead = spd ? (i !== S.hand) : true;
th[i] = lerp(th[i], lead ? -1.35 : -0.8, tW);
kn[i] = lerp(kn[i], lead ? 1.6 : 1.1, tW);
}
spX = lerp(spX, 0.35, tW);
if (spd) { hipRZ = lerp(hipRZ, -sgn * 0.95, tW); spZ = lerp(spZ, sgn * 0.55, tW); }
else { hipRZ = lerp(hipRZ, S.rollSign * 0.5, tW); spZ = lerp(spZ, -S.rollSign * 0.3, tW); }
}
// subir na borda: queixo na borda, joelho sobe, empurra e levanta
let mantleH = 0;
if (A.mM > 0.01) {
const mt = A.mt, w = A.mM;
const a = smooth(0, 0.45, mt), b = smooth(0.45, 0.92, mt);
for (let i = 0; i < 2; i++) {
const side = i === 0 ? 1 : -1;
shx[i] = lerp(shx[i], lerp(lerp(-2.85, -2.3, a), -0.5, b), w);
elx[i] = lerp(elx[i], lerp(lerp(-0.2, -1.8, a), -0.15, b), w);
shz[i] = lerp(shz[i], side * 0.2, w);
th[i] = lerp(th[i], i === 0 ? lerp(lerp(-0.6, -1.0, a), -1.55, b) : lerp(lerp(-0.2, -0.9, a), -0.25, b), w);
kn[i] = lerp(kn[i], i === 0 ? lerp(lerp(0.8, 1.3, a), 1.7, b) : lerp(0.5, 0.2, b), w);
}
spX = lerp(spX, lerp(0.05, 0.5, b) - 0.3 * smooth(0.9, 1, mt), w);
hipRZ = lerp(hipRZ, 0.08 * Math.sin(mt * 9), w);
mantleH = w;
}
// escalar: mãos e pés alternados (contralaterais), peso passando de um lado para o outro
let climbH = 0;
if (A.mC > 0.01) {
const cp = A.cPhase, w = A.mC;
for (let i = 0; i < 2; i++) {
const side = i === 0 ? 1 : -1;
const q = cp + i * Math.PI;
shx[i] = lerp(shx[i], -2.85 + 0.32 * Math.sin(q), w);
elx[i] = lerp(elx[i], -0.25 - 0.3 * Math.max(0, -Math.sin(q)), w);
shz[i] = lerp(shz[i], side * 0.2, w);
th[i] = lerp(th[i], -0.7 + 0.4 * Math.sin(q + Math.PI), w);
kn[i] = lerp(kn[i], 0.9 + 0.5 * Math.max(0, Math.sin(q + Math.PI)), w);
}
spX = lerp(spX, 0.06, w);
spY = lerp(spY, 0.16 * Math.sin(cp), w);
spZ += (0.05 * Math.sin(cp) + 0.012 * Math.sin(time * 1.3)) * w;
hipRZ = lerp(hipRZ, 0.07 * Math.sin(cp), w);
climbH = w;
}
// abrigo
if (A.mK > 0.01) {
const w = A.mK, lowW = A.kLow, cm = A.cm;
for (let i = 0; i < 2; i++) {
const side = i === 0 ? 1 : -1;
if (lowW > 0.01) {
// agachado fundo, de costas para a mureta, mãos em posição de prontidão perto do peito
shx[i] = lerp(shx[i], lerp(-0.85, -0.9, cm), w * lowW);
elx[i] = lerp(elx[i], lerp(-1.75, -1.35, cm), w * lowW);
shz[i] = lerp(shz[i], side * 0.12, w * lowW);
}
if (lowW < 0.99) {
// parede alta: costas coladas, cotovelos dobrados junto ao peito, joelhos levemente dobrados
const hw = w * (1 - lowW);
shx[i] = lerp(shx[i], -0.55, hw);
elx[i] = lerp(elx[i], -1.5, hw);
shz[i] = lerp(shz[i], side * 0.1, hw);
th[i] = lerp(th[i], -0.15, hw);
kn[i] = lerp(kn[i], 0.3, hw);
// passo lateral: a perna da frente abre, a de trás fecha
thz[i] = lerp(thz[i], S.dirLocal * 0.3 * Math.max(0, Math.sin(A.sPhase + i * Math.PI)), hw);
}
}
// mureta parado: tronco quase reto encostado; andando: inclinado para a frente
spX = lerp(spX, lerp(-0.08, 0.28, cm), w * lowW);
spX = lerp(spX, 0.0, w * (1 - lowW));
neX += lerp(-0.12, 0.0, cm) * w * lowW;
// olha na direção em que vai (parede alta); na mureta, o corpo todo já virou
neY += lerp(0.55, 0.0, lowW) * S.dirLocal * w;
hipRZ += 0.04 * Math.sin(A.sPhase) * w * (1 - lowW);
}
// altura do quadril: com os pés no chão ela vem do comprimento real das pernas
const ext = (i) => THIGH_LEN * Math.cos(th[i]) + SHIN_LEN * Math.cos(th[i] + kn[i]);
const dev = Math.max(ext(0), ext(1)) - (THIGH_LEN + SHIN_LEN);
const devK = lerp(0.55, 1, 1 - gait * (1 - cr) * (1 - lp));
const hipGround = 0.135 + THIGH_LEN + SHIN_LEN + dev * devK;
let hipY = lerp(HIP_Y - 0.01, hipGround, 1 - air);
hipY = lerp(hipY, HIP_Y - 0.42, vaultT);
hipY = lerp(hipY, HIP_Y - 0.1, mantleH);
hipY = lerp(hipY, HIP_Y - 0.05, climbH);
hipY -= 0.05 * wh;
// deslizar no chão: tronco inclinado para trás, uma perna esticada e a outra dobrada por baixo
if (A.mS > 0.01) {
const w = A.mS;
hipRX = lerp(hipRX, -1.1, w); hipY = lerp(hipY, 0.26, w);
th[0] = lerp(th[0], -0.3, w); kn[0] = lerp(kn[0], 0.05, w);
th[1] = lerp(th[1], -0.2, w); kn[1] = lerp(kn[1], 2.8, w);
spX = lerp(spX, 0.3, w); spY = lerp(spY, 0, w); spZ = lerp(spZ, 0, w); hipRZ = lerp(hipRZ, 0, w);
shx[0] = lerp(shx[0], 0.9, w); shz[0] = lerp(shz[0], 0.5, w); elx[0] = lerp(elx[0], -0.2, w);
shx[1] = lerp(shx[1], -1.2, w); shz[1] = lerp(shz[1], 0.3, w); elx[1] = lerp(elx[1], -0.5, w);
neX += 0.55 * w;
}
// mergulho em qualquer direção: de frente cai de bruços, para trás cai de costas, de lado cai de lado
if (A.mD > 0.01) {
const w = A.mD, kd = S.diveKind, sd = S.diveSide, back = kd === 1;
hipRX = lerp(hipRX, lerp(0.7, 1.5, A.dv) * (back ? -1 : 1), w);
hipRY = lerp(hipRY, kd === 2 ? -sd * 1.4 * A.dv : 0, w);
hipY = lerp(hipY, 0.38, w);
th[0] = lerp(th[0], 0.15, w); kn[0] = lerp(kn[0], 0.3, w);
th[1] = lerp(th[1], 0.5, w); kn[1] = lerp(kn[1], 1.1, w);
spX = lerp(spX, -0.2, w); spY = lerp(spY, 0, w); spZ = lerp(spZ, 0, w); hipRZ = lerp(hipRZ, 0, w);
if (back) { // de costas: braços à frente do peito, apontando a arma
shx[0] = lerp(shx[0], -1.6, w); shx[1] = lerp(shx[1], -1.6, w);
shz[0] = lerp(shz[0], 0.5, w); shz[1] = lerp(shz[1], -0.5, w);
elx[0] = lerp(elx[0], -1.6, w); elx[1] = lerp(elx[1], -1.6, w);
neX += 0.5 * w;
} else {
shx[0] = lerp(shx[0], -3.0, w); shx[1] = lerp(shx[1], -2.6, w);
shz[0] = lerp(shz[0], 0.12, w); shz[1] = lerp(shz[1], -0.12, w);
elx[0] = lerp(elx[0], -0.1, w); elx[1] = lerp(elx[1], -0.5, w);
neX += -0.7 * w;
}
}
// deitado (de bruços, de costas ou de lado): rasteja em qualquer direção e gira livre
if (A.mP > 0.01) {
const w = A.mP, pa = A.pa, sup = S.lyRx < 0, side = clamp(Math.abs(A.tw) / 1.4, 0, 1);
hipRX = lerp(hipRX, S.lyRx, w); hipRY = lerp(hipRY, A.tw, w);
hipY = lerp(hipY, (sup ? 0.2 : 0.15) + 0.21 * side, w);
spX = lerp(spX, sup ? -0.2 : -0.1, w); spY = lerp(spY, 0.14 * pa * Math.sin(A.pc), w); spZ = lerp(spZ, 0, w);
hipRZ = lerp(hipRZ, 0.1 * pa * Math.sin(A.pc), w);
for (let i = 0; i < 2; i++) {
const sd = i === 0 ? 1 : -1;
const lift = Math.max(0, Math.sin(A.pc + i * Math.PI)) * pa;
const pull = Math.max(0, Math.sin(A.pc + (1 - i) * Math.PI)) * pa;
th[i] = lerp(th[i], (sup ? 0 : -0.05) - 0.2 * lift, w);
kn[i] = lerp(kn[i], 0.1 + 0.95 * lift, w);
thz[i] = lerp(thz[i], sd * (0.1 + 0.3 * lift), w);
if (sup) {
shx[i] = lerp(shx[i], -1.6 + 0.3 * pull, w);
elx[i] = lerp(elx[i], -1.6, w);
shz[i] = lerp(shz[i], sd * 0.5, w);
} else {
shx[i] = lerp(shx[i], lerp(-2.5, -2.1, pull), w);
elx[i] = lerp(elx[i], lerp(-0.25, -1.5, pull), w);
shz[i] = lerp(shz[i], sd * 0.35, w);
}
}
neX += (sup ? 0.5 : -0.85) * w;
}
// levantando do chão
if (A.mG > 0.01) {
const w = A.mG, g = getupKey(S.gT / S.gDur, S.gProne);
hipRX = lerp(hipRX, g.rx, w);
hipY = lerp(hipY, Math.max(0.14, 0.075 + 0.06 * Math.cos(g.rx) + THIGH_LEN * Math.cos(g.rx + g.th) + SHIN_LEN * Math.cos(g.rx + g.th + g.kn)), w);
hipRY = lerp(hipRY, 0, w); spX = lerp(spX, g.sp, w); spY = lerp(spY, 0, w); spZ = lerp(spZ, 0, w); hipRZ = lerp(hipRZ, 0, w);
for (let i = 0; i < 2; i++) {
const side = i === 0 ? 1 : -1;
th[i] = lerp(th[i], g.th, w); kn[i] = lerp(kn[i], g.kn, w); thz[i] = lerp(thz[i], 0, w);
shx[i] = lerp(shx[i], g.shx, w); shz[i] = lerp(shz[i], side * g.shz, w); elx[i] = lerp(elx[i], g.elx, w);
}
neX += g.ne * w;
}
// transição suave do ragdoll para a pose de levantar
if (A.snapW > 0.003 && A.snap) {
const sn = A.snap, sw = A.snapW;
hipRX = lerp(hipRX, sn.hipRX, sw); hipRY = lerp(hipRY, sn.hipRY, sw); hipRZ = lerp(hipRZ, sn.hipRZ, sw);
hipY = lerp(hipY, sn.hipY, sw);
spX = lerp(spX, sn.spX, sw); spY = lerp(spY, sn.spY, sw); spZ = lerp(spZ, sn.spZ, sw);
neX = lerp(neX, sn.neX, sw); neZ = lerp(neZ, sn.neZ, sw);
for (let i = 0; i < 2; i++) {
shx[i] = lerp(shx[i], sn.shx[i], sw); shz[i] = lerp(shz[i], sn.shz[i], sw);
elx[i] = lerp(elx[i], sn.elx[i], sw); elz[i] = lerp(elz[i], sn.elz[i], sw);
th[i] = lerp(th[i], sn.th[i], sw); thz[i] = lerp(thz[i], sn.thz[i], sw);
kn[i] = lerp(kn[i], sn.kn[i], sw); knz[i] = lerp(knz[i], sn.knz[i], sw);
}
}
// mãos e pés vão até os alvos do mundo, resolvidos por cinemática inversa
const Rroot = rotY(c.yawVis);
const Hm = mmul(rotX(hipRX), mmul(rotY(hipRY), rotZ(hipRZ)));
const Sm = mmul(rotX(spX), mmul(rotY(spY), rotZ(spZ)));
const toHips = (x, y, z) => { const v = mtvec(Rroot, [x - P.x, y - P.y, z - P.z]); v[1] -= hipY; return mtvec(Hm, v); };
const toSpine = (x, y, z) => { const v = toHips(x, y, z); v[1] -= 0.1; return mtvec(Sm, v); };
for (let i = 0; i < 2; i++) {
const side = i === 0 ? 1 : -1;
const ta = T.arm[i], tl = T.leg[i];
if (ta) { A.ikAT[i].x = ta.x; A.ikAT[i].y = ta.y; A.ikAT[i].z = ta.z; }
A.ikA[i] += ((ta ? ta.w : 0) - A.ikA[i]) * k(18);
if (A.ikA[i] > 0.01) {
const t = A.ikAT[i], v = toSpine(t.x, t.y, t.z);
const s = solveLimb(v[0] - side * 0.28, v[1] - 0.4, v[2], UP_LEN, FORE_LEN, -1);
shz[i] = lerp(shz[i], s[0], A.ikA[i]);
shx[i] = lerp(shx[i], s[1], A.ikA[i]);
elx[i] = lerp(elx[i], s[2], A.ikA[i]);
}
if (tl) { A.ikLT[i].x = tl.x; A.ikLT[i].y = tl.y; A.ikLT[i].z = tl.z; }
A.ikL[i] += ((tl ? tl.w : 0) - A.ikL[i]) * k(18);
if (A.ikL[i] > 0.01) {
const t = A.ikLT[i], v = toHips(t.x, t.y, t.z);
const s = solveLimb(v[0] - side * 0.1, v[1] + 0.06, v[2], THIGH_LEN, SHIN_LEN, 1);
thz[i] = lerp(thz[i], s[0], A.ikL[i]);
th[i] = lerp(th[i], s[1], A.ikL[i]);
kn[i] = lerp(kn[i], s[2], A.ikL[i]);
}
}
for (let i = 0; i < 2; i++) {
legs[i].hp.rotation.x = th[i];
legs[i].hp.rotation.z = thz[i];
legs[i].kn.rotation.x = kn[i];
const pp = ph + i * Math.PI;
const roll = 0.45 * Math.max(0, -Math.sin(pp) - 0.2) * gait * (1 - cr) * (1 - air) - 0.18 * Math.max(0, Math.sin(pp) - 0.6) * gait * (1 - air);
legs[i].an.rotation.x = -(th[i] + kn[i]) * lerp(0.7, 1.0, cr) + roll;
arms[i].el.rotation.z = elz[i];
legs[i].kn.rotation.z = knz[i];
arms[i].sh.rotation.x = shx[i];
arms[i].sh.rotation.z = shz[i];
arms[i].el.rotation.x = elx[i];
lastPose.shx[i] = shx[i]; lastPose.shz[i] = shz[i]; lastPose.elx[i] = elx[i];
lastPose.th[i] = th[i]; lastPose.thz[i] = thz[i]; lastPose.kn[i] = kn[i];
}
hips.position.set(0, hipY, 0);
hips.rotation.x = hipRX;
neck.rotation.z = neZ;
hips.rotation.y = hipRY;
hips.rotation.z = hipRZ;
spine.rotation.x = spX;
spine.rotation.y = spY;
spine.rotation.z = spZ;
neck.rotation.x = -spX * 0.6 - A.jPos * 0.7 + neX;
neck.rotation.y = neY;
chest.scale.y = 1 + 0.012 * Math.sin(time * 1.7) * idleW;
lastPose.hipRX = hipRX; lastPose.hipY = hipY; lastPose.hipRY = hipRY; lastPose.hipRZ = hipRZ;
lastPose.spX = spX; lastPose.spY = spY; lastPose.spZ = spZ; lastPose.yaw = c.yawVis;
}
/* ---------- câmera sobre o ombro ---------- */
const ray = new THREE.Raycaster();
function camRay(shoulder, dist, dx, dy, dz, rx, rz, tx, ty, tz) {
let ox = -dx * dist + rx * shoulder, oy = -dy * dist, oz = -dz * dist + rz * shoulder;
const len = Math.hypot(ox, oy, oz);
ox /= len; oy /= len; oz /= len;
ray.set(new THREE.Vector3(tx, ty, tz), new THREE.Vector3(ox, oy, oz));
ray.far = len + 0.3;
const h = ray.intersectObjects(wallMeshes, false)[0];
const d = h ? clamp(h.distance - 0.3, 0.5, len) : len;
return { ox: ox, oy: oy, oz: oz, d: d, len: len };
}
function updateCamera(dt) {
const run = A.runT, cr = A.cr;
// no abrigo e na escalada a câmera gira devagar para o lado aberto
if ((S.mode === 'cover' || S.mode === 'climb') && time - cam.lastLook > 0.5) {
cam.yaw += angDiff(cam.yaw, Math.atan2(-S.info.nx, -S.info.nz)) * damp(2.5, dt);
}
if (act.swap) { act.swap = false; cam.side = -cam.side; cam.lockUntil = time + 3; }
// segue o boneco com um pequeno atraso, o que dá sensação de velocidade
const lagK = damp(S.mode === 'move' ? 20 : 30, dt);
cam.tx += (P.x - cam.tx) * lagK; cam.tz += (P.z - cam.tz) * lagK;
const walkBob = (S.mode === 'move' && P.grounded) ? 0.028 * Math.sin(2 * A.phase) * clamp(A.speedS / RUN, 0, 1) * (1 + run) : 0;
let crouchH = lerp(lerp(1.5, 1.08, cr), 0.95, A.deep);
crouchH = lerp(crouchH, lastPose.hipY + 0.5, Math.max(A.mS, A.mD, A.mP, A.mG));
if (S.mode === 'ragdoll') crouchH = 1.3;
cam.ty += (P.y + crouchH + walkBob - cam.ty) * damp(11, dt);
cam.dipV += (-110 * cam.dip - 10 * cam.dipV) * dt; // mola da aterrissagem
cam.dip += cam.dipV * dt;
const ty = cam.ty + cam.dip;
let distT = (portrait ? 4.5 : 3.4) + 0.6 * run - 0.25 * cr;
let fovT = 62 + 9 * run + cam.punch;
let rollT = 0;
if (S.mode === 'cover') { distT -= S.low ? 0.3 : 0; fovT -= 4; }
if (S.mode === 'climb') { distT += 0.5; fovT -= 2; }
if (S.mode === 'vault') { const s = Math.sin(Math.PI * clamp(S.t, 0, 1)); rollT += 0.07 * s * S.rollSign; fovT += 5 * s; }
if (S.mode === 'mantle') fovT += 3;
if (S.mode === 'slide') { distT -= 0.2; fovT += 8; rollT += 0.03; }
if (S.mode === 'dive') { distT += 0.3; fovT += 12; rollT += 0.05; }
if (S.mode === 'prone') distT -= 0.3;
if (S.mode === 'ragdoll') { distT += 0.6; fovT += 4; }
const cp = Math.cos(cam.pitch), sp = Math.sin(cam.pitch), lx = Math.sin(cam.yaw), lz = Math.cos(cam.yaw);
const dx = cp * lx, dy = -sp, dz = cp * lz; // para onde a câmera olha
const rx = -lz, rz = lx; // direita da câmera
rollT += clamp((P.vx * rx + P.vz * rz) / RUN, -1, 1) * 0.035; // inclina ao andar de lado
cam.roll += (rollT - cam.roll) * damp(8, dt);
cam.dist += (distT - cam.dist) * damp(5, dt);
cam.fov += (fovT - cam.fov) * damp(6, dt);
cam.punch *= Math.exp(-4 * dt);
cam.shake *= Math.exp(-7 * dt);
const sideT = S.mode === 'cover' ? S.coverSide : cam.side;
const shT = sideT * (portrait ? 0.55 : 0.65) * (S.mode === 'cover' ? 1.15 : 1);
cam.shoulder += (shT - cam.shoulder) * damp(8, dt);
const tx = cam.tx, tz = cam.tz;
const r1 = camRay(cam.shoulder, cam.dist, dx, dy, dz, rx, rz, tx, ty, tz);
// se o ombro está bloqueado e o outro lado está livre, troca sozinho
if (S.mode === 'move' && time > cam.lockUntil && r1.d < r1.len * 0.6) {
const alt = camRay(-cam.shoulder, cam.dist, dx, dy, dz, rx, rz, tx, ty, tz);
if (alt.d > r1.d + r1.len * 0.25) {
cam.swapT += dt;
if (cam.swapT > 0.35) { cam.side = -cam.side; cam.swapT = 0; cam.lockUntil = time + 1.2; }
} else cam.swapT = 0;
} else cam.swapT = 0;
let px = tx + r1.ox * r1.d, py = ty + r1.oy * r1.d, pz = tz + r1.oz * r1.d;
const sh = cam.shake;
if (sh > 0.0005) {
px += sh * (Math.sin(time * 61) + Math.sin(time * 37 + 1.3)) * 0.5;
py += sh * (Math.sin(time * 53 + 2.1) + Math.sin(time * 29)) * 0.5;
pz += sh * Math.sin(time * 47 + 0.7);
}
// nunca fica dentro de um obstáculo
for (const s of solids) {
if (py > s.top + 0.25) continue;
const m = 0.22;
if (px > s.minX - m && px < s.maxX + m && pz > s.minZ - m && pz < s.maxZ + m) {
const l = px - (s.minX - m), r = (s.maxX + m) - px, b = pz - (s.minZ - m), f = (s.maxZ + m) - pz, mn = Math.min(l, r, b, f);
if (mn === l) px = s.minX - m; else if (mn === r) px = s.maxX + m; else if (mn === b) pz = s.minZ - m; else pz = s.maxZ + m;
}
}
py = Math.max(0.25, py);
camera.fov = cam.fov;
camera.updateProjectionMatrix();
const roll = cam.roll + sh * 0.6 * Math.sin(time * 43);
const rl = Math.hypot(rx, rz) || 1, rxn = rx / rl, rzn = rz / rl;
const ux = -rzn * dy, uy = rzn * dx - rxn * dz, uz = rxn * dy; // cima da câmera sem rolagem
const cr2 = Math.cos(roll), sr = Math.sin(roll);
camera.up.set(ux * cr2 + rxn * sr, uy * cr2, uz * cr2 + rzn * sr);
camera.position.set(px, py, pz);
camera.lookAt(px + dx, py + dy, pz + dz);
}
/* ---------- um passo da simulação ---------- */
function labelNow() {
switch (S.mode) {
case 'vault': return S.over ? (S.vtype === 'speed' ? 'Salto rápido na mureta' : 'Pulando a mureta') : 'Subindo no obstáculo';
case 'mantle': return 'Subindo na borda';
case 'climb': return Math.abs(S.upV) > 0.2 || Math.abs(S.alongVel) > 0.2 ? 'Escalando' : 'Pendurado na parede';
case 'cover': return S.low ? 'Abrigado atrás da mureta' : 'Colado na parede';
case 'slide': return 'Deslizando';
case 'dive': return 'Mergulho (tempo de bala)';
case 'prone': return S.slideV > 0.45 ? 'Deslizando de bruços' : (A.pa > 0.2 ? 'Rastejando' : 'Deitado');
case 'getup': return 'Levantando';
case 'ragdoll': return 'Caído · levanta em ' + Math.max(0, Math.ceil(4 - RG.t)) + ' s';
}
if (!P.grounded) return A.pl > 0.5 ? 'Apoiando os pés na parede' : 'No ar';
if (A.wh > 0.5) return 'Empurrando a parede';
if (A.ws > 0.5) return 'Encostado na parede';
if (A.cr > 0.5) return A.speedS > 0.3 ? 'Andando agachado' : 'Agachado';
if (A.speedS > 3.8) return 'Correndo';
if (A.speedS > 0.3) return 'Andando';
return 'Parado';
}
function step(dt) {
time += dt;
const inp = readInput();
const sinC = Math.sin(cam.yaw), cosC = Math.cos(cam.yaw);
const dx = -cosC * inp.ix + sinC * inp.iz;
const dz = sinC * inp.ix + cosC * inp.iz;
const prevYaw = P.yaw;
switch (S.mode) {
case 'vault': stepVault(dt); break;
case 'mantle': stepMantle(dt); break;
case 'climb': stepClimb(dt, inp, dx, dz); break;
case 'cover': stepCover(dt, inp, dx, dz); break;
case 'slide': stepSlide(dt, inp, dx, dz); break;
case 'dive': stepDive(dt); break;
case 'prone': stepProne(dt, inp, dx, dz); break;
case 'getup': stepGetup(dt); break;
case 'ragdoll': stepRagdoll(dt); break;
default: stepMove(dt, inp, dx, dz);
}
act.dive = false;
if (S.mode !== 'move' && jumpBuf > 0) jumpBuf = Math.max(0, jumpBuf - dt);
const c = S.mode === 'move' ? wallContext(inp, dx, dz) : { wallHead: 0, wallSide: 0, wallSign: 1, reach: 0.38, plant: 0, wall: null };
c.yawRate = angDiff(prevYaw, P.yaw) / Math.max(dt, 1e-3);
c.yawVis = P.yaw + (S.mode === 'vault' ? S.yawOff : 0);
if (S.mode === 'ragdoll') {
applyRagdoll();
root.position.set(0, 0, 0);
root.rotation.y = 0;
} else {
const T = buildIK(c);
pose(dt, c, T);
root.position.set(P.x, P.y, P.z);
root.rotation.y = c.yawVis;
}
sun.position.set(P.x + 10, 18, P.z + 8);
sun.target.position.set(P.x, 0, P.z);
updateCamera(dt);
hudTimer -= dt;
const label = labelNow();
if (label !== hudLabel) { hudLabel = label; statusEl.textContent = label; }
if (hudTimer <= 0) {
hudTimer = 0.12;
const shown = S.mode === 'cover' || S.mode === 'climb' ? Math.max(Math.abs(S.alongVel), Math.abs(S.upV)) : A.speedS;
speedEl.textContent = shown.toFixed(1).replace('.', ',') + ' m/s';
}
}
/* ---------- tamanho e laço principal ---------- */
function resize() {
const w = stage.clientWidth || window.innerWidth, h = stage.clientHeight || window.innerHeight;
renderer.setSize(w, h, false);
camera.aspect = w / h;
camera.updateProjectionMatrix();
portrait = w / h < 0.85;
}
if (typeof ResizeObserver !== 'undefined') new ResizeObserver(resize).observe(stage);
window.addEventListener('resize', resize);
resize();
let last = performance.now(), ts = 1;
function frame(now) {
requestAnimationFrame(frame);
let dt = (now - last) / 1000;
last = now;
if (!(dt > 0)) dt = 0.016;
const tgt = S.mode === 'dive' ? 0.72 : (S.mode === 'prone' && S.slideV > 0.8 ? 0.7 : 1);
ts += (tgt - ts) * damp(7, dt);
step(Math.min(dt, 0.033) * ts);
renderer.render(scene, camera);
}
requestAnimationFrame(frame);
})();
</script>
</body>
</html>