3D 리플레이 자동 시점 · Tab 점수판: 카메라 "자동"(교전 직전에 이긴 선수 1인칭, 직전 우리 팀 콜이 있으면 그 말부터 · 설치/해체 · 혼자 남은 선수 · 교전이 없으면 살아 있는 선수가 다 보이게 위에서) · Tab 을 누르고 있으면 게임처럼 팀 점수 · 궁극기 · K/D/A · 주무기 · 크레딧 · 변환기 scoreboard (크레딧 · 궁 점수 · 킬/데스/어시 · 전투 점수, BasicCombatStats · PlayerScore 하위 객체 읽기) · self-test · 테스트

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-11-08 22:46:54 +09:00
parent c539c2b9dc
commit c36db3ef9a
11 changed files with 1020 additions and 27 deletions

View File

@@ -0,0 +1,78 @@
import type { MatchDetail, MatchPlayer } from '@gvr/shared';
import { equipLabel, type ReplayFile } from '../lib/replay';
import { boardAt, teamScoreAt, type BoardIndex, type BoardRow } from '../lib/scoreboard';
interface RosterItem {
idx: number;
info: MatchPlayer | null;
name: string;
ally: boolean;
}
/** 리플레이 점수판: 게임에서 Tab 을 누른 것처럼 그 시각의 팀 점수 · 궁극기 · K/D/A · 무기 · 크레딧 */
export default function ReplayScoreboard({ m, replay, ix, roster, t }: { m: MatchDetail; replay: ReplayFile; ix: BoardIndex; roster: RosterItem[]; t: number }) {
const rows = roster.map((r) => ({ r, b: boardAt(replay, ix, r.idx, t) }));
// 게임처럼 전투 점수 순 (없으면 킬 순)
const order = (a: { b: BoardRow }, c: { b: BoardRow }) => (c.b.score ?? -1) - (a.b.score ?? -1) || c.b.kills - a.b.kills || a.b.deaths - c.b.deaths;
const ally = rows.filter((x) => x.r.ally).sort(order);
const enemy = rows.filter((x) => !x.r.ally).sort(order);
const sc = teamScoreAt(replay, m.rounds, t);
const team = (list: typeof rows, side: 'a' | 'e') => (
<tbody className={`r3d-sb-team ${side}`}>
{list.map(({ r, b }) => (
<tr key={r.idx} className={b.dead ? 'dead' : undefined}>
<td className="ag">
{r.info?.character?.icon ? <img src={r.info.character.icon} alt="" /> : <span className="ag-ph" />}
</td>
<td className="nm">
<b>{r.name}</b>
{r.info?.character?.name && <span className="muted"> {r.info.character.name}</span>}
</td>
<td className="ult" title={b.ult == null ? '궁극기 점수 모름' : `궁극기 ${b.ult} / ${b.ultMax}`}>
{b.ult == null ? (
<span className="muted">-</span>
) : b.ult >= b.ultMax ? (
<span className="ult-ready">궁 준비</span>
) : (
<span className="ult-dots" aria-label={`궁극기 ${b.ult} / ${b.ultMax}`}>
{Array.from({ length: b.ultMax }, (_, i) => (
<i key={i} className={i < b.ult! ? 'on' : undefined} />
))}
</span>
)}
</td>
<td className="num">{b.kills}</td>
<td className="num">{b.deaths}</td>
<td className="num">{b.assists ?? '-'}</td>
<td className="wp">{equipLabel(b.weapon ?? undefined) ?? '-'}</td>
<td className="num money">{b.money == null ? '-' : `${b.money.toLocaleString('ko-KR')}`}</td>
</tr>
))}
</tbody>
);
return (
<div className="r3d-sb" role="dialog" aria-label="점수판">
<div className="r3d-sb-head">
<span className="a">아군 {sc.ally}</span>
<span className="muted">R{sc.round}</span>
<span className="e">{sc.enemy} 상대</span>
</div>
<table>
<thead>
<tr>
<th colSpan={2}>선수</th>
<th>궁극기</th>
<th className="num">K</th>
<th className="num">D</th>
<th className="num">A</th>
<th>무기</th>
<th className="num">크레딧</th>
</tr>
</thead>
{team(ally, 'a')}
{team(enemy, 'e')}
</table>
{!ix.has && <div className="muted small r3d-sb-note">이 리플레이는 예전 변환 결과라 크레딧 · 궁극기 · 어시스트가 없습니다. 게임 PC 앱을 1.10.0 이상으로 올리면 다음에 열 때 다시 변환합니다.</div>}
</div>
);
}

View File

