diff --git a/docs/dev/replay-3d.md b/docs/dev/replay-3d.md index 04eaceb..1d20c7a 100644 --- a/docs/dev/replay-3d.md +++ b/docs/dev/replay-3d.md @@ -106,3 +106,14 @@ - 사이트 `lib/crosshair.ts` (그리기 · 발로란트 조준점 코드 읽기) · `components/CrosshairPanel.tsx`: 1인칭 "조준점" 버튼 → 선수 조준점(없으면 내 조준점) / 모든 선수에 내 조준점, 내 조준점 직접 고치기 · 코드 가져오기 · 선수 조준점 복사. 설정은 브라우저 `gvr.settings.v1` `crosshair`. - 정조준(저격총 아님) 중에 고급 설정 + 정조준 조준점 따로면 ads, 저격 줌은 조준경 가운데 점. 사격 오차 · 이동 오차 켠 선은 쏜 뒤 0.35초 · 걷는 동안 벌어진다 (총마다 다른 실제 퍼짐이 아니라 대략). - 옛 리플레이 JSON 에는 없다. 앱은 버전이 바뀌면 다시 변환하므로 1.8.2 로 올리면 다음에 열 때 생긴다. + +## 자동 시점 · Tab 점수판 (2026-11-08) +- 변환기: `scoreboard` 행 `[t, 선수, 크레딧, 궁 점수, 킬, 데스, 어시, 전투 점수]` (바뀔 때마다 그 선수 전체 값, 모르는 값 -1). 크레딧은 `MoneyManagementComponent.Money`, 궁은 `BombPlayerState.NumUltimatePoints` (파서 기본 목록), 킬/데스/어시 · 전투 점수는 PlayerState 하위 객체 `BasicCombatStatsComponent` · `PlayerScoreComponent` 를 이름으로 목록에 더해 읽는다 (`Collector.Catalog`, 하위 객체 이름 → 클래스 `AddSubobjectClassPath` 가 없으면 그룹이 비어 온다). 게임은 기본값(0)과 다를 때만 보내므로 사이트는 안 온 숫자를 0 으로 본다. + - 13.08 어비스: 행 1706개, 변환 6.8초(+0.2초). 체력 · 방어구(`ChildDamageSectionComponent`)는 리플레이에 값이 오지 않는다. + - 궁극기 점수는 리플레이에 없다: 사이트가 궁을 쓴 순간(0 으로 떨어지기 직전 값, 절반 넘는 선수가 3초 안에 같이 0 이 되는 공수 교대 초기화는 뺌)으로 정하고, 쓴 적이 없으면 요원 표(`lib/scoreboard.ts` ULT_COST)와 모은 최대값 중 큰 것. 13.08 실측 피닉스 7 · 나머지 8. +- 사이트 `lib/scoreboard.ts` · `components/ReplayScoreboard.tsx`: 재생기 위에 마우스가 있거나 재생기 안을 누른 뒤 Tab 을 누르고 있는 동안 (버튼으로 켜고 끌 수도). 팀 점수(그 라운드 전까지) · 궁극기 점 · K/D/A · 이 라운드 주무기 · 크레딧, 전투 점수 순, 죽은 선수 흐리게. 옛 JSON 은 킬 · 데스만 킬 기록으로. +- 자동 시점 `lib/director.ts` (카메라 "자동"): 시각만으로 장면을 정한다 (되감기 · 배속에도 같음). + - 교전: 킬마다 죽인 선수 1인칭. 교전 시작(둘 사이 첫 맞은 기록 · 죽인 선수의 이어진 사격, 8초 안) 2.5초 전부터. 우리 팀이 낀 교전이면 교전 시작 6초 안에 시작한 대화(콜)부터 보여 주고 화면에 콜 글. 같은 선수가 이어 죽이면 한 장면, 다음 킬은 앞 킬 0.5초 뒤에 넘어가고 넘어간 뒤 0.7초 안에 킬이면 넘어가지 않는다 (맞킬). + - 빈 곳: 스파이크 설치 · 해체 > 킬 없는 교전(가장 많이 맞힌 산 선수) > 혼자 남은 선수(1 대 N) > 위에서 (구매 · 전략 보기 · 라운드 끝). 위에서는 살아 있는 선수가 모두 들어오게 부드럽게 따라간다. 2초보다 짧은 위에서 보기 · 0.9초보다 짧은 1인칭은 앞 장면에 붙인다. + - 13.08 어비스: 장면 265개 · 계산 15ms, 상대 팀끼리 킬 145개 중 126개를 죽인 선수 1인칭으로 (나머지는 1초 안 맞킬). +- 시험: `site/server/test/replay-director.test.ts`, 변환기 `gvr-replay --self-test` (점수판 줄 합치기). diff --git a/site/server/test/replay-director.test.ts b/site/server/test/replay-director.test.ts new file mode 100644 index 0000000..65b2e95 --- /dev/null +++ b/site/server/test/replay-director.test.ts @@ -0,0 +1,132 @@ +// 사이트 3D 리플레이: 자동 시점(관전) 장면 나누기 · 점수판 (site/web/src/lib/director.ts · scoreboard.ts) +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import type { ReplayFile } from '../../web/src/lib/replay.ts'; +import { buildDirector, shotIndexAt, FIGHT_LEAD, type Shot } from '../../web/src/lib/director.ts'; +import { boardAt, boardIndex, loadoutAt, teamScoreAt } from '../../web/src/lib/scoreboard.ts'; + +// 선수 0·1·4 아군, 2·3·5 상대. 라운드 1: 구매 0~30초, 교전 30초~, 끝 90초. 라운드 2: 100초~ +const still = (n = 2000) => { + const t = Array.from({ length: n }, (_, i) => i * 100); + return { t, x: t.map(() => 0), y: t.map(() => 0), z: t.map(() => 100), yaw: t.map(() => 0), pitch: t.map(() => 0) }; +}; +function replay(extra: Partial = {}): ReplayFile { + return { + format: 'gvr-replay', v: 2, matchId: 'm1', map: null, build: null, recordedAt: 0, durationMs: 200_000, sampleMs: 100, + players: [0, 1, 2, 3, 4, 5].map((i) => ({ puuid: `p${i}`, character: i === 1 ? 'Phoenix_PC_C' : 'Wushu_PC_C', track: still() })), + rounds: [{ num: 1, buy: 0, combat: 30_000, end: 90_000 }, { num: 2, buy: 100_000, combat: 130_000, end: -1 }], + phases: [], shots: [], objects: [], objectKinds: [], kills: [], hits: [], + ...extra, + }; +} +const ally = [true, true, false, false, true, false]; +const at = (shots: Shot[], t: number) => shots[shotIndexAt(shots, t)]; +const hit = (t: number, a: number, v: number, killed = 0) => [t, a, v, 0, 0, 0, 0, 0, 0, 2, killed]; + +test('교전: 킬 시각에는 이긴(죽인) 선수 1인칭, 교전 시작보다 먼저 넘어간다', () => { + const r = replay({ kills: [[40_000, 0, 2, -1]], hits: [hit(38_000, 2, 0), hit(39_000, 0, 2), hit(40_000, 0, 2, 1)] }); + const shots = buildDirector({ replay: r, ally, talks: [] }); + const s = at(shots, 40_000); + assert.equal(s.kind, 'fight'); + assert.equal(s.pov, 0); + // 둘 사이 첫 맞은 기록(38초)보다 FIGHT_LEAD 앞에서 시작 + assert.ok(s.t0 <= 38_000 - FIGHT_LEAD, `시작 ${s.t0}`); + // 교전이 없을 때: 구매 단계 · 전략 보기는 위에서 + assert.equal(at(shots, 10_000).kind, 'buy'); + assert.equal(at(shots, 10_000).pov, null); + assert.equal(at(shots, 70_000).kind, 'overview'); + assert.equal(at(shots, 70_000).pov, null); + assert.equal(at(shots, 95_000).kind, 'post'); + // 빈틈 · 겹침 없이 처음부터 끝까지 + assert.equal(shots[0].t0, 0); + assert.equal(shots[shots.length - 1].t1, r.durationMs); + for (let i = 1; i < shots.length; i++) assert.equal(shots[i].t0, shots[i - 1].t1); +}); + +test('교전 직전 우리 팀 콜이 있으면 그 말부터 보여 주고 콜 글을 단다', () => { + const r = replay({ kills: [[40_000, 2, 0, -1]], hits: [hit(38_000, 2, 0), hit(40_000, 2, 0, 1)] }); + const shots = buildDirector({ replay: r, ally, talks: [{ t0: 33_000, t1: 34_500, text: '비 메인 두 명' }] }); + const s = at(shots, 40_000); + // 상대가 이겼으면 상대 시점 + assert.equal(s.pov, 2); + assert.equal(s.call, '비 메인 두 명'); + assert.ok(s.t0 <= 33_000 && s.t0 >= 32_000, `시작 ${s.t0}`); + // 교전과 먼 대화는 콜로 보지 않는다 + const far = buildDirector({ replay: r, ally, talks: [{ t0: 20_000, t1: 21_000, text: '사러 가자' }] }); + assert.equal(at(far, 40_000).call, undefined); +}); + +test('같은 선수가 이어서 죽이면 한 장면 · 거의 동시에 맞바꾼 킬은 넘어가지 않는다 · 짧은 장면 없음', () => { + const r = replay({ + kills: [[40_000, 0, 2, -1], [42_000, 0, 3, -1], [60_000, 1, 2, -1], [60_300, 3, 1, -1]], + hits: [hit(39_500, 0, 2, 1), hit(41_800, 0, 3, 1), hit(59_000, 1, 2), hit(60_200, 3, 1)], + }); + const shots = buildDirector({ replay: r, ally, talks: [] }); + const multi = at(shots, 41_000); + assert.equal(multi.pov, 0); + assert.equal(multi.kills, 2); + assert.equal(at(shots, 42_000), multi); + // 0.3초 뒤 맞킬: 앞 킬을 보여 주던 선수 시점 그대로 + assert.equal(at(shots, 60_300).pov, 1); + for (const s of shots) if (s.pov != null) assert.ok(s.t1 - s.t0 >= 900, `짧은 1인칭 ${s.t0}~${s.t1}`); +}); + +test('스파이크 설치 · 해체는 하는 선수 시점, 혼자 남은 선수는 그 선수 시점', () => { + const r = replay({ + actions: [[50_000, 54_000, 3, 0]], + actionKinds: ['Plant'], + kills: [[60_000, 2, 0, -1], [62_000, 3, 4, -1]], + hits: [hit(59_000, 2, 0, 1), hit(61_500, 3, 4, 1)], + }); + const shots = buildDirector({ replay: r, ally, talks: [] }); + assert.equal(at(shots, 52_000).kind, 'plant'); + assert.equal(at(shots, 52_000).pov, 3); + // 60초에 0 이 죽고, 62초에 4 가 죽어 아군은 1 혼자 + const c = at(shots, 75_000); + assert.equal(c.kind, 'clutch'); + assert.equal(c.pov, 1); +}); + +test('점수판: 궁극기 점수는 쓴 기록에서 · 공수 교대 초기화는 쓴 것이 아니다 · 안 온 숫자는 0', () => { + // [t, 선수, 크레딧, 궁, 킬, 데스, 어시, 점수] + const sb = [ + [1000, 0, 800, -1, -1, -1, -1, -1], + [1000, 1, 800, -1, -1, -1, -1, -1], + [20_000, 1, 800, 7, -1, -1, -1, -1], + [25_000, 1, 800, 0, -1, -1, -1, -1], // 1 이 궁을 씀 (7점) + [40_000, 0, 3900, 5, 2, 1, 1, 400], + [41_000, 1, 2000, 3, -1, -1, -1, -1], + [42_000, 2, 800, 2, -1, -1, -1, -1], + [42_000, 3, 800, 1, -1, -1, -1, -1], + // 공수 교대: 모두 0 + [95_000, 0, 800, 0, 2, 1, 1, 400], + [95_000, 1, 800, 0, -1, -1, -1, -1], + [95_100, 2, 800, 0, -1, -1, -1, -1], + [95_100, 3, 800, 0, -1, -1, -1, -1], + ]; + const r = replay({ scoreboard: sb, kills: [[40_000, 0, 2, -1]], equips: [[31_000, 0, 0], [32_000, 0, 1], [33_000, 0, 2]], equipKinds: ['Classic', 'Vandal', 'Melee'] }); + const ix = boardIndex(r); + assert.equal(ix.has, true); + assert.equal(ix.ultMax[1], 7); // 쓴 기록 (요원 표와 상관없이) + assert.equal(ix.ultMax[0], 8); // 쓴 기록 없음: 요원 표 (제트 8) + const b = boardAt(r, ix, 0, 50_000); + assert.deepEqual([b.money, b.ult, b.kills, b.deaths, b.assists, b.score, b.weapon], [3900, 5, 2, 1, 1, 400, 'Vandal']); + // 아직 안 온 킬 · 어시는 0, 크레딧은 처음 값 + const b1 = boardAt(r, ix, 1, 50_000); + assert.deepEqual([b1.money, b1.ult, b1.kills, b1.assists], [2000, 3, 0, 0]); + // 주무기는 라운드마다: 다음 라운드에는 아직 없음 + assert.equal(loadoutAt(r, 0, 120_000), null); + // 죽은 선수 (시험 이동 기록은 죽은 뒤에도 표본이 있어 죽은 직후로 본다) + assert.equal(boardAt(r, ix, 2, 41_000).dead, true); +}); + +test('점수판: 예전 리플레이(값 없음)는 킬 · 데스를 킬 기록으로 세고 나머지는 비운다 · 팀 점수는 그 라운드 전까지', () => { + const r = replay({ kills: [[40_000, 0, 2, -1], [50_000, 3, 0, -1]] }); + const ix = boardIndex(r); + assert.equal(ix.has, false); + const b = boardAt(r, ix, 0, 60_000); + assert.deepEqual([b.kills, b.deaths, b.money, b.ult, b.assists], [1, 1, null, null, null]); + const rounds = [{ num: 1, score: { ally: 1, enemy: 0 } }, { num: 2, score: { ally: 1, enemy: 1 } }]; + assert.deepEqual(teamScoreAt(r, rounds, 50_000), { round: 1, ally: 0, enemy: 0 }); + assert.deepEqual(teamScoreAt(r, rounds, 150_000), { round: 2, ally: 1, enemy: 0 }); +}); diff --git a/site/web/src/components/ReplayScoreboard.tsx b/site/web/src/components/ReplayScoreboard.tsx new file mode 100644 index 0000000..a617c5a --- /dev/null +++ b/site/web/src/components/ReplayScoreboard.tsx @@ -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') => ( + + {list.map(({ r, b }) => ( + + + {r.info?.character?.icon ? : } + + + {r.name} + {r.info?.character?.name && {r.info.character.name}} + + + {b.ult == null ? ( + - + ) : b.ult >= b.ultMax ? ( + 궁 준비 + ) : ( + + {Array.from({ length: b.ultMax }, (_, i) => ( + + ))} + + )} + + {b.kills} + {b.deaths} + {b.assists ?? '-'} + {equipLabel(b.weapon ?? undefined) ?? '-'} + {b.money == null ? '-' : `${b.money.toLocaleString('ko-KR')}`} + + ))} + + ); + return ( +
+
+ 아군 {sc.ally} + R{sc.round} + {sc.enemy} 상대 +
+ + + + + + + + + + + + + {team(ally, 'a')} + {team(enemy, 'e')} +
선수궁극기KDA무기크레딧
+ {!ix.has &&
이 리플레이는 예전 변환 결과라 크레딧 · 궁극기 · 어시스트가 없습니다. 게임 PC 앱을 1.10.0 이상으로 올리면 다음에 열 때 다시 변환합니다.
} +
+ ); +} diff --git a/site/web/src/components/ReplayViewer.tsx b/site/web/src/components/ReplayViewer.tsx index 27d565f..00cfcff 100644 --- a/site/web/src/components/ReplayViewer.tsx +++ b/site/web/src/components/ReplayViewer.tsx @@ -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 = { top: '위에서', fp: '1인칭', free: '자유시점' }; +/** 카메라: 자동(관전처럼 장면마다 1인칭 · 위에서) · 위에서 보기(돌리기) · 1인칭(고른 선수 눈) · 자유시점(WASD) */ +type CamMode = 'auto' | 'top' | 'fp' | 'free'; +type View = Exclude; +const CAM_LABEL: Record = { 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(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
이 경기에는 미니맵 좌표 정보가 없어 3D 리플레이를 그릴 수 없습니다
; return ( -
+
(hoverRef.current = true)} onPointerLeave={() => (hoverRef.current = false)}>
{rd ? `R${rd.num}` : ''} {clock} @@ -1075,18 +1185,38 @@ export default function ReplayViewer({ m, replay, sync }: Props) { ))}
)} - {cam === 'fp' && scoped &&
} - {cam === 'fp' && } - {cam === 'fp' && xOpen && ( + {fpView && scoped &&
} + {fpView && } + {fpView && xOpen && ( setXOpen(false)} /> )} {cam === 'free' &&
끌기: 둘러보기 · W A S D: 이동 · Q / E: 아래 / 위 · Shift: 빠르게 (화면을 한 번 누른 뒤)
} - {selInfo && cam !== 'free' && ( + {cam === 'auto' && shot && ( +
+
자동 · {SHOT_LABEL[shot.kind]}
+ {shot.pov != null ? ( +
+ {roster[shot.pov]?.name} + {roster[shot.pov]?.info?.character?.name && · {roster[shot.pov].info!.character.name}} 시점 + {shot.kind === 'fight' && (shot.kills ?? 0) > 1 && · {shot.kills}킬} + {(() => { + const w = equipLabel(replay.equipKinds?.[equipAt(equipByPlayer[shot.pov], ui.t)]); + return w ?
🔫 {w}
: null; + })()} +
+ ) : ( +
살아 있는 선수가 모두 보이게 위에서 봅니다
+ )} + {shot.call &&
콜 “{shot.call}”
} +
+ )} + {board && } + {selInfo && cam !== 'free' && cam !== 'auto' && (
{selInfo.name} {selInfo.info?.character?.name && · {selInfo.info.character.name}} @@ -1145,13 +1275,22 @@ export default function ReplayViewer({ m, replay, sync }: Props) { )} - {(['top', 'fp', 'free'] as CamMode[]).map((c) => ( - ))} - {cam === 'fp' && ( + + {fpView && ( @@ -1163,7 +1302,14 @@ export default function ReplayViewer({ m, replay, sync }: Props) { )}
- {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)}초)` : '대화 동기화: 라운드 시작으로 대략 맞춤'} diff --git a/site/web/src/lib/director.ts b/site/web/src/lib/director.ts new file mode 100644 index 0000000..2d0f045 --- /dev/null +++ b/site/web/src/lib/director.ts @@ -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(); + 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 = { + fight: '교전', + skirmish: '교전 (킬 없음)', + plant: '스파이크 설치', + defuse: '스파이크 해체', + clutch: '혼자 남음', + buy: '구매 단계 · 전체 보기', + overview: '전략 보기', + post: '라운드 끝', +}; diff --git a/site/web/src/lib/replay.ts b/site/web/src/lib/replay.ts index 17a819d..76077fb 100644 --- a/site/web/src/lib/replay.ts +++ b/site/web/src/lib/replay.ts @@ -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 { diff --git a/site/web/src/lib/scoreboard.ts b/site/web/src/lib/scoreboard.ts new file mode 100644 index 0000000..dc94ff5 --- /dev/null +++ b/site/web/src/lib/scoreboard.ts @@ -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 = { + 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(); + 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]; +} diff --git a/site/web/src/styles.css b/site/web/src/styles.css index 105e9aa..0a6fc3a 100644 --- a/site/web/src/styles.css +++ b/site/web/src/styles.css @@ -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; diff --git a/tools/replay-extract/src/Collector.cs b/tools/replay-extract/src/Collector.cs index 0f27b30..fa28b6f 100644 --- a/tools/replay-extract/src/Collector.cs +++ b/tools/replay-extract/src/Collector.cs @@ -5,6 +5,7 @@ using Replay.Models.Unreal; using Replay.Valorant.Combat; using Replay.Valorant.Descriptors; using Replay.Valorant.Descriptors.Agents; +using Replay.Valorant.Economy; using Replay.Valorant.Events.Combat; using Replay.Valorant.Events.Movement; using Replay.Valorant.Flashes.Descriptors; @@ -50,6 +51,55 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink private readonly Dictionary _equipName = []; private readonly List<(int T, uint Character, uint Equip)> _equips = []; private readonly List<(int T, uint State, string Name)> _shotEquips = []; + // 점수판 (게임 Tab): PlayerState 액터별 크레딧 · 궁극기 점수 · 킬/데스/어시 · 전투 점수가 바뀐 시각 + private readonly List<(int T, uint State, int Field, int Value)> _board = []; + + /// 점수판 열 (scoreboard 행의 2번째부터): 크레딧 · 궁극기 점수 · 킬 · 데스 · 어시스트 · 전투 점수 + public const int BoardMoney = 0, BoardUlt = 1, BoardKills = 2, BoardDeaths = 3, BoardAssists = 4, BoardScore = 5, BoardFields = 6; + public const string CombatStatsPath = "/Script/ShooterGame.BasicCombatStatsComponent"; + public const string ScorePath = "/Script/ShooterGame.PlayerScoreComponent"; + private static readonly Dictionary CombatFields = new() + { + ["AggregateKills"] = BoardKills, ["AggregateDeaths"] = BoardDeaths, ["AggregateAssists"] = BoardAssists, ["Score"] = BoardScore, + }; + + /// + /// 점수판 행: 선수 값이 바뀔 때마다 그 선수 전체 값 [t, 선수, 크레딧, 궁 점수, 킬, 데스, 어시, 전투 점수] (아직 안 온 값 -1). + /// 같은 시각에 나눠 온 것은 한 줄로, 값이 그대로면 줄을 넣지 않는다. 선수를 모르는 기록(-1)은 건너뛴다 + /// + public static List BuildScoreboard(IEnumerable<(int T, int Player, int Field, int Value)> rows) + { + var board = new List(); + var now = new Dictionary(); + foreach (var (t, pi, field, value) in rows.OrderBy(b => b.T)) + { + if (pi < 0) continue; + if (!now.TryGetValue(pi, out var cur)) now[pi] = cur = Enumerable.Repeat(-1, BoardFields).ToArray(); + if (cur[field] == value) continue; + cur[field] = value; + var row = new int[2 + BoardFields]; + row[0] = t; + row[1] = pi; + Array.Copy(cur, 0, row, 2, BoardFields); + if (board.Count > 0 && board[^1][0] == t && board[^1][1] == pi) board[^1] = row; + else board.Add(row); + } + return board; + } + + /// 파서 기본 목록에 없는 점수판 필드 (킬 · 데스 · 어시 · 전투 점수). 이름으로 찾으므로 패치로 번호가 밀려도 된다 + public static DescriptorCatalog Catalog() + { + var c = ValorantDescriptors.CreateCatalog(); + // PlayerState 의 하위 객체 이름 → 클래스 (파서 목록에 없다) + c.AddSubobjectClassPath("BasicCombatStatsComponent", CombatStatsPath); + c.AddSubobjectClassPath("PlayerScoreComponent", ScorePath); + FieldDescriptor F(string name) => new() { ExportName = name, PropertyName = name, Categories = ExportCategory.GameState, Decoder = Replay.Unreal.Parsing.PrimitiveDecoders.Int32 }; + c.Add(new ExportGroupDescriptor(CombatStatsPath, ExportCategory.GameState, ExportGroupKind.Component, + fields: [F("AggregateKills"), F("AggregateDeaths"), F("AggregateAssists")])); + c.Add(new ExportGroupDescriptor(ScorePath, ExportCategory.GameState, ExportGroupKind.Component, fields: [F("Score")])); + return c; + } private static int Ms(float seconds) => (int)Math.Round(seconds * 1000.0); private static int R(double v) => (int)Math.Round(v); @@ -123,7 +173,12 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink if (eq != 0) _equips.Add((Ms(x.TimeSeconds), ch, eq)); break; } + case MoneyManagementComponentDescriptor mm when mm.HasDecoded(nameof(MoneyManagementComponentDescriptor.Money)) && mm.Money is { } money: + _board.Add((Ms(x.TimeSeconds), x.ActorNetGuid, BoardMoney, money)); + break; case BombPlayerStateDescriptor ps: + if (ps.HasDecoded(nameof(BombPlayerStateDescriptor.NumUltimatePoints))) + _board.Add((Ms(x.TimeSeconds), x.ActorNetGuid, BoardUlt, ps.NumUltimatePoints)); if (ps.HasDecoded(nameof(BombPlayerStateDescriptor.Subject)) && !string.IsNullOrEmpty(ps.Subject)) _subjectByState[x.ActorNetGuid] = ps.Subject!; if (ps.HasDecoded(nameof(BombPlayerStateDescriptor.SpawnedCharacter)) && ps.SpawnedCharacter.NetGuid != 0) @@ -142,9 +197,15 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink private void OnFields(ExportGroupReceived x) { var a = x.ActorNetGuid; + var board = x.ExportGroupPath is CombatStatsPath or ScorePath; foreach (var f in x.DiagnosticFields) { var v = f.Value; + if (board && v.Kind == DecodedFieldValueKind.Int32 && f.Name is { } fn && CombatFields.TryGetValue(fn, out var bf)) + { + _board.Add((Ms(x.TimeSeconds), a, bf, v.Int32Value)); + continue; + } switch (v.Kind) { case DecodedFieldValueKind.ObjectReference when v.ObjectReferenceValue.NetGuid != 0: @@ -490,8 +551,11 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink } + var scoreboard = BuildScoreboard(_board.Select(b => (b.T, PlayerOfState(b.State), b.Field, b.Value))); + return new ReplayFile { + Scoreboard = scoreboard, Equips = equips, EquipKinds = equipKinds, MatchId = _matchId, diff --git a/tools/replay-extract/src/Model.cs b/tools/replay-extract/src/Model.cs index 5fd2b8d..c6e81cd 100644 --- a/tools/replay-extract/src/Model.cs +++ b/tools/replay-extract/src/Model.cs @@ -44,6 +44,8 @@ public sealed class ReplayFile /// 들고 있는 것이 바뀐 시각 [t, player, kind 번호]. 총은 영어 이름(Vandal 등), 칼은 Melee, 스파이크는 Spike, 스킬은 클래스 이름 public List Equips { get; set; } = []; public List EquipKinds { get; set; } = []; + /// 점수판 (게임 Tab 화면): 선수 값이 바뀔 때마다 [t, player, 크레딧, 궁극기 점수, 킬, 데스, 어시스트, 전투 점수] (아직 모르는 값 -1, 변환기 1.10.0~) + public List Scoreboard { get; set; } = []; } public sealed class ReplayPlayer diff --git a/tools/replay-extract/src/Program.cs b/tools/replay-extract/src/Program.cs index 3b3fecd..19d06fa 100644 --- a/tools/replay-extract/src/Program.cs +++ b/tools/replay-extract/src/Program.cs @@ -52,6 +52,21 @@ public static class Program var cs = Crosshair.Snapshot(0, new Dictionary { ["p.cb"] = 0, ["p.cg"] = 0, ["a.useCustom"] = true, ["a.ur"] = 0 }); if (cs.Primary.Color != "#ff0000") fails.Add($"주 조준점 색: {cs.Primary.Color} (기대 #ff0000)"); if (cs.Ads.Color != "#00ffff") fails.Add($"정조준 사용자 지정 색: {cs.Ads.Color} (기대 #00ffff)"); + // 점수판: 같은 시각 값은 한 줄 · 값이 그대로면 줄 없음 · 모르는 선수 건너뜀 · 시간 순 + var sb = Collector.BuildScoreboard([ + (2000, 0, Collector.BoardUlt, 3), (1000, 0, Collector.BoardMoney, 800), (1000, 0, Collector.BoardKills, 0), + (1500, 0, Collector.BoardMoney, 800), (1500, -1, Collector.BoardMoney, 100), (2000, 1, Collector.BoardMoney, 4000), + ]); + Eq("점수판 줄 수", sb.Count, 3); + if (sb.Count == 3) + { + Eq("첫 줄 크레딧", sb[0][2 + Collector.BoardMoney], 800); + Eq("첫 줄 킬", sb[0][2 + Collector.BoardKills], 0); + Eq("첫 줄 궁(아직 모름)", sb[0][2 + Collector.BoardUlt], -1); + Eq("둘째 줄 궁", sb[1][2 + Collector.BoardUlt], 3); + Eq("둘째 줄 크레딧 유지", sb[1][2 + Collector.BoardMoney], 800); + Eq("셋째 줄 선수", sb[2][1], 1); + } foreach (var f in fails) Console.Error.WriteLine("FAIL " + f); Console.WriteLine(JsonSerializer.Serialize(new { ok = fails.Count == 0, selfTest = true, failed = fails.Count })); return fails.Count == 0 ? 0 : 1; @@ -79,7 +94,7 @@ public static class Program var enricher = new ValorantEventEnricher(collector); // 진단 필드: 스킬 주인(Instigator) · 투사체 비행(ReplicatedMovement) · 무기 상태(CurrentState)를 페이로드 종류와 상관없이 읽는다 var profile = new ParseProfile { EnabledCategories = ExportCategory.All, CaptureDiagnosticFields = true }; - var result = ValorantReplayReader.CreateDefault(null, enricher, profile).Read(archive); + var result = new ValorantReplayReader(null, enricher, profile, Collector.Catalog()).Read(archive); enricher.Complete(); var info = result.Metadata.ReplayInfo; if (args[1] == "--fields") @@ -127,6 +142,7 @@ public static class Program players = replay.Players.Count, rounds = replay.Rounds.Count, kills = replay.Kills.Count, + scoreboard = replay.Scoreboard.Count, crosshairs, elapsedMs = sw.ElapsedMilliseconds, status = result.Status.ToString(),