@@ -15,6 +15,9 @@ import CrosshairPanel from './CrosshairPanel';
import { buildAnimIndex, rigInput } from '../lib/replayAnim';
import { abilityLook, type AbilityLook } from '../lib/abilities';
import { loadVfxDb, vfxCoverage, VfxObject, type Place, type VfxDb } from '../lib/vfx';
import { buildDirector, shotIndexAt, SHOT_LABEL } from '../lib/director';
import { boardIndex } from '../lib/scoreboard';
import ReplayScoreboard from './ReplayScoreboard';
/**
* 3D 리플레이 (발로란트 .vrf → tools/replay-extract → gvr-replay JSON).
@@ -41,9 +44,12 @@ const REAL_LABEL_CM = 190;
/** 위에서 볼 때 요원 몸을 이만큼 키운다 (맵 전체를 볼 때도 보이게) */
const TOP_MODEL_SCALE = 1.8;
/** 카메라: 위에서 보기(돌리기) · 1인칭(고른 선수 눈) · 자유시점(WASD) */
type CamMode = 'top' | 'fp' | 'free';
const CAM_LABEL: Record<CamMode, string> = { top: '위에서', fp: '1인칭', free: '자유시점' };
/** 카메라: 자동(관전처럼 장면마다 1인칭 · 위에서) · 위에서 보기(돌리기) · 1인칭(고른 선수 눈) · 자유시점(WASD) */
type CamMode = 'auto' | 'top' | 'fp' | 'free';
type View = Exclude<CamMode, 'auto'>;
const CAM_LABEL: Record<CamMode, string> = { auto: '자동', top: '위에서', fp: '1인칭', free: '자유시점' };
/** 자동 · 위에서 볼 때 카메라가 따라가는 빠르기 (1초에 남은 거리의 이만큼) */
const AUTO_EASE = 2.2;
type MapState = { state: 'none' | 'loading' | 'ready' | 'error'; progress?: number };
/** 천장 자르기: 자동 · 끔 · 직접(가장 낮은 층에서 cm) */
@@ -141,6 +147,52 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
xhairRef.current = cfg.crosshair;
const [xOpen, setXOpen] = useState(false);
const hasCrosshairs = useMemo(() => replay.players.some((p) => !!p.crosshair?.length), [replay]);
// 자동 시점: 지금 장면 번호 (화면 표시 · 1인칭 조준점용)
const [shotIdx, setShotIdx] = useState(-1);
// 점수판 (Tab 을 누르는 동안 · 버튼으로 켜고 끔)
const [board, setBoard] = useState(false);
const boardIx = useMemo(() => boardIndex(replay), [replay]);
const rootRef = useRef<HTMLDivElement>(null);
const hoverRef = useRef(false);
// 게임처럼 Tab 을 누르고 있는 동안 점수판. 재생기 위에 마우스가 있거나 재생기 안을 누른 뒤에만 (글 입력 중은 그대로)
useEffect(() => {
let held = false;
const active = () => {
const el = rootRef.current;
return !!el && (hoverRef.current || el.contains(document.activeElement));
};
const typing = (e: KeyboardEvent) => {
const el = e.target as HTMLElement | null;
if (!el) return false;
if (el.isContentEditable || el.tagName === 'TEXTAREA') return true;
return el.tagName === 'INPUT' && !['range', 'checkbox', 'button', 'radio'].includes((el as HTMLInputElement).type);
};
const down = (e: KeyboardEvent) => {
if (e.key !== 'Tab' || e.altKey || e.ctrlKey || e.metaKey || typing(e) || !active()) return;
e.preventDefault();
held = true;
if (!e.repeat) setBoard(true);
};
const up = (e: KeyboardEvent) => {
if (e.key !== 'Tab' || !held) return;
e.preventDefault();
held = false;
setBoard(false);
};
const blur = () => {
if (!held) return;
held = false;
setBoard(false);
};
window.addEventListener('keydown', down, true);
window.addEventListener('keyup', up, true);
window.addEventListener('blur', blur);
return () => {
window.removeEventListener('keydown', down, true);
window.removeEventListener('keyup', up, true);
window.removeEventListener('blur', blur);
};
}, []);
// 바닥(미니맵) 높이: 선수 높이의 하위 5% (떨어져 죽은 기록은 뺀다)
const zBase = useMemo(() => {
@@ -173,6 +225,18 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
for (const r of roster) if (r.info?.userId) map.set(r.info.userId, r.idx);
return map;
}, [roster]);
// 자동 시점 장면 (리플레이 기록 + 우리 팀 대화)
const shots = useMemo(
() =>
buildDirector({
replay,
ally: roster.map((r) => r.ally),
talks: m.utterances.filter((u) => !u.noise && u.text).map((u) => ({ t0: u.ts - base, t1: u.endTs - base, text: u.text! })),
}),
[replay, roster, m.utterances, base],
);
const shotsRef = useRef(shots);
shotsRef.current = shots;
useEffect(() => {
const mount = mountRef.current;
@@ -599,7 +663,13 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
let raf = 0;
let lastUi = 0;
let lastNow = 0;
let lastMode: CamMode = 'top';
let lastMode: View = 'top';
let lastAuto = false;
let lastShot = -1;
// 자동 · 위에서: 카메라가 보는 곳 (부드럽게 따라감)
const autoTarget = new THREE.Vector3();
const autoGoal = new THREE.Vector3();
let autoDist = 100;
const tmp = new THREE.Vector3();
const euler = new THREE.Euler(0, 0, 0, 'YXZ');
/** 1인칭 선수의 손 상태 (모두 리플레이 시각 t 로만 정한다) */
@@ -653,14 +723,30 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
raf = requestAnimationFrame(frame);
const dt = lastNow ? Math.min(0.1, (now - lastNow) / 1000) : 0;
lastNow = now;
const mode = camRef.current;
if (mode !== lastMode) {
controls.enabled = mode === 'top';
const ps = player.state;
const inScene = ps.mode === 'scene' && ps.scene?.label === REPLAY_SCENE_LABEL && ps.sceneTs != null;
const t = inScene ? ps.sceneTs! - base : localT.current;
if (!inScene) localT.current = t;
// 자동: 장면마다 1인칭(그 선수) 또는 위에서 (살아 있는 선수가 다 보이게)
const auto = camRef.current === 'auto';
const si = auto ? shotIndexAt(shotsRef.current, t) : -1;
const shot = si >= 0 ? shotsRef.current[si] : null;
if (si !== lastShot) setShotIdx((lastShot = si));
const mode: View = auto ? (shot?.pov != null ? 'fp' : 'top') : (camRef.current as View);
if (mode !== lastMode || auto !== lastAuto) {
controls.enabled = mode === 'top' && !auto;
camera.near = mode === 'top' ? 0.5 : 0.01;
camera.far = mode === 'top' ? 2000 : 600;
camera.fov = mode === 'fp' ? 70 : 45;
camera.updateProjectionMatrix();
if (mode === 'top') resetCam.current();
// 자동은 1인칭 → 위에서 넘어갈 때 지금 자리에서 부드럽게 빠진다. 자동을 끄면 보던 자리에서 돌리기
if (mode === 'top' && !auto) {
if (lastAuto) {
controls.target.copy(autoTarget);
controls.update();
} else resetCam.current();
}
if (auto && !lastAuto) autoTarget.copy(controls.target);
if (mode === 'free') {
// 지금 보던 방향에서 시작
euler.setFromQuaternion(camera.quaternion);
@@ -669,12 +755,9 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
}
free.keys.clear();
lastMode = mode;
lastAuto = auto;
}
const real = mode !== 'top';
const ps = player.state;
const inScene = ps.mode === 'scene' && ps.scene?.label === REPLAY_SCENE_LABEL && ps.sceneTs != null;
const t = inScene ? ps.sceneTs! - base : localT.current;
if (!inScene) localT.current = t;
const ts = base + t;
// 리플레이 시간 흐름 (애니메이션용, 시간을 크게 옮기면 0)
const dtR = t - prevT >= 0 && t - prevT < 1000 ? (t - prevT) / 1000 : 0;
@@ -685,7 +768,7 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
const i = playerByUser.get(u.userId);
if (i != null) speaking.add(i);
}
const selIdx = selRef.current;
const selIdx = auto ? shot?.pov ?? null : selRef.current;
for (const v of views) {
const tr = replay.players[v.idx].track;
const p = samplePlayer(tr, t, replay.sampleMs * 6);
@@ -695,7 +778,7 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
continue;
}
// 1인칭으로 보는 선수 자신은 숨긴다
v.group.visible = !(mode === 'fp' && v.idx === selRef.current);
v.group.visible = !(mode === 'fp' && v.idx === selIdx);
v.drop.visible = v.shadow.visible = !mapReady && !real;
v.group.position.copy(toWorld(p.x, p.y, Math.max(p.z, zBase - 400) + (real ? REAL_LABEL_CM - FOOT_CM : 0), zBase));
v.group.scale.setScalar(real ? REAL_SCALE : 1);
@@ -772,7 +855,7 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
trailGeo.setDrawRange(0, n);
pos.needsUpdate = true;
trail.visible = n > 1;
if (mode === 'top' && followRef.current && views[selIdx].group.visible) {
if (mode === 'top' && !auto && followRef.current && views[selIdx].group.visible) {
const target = views[selIdx].group.position;
tmp.copy(target).sub(controls.target);
controls.target.add(tmp.multiplyScalar(0.15));
@@ -958,6 +1041,29 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
const speed = (k.has('ShiftLeft') || k.has('ShiftRight') ? 40 : 12) * dt;
tmp.set((k.has('KeyD') || k.has('ArrowRight') ? 1 : 0) - (k.has('KeyA') || k.has('ArrowLeft') ? 1 : 0), (k.has('KeyE') ? 1 : 0) - (k.has('KeyQ') ? 1 : 0), (k.has('KeyS') || k.has('ArrowDown') ? 1 : 0) - (k.has('KeyW') || k.has('ArrowUp') ? 1 : 0));
if (tmp.lengthSq() > 0) camera.position.add(tmp.normalize().multiplyScalar(speed).applyQuaternion(camera.quaternion));
} else if (auto) {
// 전략 보기: 살아 있는 선수(없으면 모두)가 다 들어오게 내려다본다
let n = 0;
let x0 = Infinity, x1 = -Infinity, z0 = Infinity, z1 = -Infinity, ySum = 0;
for (const pass of [0, 1]) {
for (const v of views) {
if (!v.group.visible || (pass === 0 && isDead(replay, v.idx, t))) continue;
const q = v.group.position;
x0 = Math.min(x0, q.x); x1 = Math.max(x1, q.x); z0 = Math.min(z0, q.z); z1 = Math.max(z1, q.z);
ySum += q.y;
n++;
}
if (n) break;
}
if (n) {
autoGoal.set((x0 + x1) / 2, ySum / n, (z0 + z1) / 2);
autoDist = Math.max(36, Math.min(125, Math.max(x1 - x0, (z1 - z0) * camera.aspect * 0.8) * 0.95 + 26));
}
const k = 1 - Math.exp(-dt * AUTO_EASE);
autoTarget.lerp(autoGoal, k);
tmp.set(autoTarget.x, autoTarget.y + autoDist * 0.92, autoTarget.z + autoDist * 0.42);
camera.position.lerp(tmp, k);
camera.lookAt(autoTarget);
} else controls.update();
if (mode !== 'fp') {
vmOn = false;
@@ -1035,6 +1141,10 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
if (to) seek(to.combat >= 0 ? to.combat - 3000 : to.buy);
};
const shot = cam === 'auto' && shotIdx >= 0 ? shots[shotIdx] : null;
// 지금 화면이 1인칭인지 (자동이 1인칭 장면일 때 포함)
const fpView = cam === 'fp' || (cam === 'auto' && shot?.pov != null);
const fpWho = cam === 'auto' ? shot?.pov ?? null : sel;
const chooseCam = (c: CamMode) => {
// 1인칭은 고른 선수가 있어야 한다: 없으면 지금 살아 있는 첫 아군
if (c === 'fp' && sel == null) {
@@ -1046,7 +1156,7 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
if (!T) return <div className="map-missing">이 경기에는 미니맵 좌표 정보가 없어 3D 리플레이를 그릴 수 없습니다</div>;
return (
<div className="r3d">
<div className="r3d" ref={rootRef} onPointerEnter={() => (hoverRef.current = true)} onPointerLeave={() => (hoverRef.current = false)}>
<div className="r3d-stage" ref={mountRef}>
<div className="r3d-hud tl">
<b>{rd ? `R${rd.num}` : ''}</b> <span className="mono">{clock}</span>
@@ -1075,18 +1185,38 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
))}
</div>
)}
{cam === 'fp' && scoped && <div className="r3d-scope" />}
{cam === 'fp' && <canvas ref={crossRef} className="r3d-xcanvas" aria-hidden />}
{cam === 'fp' && xOpen && (
{fpView && scoped && <div className="r3d-scope" />}
{fpView && <canvas ref={crossRef} className="r3d-xcanvas" aria-hidden />}
{fpView && xOpen && (
<CrosshairPanel
playerName={selInfo?.name ?? null}
player={sel != null ? crosshairAt(replay.players[sel].crosshair, ui.t) : null}
playerName={fpWho != null ? roster[fpWho]?.name ?? null : null}
player={fpWho != null ? crosshairAt(replay.players[fpWho].crosshair, ui.t) : null}
hasAny={hasCrosshairs}
onClose={() => setXOpen(false)}
/>
)}
{cam === 'free' && <div className="r3d-hud bl muted small">끌기: 둘러보기 · W A S D: 이동 · Q / E: 아래 / 위 · Shift: 빠르게 (화면을 한 번 누른 뒤)</div>}
{selInfo && cam !== 'free' && (
{cam === 'auto' && shot && (
<div className="r3d-hud bl r3d-auto">
<div className="muted small">자동 · {SHOT_LABEL[shot.kind]}</div>
{shot.pov != null ? (
<div>
<b className={roster[shot.pov]?.ally ? 'a' : 'e'}>{roster[shot.pov]?.name}</b>
{roster[shot.pov]?.info?.character?.name && <span className="muted"> · {roster[shot.pov].info!.character.name}</span>} 시점
{shot.kind === 'fight' && (shot.kills ?? 0) > 1 && <span className="muted"> · {shot.kills}킬</span>}
{(() => {
const w = equipLabel(replay.equipKinds?.[equipAt(equipByPlayer[shot.pov], ui.t)]);
return w ? <div>🔫 {w}</div> : null;
})()}
</div>
) : (
<div className="muted small">살아 있는 선수가 모두 보이게 위에서 봅니다</div>
)}
{shot.call && <div className="r3d-call">콜 “{shot.call}”</div>}
</div>
)}
{board && <ReplayScoreboard m={m} replay={replay} ix={boardIx} roster={roster} t={ui.t} />}
{selInfo && cam !== 'free' && cam !== 'auto' && (
<div className="r3d-hud bl">
<b className={selInfo.ally ? 'a' : 'e'}>{selInfo.name}</b>
{selInfo.info?.character?.name && <span className="muted"> · {selInfo.info.character.name}</span>}
@@ -1145,13 +1275,22 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
</span>
)}
<span className="r3d-cams" role="group" aria-label="카메라">
{(['top', 'fp', 'free'] as CamMode[]).map((c) => (
<button key={c} className={`chip${cam === c ? ' on' : ''}`} onClick={() => chooseCam(c)} aria-pressed={cam === c}>
{(['auto', 'top', 'fp', 'free'] as CamMode[]).map((c) => (
<button
key={c}
className={`chip${cam === c ? ' on' : ''}`}
onClick={() => chooseCam(c)}
aria-pressed={cam === c}
title={c === 'auto' ? '관전처럼 자동으로: 교전 직전에 이긴 선수 1인칭 · 교전이 없으면 위에서 전체 · 설치/해체 · 혼자 남은 선수' : undefined}
>
{CAM_LABEL[c]}
</button>
))}
</span>
{cam === 'fp' && (
<button className={`chip${board ? ' on' : ''}`} onClick={() => setBoard((b) => !b)} aria-pressed={board} title="점수판: 크레딧 · 궁극기 · K/D/A (화면에서 Tab 을 누르고 있어도 됩니다)">
점수판 (Tab)
</button>
{fpView && (
<button className={`chip${xOpen ? ' on' : ''}`} onClick={() => setXOpen((o) => !o)} aria-pressed={xOpen} title="1인칭 조준점: 선수 조준점 · 내 조준점 설정">
조준점
</button>
@@ -1163,7 +1302,14 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
)}
</div>
<div className="r3d-foot muted">
{cam === 'top' ? '마우스 왼쪽 끌기: 회전 · 오른쪽 끌기: 이동 · 휠: 확대 · 선수 클릭: 선택' : cam === 'fp' ? '1인칭: 고른 선수 눈높이 · 다른 선수를 누르면 그 선수로' : '자유시점: 끌어서 둘러보기 · WASD 이동'} ·{' '}
{cam === 'auto'
? '자동: 교전 직전에 이긴 선수 1인칭으로 넘어가고(직전 콜이 있으면 그 말부터), 교전이 없으면 위에서 전체를 봅니다'
: cam === 'top'
? '마우스 왼쪽 끌기: 회전 · 오른쪽 끌기: 이동 · 휠: 확대 · 선수 클릭: 선택'
: cam === 'fp'
? '1인칭: 고른 선수 눈높이 · 다른 선수를 누르면 그 선수로'
: '자유시점: 끌어서 둘러보기 · WASD 이동'}{' '}
· Tab: 점수판 ·{' '}
{sync.matched >= 3
? `대화 동기화: 킬 ${sync.matched}개로 맞춤 (최대 오차 ${((sync.spreadMs ?? 0) / 1000).toFixed(2)}초)`
: '대화 동기화: 라운드 시작으로 대략 맞춤'}

View File

@@ -0,0 +1,272 @@
import { isDead, type ReplayFile } from './replay';
/**
* 자동 관전 (자동 시점): 리플레이 기록(맞은 것 · 킬 · 사격 · 설치/해체)과 그때 나눈 대화로 장면을 나눈다.
* - 교전: 킬마다 이긴 선수(죽인 선수) 1인칭. 교전이 시작되기 FIGHT_LEAD 전에 미리 넘어간다.
* 교전 직전에 우리 팀이 말을 했으면(콜) 그 말이 시작될 때부터 보여 준다 (최대 CALL_LEAD).
* - 스파이크 설치 · 해체: 하는 선수 1인칭
* - 혼자 남은 선수(1 대 N): 그 선수 1인칭
* - 교전이 없을 때: 살아 있는 선수 모두가 보이게 위에서 (전략 보기)
* 시각(t)만으로 정해지므로 되감기 · 건너뛰기 · 배속에도 같은 장면이 나온다.
*/
export type ShotKind = 'fight' | 'skirmish' | 'plant' | 'defuse' | 'clutch' | 'buy' | 'overview' | 'post';
export interface Shot {
t0: number;
t1: number;
kind: ShotKind;
/** 1인칭으로 볼 선수 (리플레이 선수 번호). null 이면 위에서 */
pov: number | null;
/** 이 장면에서 pov 가 낸 킬 수 (교전) */
kills?: number;
/** 교전 직전 콜 (대화 글) */
call?: string;
}
export interface Talk {
/** 리플레이 시각 (ms) */
t0: number;
t1: number;
text: string;
}
export interface DirectorInput {
replay: ReplayFile;
/** 선수별 우리 팀 여부 */
ally: boolean[];
/** 우리 팀 대화 (녹음된 사람은 모두 우리 팀) */
talks: Talk[];
}
/** 교전 시작 전에 미리 넘어가는 시간 */
export const FIGHT_LEAD = 2500;
/** 교전 직전 콜을 찾는 범위 · 콜부터 보여 줄 때 가장 이른 시각 (교전 시작 기준) */
export const CALL_LEAD = 6000;
/** 킬 뒤에 그 선수를 더 보여 주는 시간 */
const FIGHT_TAIL = 1200;
/** 같은 교전으로 보는 사격 간격 · 킬 전에 교전 시작을 찾는 범위 */
const BURST_GAP = 1500;
const DUEL_BACK = 8000;
/** 다음 킬로 넘어갈 때 앞 킬 뒤로 최소 이만큼은 보여 준다 */
const AFTER_KILL = 500;
/** 넘어간 뒤 킬까지 이보다 짧으면 넘어가지 않는다 (무슨 일인지 볼 틈이 없음) */
const MIN_ORIENT = 700;
/** 1인칭 장면 사이 위에서 보기가 이보다 짧으면 앞 장면을 늘린다 · 이보다 짧은 1인칭은 앞 장면에 붙인다 */
const MIN_OVERVIEW = 2000;
const MIN_POV = 900;
type Seg = Shot;
export function buildDirector({ replay: r, ally, talks }: DirectorInput): Shot[] {
const end = r.durationMs;
const team = (p: number) => (p >= 0 ? (ally[p] ? 0 : 1) : -1);
const rounds = r.rounds.map((rd, i) => ({ ...rd, next: r.rounds[i + 1]?.buy ?? end }));
const roundOf = (t: number) => {
let cur = rounds[0];
for (const rd of rounds) if (rd.buy <= t) cur = rd;
return cur;
};
const roundStart = (t: number) => roundOf(t)?.buy ?? 0;
const hits = (r.hits ?? []).filter((h) => h[1] >= 0 && h[2] >= 0 && h[1] !== h[2] && team(h[1]) !== team(h[2])).sort((a, b) => a[0] - b[0]);
const shotsBy: number[][] = r.players.map(() => []);
for (const s of r.shots) if (s[1] >= 0) shotsBy[s[1]]?.push(s[0]);
for (const a of shotsBy) a.sort((x, y) => x - y);
const talksSorted = [...talks].filter((x) => x.text?.trim()).sort((a, b) => a.t0 - b.t0);
// ── 교전 (킬마다) ─────────────────────────────
const duels: { start: number; kill: number; pov: number; call?: string; victim: number }[] = [];
const kills = [...r.kills].sort((a, b) => a[0] - b[0]);
for (const [tk, k, v] of kills) {
if (k < 0 || v < 0 || k === v || team(k) === team(v)) continue;
const floor = Math.max(roundStart(tk), tk - DUEL_BACK);
// 둘 사이 첫 맞은 기록
let start = tk;
for (const h of hits) {
if (h[0] < floor) continue;
if (h[0] > tk) break;
if ((h[1] === k && h[2] === v) || (h[1] === v && h[2] === k)) {
start = Math.min(start, h[0]);
break;
}
}
// 죽인 선수의 이어진 사격 (킬에서 거슬러 올라가며 간격 BURST_GAP 안)
const st = shotsBy[k] ?? [];
let j = upper(st, tk) - 1;
let burst = tk;
while (j >= 0 && st[j] >= floor && burst - st[j] <= BURST_GAP) burst = st[j--];
start = Math.min(start, burst, tk - 1000);
let from = Math.max(floor, start - FIGHT_LEAD);
// 교전 직전 콜: 우리 팀이 낀 교전이면, 교전 시작 CALL_LEAD 안에 시작한 말부터
let call: string | undefined;
if (ally[k] || ally[v]) {
const lo = start - CALL_LEAD;
for (const x of talksSorted) {
if (x.t0 > start) break;
if (x.t0 >= lo && x.t1 >= lo) {
call = x.text.trim();
from = Math.max(roundStart(tk), Math.min(from, x.t0 - 300));
break;
}
}
}
duels.push({ start: from, kill: tk, pov: k, call, victim: v });
}
const segs: Seg[] = [];
for (const d of duels) {
const prev = segs[segs.length - 1];
if (prev && prev.kind === 'fight' && prev.pov === d.pov && d.start <= prev.t1 + MIN_OVERVIEW) {
// 같은 선수가 이어서 죽였다 (멀티킬): 그대로 이어 본다
prev.t1 = Math.max(prev.t1, d.kill + FIGHT_TAIL);
prev.kills = (prev.kills ?? 1) + 1;
prev.call ??= d.call;
continue;
}
let from = d.start;
if (prev && from < prev.t1) {
// 앞 장면과 겹친다: 앞 킬을 보여 준 뒤 넘어간다. 볼 틈이 없으면 넘어가지 않는다
const prevKill = prev.t1 - FIGHT_TAIL;
from = Math.max(from, prevKill + AFTER_KILL);
if (d.kill - from < MIN_ORIENT) continue;
prev.t1 = from;
}
segs.push({ t0: from, t1: Math.min(end, d.kill + FIGHT_TAIL), kind: 'fight', pov: d.pov, kills: 1, call: d.call });
}
// ── 그 밖의 장면: 빈 곳에만 채운다 (설치 · 해체 > 킬 없는 교전 > 혼자 남은 선수) ─────────
const fill: Seg[] = [];
for (const [a0, a1, p, ak] of r.actions ?? []) {
const kind = r.actionKinds?.[ak];
if (kind !== 'Plant' && kind !== 'Defuse') continue;
fill.push({ t0: a0 - 800, t1: (a1 >= a0 ? a1 : a0 + 4000) + 800, kind: kind === 'Plant' ? 'plant' : 'defuse', pov: p });
}
// 킬 없는 교전: 서로 맞힌 기록 묶음 (간격 2.5초 안). 가장 많이 맞힌 선수
const covered = (t: number) => segs.some((s) => s.t0 <= t && t <= s.t1);
for (let i = 0; i < hits.length; ) {
let j = i;
while (j + 1 < hits.length && hits[j + 1][0] - hits[j][0] <= 2500 && roundOf(hits[j + 1][0]) === roundOf(hits[i][0])) j++;
const group = hits.slice(i, j + 1);
i = j + 1;
// 라운드가 끝난 뒤 쏜 것은 교전이 아니다
const rd = roundOf(group[0][0]);
if (rd && rd.end >= 0 && group[0][0] >= rd.end) continue;
if (group.some((h) => covered(h[0]))) continue;
const by = new Map<number, number>();
for (const h of group) by.set(h[1], (by.get(h[1]) ?? 0) + 1);
const last = group[group.length - 1][0];
const best = [...by.entries()].filter(([p]) => !isDead(r, p, last)).sort((a, b) => b[1] - a[1])[0];
if (!best) continue;
fill.push({ t0: Math.max(roundStart(group[0][0]), group[0][0] - FIGHT_LEAD), t1: last + 1000, kind: 'skirmish', pov: best[0] });
}
// 혼자 남은 선수: 킬 뒤 한 팀이 1명이고 상대가 1명 이상이면, 라운드가 끝날 때까지 (그 선수가 죽으면 거기까지)
for (const rd of rounds) {
if (rd.combat < 0) continue;
const stop = rd.end >= 0 ? rd.end : rd.next;
let clutch: { p: number; from: number } | null = null;
for (const [tk] of kills) {
if (tk < rd.combat || tk >= stop) continue;
const alive = [0, 1].map((tm) => r.players.map((_, p) => p).filter((p) => team(p) === tm && !isDead(r, p, tk + 1)));
if (clutch && isDead(r, clutch.p, tk + 1)) {
fill.push({ t0: clutch.from, t1: tk + FIGHT_TAIL, kind: 'clutch', pov: clutch.p });
clutch = null;
}
if (!clutch) {
for (const tm of [0, 1]) {
if (alive[tm].length === 1 && alive[1 - tm].length >= 1) {
clutch = { p: alive[tm][0], from: tk + FIGHT_TAIL };
break;
}
}
}
}
if (clutch) fill.push({ t0: clutch.from, t1: stop, kind: 'clutch', pov: clutch.p });
}
let out = segs;
for (const f of fill) out = paint(out, f);
// ── 나머지: 위에서 (구매 · 전략 보기 · 라운드 끝) ─────────
for (const rd of rounds) {
const combat = rd.combat >= 0 ? rd.combat : rd.buy;
const stop = rd.end >= 0 ? rd.end : rd.next;
out = paint(out, { t0: rd.buy, t1: combat, kind: 'buy', pov: null });
out = paint(out, { t0: combat, t1: stop, kind: 'overview', pov: null });
out = paint(out, { t0: stop, t1: rd.next, kind: 'post', pov: null });
}
out = paint(out, { t0: 0, t1: end, kind: 'overview', pov: null });
return tidy(out.filter((s) => s.t1 > s.t0).map((s) => ({ ...s, t0: Math.max(0, s.t0), t1: Math.min(end, s.t1) })));
}
/** 빈 곳에만 칠한다 (segs 는 시간 순 · 겹치지 않음) */
function paint(segs: Seg[], c: Seg): Seg[] {
if (c.t1 <= c.t0) return segs;
const out: Seg[] = [];
let cur = c.t0;
for (const s of segs) {
if (s.t0 > cur && cur < c.t1) out.push({ ...c, t0: cur, t1: Math.min(s.t0, c.t1) });
out.push(s);
cur = Math.max(cur, s.t1);
}
if (cur < c.t1) out.push({ ...c, t0: cur, t1: c.t1 });
return out.sort((a, b) => a.t0 - b.t0);
}
/** 깜빡이지 않게: 1인칭 사이 짧은 위에서 보기는 앞 장면을 늘리고, 짧은 1인칭은 앞 장면에 붙이고, 같은 장면은 합친다 */
function tidy(segs: Seg[]): Shot[] {
const out: Seg[] = [];
for (let i = 0; i < segs.length; i++) {
const s = { ...segs[i] };
const prev = out[out.length - 1];
const next = segs[i + 1];
const len = s.t1 - s.t0;
if (prev && s.pov == null && prev.pov != null && next?.pov != null && len < MIN_OVERVIEW) {
prev.t1 = s.t1;
continue;
}
if (prev && s.pov != null && len < MIN_POV) {
prev.t1 = s.t1;
continue;
}
if (prev && prev.kind === s.kind && prev.pov === s.pov && prev.t1 >= s.t0) {
prev.t1 = s.t1;
prev.kills = (prev.kills ?? 0) + (s.kills ?? 0) || undefined;
prev.call ??= s.call;
continue;
}
out.push(s);
}
return out;
}
/** t 시점 장면 (번호). 없으면 -1 */
export function shotIndexAt(shots: Shot[], t: number): number {
let lo = 0;
let hi = shots.length - 1;
if (hi < 0 || t < shots[0].t0) return shots.length ? 0 : -1;
while (lo < hi) {
const mid = (lo + hi + 1) >> 1;
if (shots[mid].t0 <= t) lo = mid;
else hi = mid - 1;
}
return lo;
}
function upper(a: number[], t: number) {
let lo = 0;
let hi = a.length;
while (lo < hi) {
const mid = (lo + hi) >> 1;
if (a[mid] <= t) lo = mid + 1;
else hi = mid;
}
return lo;
}
export const SHOT_LABEL: Record<ShotKind, string> = {
fight: '교전',
skirmish: '교전 (킬 없음)',
plant: '스파이크 설치',
defuse: '스파이크 해체',
clutch: '혼자 남음',
buy: '구매 단계 · 전체 보기',
overview: '전략 보기',
post: '라운드 끝',
};

View File

@@ -48,6 +48,8 @@ export interface ReplayFile {
/** 들고 있는 것이 바뀐 시각 [t, player, kind] (변환기 새 버전부터. 옛 리플레이 JSON 에는 없다) */
equips?: [number, number, number][];
equipKinds?: string[];
/** 점수판 (게임 Tab): 선수 값이 바뀔 때마다 [t, player, 크레딧, 궁극기 점수, 킬, 데스, 어시스트, 전투 점수] (모르는 값 -1, 변환기 1.10.0~) */
scoreboard?: number[][];
}
export interface ObjectPath {

View File

@@ -0,0 +1,147 @@
import { indexAt, isDead, roundAt, type ReplayFile } from './replay';
/**
* 리플레이 점수판 (게임에서 Tab 을 누른 화면): 크레딧 · 궁극기 점수 · 킬/데스/어시 · 전투 점수.
* 값은 변환기(1.10.0~)의 scoreboard 행 [t, 선수, 크레딧, 궁 점수, 킬, 데스, 어시, 전투 점수] (모르는 값 -1).
* 옛 리플레이 JSON 에는 없어서 킬 · 데스만 리플레이 킬 기록으로 센다.
*/
const MONEY = 2;
const ULT = 3;
const KILLS = 4;
const DEATHS = 5;
const ASSISTS = 6;
const SCORE = 7;
/** 요원(캐릭터 클래스 코드)별 궁극기 점수. 경기에서 궁을 쓴 기록이 있으면 그 값을 쓰고, 없을 때만 이 표 (패치로 바뀔 수 있다) */
const ULT_COST: Record<string, number> = {
Wushu: 8, Sarge: 8, Phoenix: 7, Hunter: 8, Thorne: 8, Pandemic: 9, Wraith: 7, Clay: 8, Vampire: 7, Breach: 8, Gumshoe: 6,
Killjoy: 9, Guide: 8, Stealth: 8, Rift: 7, Grenadier: 8, Deadeye: 8, Sprinter: 7, BountyHunter: 8, Mage: 7, AggroBot: 8,
Cable: 7, Sequoia: 7, Smonk: 8, Nox: 8, Cashew: 8, Terra: 8,
};
const DEFAULT_ULT = 8;
const PRIMARY = new Set(['Stinger', 'Spectre', 'Bucky', 'Judge', 'Bulldog', 'Guardian', 'Phantom', 'Vandal', 'Marshal', 'Outlaw', 'Operator', 'Ares', 'Odin']);
const SIDEARM = new Set(['Classic', 'Shorty', 'Frenzy', 'Ghost', 'Sheriff', 'Compact Pistol']);
export interface BoardIndex {
/** 선수별 행 · 행 시각 */
rows: number[][][];
times: number[][];
/** 선수별 궁극기 점수 (다 모으면 궁 준비) */
ultMax: number[];
has: boolean;
}
export function boardIndex(r: ReplayFile): BoardIndex {
const rows: number[][][] = r.players.map(() => []);
for (const row of r.scoreboard ?? []) rows[row[1]]?.push(row);
for (const a of rows) a.sort((x, y) => x[0] - y[0]);
const times = rows.map((a) => a.map((x) => x[0]));
return { rows, times, ultMax: ultCosts(r, rows), has: rows.some((a) => a.length > 0) };
}
/**
* 궁극기 점수: 궁을 쓴 순간(점수가 0 으로 떨어짐) 바로 앞 점수. 모두가 같은 때 0 이 되는 것(공수 교대 초기화)은 쓴 것이 아니다.
* 쓴 기록이 없으면 요원 표 값과 경기에서 모은 가장 큰 점수 중 큰 것
*/
export function ultCosts(r: ReplayFile, rows: number[][][]): number[] {
const drops: { t: number; p: number; from: number }[] = [];
const maxSeen = rows.map(() => 0);
rows.forEach((a, p) => {
let last = -1;
for (const row of a) {
const v = row[ULT];
if (v < 0) continue;
maxSeen[p] = Math.max(maxSeen[p], v);
if (last > 0 && v === 0) drops.push({ t: row[0], p, from: last });
last = v;
}
});
const used: number[][] = rows.map(() => []);
for (const d of drops) {
const same = drops.filter((x) => Math.abs(x.t - d.t) <= 3000).length;
if (same >= Math.max(3, Math.ceil(r.players.length / 2))) continue; // 초기화
used[d.p].push(d.from);
}
return r.players.map((pl, p) => {
if (used[p].length) return mode(used[p]);
const code = (pl.character ?? '').replace(/_PC_C$/, '');
return Math.max(ULT_COST[code] ?? DEFAULT_ULT, maxSeen[p]);
});
}
export interface BoardRow {
idx: number;
money: number | null;
ult: number | null;
ultMax: number;
kills: number;
deaths: number;
assists: number | null;
score: number | null;
/** 이 라운드에 가진 주무기 (없으면 보조무기) 영어 이름 */
weapon: string | null;
dead: boolean;
}
export function boardAt(r: ReplayFile, ix: BoardIndex, p: number, t: number): BoardRow {
const i = indexAt(ix.times[p] ?? [], t);
const row = i >= 0 ? ix.rows[p][i] : null;
// 게임은 기본값(0)과 다를 때만 값을 보낸다: 점수판이 있는 리플레이에서 안 온 숫자는 0. 크레딧은 처음부터 오므로 모르면 비운다
const val = (k: number) => (row && row[k] >= 0 ? row[k] : ix.has && k !== MONEY ? 0 : null);
let kills = val(KILLS);
let deaths = val(DEATHS);
if (kills == null || deaths == null) {
// 옛 리플레이: 킬 기록으로 센다
let k = 0;
let d = 0;
for (const [kt, ki, vi] of r.kills) {
if (kt > t) continue;
if (ki === p && vi !== p) k++;
if (vi === p) d++;
}
kills ??= k;
deaths ??= d;
}
return {
idx: p,
money: val(MONEY),
ult: val(ULT),
ultMax: ix.ultMax[p] ?? DEFAULT_ULT,
kills,
deaths,
assists: val(ASSISTS),
score: val(SCORE),
weapon: loadoutAt(r, p, t),
dead: isDead(r, p, t),
};
}
/** 이 라운드(구매 단계부터 t 까지) 마지막으로 든 주무기, 없으면 보조무기 */
export function loadoutAt(r: ReplayFile, p: number, t: number): string | null {
const rd = roundAt(r, t);
const from = rd?.buy ?? 0;
let primary: string | null = null;
let side: string | null = null;
for (const [et, ep, k] of r.equips ?? []) {
if (ep !== p || et < from || et > t) continue;
const name = r.equipKinds?.[k] ?? '';
if (PRIMARY.has(name)) primary = name;
else if (SIDEARM.has(name)) side = name;
}
return primary ?? side;
}
/** 라운드 · 팀 점수: t 가 속한 라운드 번호와 그 라운드 전까지 이긴 수 */
export function teamScoreAt(r: ReplayFile, rounds: { num: number; score: { ally: number; enemy: number } }[] | undefined, t: number) {
const rd = roundAt(r, t);
const num = rd?.num ?? 1;
const before = rounds?.filter((x) => x.num < num).sort((a, b) => b.num - a.num)[0];
return { round: num, ally: before?.score.ally ?? 0, enemy: before?.score.enemy ?? 0 };
}
function mode(a: number[]) {
const c = new Map<number, number>();
for (const v of a) c.set(v, (c.get(v) ?? 0) + 1);
return [...c.entries()].sort((x, y) => y[1] - x[1] || y[0] - x[0])[0][0];
}

View File

@@ -4075,6 +4075,129 @@ button.match:hover {
color: var(--gold);
margin-right: 6px;
}
/* 자동 시점 표시 */
.r3d-auto {
pointer-events: none;
max-width: min(44%, 420px);
}
.r3d-call {
margin-top: 4px;
color: var(--gold);
font-size: 13px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
/* 점수판 (게임 Tab 화면) */
.r3d-sb {
position: absolute;
z-index: 4;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
width: min(94%, 760px);
max-height: calc(100% - 24px);
overflow: auto;
padding: 10px 12px 12px;
border-radius: 12px;
background: rgba(8, 14, 20, 0.9);
border: 1px solid rgba(255, 255, 255, 0.08);
pointer-events: none;
}
.r3d-sb-head {
display: flex;
justify-content: center;
align-items: baseline;
gap: 18px;
font-size: 22px;
font-weight: 800;
margin-bottom: 8px;
}
.r3d-sb-head .muted {
font-size: 14px;
font-weight: 600;
}
.r3d-sb table {
width: 100%;
border-collapse: separate;
border-spacing: 0 3px;
font-size: 14px;
}
.r3d-sb th {
text-align: left;
font-size: 12px;
font-weight: 600;
color: var(--muted, #8a97a6);
padding: 0 8px 2px;
}
.r3d-sb td {
padding: 5px 8px;
white-space: nowrap;
}
.r3d-sb .num {
text-align: right;
font-variant-numeric: tabular-nums;
}
.r3d-sb-team.a td {
background: rgba(63, 182, 255, 0.13);
}
.r3d-sb-team.e td {
background: rgba(255, 77, 94, 0.13);
}
.r3d-sb-team td:first-child {
border-radius: 6px 0 0 6px;
}
.r3d-sb-team td:last-child {
border-radius: 0 6px 6px 0;
}
.r3d-sb-team.e tr:first-child td {
border-top: 6px solid transparent;
background-clip: padding-box;
}
.r3d-sb tr.dead td {
opacity: 0.5;
}
.r3d-sb .ag {
width: 30px;
padding-right: 0;
}
.r3d-sb .ag img,
.r3d-sb .ag-ph {
display: block;
width: 28px;
height: 28px;
border-radius: 6px;
background: rgba(255, 255, 255, 0.08);
}
.r3d-sb .nm {
max-width: 220px;
overflow: hidden;
text-overflow: ellipsis;
}
.r3d-sb .money {
color: #9be89b;
}
.ult-dots {
display: inline-flex;
gap: 3px;
}
.ult-dots i {
width: 7px;
height: 7px;
border-radius: 50%;
border: 1px solid rgba(255, 255, 255, 0.45);
}
.ult-dots i.on {
background: #f5e6a3;
border-color: #f5e6a3;
}
.ult-ready {
color: #f5e6a3;
font-weight: 800;
}
.r3d-sb-note {
margin-top: 8px;
}
.r3d-follow {
display: flex;
align-items: center;