3D 리플레이 1단계: .vrf 변환기(tools/replay-extract) · 사이트 3D 재생기 · 대화 동기화
- tools/replay-extract: ValorantReplayParser(MIT, 고정 커밋) → gvr-replay JSON v1 (선수 이동 10Hz · 라운드 · 킬 · 사격 · 스킬/설치물 · 녹화 시작 시각) - 사이트: 경기 화면 '3D 리플레이' 칸 (three.js 지연 로드). 미니맵 바닥 + 실제 높이, 회전 · 확대 · 선수 선택 · 따라가기 · 킬피드 · 자막 · 말하는 사람 표시 - 동기화: 같은 킬의 경기 기록 시각과 리플레이 시각 차이 중앙값 (못 맞추면 라운드 시작) 현장 모드 시계에 묶어 재생 · 멈춤 · 이동 · 배속이 대화와 같이 움직임 - 목 서버 데모(GVR_MOCK_REPLAY), 동기화 테스트 4개 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
19
docs/dev/replay-3d.md
Normal file
19
docs/dev/replay-3d.md
Normal file
@@ -0,0 +1,19 @@
|
||||
# 3D 리플레이 · 대화 동기화 (작업 노트, 2026-10-17)
|
||||
|
||||
## 결론 (조사)
|
||||
- 발로란트는 리플레이 재생 위치를 주는 API가 없다 (로컬 API는 "리플레이 보는 중"까지). 2026-10-17 사용자 ShooterGame.log 에도 재생 위치는 없다 (열기 · 닫기 · 매치 ID · 시간 옮길 때 선수 재생성만 남음).
|
||||
- 그래서 인게임 리플레이를 따라가지 않고, `.vrf` 를 풀어 **사이트에서 재생**한다. 대화는 사이트 플레이어 "현장 모드" 시계(sceneTs)에 묶여 재생 · 멈춤 · 이동 · 배속이 같이 움직인다.
|
||||
|
||||
## 구성
|
||||
- `tools/replay-extract/` (C#, net10): ValorantReplayParser(MIT, `fetch-parser.sh` 로 고정 커밋을 vendor/ 에 받음) → `gvr-replay` JSON v1
|
||||
- 선수 10명 이동 10Hz (x,y,z,yaw,pitch) · 라운드(구매/교전/끝) · 킬 · 사격 · 스킬/설치물(스파이크 TimedBomb_C 포함) · `recordedAt`(녹화 시작, ReplayInfo.Timestamp)
|
||||
- 13.08 실제 경기(73.8MB): 6초, JSON 5.3MB / gzip 1.4MB, 진단 0
|
||||
- 사이트 `site/web/src/lib/replay.ts` (동기화 · 보간 · 죽음 판정), `components/ReplayViewer.tsx` (three.js, 지연 로드), `ReplayPanel.tsx`
|
||||
- 동기화: `ts = recordedAt + t + offset`, offset = 같은 킬(죽인/죽은 puuid)의 경기 기록 ts − 리플레이 시각의 중앙값. 킬이 3개 미만이면 라운드 교전 시작으로.
|
||||
- 3D: 바닥은 미니맵, 선수는 실제 높이. 맵 벽 · 지형 3D 모델은 없음 (게임 파일 추출 필요 · 저작권 문제로 보류)
|
||||
- 목 서버: `GVR_MOCK_REPLAY=<json> GVR_MOCK_REPLAY_MAP_FILE=<어비스 png> npm run dev` → `/matches/val-replay-demo` (경기 기록 킬을 1234ms 늦게 찍어 동기화 확인)
|
||||
|
||||
## 남은 일
|
||||
1. 앱: `%LOCALAPPDATA%\VALORANT\Saved` 아래 `<matchId>.vrf` 찾기 → `gvr-replay.exe` 실행 → `GVR-Data/replays/<matchId>.json.gz` → `GET /api/matches/:id/replay` (content-encoding gzip, 사이트는 /api/* 그대로 중계)
|
||||
2. 빌드: win-ci 에 .NET SDK 설치 · `dotnet publish -r win-x64` 단일 파일 → electron-builder extraResources `replay/`
|
||||
3. 실제 경기로 동기화 오차 확인 (사이트 아래 줄 "킬 N개로 맞춤 (최대 오차 X초)")
|
||||
59
site/server/test/replay-sync.test.ts
Normal file
59
site/server/test/replay-sync.test.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
// 사이트 3D 리플레이: 리플레이 시간 ↔ 기록 시각 맞추기 · 위치 보간 · 죽음 판정 (site/web/src/lib/replay.ts)
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { computeSync, isDead, samplePlayer, type ReplayFile } from '../../web/src/lib/replay.ts';
|
||||
|
||||
const track = (pts: [number, number][]) => ({ t: pts.map((p) => p[0]), x: pts.map((p) => p[1]), y: pts.map(() => 0), z: pts.map(() => 100), yaw: pts.map(() => 350), pitch: pts.map(() => 0) });
|
||||
function replay(): ReplayFile {
|
||||
return {
|
||||
format: 'gvr-replay', v: 1, matchId: 'm1', map: null, build: null, recordedAt: 1_000_000, durationMs: 200_000, sampleMs: 100,
|
||||
players: [
|
||||
{ puuid: 'a', character: null, track: track([[0, 0], [10_000, 1000], [50_000, 1000]]) },
|
||||
{ puuid: 'b', character: null, track: track([[0, 0], [40_000, 500]]) },
|
||||
{ puuid: 'c', character: null, track: track([[0, 0], [90_000, 0]]) },
|
||||
],
|
||||
rounds: [{ num: 1, buy: 0, combat: 30_000, end: 80_000 }, { num: 2, buy: 100_000, combat: 130_000, end: -1 }],
|
||||
phases: [], shots: [], objects: [], objectKinds: [],
|
||||
kills: [[40_000, 0, 1], [60_000, 2, 0], [140_000, 0, 2]],
|
||||
};
|
||||
}
|
||||
const kill = (id: string, ts: number, killer: string, victim: string) => ({ kind: 'event', id, ts, type: 'kill', data: { killer: { puuid: killer, name: killer }, victim: { puuid: victim, name: victim }, assists: [], weapon: null } });
|
||||
|
||||
test('킬 시각 차이의 중앙값으로 맞추고, 킬별 오차를 낸다', () => {
|
||||
const r = replay();
|
||||
// 경기 기록이 리플레이보다 2.5초 늦게 찍혔고, 한 킬은 0.2초 더 늦다
|
||||
const m: any = { startedAt: 0, rounds: [], events: [kill('k1', 1_000_000 + 40_000 + 2500, 'a', 'b'), kill('k2', 1_000_000 + 60_000 + 2500, 'c', 'a'), kill('k3', 1_000_000 + 140_000 + 2700, 'a', 'c')] };
|
||||
const s = computeSync(m, r);
|
||||
assert.equal(s.matched, 3);
|
||||
assert.equal(s.offset, 2500);
|
||||
assert.equal(s.spreadMs, 200);
|
||||
});
|
||||
|
||||
test('킬을 못 맞추면 라운드 교전 시작(앱이 저장한 라운드 시작 + 30초)으로 맞춘다', () => {
|
||||
const r = replay();
|
||||
const m: any = { startedAt: 0, events: [], rounds: [{ num: 1, startedAt: 1_000_000 + 30_000 - 30_000 + 4000 }, { num: 2, startedAt: 1_000_000 + 130_000 - 30_000 + 4000 }] };
|
||||
const s = computeSync(m, r);
|
||||
assert.equal(s.matched, 0);
|
||||
assert.equal(s.offset, 4000);
|
||||
assert.equal(s.spreadMs, null);
|
||||
});
|
||||
|
||||
test('위치는 앞뒤 표본 사이를 보간하고, 방향은 짧은 쪽으로 돈다', () => {
|
||||
const tr = track([[0, 0], [100, 100]]);
|
||||
tr.yaw = [350, 10];
|
||||
const p = samplePlayer(tr, 50, 600)!;
|
||||
assert.equal(p.x, 50);
|
||||
assert.equal(p.yaw, 360);
|
||||
assert.equal(samplePlayer(tr, -1000, 600), null);
|
||||
});
|
||||
|
||||
test('죽음: 이 라운드에서 죽은 뒤 다시 움직이지 않으면 죽은 상태, 다음 라운드엔 살아남', () => {
|
||||
const r = replay();
|
||||
assert.equal(isDead(r, 1, 39_000), false);
|
||||
assert.equal(isDead(r, 1, 45_000), true);
|
||||
// a 는 60초에 죽었지만 기록은 50초까지뿐 → 죽음. 다음 라운드(100초~)에는 다시 산다
|
||||
assert.equal(isDead(r, 0, 70_000), true);
|
||||
assert.equal(isDead(r, 0, 110_000), false);
|
||||
// c 는 60초 킬 뒤에도 90초까지 움직였으므로 140초 킬 전까지 살아 있음
|
||||
assert.equal(isDead(r, 2, 120_000), false);
|
||||
});
|
||||
@@ -2,6 +2,8 @@
|
||||
// 롤 1판(19:40 무렵) → 발로란트 바인드(패) → 발로란트 어센트(13:9 승) → 경기 후 잡담.
|
||||
// 이미지 URL 은 실제 사이트 서버 캐시 경로 형식(/game-assets/...)을 흉내 낸 /game-assets/mock/...
|
||||
|
||||
import fs from 'node:fs';
|
||||
|
||||
export const A = (p) => `/game-assets/mock/${p}`;
|
||||
|
||||
function mulberry32(a) {
|
||||
@@ -505,6 +507,79 @@ post.forEach(([u, text, status], i) => {
|
||||
addUtt({ user: u, ts, text, status, time: realLabel(ts) });
|
||||
});
|
||||
|
||||
// ── 3D 리플레이 데모 (선택) ─────────────────────────────
|
||||
// GVR_MOCK_REPLAY=<gvr-replay JSON 경로> (+ GVR_MOCK_REPLAY_MAP_FILE=<어비스 미니맵 png>) 를 주면 그 리플레이로 경기 하나를 만든다 (실제 리플레이는 저장소에 넣지 않는다).
|
||||
// 경기 기록(킬 시각)은 리플레이보다 MOCK_SYNC_OFFSET 만큼 늦게 찍어, 사이트가 그 차이를 맞추는지 본다.
|
||||
export const MOCK_SYNC_OFFSET = 1234;
|
||||
function genReplayDemo(file) {
|
||||
const r = JSON.parse(fs.readFileSync(file, 'utf8'));
|
||||
const id = 'val-replay-demo';
|
||||
const base = r.recordedAt + MOCK_SYNC_OFFSET;
|
||||
// 팀: 같은 팀끼리는 (거의) 안 죽이므로 킬 관계로 두 편을 나눈다 (실제 사이트는 경기 기록의 팀을 쓴다)
|
||||
const adj = r.players.map(() => new Set());
|
||||
for (const [, k, v] of r.kills) if (k >= 0 && v >= 0 && k !== v) (adj[k].add(v), adj[v].add(k));
|
||||
const side = new Map([[0, 0]]);
|
||||
const stack = [0];
|
||||
while (stack.length) {
|
||||
const x = stack.pop();
|
||||
for (const y of adj[x]) if (!side.has(y)) (side.set(y, 1 - side.get(x)), stack.push(y));
|
||||
}
|
||||
const allyIdx = new Set(r.players.map((_, i) => i).filter((i) => side.get(i) === 0));
|
||||
const AGK = { Wushu_PC_C: AG.jett, Hunter_PC_C: AG.sova, Thorne_PC_C: AG.sage, Wraith_PC_C: AG.omen, Killjoy_PC_C: AG.killjoy, Clay_PC_C: AG.raze, Vampire_PC_C: AG.reyna };
|
||||
let si = 0;
|
||||
let an = 0;
|
||||
let en = 0;
|
||||
const players = r.players.map((p, i) => {
|
||||
const ally = allyIdx.has(i);
|
||||
const user = ally && si < SPEAKERS.length ? SPEAKERS[si++] : null;
|
||||
const name = user ? user.name : ally ? `아군${++an}` : `상대${++en}`;
|
||||
const cls = (p.character ?? '').replace(/_PC_C$/, '');
|
||||
return { puuid: p.puuid, name, tag: 'KR1', team: ally ? 'Blue' : 'Red', ally, character: AGK[p.character] ?? { id: cls, name: cls, icon: null }, userId: user?.id, kills: 0, deaths: 0, assists: 0, score: 0, rank: null };
|
||||
});
|
||||
const ref = (i) => (i >= 0 ? { puuid: players[i].puuid, name: players[i].name, team: players[i].team, character: players[i].character, userId: players[i].userId } : null);
|
||||
const mEvents = [];
|
||||
const mUtts = [];
|
||||
const rounds = [];
|
||||
let score = { ally: 0, enemy: 0 };
|
||||
r.rounds.forEach((rd, k) => {
|
||||
const next = r.rounds[k + 1];
|
||||
const startedAt = base + (rd.combat >= 0 ? rd.combat - 30000 : rd.buy);
|
||||
const endedAt = base + (next ? (next.combat >= 0 ? next.combat - 30000 : next.buy) : r.durationMs);
|
||||
const kills = r.kills.filter(([t]) => t >= rd.buy && (!next || t < next.buy));
|
||||
const allyDead = kills.filter(([, , v]) => allyIdx.has(v)).length;
|
||||
const enemyDead = kills.filter(([, , v]) => !allyIdx.has(v)).length;
|
||||
const win = enemyDead >= allyDead;
|
||||
win ? score.ally++ : score.enemy++;
|
||||
rounds.push({ num: rd.num, startedAt, endedAt, win, result: 'Elimination', score: { ...score }, economy: {}, players: {} });
|
||||
const label = (ts) => {
|
||||
const inRound = ts - startedAt;
|
||||
return { primary: inRound < 30000 ? `R${rd.num} · 구매` : `R${rd.num} · ${fmtClock(inRound - 30000)}`, secondary: fmtClock(ts - base), real: ts };
|
||||
};
|
||||
for (const [t, ki, vi] of kills) {
|
||||
const ts = base + t;
|
||||
if (ki >= 0) players[ki].kills++;
|
||||
if (vi >= 0) players[vi].deaths++;
|
||||
mEvents.push({ kind: 'event', id: nid('ev_'), ts, game: 'valorant', matchId: id, type: 'kill', round: rd.num, data: { killer: ref(ki), victim: ref(vi), assists: [], weapon: null, location: null, ally: ki >= 0 && allyIdx.has(ki) }, time: label(ts) });
|
||||
}
|
||||
mEvents.push({ kind: 'event', id: nid('ev_'), ts: endedAt - 1, game: 'valorant', matchId: id, type: 'round_end', round: rd.num, data: { round: rd.num, win, result: 'Elimination', score: { ...score } }, time: label(endedAt - 1) });
|
||||
// 대화: 라운드마다 3~5개
|
||||
const n = irange(3, 5);
|
||||
for (let j = 0; j < n; j++) {
|
||||
const ts = startedAt + irange(5, Math.max(6, Math.floor((endedAt - startedAt) / 1000) - 3)) * 1000;
|
||||
mUtts.push(addUtt({ user: pick(SPEAKERS), ts, text: pick(VAL_LINES), game: { type: 'valorant', matchId: id, round: rd.num }, time: label(ts) }));
|
||||
}
|
||||
});
|
||||
const endedAt = base + r.durationMs;
|
||||
events.push(...mEvents);
|
||||
const T = { xMultiplier: 8.1e-5, yMultiplier: -8.1e-5, xScalarToAdd: 0.5, yScalarToAdd: 0.5 };
|
||||
const summary = {
|
||||
id, game: 'valorant', startedAt: base, endedAt, map: { id: '224b0a95-48b9-f703-1bd8-67aca101a61f', name: '어비스', image: process.env.GVR_MOCK_REPLAY_MAP_FILE ? A('replay-map.png') : null },
|
||||
mode: '경쟁전', win: score.ally > score.enemy, score, status: 'complete', participants: SPEAKERS.map((u) => u.id),
|
||||
};
|
||||
matches.push({ ...summary, players, rounds, events: mEvents, utterances: mUtts, mapTransform: { valorant: T }, replayPath: file });
|
||||
}
|
||||
if (process.env.GVR_MOCK_REPLAY) genReplayDemo(process.env.GVR_MOCK_REPLAY);
|
||||
|
||||
// ── 내보내기 ─────────────────────────────────────────
|
||||
export const db = {
|
||||
users: USERS,
|
||||
|
||||
@@ -182,6 +182,11 @@ async function handle(req, res) {
|
||||
}
|
||||
|
||||
// 게임 이미지 (목: docs/report/mock/assets)
|
||||
// 3D 리플레이 데모 바닥 미니맵 (GVR_MOCK_REPLAY_MAP_FILE, 데이터 생성은 data.mjs genReplayDemo)
|
||||
if (p === '/game-assets/mock/replay-map.png' && process.env.GVR_MOCK_REPLAY_MAP_FILE) {
|
||||
res.writeHead(200, { 'content-type': 'image/png' });
|
||||
return fs.createReadStream(process.env.GVR_MOCK_REPLAY_MAP_FILE).pipe(res);
|
||||
}
|
||||
if (p.startsWith('/game-assets/mock/')) {
|
||||
const f = path.resolve(ASSET_DIR, decodeURIComponent(p.slice('/game-assets/mock/'.length)));
|
||||
if (!f.startsWith(ASSET_DIR) || !fs.existsSync(f)) return json(res, 404, { error: 'not_found' });
|
||||
@@ -270,7 +275,16 @@ async function handle(req, res) {
|
||||
}
|
||||
if ((m = p.match(/^\/api\/matches\/([^/]+)$/))) {
|
||||
const mt = db.matches.find((x) => x.id === decodeURIComponent(m[1]));
|
||||
return mt ? json(res, 200, mt) : json(res, 404, { error: 'not_found' });
|
||||
if (!mt) return json(res, 404, { error: 'not_found' });
|
||||
const { replayPath, ...rest } = mt;
|
||||
return json(res, 200, rest);
|
||||
}
|
||||
if ((m = p.match(/^\/api\/matches\/([^/]+)\/replay$/))) {
|
||||
const mt = db.matches.find((x) => x.id === decodeURIComponent(m[1]));
|
||||
if (!mt) return json(res, 404, { error: 'not_found' });
|
||||
if (!mt.replayPath) return json(res, 404, { error: 'replay_not_found' });
|
||||
res.writeHead(200, { 'content-type': 'application/json' });
|
||||
return fs.createReadStream(mt.replayPath).pipe(res);
|
||||
}
|
||||
if ((m = p.match(/^\/api\/utterances\/([^/]+)$/)) && req.method === 'PATCH') {
|
||||
const it = db.utterances.find((u) => u.id === decodeURIComponent(m[1]));
|
||||
|
||||
64
site/web/package-lock.json
generated
64
site/web/package-lock.json
generated
@@ -12,12 +12,14 @@
|
||||
"react": "^19.3.0",
|
||||
"react-dom": "^19.3.0",
|
||||
"react-router": "^7.18.4",
|
||||
"three": "^0.180.0",
|
||||
"wavesurfer.js": "^7.12.12"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.20.5",
|
||||
"@types/react": "^19.3.0",
|
||||
"@types/react-dom": "^19.2.0",
|
||||
"@types/three": "^0.180.0",
|
||||
"@vitejs/plugin-react": "^5.2.0",
|
||||
"typescript": "~5.9.3",
|
||||
"vite": "^7.3.7",
|
||||
@@ -287,6 +289,12 @@
|
||||
"node": ">=6.9.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@dimforge/rapier3d-compat": {
|
||||
"version": "0.12.0",
|
||||
"resolved": "https://registry.npmjs.org/@dimforge/rapier3d-compat/-/rapier3d-compat-0.12.0.tgz",
|
||||
"integrity": "sha512-uekIGetywIgopfD97oDL5PfeezkFpNhwlzlaEYNOA0N6ghdsOvh/HYjSMek5Q2O1PYvRSDFcqFVJl4r4ZBwOow==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/@esbuild/aix-ppc64": {
|
||||
"version": "0.28.2",
|
||||
"resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.28.2.tgz",
|
||||
@@ -1095,6 +1103,12 @@
|
||||
"win32"
|
||||
]
|
||||
},
|
||||
"node_modules/@tweenjs/tween.js": {
|
||||
"version": "23.1.3",
|
||||
"resolved": "https://registry.npmjs.org/@tweenjs/tween.js/-/tween.js-23.1.3.tgz",
|
||||
"integrity": "sha512-vJmvvwFxYuGnF2axRtPYocag6Clbb5YS7kLL+SO/TeVFzHqDIWrNKYtcsPMibjDx9O+bu+psAy9NKfWklassUA==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/@types/babel__core": {
|
||||
"version": "7.20.5",
|
||||
"resolved": "https://registry.npmjs.org/@types/babel__core/-/babel__core-7.20.5.tgz",
|
||||
@@ -1169,6 +1183,33 @@
|
||||
"@types/react": "^19.3.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/stats.js": {
|
||||
"version": "0.17.4",
|
||||
"resolved": "https://registry.npmjs.org/@types/stats.js/-/stats.js-0.17.4.tgz",
|
||||
"integrity": "sha512-jIBvWWShCvlBqBNIZt0KAshWpvSjhkwkEu4ZUcASoAvhmrgAUI2t1dXrjSL4xXVLB4FznPrIsX3nKXFl/Dt4vA==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/@types/three": {
|
||||
"version": "0.180.0",
|
||||
"resolved": "https://registry.npmjs.org/@types/three/-/three-0.180.0.tgz",
|
||||
"integrity": "sha512-ykFtgCqNnY0IPvDro7h+9ZeLY+qjgUWv+qEvUt84grhenO60Hqd4hScHE7VTB9nOQ/3QM8lkbNE+4vKjEpUxKg==",
|
||||
"dev": true,
|
||||
"dependencies": {
|
||||
"@dimforge/rapier3d-compat": "~0.12.0",
|
||||
"@tweenjs/tween.js": "~23.1.3",
|
||||
"@types/stats.js": "*",
|
||||
"@types/webxr": "*",
|
||||
"@webgpu/types": "*",
|
||||
"fflate": "~0.8.2",
|
||||
"meshoptimizer": "~0.22.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@types/webxr": {
|
||||
"version": "0.5.24",
|
||||
"resolved": "https://registry.npmjs.org/@types/webxr/-/webxr-0.5.24.tgz",
|
||||
"integrity": "sha512-h8fgEd/DpoS9CBrjEQXR+dIDraopAEfu4wYVNY2tEPwk60stPWhvZMf4Foo5FakuQ7HFZoa8WceaWFervK2Ovg==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/@vitejs/plugin-react": {
|
||||
"version": "5.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-5.2.0.tgz",
|
||||
@@ -1189,6 +1230,12 @@
|
||||
"vite": "^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/@webgpu/types": {
|
||||
"version": "0.1.74",
|
||||
"resolved": "https://registry.npmjs.org/@webgpu/types/-/types-0.1.74.tgz",
|
||||
"integrity": "sha512-lgiI4hbuLcI9unnm2cL/tvCaQU45dp0xcLWJh5uB/9MBGvIA4F8XIk7nSiBeg+K4xWGYwgZKn80LmERI5CxoTA==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/baseline-browser-mapping": {
|
||||
"version": "2.11.28",
|
||||
"resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.11.28.tgz",
|
||||
@@ -1368,6 +1415,12 @@
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/fflate": {
|
||||
"version": "0.8.3",
|
||||
"resolved": "https://registry.npmjs.org/fflate/-/fflate-0.8.3.tgz",
|
||||
"integrity": "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/framer-motion": {
|
||||
"version": "12.43.0",
|
||||
"resolved": "https://registry.npmjs.org/framer-motion/-/framer-motion-12.43.0.tgz",
|
||||
@@ -1456,6 +1509,12 @@
|
||||
"yallist": "^3.0.2"
|
||||
}
|
||||
},
|
||||
"node_modules/meshoptimizer": {
|
||||
"version": "0.22.0",
|
||||
"resolved": "https://registry.npmjs.org/meshoptimizer/-/meshoptimizer-0.22.0.tgz",
|
||||
"integrity": "sha512-IebiK79sqIy+E4EgOr+CAw+Ke8hAspXKzBd0JdgEmPHiAwmvEj2S4h1rfvo+o/BnfEYd/jAOg5IeeIjzlzSnDg==",
|
||||
"dev": true
|
||||
},
|
||||
"node_modules/motion-dom": {
|
||||
"version": "12.43.0",
|
||||
"resolved": "https://registry.npmjs.org/motion-dom/-/motion-dom-12.43.0.tgz",
|
||||
@@ -1670,6 +1729,11 @@
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/three": {
|
||||
"version": "0.180.0",
|
||||
"resolved": "https://registry.npmjs.org/three/-/three-0.180.0.tgz",
|
||||
"integrity": "sha512-o+qycAMZrh+TsE01GqWUxUIKR1AL0S8pq7zDkYOQw8GqfX8b8VoCKYUoHbhiX5j+7hr8XsuHDVU6+gkQJQKg9w=="
|
||||
},
|
||||
"node_modules/tinyglobby": {
|
||||
"version": "0.2.17",
|
||||
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
|
||||
|
||||
@@ -16,12 +16,14 @@
|
||||
"react": "^19.3.0",
|
||||
"react-dom": "^19.3.0",
|
||||
"react-router": "^7.18.4",
|
||||
"three": "^0.180.0",
|
||||
"wavesurfer.js": "^7.12.12"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.20.5",
|
||||
"@types/react": "^19.3.0",
|
||||
"@types/react-dom": "^19.2.0",
|
||||
"@types/three": "^0.180.0",
|
||||
"@vitejs/plugin-react": "^5.2.0",
|
||||
"typescript": "~5.9.3",
|
||||
"vite": "^7.3.7",
|
||||
|
||||
58
site/web/src/components/ReplayPanel.tsx
Normal file
58
site/web/src/components/ReplayPanel.tsx
Normal file
@@ -0,0 +1,58 @@
|
||||
import { lazy, Suspense, useEffect, useMemo, useState } from 'react';
|
||||
import type { MatchDetail } from '@gvr/shared';
|
||||
import { api, ApiError } from '../lib/api';
|
||||
import { computeSync, type ReplayFile } from '../lib/replay';
|
||||
import { Panel, Spinner } from './common';
|
||||
|
||||
// three.js 는 크므로 3D 리플레이를 열 때만 받는다
|
||||
const ReplayViewer = lazy(() => import('./ReplayViewer'));
|
||||
|
||||
/** 경기 화면의 "3D 리플레이" 칸. 열면 게임 PC 에서 리플레이 데이터를 받아 온다 */
|
||||
export function ReplayPanel({ m }: { m: MatchDetail }) {
|
||||
const [open, setOpen] = useState(false);
|
||||
const [replay, setReplay] = useState<ReplayFile | null>(null);
|
||||
const [err, setErr] = useState<unknown>(null);
|
||||
useEffect(() => {
|
||||
if (!open || replay) return;
|
||||
let alive = true;
|
||||
setErr(null);
|
||||
api
|
||||
.replay(m.id)
|
||||
.then((r) => alive && setReplay(r))
|
||||
.catch((e) => alive && setErr(e));
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [open, m.id, replay]);
|
||||
const sync = useMemo(() => (replay ? computeSync(m, replay) : null), [m, replay]);
|
||||
const missing = err instanceof ApiError && err.status === 404;
|
||||
return (
|
||||
<Panel
|
||||
className={`replay-panel${open ? ' open' : ''}`}
|
||||
title="3D 리플레이 · 대화 동기화"
|
||||
right={
|
||||
<button className="mini-btn" onClick={() => setOpen((o) => !o)} aria-expanded={open}>
|
||||
{open ? '닫기' : '열기'}
|
||||
</button>
|
||||
}
|
||||
>
|
||||
{!open ? (
|
||||
<div className="dim small">
|
||||
발로란트에서 이 경기 리플레이를 내려받으면 선수 10명의 움직임을 3D로 보면서 그때 나눈 대화를 같이 들을 수 있습니다.
|
||||
</div>
|
||||
) : missing ? (
|
||||
<div className="dim small">
|
||||
이 경기 리플레이가 아직 없습니다. 발로란트 경력 탭에서 이 경기의 리플레이를 내려받으면 게임 PC 앱이 찾아서 변환합니다 (몇 초 걸림).
|
||||
</div>
|
||||
) : err ? (
|
||||
<div className="dim small">리플레이를 불러오지 못했습니다: {err instanceof Error ? err.message : String(err)}</div>
|
||||
) : !replay || !sync ? (
|
||||
<Spinner label="리플레이 불러오는 중" />
|
||||
) : (
|
||||
<Suspense fallback={<Spinner label="3D 화면 준비 중" />}>
|
||||
<ReplayViewer m={m} replay={replay} sync={sync} />
|
||||
</Suspense>
|
||||
)}
|
||||
</Panel>
|
||||
);
|
||||
}
|
||||
510
site/web/src/components/ReplayViewer.tsx
Normal file
510
site/web/src/components/ReplayViewer.tsx
Normal file
@@ -0,0 +1,510 @@
|
||||
import { useEffect, useMemo, useRef, useState } from 'react';
|
||||
import * as THREE from 'three';
|
||||
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
|
||||
import type { MatchDetail, MatchPlayer } from '@gvr/shared';
|
||||
import { player } from '../store/player';
|
||||
import { settings, useSettings } from '../store/settings';
|
||||
import { useData } from '../store/app';
|
||||
import { fmtClock } from '../lib/format';
|
||||
import { isDead, roundAt, samplePlayer, type ReplayFile, type ReplaySync } from '../lib/replay';
|
||||
|
||||
/**
|
||||
* 3D 리플레이 (발로란트 .vrf → tools/replay-extract → gvr-replay JSON).
|
||||
* 바닥은 미니맵, 선수는 실제 높이(z)에 세운다. 맵 벽 · 지형 3D 모델은 없다.
|
||||
* 시계는 플레이어 "현장 모드"(대화를 실제 시각대로 겹쳐 재생)와 같은 값을 쓴다:
|
||||
* 기록 시각 ts = recordedAt + t + sync.offset
|
||||
* 그래서 재생 · 멈춤 · 시간 옮기기 · 배속이 대화와 같이 움직인다.
|
||||
*/
|
||||
export const REPLAY_SCENE_LABEL = '3D 리플레이';
|
||||
const S = 100; // 미니맵 한 변 (3D 단위)
|
||||
const VEX = 1; // 높이 배율 (1 = 실제 비율)
|
||||
const ALLY = 0x3fb6ff;
|
||||
const ENEMY = 0xff4d5e;
|
||||
const RATES = [0.5, 1, 1.5, 2];
|
||||
|
||||
type T4 = { xMultiplier: number; yMultiplier: number; xScalarToAdd: number; yScalarToAdd: number };
|
||||
|
||||
interface Props {
|
||||
m: MatchDetail;
|
||||
replay: ReplayFile;
|
||||
sync: ReplaySync;
|
||||
}
|
||||
|
||||
function labelSprite(text: string, color: string) {
|
||||
const c = document.createElement('canvas');
|
||||
const ctx = c.getContext('2d')!;
|
||||
const font = '600 44px Pretendard, "Noto Sans KR", sans-serif';
|
||||
ctx.font = font;
|
||||
const w = Math.ceil(ctx.measureText(text).width) + 36;
|
||||
c.width = w;
|
||||
c.height = 68;
|
||||
ctx.font = font;
|
||||
ctx.fillStyle = 'rgba(8,14,20,0.78)';
|
||||
ctx.beginPath();
|
||||
ctx.roundRect(0, 0, w, 68, 18);
|
||||
ctx.fill();
|
||||
ctx.fillStyle = color;
|
||||
ctx.textBaseline = 'middle';
|
||||
ctx.fillText(text, 18, 36);
|
||||
const tex = new THREE.CanvasTexture(c);
|
||||
tex.colorSpace = THREE.SRGBColorSpace;
|
||||
const sp = new THREE.Sprite(new THREE.SpriteMaterial({ map: tex, depthTest: false, transparent: true }));
|
||||
sp.scale.set((w / 68) * 2.2, 2.2, 1);
|
||||
sp.renderOrder = 10;
|
||||
return sp;
|
||||
}
|
||||
|
||||
interface PlayerView {
|
||||
idx: number;
|
||||
info: MatchPlayer | null;
|
||||
name: string;
|
||||
ally: boolean;
|
||||
group: THREE.Group;
|
||||
body: THREE.Mesh;
|
||||
cone: THREE.Mesh;
|
||||
label: THREE.Sprite;
|
||||
voice: THREE.Sprite;
|
||||
ring: THREE.Mesh;
|
||||
/** 바닥(미니맵)까지 내린 선과 그림자 점: 높이가 있어도 평면 위치가 보이게 */
|
||||
drop: THREE.Line;
|
||||
shadow: THREE.Mesh;
|
||||
}
|
||||
|
||||
export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
const mountRef = useRef<HTMLDivElement>(null);
|
||||
const cfg = useSettings();
|
||||
const { userById } = useData();
|
||||
const base = replay.recordedAt + sync.offset;
|
||||
const firstCombat = replay.rounds.find((r) => r.combat >= 0)?.combat ?? 0;
|
||||
const localT = useRef(firstCombat);
|
||||
const [ui, setUi] = useState({ t: firstCombat, playing: false });
|
||||
const [sel, setSel] = useState<number | null>(null);
|
||||
const [follow, setFollow] = useState(false);
|
||||
const selRef = useRef(sel);
|
||||
const followRef = useRef(follow);
|
||||
selRef.current = sel;
|
||||
followRef.current = follow;
|
||||
const resetCam = useRef<() => void>(() => {});
|
||||
|
||||
// 바닥(미니맵) 높이: 선수 높이의 하위 5% (떨어져 죽은 기록은 뺀다)
|
||||
const zBase = useMemo(() => {
|
||||
const zs: number[] = [];
|
||||
for (const p of replay.players) for (let i = 0; i < p.track.z.length; i += 40) if (p.track.z[i] > -1500) zs.push(p.track.z[i]);
|
||||
zs.sort((a, b) => a - b);
|
||||
return zs.length ? zs[Math.floor(zs.length * 0.05)] : 0;
|
||||
}, [replay]);
|
||||
const T = (m.mapTransform && 'valorant' in m.mapTransform ? m.mapTransform.valorant : null) as T4 | null;
|
||||
|
||||
// 리플레이 선수 ↔ 경기 기록 선수 (puuid)
|
||||
const roster = useMemo(
|
||||
() =>
|
||||
replay.players.map((p, idx) => {
|
||||
const info = m.players.find((x) => x.puuid === p.puuid) ?? null;
|
||||
return { idx, info, name: info?.name ?? p.character?.replace(/_PC_C$/, '') ?? `선수 ${idx + 1}`, ally: info?.ally ?? false };
|
||||
}),
|
||||
[m, replay],
|
||||
);
|
||||
// 디스코드 유저 → 리플레이 선수 (말하는 사람 표시)
|
||||
const playerByUser = useMemo(() => {
|
||||
const map = new Map<string, number>();
|
||||
for (const r of roster) if (r.info?.userId) map.set(r.info.userId, r.idx);
|
||||
return map;
|
||||
}, [roster]);
|
||||
|
||||
useEffect(() => {
|
||||
const mount = mountRef.current;
|
||||
if (!mount || !T) return;
|
||||
const toWorld = (x: number, y: number, z: number, zBase: number) =>
|
||||
new THREE.Vector3((y * T.xMultiplier + T.xScalarToAdd - 0.5) * S, (z - zBase) * Math.abs(T.xMultiplier) * S * VEX, (x * T.yMultiplier + T.yScalarToAdd - 0.5) * S);
|
||||
const dirOf = (yaw: number) => {
|
||||
const a = (yaw * Math.PI) / 180;
|
||||
return new THREE.Vector3(Math.sin(a) * Math.sign(T.xMultiplier), 0, Math.cos(a) * Math.sign(T.yMultiplier)).normalize();
|
||||
};
|
||||
|
||||
const renderer = new THREE.WebGLRenderer({ antialias: true, alpha: false });
|
||||
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
|
||||
renderer.setClearColor(0x0b141c);
|
||||
renderer.outputColorSpace = THREE.SRGBColorSpace;
|
||||
mount.appendChild(renderer.domElement);
|
||||
const scene = new THREE.Scene();
|
||||
const camera = new THREE.PerspectiveCamera(45, 1, 0.5, 2000);
|
||||
const controls = new OrbitControls(camera, renderer.domElement);
|
||||
controls.enableDamping = true;
|
||||
controls.maxPolarAngle = Math.PI * 0.49;
|
||||
controls.minDistance = 8;
|
||||
controls.maxDistance = 260;
|
||||
resetCam.current = () => {
|
||||
camera.position.set(0, 122, 34);
|
||||
controls.target.set(0, 0, 0);
|
||||
controls.update();
|
||||
};
|
||||
resetCam.current();
|
||||
scene.add(new THREE.HemisphereLight(0xffffff, 0x223344, 1.6));
|
||||
const sun = new THREE.DirectionalLight(0xffffff, 1.2);
|
||||
sun.position.set(30, 80, 20);
|
||||
scene.add(sun);
|
||||
|
||||
// 바닥 미니맵
|
||||
const floorMat = new THREE.MeshBasicMaterial({ color: 0x5a6b7a, transparent: true });
|
||||
const floor = new THREE.Mesh(new THREE.PlaneGeometry(S, S), floorMat);
|
||||
floor.rotation.x = -Math.PI / 2;
|
||||
scene.add(floor);
|
||||
if (m.map.image) {
|
||||
const loader = new THREE.TextureLoader();
|
||||
loader.setCrossOrigin('anonymous');
|
||||
loader.load(m.map.image, (tex) => {
|
||||
tex.colorSpace = THREE.SRGBColorSpace;
|
||||
tex.anisotropy = renderer.capabilities.getMaxAnisotropy();
|
||||
floorMat.map = tex;
|
||||
floorMat.color.set(0xffffff);
|
||||
floorMat.needsUpdate = true;
|
||||
});
|
||||
}
|
||||
const grid = new THREE.GridHelper(S, 20, 0x1d2c3a, 0x15212c);
|
||||
grid.position.y = -0.05;
|
||||
scene.add(grid);
|
||||
|
||||
// 선수
|
||||
const views: PlayerView[] = roster.map((r) => {
|
||||
const color = r.ally ? ALLY : ENEMY;
|
||||
const group = new THREE.Group();
|
||||
const body = new THREE.Mesh(new THREE.CylinderGeometry(0.9, 0.9, 2.4, 20), new THREE.MeshStandardMaterial({ color, roughness: 0.5, transparent: true }));
|
||||
body.position.y = 1.2;
|
||||
body.userData.idx = r.idx;
|
||||
const cone = new THREE.Mesh(new THREE.ConeGeometry(0.55, 3.2, 12), new THREE.MeshStandardMaterial({ color: 0xffffff, transparent: true, opacity: 0.85 }));
|
||||
cone.geometry.rotateX(Math.PI / 2);
|
||||
cone.geometry.translate(0, 0, 2.2);
|
||||
cone.position.y = 1.9;
|
||||
const label = labelSprite(r.info?.character?.name ? `${r.name} · ${r.info.character.name}` : r.name, r.ally ? '#8fd8ff' : '#ff9aa5');
|
||||
label.position.y = 4.4;
|
||||
label.userData.idx = r.idx;
|
||||
const voice = labelSprite('🔊 말하는 중', '#ffe08a');
|
||||
voice.position.y = 6.6;
|
||||
voice.visible = false;
|
||||
const ring = new THREE.Mesh(new THREE.RingGeometry(1.4, 1.8, 32), new THREE.MeshBasicMaterial({ color: 0xffe08a, side: THREE.DoubleSide }));
|
||||
ring.rotation.x = -Math.PI / 2;
|
||||
ring.position.y = 0.05;
|
||||
ring.visible = false;
|
||||
group.add(body, cone, label, voice, ring);
|
||||
scene.add(group);
|
||||
const dropGeo = new THREE.BufferGeometry().setFromPoints([new THREE.Vector3(), new THREE.Vector3()]);
|
||||
const drop = new THREE.Line(dropGeo, new THREE.LineBasicMaterial({ color, transparent: true, opacity: 0.7 }));
|
||||
drop.frustumCulled = false;
|
||||
const shadow = new THREE.Mesh(new THREE.CircleGeometry(0.75, 20), new THREE.MeshBasicMaterial({ color, transparent: true, opacity: 0.85 }));
|
||||
shadow.rotation.x = -Math.PI / 2;
|
||||
scene.add(drop, shadow);
|
||||
return { idx: r.idx, info: r.info, name: r.name, ally: r.ally, group, body, cone, label, voice, ring, drop, shadow };
|
||||
});
|
||||
|
||||
// 선택한 선수 이동 경로 (최근 6초)
|
||||
const trailGeo = new THREE.BufferGeometry();
|
||||
trailGeo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(3 * 80), 3));
|
||||
const trail = new THREE.Line(trailGeo, new THREE.LineBasicMaterial({ color: 0xffe08a }));
|
||||
trail.frustumCulled = false;
|
||||
scene.add(trail);
|
||||
|
||||
// 사격 궤적 (최근 150ms)
|
||||
const MAX_SHOTS = 48;
|
||||
const shotGeo = new THREE.BufferGeometry();
|
||||
shotGeo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(MAX_SHOTS * 6), 3));
|
||||
const shots = new THREE.LineSegments(shotGeo, new THREE.LineBasicMaterial({ color: 0xfff1a8, transparent: true, opacity: 0.9 }));
|
||||
shots.frustumCulled = false;
|
||||
scene.add(shots);
|
||||
|
||||
// 킬 표시 (죽은 자리 X)
|
||||
const killGroup = new THREE.Group();
|
||||
scene.add(killGroup);
|
||||
const xGeo = new THREE.TorusGeometry(1.1, 0.22, 6, 4);
|
||||
const killMarks = replay.kills.map(([kt, ki, vi]) => {
|
||||
const v = replay.players[vi];
|
||||
const p = v ? samplePlayer(v.track, kt, 1500) : null;
|
||||
const ally = roster[vi]?.ally ?? false;
|
||||
const mk = new THREE.Mesh(xGeo, new THREE.MeshBasicMaterial({ color: ally ? ALLY : ENEMY, transparent: true }));
|
||||
mk.rotation.x = -Math.PI / 2;
|
||||
mk.rotation.z = Math.PI / 4;
|
||||
if (p) mk.position.copy(toWorld(p.x, p.y, Math.max(p.z, zBase), zBase)).add(new THREE.Vector3(0, 0.2, 0));
|
||||
mk.visible = false;
|
||||
killGroup.add(mk);
|
||||
return { t: kt, killer: ki, victim: vi, mk };
|
||||
});
|
||||
|
||||
// 스킬 · 설치물
|
||||
const objMeshes = new Map<number, THREE.Mesh>();
|
||||
const objMesh = (i: number) => {
|
||||
let mesh = objMeshes.get(i);
|
||||
if (mesh) return mesh;
|
||||
const [, , kind, x, y, z] = replay.objects[i];
|
||||
const name = replay.objectKinds[kind] ?? '';
|
||||
const smoke = /Smoke/i.test(name) && !/Projectile/.test(name);
|
||||
const spike = name === 'TimedBomb_C';
|
||||
const geo = smoke ? new THREE.SphereGeometry(3.6, 20, 14) : spike ? new THREE.OctahedronGeometry(1.2) : new THREE.SphereGeometry(0.45, 10, 8);
|
||||
const color = spike ? 0xff2d3d : smoke ? 0xb9c4cf : /Patch|Molotov|Fire/i.test(name) ? 0xff8a3d : /Trap|Wire|Tether/i.test(name) ? 0xc58bff : 0x9fffe0;
|
||||
mesh = new THREE.Mesh(geo, new THREE.MeshStandardMaterial({ color, transparent: true, opacity: smoke ? 0.38 : 0.9, depthWrite: !smoke }));
|
||||
mesh.position.copy(toWorld(x, y, z, zBase));
|
||||
if (smoke) mesh.position.y += 1.5;
|
||||
scene.add(mesh);
|
||||
objMeshes.set(i, mesh);
|
||||
return mesh;
|
||||
};
|
||||
|
||||
// 크기
|
||||
const resize = () => {
|
||||
const w = mount.clientWidth;
|
||||
const h = mount.clientHeight;
|
||||
renderer.setSize(w, h, false);
|
||||
camera.aspect = w / Math.max(1, h);
|
||||
camera.updateProjectionMatrix();
|
||||
};
|
||||
const ro = new ResizeObserver(resize);
|
||||
ro.observe(mount);
|
||||
resize();
|
||||
|
||||
// 선수 눌러서 고르기
|
||||
const ray = new THREE.Raycaster();
|
||||
const down = { x: 0, y: 0 };
|
||||
const onDown = (e: PointerEvent) => {
|
||||
down.x = e.clientX;
|
||||
down.y = e.clientY;
|
||||
};
|
||||
const onUp = (e: PointerEvent) => {
|
||||
if (Math.hypot(e.clientX - down.x, e.clientY - down.y) > 5) return; // 끌기(회전)는 고르기 아님
|
||||
const r = renderer.domElement.getBoundingClientRect();
|
||||
ray.setFromCamera(new THREE.Vector2(((e.clientX - r.left) / r.width) * 2 - 1, -((e.clientY - r.top) / r.height) * 2 + 1), camera);
|
||||
// 몸통은 위에서 보면 작아서 이름표를 눌러도 고른다
|
||||
const hit = ray.intersectObjects(views.flatMap((v) => (v.group.visible ? [v.body, v.label] : [])))[0];
|
||||
setSel(hit ? (hit.object.userData.idx as number) : null);
|
||||
};
|
||||
renderer.domElement.addEventListener('pointerdown', onDown);
|
||||
renderer.domElement.addEventListener('pointerup', onUp);
|
||||
|
||||
let raf = 0;
|
||||
let lastUi = 0;
|
||||
const tmp = new THREE.Vector3();
|
||||
const frame = (now: number) => {
|
||||
raf = requestAnimationFrame(frame);
|
||||
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;
|
||||
// 지금 말하는 사람
|
||||
const speaking = new Set<number>();
|
||||
for (const u of m.utterances) if (u.ts <= ts && ts <= u.endTs && !u.noise) {
|
||||
const i = playerByUser.get(u.userId);
|
||||
if (i != null) speaking.add(i);
|
||||
}
|
||||
const selIdx = selRef.current;
|
||||
for (const v of views) {
|
||||
const tr = replay.players[v.idx].track;
|
||||
const p = samplePlayer(tr, t, replay.sampleMs * 6);
|
||||
if (!p) {
|
||||
v.group.visible = v.drop.visible = v.shadow.visible = false;
|
||||
continue;
|
||||
}
|
||||
v.group.visible = v.drop.visible = v.shadow.visible = true;
|
||||
v.group.position.copy(toWorld(p.x, p.y, Math.max(p.z, zBase - 400), zBase));
|
||||
v.shadow.position.set(v.group.position.x, 0.04, v.group.position.z);
|
||||
const dp = v.drop.geometry.getAttribute('position') as THREE.BufferAttribute;
|
||||
dp.setXYZ(0, v.group.position.x, v.group.position.y, v.group.position.z);
|
||||
dp.setXYZ(1, v.group.position.x, 0.04, v.group.position.z);
|
||||
dp.needsUpdate = true;
|
||||
const d = dirOf(p.yaw);
|
||||
v.cone.rotation.y = Math.atan2(d.x, d.z);
|
||||
const dead = isDead(replay, v.idx, t);
|
||||
const op = dead ? 0.22 : 1;
|
||||
(v.body.material as THREE.MeshStandardMaterial).opacity = op;
|
||||
(v.cone.material as THREE.MeshStandardMaterial).opacity = dead ? 0 : 0.85;
|
||||
v.label.material.opacity = dead ? 0.35 : 1;
|
||||
(v.shadow.material as THREE.MeshBasicMaterial).opacity = dead ? 0.25 : 0.85;
|
||||
v.voice.visible = speaking.has(v.idx) && !dead;
|
||||
v.ring.visible = v.idx === selIdx;
|
||||
}
|
||||
// 경로
|
||||
if (selIdx != null) {
|
||||
const tr = replay.players[selIdx].track;
|
||||
const pos = trailGeo.getAttribute('position') as THREE.BufferAttribute;
|
||||
let n = 0;
|
||||
for (let k = 0; k < 80; k++) {
|
||||
const p = samplePlayer(tr, t - 6000 + (6000 * k) / 79, replay.sampleMs * 6);
|
||||
if (!p) continue;
|
||||
tmp.copy(toWorld(p.x, p.y, Math.max(p.z, zBase - 400), zBase));
|
||||
pos.setXYZ(n++, tmp.x, tmp.y + 0.3, tmp.z);
|
||||
}
|
||||
trailGeo.setDrawRange(0, n);
|
||||
pos.needsUpdate = true;
|
||||
trail.visible = n > 1;
|
||||
if (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));
|
||||
camera.position.add(tmp);
|
||||
}
|
||||
} else trail.visible = false;
|
||||
// 사격
|
||||
const sp = shotGeo.getAttribute('position') as THREE.BufferAttribute;
|
||||
let ns = 0;
|
||||
for (let i = lowerBound(replay.shots, t - 150); i < replay.shots.length && replay.shots[i][0] <= t && ns < MAX_SHOTS; i++) {
|
||||
const [, , x, y, z, yaw, pitch] = replay.shots[i];
|
||||
const a = toWorld(x, y, z, zBase);
|
||||
const d = dirOf(yaw);
|
||||
const len = 26;
|
||||
const b = a.clone().add(d.multiplyScalar(len * Math.cos((pitch * Math.PI) / 180))).add(new THREE.Vector3(0, len * Math.sin((pitch * Math.PI) / 180) * 0.3, 0));
|
||||
sp.setXYZ(ns * 2, a.x, a.y + 1.6, a.z);
|
||||
sp.setXYZ(ns * 2 + 1, b.x, b.y + 1.6, b.z);
|
||||
ns++;
|
||||
}
|
||||
shotGeo.setDrawRange(0, ns * 2);
|
||||
sp.needsUpdate = true;
|
||||
// 킬 표시: 이 라운드에서 이미 난 킬
|
||||
const rd = roundAt(replay, t);
|
||||
for (const k of killMarks) {
|
||||
const on = !!rd && k.t >= rd.buy && k.t <= t;
|
||||
k.mk.visible = on;
|
||||
if (on) {
|
||||
const age = t - k.t;
|
||||
const s = age < 600 ? 1 + (600 - age) / 300 : 1;
|
||||
k.mk.scale.setScalar(s);
|
||||
}
|
||||
}
|
||||
// 스킬 · 설치물: 생긴 뒤 사라질 때까지 (사라진 시각을 모르면 12초)
|
||||
for (let i = 0; i < replay.objects.length; i++) {
|
||||
const [t0, t1] = replay.objects[i];
|
||||
const end = t1 >= 0 ? t1 : t0 + 12000;
|
||||
const on = t >= t0 && t <= end;
|
||||
if (on) objMesh(i).visible = true;
|
||||
else {
|
||||
const mesh = objMeshes.get(i);
|
||||
if (mesh) mesh.visible = false;
|
||||
}
|
||||
}
|
||||
controls.update();
|
||||
renderer.render(scene, camera);
|
||||
if (now - lastUi > 100) {
|
||||
lastUi = now;
|
||||
setUi((u) => (Math.abs(u.t - t) < 50 && u.playing === (inScene && ps.playing) ? u : { t, playing: inScene && ps.playing }));
|
||||
}
|
||||
};
|
||||
raf = requestAnimationFrame(frame);
|
||||
return () => {
|
||||
cancelAnimationFrame(raf);
|
||||
ro.disconnect();
|
||||
renderer.domElement.removeEventListener('pointerdown', onDown);
|
||||
renderer.domElement.removeEventListener('pointerup', onUp);
|
||||
controls.dispose();
|
||||
scene.traverse((o) => {
|
||||
const mesh = o as THREE.Mesh;
|
||||
mesh.geometry?.dispose?.();
|
||||
const mat = mesh.material as THREE.Material | THREE.Material[] | undefined;
|
||||
(Array.isArray(mat) ? mat : mat ? [mat] : []).forEach((mm) => {
|
||||
(mm as THREE.MeshBasicMaterial).map?.dispose();
|
||||
mm.dispose();
|
||||
});
|
||||
});
|
||||
renderer.dispose();
|
||||
renderer.domElement.remove();
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [m, replay, base, roster, playerByUser, zBase]);
|
||||
|
||||
const inScene = () => player.state.mode === 'scene' && player.state.scene?.label === REPLAY_SCENE_LABEL;
|
||||
const seek = (t: number) => {
|
||||
const v = Math.max(0, Math.min(replay.durationMs, t));
|
||||
if (inScene()) player.seekScene(v);
|
||||
else localT.current = v;
|
||||
setUi((u) => ({ ...u, t: v }));
|
||||
};
|
||||
const togglePlay = () => {
|
||||
if (inScene()) player.toggle();
|
||||
else {
|
||||
const from = localT.current;
|
||||
player.startScene({ start: base, end: base + replay.durationMs, label: REPLAY_SCENE_LABEL, items: m.utterances });
|
||||
player.seekScene(from);
|
||||
}
|
||||
};
|
||||
|
||||
const rd = roundAt(replay, ui.t);
|
||||
const mr = rd ? m.rounds?.find((r) => r.num === rd.num) : undefined;
|
||||
const clock = !rd ? '' : rd.combat >= 0 && ui.t >= rd.combat ? fmtClock(ui.t - rd.combat) : `구매 ${fmtClock(Math.max(0, (rd.combat >= 0 ? rd.combat : rd.buy + 30000) - ui.t))}`;
|
||||
const ts = base + ui.t;
|
||||
const captions = m.utterances.filter((u) => !u.noise && u.text && u.ts <= ts && ts <= u.endTs + 1500).slice(-3);
|
||||
const feed = replay.kills.filter(([kt]) => kt <= ui.t && ui.t - kt < 6000).slice(-5);
|
||||
const selInfo = sel != null ? roster[sel] : null;
|
||||
const selPos = sel != null ? samplePlayer(replay.players[sel].track, ui.t, replay.sampleMs * 6) : null;
|
||||
const jumpRound = (dir: -1 | 1) => {
|
||||
const i = rd ? replay.rounds.indexOf(rd) : 0;
|
||||
const to = replay.rounds[Math.max(0, Math.min(replay.rounds.length - 1, i + dir))];
|
||||
if (to) seek(to.combat >= 0 ? to.combat - 3000 : to.buy);
|
||||
};
|
||||
|
||||
if (!T) return <div className="map-missing">이 경기에는 미니맵 좌표 정보가 없어 3D 리플레이를 그릴 수 없습니다</div>;
|
||||
return (
|
||||
<div className="r3d">
|
||||
<div className="r3d-stage" ref={mountRef}>
|
||||
<div className="r3d-hud tl">
|
||||
<b>{rd ? `R${rd.num}` : ''}</b> <span className="mono">{clock}</span>
|
||||
{mr && <span className="muted"> · {mr.score.ally}:{mr.score.enemy} 후 {mr.win ? '승리' : '패배'}</span>}
|
||||
</div>
|
||||
<div className="r3d-hud tr">
|
||||
{feed.map(([kt, ki, vi]) => (
|
||||
<div key={`${kt}:${vi}`} className="r3d-kill">
|
||||
<span className={roster[ki]?.ally ? 'a' : 'e'}>{roster[ki]?.name ?? '?'}</span> ✕ <span className={roster[vi]?.ally ? 'a' : 'e'}>{roster[vi]?.name ?? '?'}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
{captions.length > 0 && (
|
||||
<div className="r3d-cap">
|
||||
{captions.map((u) => (
|
||||
<div key={u.id}>
|
||||
<b>{userById(u.userId)?.name ?? '알 수 없음'}</b> {u.text}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{selInfo && (
|
||||
<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>}
|
||||
{selPos && <div className="mono muted">가장 낮은 층보다 {Math.max(0, Math.round((selPos.z - zBase) / 100))}m 위 · 보는 방향 {Math.round(((selPos.yaw % 360) + 360) % 360)}°</div>}
|
||||
<label className="r3d-follow">
|
||||
<input type="checkbox" checked={follow} onChange={(e) => setFollow(e.target.checked)} /> 따라가기
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="r3d-bar">
|
||||
<button className="chip" onClick={() => jumpRound(-1)} title="이전 라운드">⏮</button>
|
||||
<button className="chip r3d-play" onClick={togglePlay} title="대화와 같이 재생 / 멈춤">{ui.playing ? '⏸' : '▶'}</button>
|
||||
<button className="chip" onClick={() => jumpRound(1)} title="다음 라운드">⏭</button>
|
||||
<div className="r3d-scrub">
|
||||
{replay.rounds.map((r) => (
|
||||
<i key={r.num} style={{ left: `${(r.buy / replay.durationMs) * 100}%` }} data-tip={`R${r.num}`} />
|
||||
))}
|
||||
<input type="range" min={0} max={replay.durationMs} step={100} value={ui.t} onChange={(e) => seek(Number(e.target.value))} aria-label="리플레이 시간" />
|
||||
</div>
|
||||
<span className="mono muted">{fmtClock(ui.t)} / {fmtClock(replay.durationMs)}</span>
|
||||
<button className="chip mono" onClick={() => settings.set({ rate: RATES[(RATES.indexOf(cfg.rate) + 1) % RATES.length] ?? 1 })} title="재생 속도">
|
||||
{cfg.rate}x
|
||||
</button>
|
||||
<button className="chip" onClick={() => resetCam.current()} title="카메라 처음 위치로">전체 보기</button>
|
||||
</div>
|
||||
<div className="r3d-foot muted">
|
||||
마우스 왼쪽 끌기: 회전 · 오른쪽 끌기: 이동 · 휠: 확대 · 선수 클릭: 선택 ·{' '}
|
||||
{sync.matched >= 3
|
||||
? `대화 동기화: 킬 ${sync.matched}개로 맞춤 (최대 오차 ${((sync.spreadMs ?? 0) / 1000).toFixed(2)}초)`
|
||||
: '대화 동기화: 라운드 시작으로 대략 맞춤'}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function lowerBound(a: [number, ...number[]][], t: number) {
|
||||
let lo = 0;
|
||||
let hi = a.length;
|
||||
while (lo < hi) {
|
||||
const mid = (lo + hi) >> 1;
|
||||
if (a[mid][0] < t) lo = mid + 1;
|
||||
else hi = mid;
|
||||
}
|
||||
return lo;
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ import type {
|
||||
} from '@gvr/shared';
|
||||
|
||||
import { reportClient } from './report';
|
||||
import type { ReplayFile } from './replay';
|
||||
|
||||
/** 전역 신호: 401 → 로그인 화면, 503 device_offline → 잠금 화면 */
|
||||
type Signal = 'unauthorized' | 'not_member' | 'device_offline';
|
||||
@@ -135,6 +136,8 @@ export const api = {
|
||||
),
|
||||
matches: (o: { game?: GameType; limit?: number; before?: number } = {}) => request<MatchSummary[]>(`/api/matches${qs(o)}`),
|
||||
match: (id: string) => request<MatchDetail>(`/api/matches/${encodeURIComponent(id)}`),
|
||||
/** 발로란트 리플레이(.vrf)에서 뽑은 재생 데이터. 없으면 404 replay_not_found */
|
||||
replay: (id: string) => request<ReplayFile>(`/api/matches/${encodeURIComponent(id)}/replay`),
|
||||
culpritMatches: (o: { game?: GameType; limit?: number } = {}) => request<CulpritMatchItem[]>(`/api/culprit/matches${qs(o)}`),
|
||||
culpritMatch: (id: string) => request<CulpritMatchInfo>(`/api/culprit/matches/${encodeURIComponent(id)}`),
|
||||
culpritBudget: () => request<CulpritBudget>('/api/culprit/budget'),
|
||||
|
||||
141
site/web/src/lib/replay.ts
Normal file
141
site/web/src/lib/replay.ts
Normal file
@@ -0,0 +1,141 @@
|
||||
import type { KillData, MatchDetail } from '@gvr/shared';
|
||||
|
||||
/** tools/replay-extract (gvr-replay v1) 출력. t 는 리플레이 시작부터 ms, 좌표는 게임 월드 단위 */
|
||||
export interface ReplayFile {
|
||||
format: 'gvr-replay';
|
||||
v: 1;
|
||||
matchId: string | null;
|
||||
map: string | null;
|
||||
build: string | null;
|
||||
/** 리플레이 녹화 시작 (서버 시계, 유닉스 ms) */
|
||||
recordedAt: number;
|
||||
durationMs: number;
|
||||
sampleMs: number;
|
||||
players: { puuid: string | null; character: string | null; track: { t: number[]; x: number[]; y: number[]; z: number[]; yaw: number[]; pitch: number[] } }[];
|
||||
rounds: { num: number; buy: number; combat: number; end: number }[];
|
||||
phases: [number, number][];
|
||||
/** [t, killer, victim] */
|
||||
kills: [number, number, number][];
|
||||
/** [t, player, x, y, z, yaw, pitch] */
|
||||
shots: [number, number, number, number, number, number, number][];
|
||||
/** [t0, t1, kind, x, y, z, owner] */
|
||||
objects: [number, number, number, number, number, number, number][];
|
||||
objectKinds: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* 리플레이 시간(t) ↔ 기록 시각(ts, 게임 PC 시계) 맞추기.
|
||||
* 기본: ts = recordedAt + t + offset. offset 은 같은 킬(죽인 사람 · 죽은 사람이 같은 것)이
|
||||
* 경기 기록(match-details → 킬 이벤트 ts)과 리플레이에서 각각 언제인지 비교한 차이의 중앙값.
|
||||
* 킬을 못 맞추면 라운드 교전 시작으로 맞춘다 (정확도 낮음).
|
||||
*/
|
||||
export interface ReplaySync {
|
||||
offset: number;
|
||||
/** 맞춘 킬 수 */
|
||||
matched: number;
|
||||
/** 킬별 차이가 중앙값에서 벗어난 정도 (절대값 최대, ms). 이게 작아야 동기화가 정확하다 */
|
||||
spreadMs: number | null;
|
||||
/** 킬별 차이 (ms, 중앙값 기준) */
|
||||
residuals: number[];
|
||||
}
|
||||
|
||||
export function computeSync(m: MatchDetail, r: ReplayFile): ReplaySync {
|
||||
const kills = m.events.filter((e) => e.type === 'kill');
|
||||
const used = new Set<string>();
|
||||
const diffs: number[] = [];
|
||||
for (const [t, ki, vi] of r.kills) {
|
||||
const killer = r.players[ki]?.puuid;
|
||||
const victim = r.players[vi]?.puuid;
|
||||
if (!victim) continue;
|
||||
const at = r.recordedAt + t;
|
||||
let best: { id: string; d: number } | null = null;
|
||||
for (const e of kills) {
|
||||
if (used.has(e.id)) continue;
|
||||
const d = e.data as KillData;
|
||||
if (d.victim?.puuid !== victim) continue;
|
||||
if (killer && d.killer?.puuid && d.killer.puuid !== killer) continue;
|
||||
const diff = e.ts - at;
|
||||
// 1분 넘게 차이 나면 다른 라운드의 킬
|
||||
if (Math.abs(diff - (diffs.length ? median(diffs) : diff)) > 60000) continue;
|
||||
if (!best || Math.abs(diff) < Math.abs(best.d)) best = { id: e.id, d: diff };
|
||||
}
|
||||
if (best) {
|
||||
used.add(best.id);
|
||||
diffs.push(best.d);
|
||||
}
|
||||
}
|
||||
if (diffs.length >= 3) {
|
||||
const off = median(diffs);
|
||||
const residuals = diffs.map((d) => d - off);
|
||||
return { offset: off, matched: diffs.length, spreadMs: Math.max(...residuals.map(Math.abs)), residuals };
|
||||
}
|
||||
// 킬로 못 맞추면 라운드 교전 시작으로 맞춘다. 앱은 라운드 시작을 "교전 시작 - 30초" 로 저장한다 (valorant.ts BUY_MS)
|
||||
const rd: number[] = [];
|
||||
for (const mr of m.rounds ?? []) {
|
||||
const rr = r.rounds.find((x) => x.num === mr.num);
|
||||
if (rr && rr.combat >= 0) rd.push(mr.startedAt + 30000 - (r.recordedAt + rr.combat));
|
||||
}
|
||||
if (rd.length) return { offset: median(rd), matched: 0, spreadMs: null, residuals: [] };
|
||||
return { offset: 0, matched: 0, spreadMs: null, residuals: [] };
|
||||
}
|
||||
|
||||
function median(a: number[]): number {
|
||||
const s = [...a].sort((x, y) => x - y);
|
||||
const n = s.length;
|
||||
return n % 2 ? s[(n - 1) / 2] : (s[n / 2 - 1] + s[n / 2]) / 2;
|
||||
}
|
||||
|
||||
/** 이동 기록에서 t 시점 위치 (앞뒤 표본 사이 직선 보간). 표본이 sampleMs*5 넘게 끊겼으면 그 사이는 없음 */
|
||||
export function samplePlayer(tr: ReplayFile['players'][number]['track'], t: number, gapMs: number) {
|
||||
const T = tr.t;
|
||||
if (!T.length || t < T[0] - gapMs) return null;
|
||||
let lo = 0;
|
||||
let hi = T.length - 1;
|
||||
while (lo < hi) {
|
||||
const mid = (lo + hi + 1) >> 1;
|
||||
if (T[mid] <= t) lo = mid;
|
||||
else hi = mid - 1;
|
||||
}
|
||||
const i = lo;
|
||||
const j = Math.min(i + 1, T.length - 1);
|
||||
if (t - T[i] > gapMs) return { x: tr.x[i], y: tr.y[i], z: tr.z[i], yaw: tr.yaw[i], pitch: tr.pitch[i], stale: true };
|
||||
const span = T[j] - T[i];
|
||||
const k = j === i || span > gapMs || span <= 0 ? 0 : Math.min(1, Math.max(0, (t - T[i]) / span));
|
||||
let dy = tr.yaw[j] - tr.yaw[i];
|
||||
if (dy > 180) dy -= 360;
|
||||
if (dy < -180) dy += 360;
|
||||
return {
|
||||
x: tr.x[i] + (tr.x[j] - tr.x[i]) * k,
|
||||
y: tr.y[i] + (tr.y[j] - tr.y[i]) * k,
|
||||
z: tr.z[i] + (tr.z[j] - tr.z[i]) * k,
|
||||
yaw: tr.yaw[i] + dy * k,
|
||||
pitch: tr.pitch[i] + (tr.pitch[j] - tr.pitch[i]) * k,
|
||||
stale: false,
|
||||
};
|
||||
}
|
||||
|
||||
/** t 가 속한 라운드 (구매 단계 시작 기준) */
|
||||
export function roundAt(r: ReplayFile, t: number) {
|
||||
let cur = r.rounds[0] ?? null;
|
||||
for (const rd of r.rounds) if (rd.buy <= t) cur = rd;
|
||||
return cur;
|
||||
}
|
||||
|
||||
/** 이 라운드에서 t 전에 죽었는지 (다시 움직인 기록이 있으면 부활로 본다) */
|
||||
export function isDead(r: ReplayFile, player: number, t: number) {
|
||||
const rd = roundAt(r, t);
|
||||
if (!rd) return false;
|
||||
let death = -1;
|
||||
for (const [kt, , v] of r.kills) if (v === player && kt >= rd.buy && kt <= t) death = kt;
|
||||
if (death < 0) return false;
|
||||
const T = r.players[player]?.track.t ?? [];
|
||||
// 죽은 뒤 2초 넘어 움직인 표본이 t 전에 있으면 살아난 것
|
||||
let lo = 0;
|
||||
let hi = T.length;
|
||||
while (lo < hi) {
|
||||
const mid = (lo + hi) >> 1;
|
||||
if (T[mid] <= death + 2000) lo = mid + 1;
|
||||
else hi = mid;
|
||||
}
|
||||
return !(lo < T.length && T[lo] <= t);
|
||||
}
|
||||
@@ -13,6 +13,7 @@ import { UtteranceRow } from '../components/UtteranceRow';
|
||||
import { KillLine, SeparatorRow } from '../components/EventRow';
|
||||
import { IPlay, IWaves } from '../components/Icons';
|
||||
import { matchMeta } from './MatchPage';
|
||||
import { ReplayPanel } from '../components/ReplayPanel';
|
||||
|
||||
const BUY_MS = 30000;
|
||||
/** "R7 · 0:38" → "0:38" */
|
||||
@@ -299,6 +300,7 @@ export function ValorantMatch({ m }: { m: MatchDetail }) {
|
||||
</div>
|
||||
<RoundStrip rounds={rounds} sel={round.num} onSelect={select} />
|
||||
</div>
|
||||
<ReplayPanel m={m} />
|
||||
<div className="mgrid">
|
||||
<Panel
|
||||
className="map-panel"
|
||||
|
||||
@@ -3934,3 +3934,139 @@ button.match:hover {
|
||||
opacity: 0.45;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
/* ── 3D 리플레이 (components/ReplayViewer.tsx) ── */
|
||||
.replay-panel {
|
||||
flex: none;
|
||||
}
|
||||
.match.val:has(.replay-panel.open) {
|
||||
height: auto;
|
||||
}
|
||||
.match.val:has(.replay-panel.open) .mgrid {
|
||||
flex: none;
|
||||
height: 680px;
|
||||
}
|
||||
.r3d {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
.r3d-stage {
|
||||
position: relative;
|
||||
height: min(72vh, 760px);
|
||||
min-height: 420px;
|
||||
border-radius: 10px;
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--line);
|
||||
background: #0b141c;
|
||||
}
|
||||
.r3d-stage canvas {
|
||||
display: block;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
cursor: grab;
|
||||
}
|
||||
.r3d-stage canvas:active {
|
||||
cursor: grabbing;
|
||||
}
|
||||
.r3d-hud {
|
||||
position: absolute;
|
||||
z-index: 2;
|
||||
padding: 8px 12px;
|
||||
border-radius: 10px;
|
||||
background: rgba(8, 14, 20, 0.72);
|
||||
font-size: 14px;
|
||||
pointer-events: none;
|
||||
}
|
||||
.r3d-hud.tl {
|
||||
top: 10px;
|
||||
left: 10px;
|
||||
font-size: 16px;
|
||||
}
|
||||
.r3d-hud.tr {
|
||||
top: 10px;
|
||||
right: 10px;
|
||||
background: none;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
align-items: flex-end;
|
||||
}
|
||||
.r3d-hud.bl {
|
||||
left: 10px;
|
||||
bottom: 10px;
|
||||
pointer-events: auto;
|
||||
}
|
||||
.r3d-kill {
|
||||
background: rgba(8, 14, 20, 0.78);
|
||||
border-radius: 8px;
|
||||
padding: 4px 10px;
|
||||
font-size: 13px;
|
||||
}
|
||||
.r3d .a {
|
||||
color: #8fd8ff;
|
||||
}
|
||||
.r3d .e {
|
||||
color: #ff9aa5;
|
||||
}
|
||||
.r3d-cap {
|
||||
position: absolute;
|
||||
z-index: 2;
|
||||
left: 50%;
|
||||
bottom: 14px;
|
||||
transform: translateX(-50%);
|
||||
max-width: min(70%, 760px);
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
pointer-events: none;
|
||||
}
|
||||
.r3d-cap > div {
|
||||
background: rgba(8, 14, 20, 0.82);
|
||||
border-radius: 8px;
|
||||
padding: 6px 12px;
|
||||
font-size: 15px;
|
||||
text-align: center;
|
||||
}
|
||||
.r3d-cap b {
|
||||
color: var(--gold);
|
||||
margin-right: 6px;
|
||||
}
|
||||
.r3d-follow {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin-top: 6px;
|
||||
font-size: 13px;
|
||||
cursor: pointer;
|
||||
}
|
||||
.r3d-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
.r3d-play {
|
||||
min-width: 44px;
|
||||
}
|
||||
.r3d-scrub {
|
||||
position: relative;
|
||||
flex: 1;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
.r3d-scrub input {
|
||||
width: 100%;
|
||||
accent-color: var(--accent);
|
||||
}
|
||||
.r3d-scrub i {
|
||||
position: absolute;
|
||||
top: -6px;
|
||||
width: 1px;
|
||||
height: 8px;
|
||||
background: var(--muted);
|
||||
pointer-events: none;
|
||||
}
|
||||
.r3d-foot {
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
4
tools/replay-extract/.gitignore
vendored
Normal file
4
tools/replay-extract/.gitignore
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
vendor/
|
||||
bin/
|
||||
obj/
|
||||
out/
|
||||
20
tools/replay-extract/ReplayExtract.csproj
Normal file
20
tools/replay-extract/ReplayExtract.csproj
Normal file
@@ -0,0 +1,20 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<!-- 발로란트 리플레이(.vrf) → 사이트 재생기용 작은 JSON. 파서는 fetch-parser.sh 로 vendor/ 에 받는다 -->
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net10.0</TargetFramework>
|
||||
<ImplicitUsings>enable</ImplicitUsings>
|
||||
<Nullable>enable</Nullable>
|
||||
<AssemblyName>gvr-replay</AssemblyName>
|
||||
<InvariantGlobalization>true</InvariantGlobalization>
|
||||
<EnableDefaultCompileItems>false</EnableDefaultCompileItems>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="src/**/*.cs" />
|
||||
<ProjectReference Include="vendor/ValorantReplayParser/src/Replay.Encoding/Replay.Encoding.csproj" />
|
||||
<ProjectReference Include="vendor/ValorantReplayParser/src/Replay.Models/Replay.Models.csproj" />
|
||||
<ProjectReference Include="vendor/ValorantReplayParser/src/Replay.Unreal/Replay.Unreal.csproj" />
|
||||
<ProjectReference Include="vendor/ValorantReplayParser/src/Replay.Valorant/Replay.Valorant.csproj" />
|
||||
<ProjectReference Include="vendor/ValorantReplayParser/src/Replay.Valorant.Events/Replay.Valorant.Events.csproj" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
21
tools/replay-extract/fetch-parser.sh
Executable file
21
tools/replay-extract/fetch-parser.sh
Executable file
@@ -0,0 +1,21 @@
|
||||
#!/usr/bin/env bash
|
||||
# ValorantReplayParser (MIT, https://github.com/michel-giehl/ValorantReplayParser) 를 고정 커밋으로 받아 vendor/ 에 둔다.
|
||||
# 발로란트 패치로 리플레이 형식이 바뀌면 PARSER_COMMIT 을 새 커밋으로 올린다.
|
||||
set -euo pipefail
|
||||
PARSER_COMMIT="${PARSER_COMMIT:-28e24af44f5d2e2444fb679f500b6ec04ab60672}"
|
||||
here="$(cd "$(dirname "$0")" && pwd)"
|
||||
dst="$here/vendor/ValorantReplayParser"
|
||||
if [ ! -d "$dst/.git" ]; then
|
||||
git clone --quiet https://github.com/michel-giehl/ValorantReplayParser "$dst"
|
||||
fi
|
||||
git -C "$dst" fetch --quiet origin
|
||||
git -C "$dst" checkout --quiet --force "$PARSER_COMMIT"
|
||||
# 저장소의 global.json 은 SDK 패치 버전까지 고정한다. 같은 10.0 대 SDK 면 쓰게 풀어 준다
|
||||
python3 - "$dst/global.json" <<'P'
|
||||
import json, sys
|
||||
p = sys.argv[1]
|
||||
d = json.load(open(p))
|
||||
d.setdefault('sdk', {})['rollForward'] = 'latestFeature'
|
||||
json.dump(d, open(p, 'w'), indent=2)
|
||||
P
|
||||
echo "parser @ $(git -C "$dst" rev-parse --short HEAD)"
|
||||
265
tools/replay-extract/src/Collector.cs
Normal file
265
tools/replay-extract/src/Collector.cs
Normal file
@@ -0,0 +1,265 @@
|
||||
using System.Text.RegularExpressions;
|
||||
using Replay.Models.Events;
|
||||
using Replay.Models.Unreal;
|
||||
using Replay.Valorant.Combat;
|
||||
using Replay.Valorant.Descriptors;
|
||||
using Replay.Valorant.Descriptors.Agents;
|
||||
using Replay.Valorant.Events.Combat;
|
||||
using Replay.Valorant.Events.Movement;
|
||||
using Replay.Valorant.GameState;
|
||||
|
||||
namespace GvrReplay;
|
||||
|
||||
/// 파서 이벤트 → 필요한 것만 모은다 (선수 이동은 sampleMs 간격으로 줄임)
|
||||
public sealed partial class Collector(int sampleMs) : IReplayEventSink
|
||||
{
|
||||
private string? _matchId;
|
||||
private string? _map;
|
||||
private readonly Dictionary<uint, string> _archetypeByActor = [];
|
||||
private readonly Dictionary<uint, string> _subjectByState = [];
|
||||
private readonly Dictionary<uint, uint> _stateByCharacter = [];
|
||||
// 조종 중인 폰 (드론 · 카메라 · 클로브 사후 몸 등). 요원 몸(*_PC_C)만 선수 이동으로 쓴다
|
||||
private readonly Dictionary<uint, uint> _possessedByState = [];
|
||||
private readonly Dictionary<uint, List<int[]>> _moves = [];
|
||||
private readonly Dictionary<uint, int> _lastMoveT = [];
|
||||
private readonly List<int[]> _phases = [];
|
||||
private readonly List<(int T, int NewRoundIndex)> _roundEnds = [];
|
||||
private readonly List<(int T, uint Killer, uint Victim)> _kills = [];
|
||||
private readonly List<(int T, uint State, int X, int Y, int Z, int Yaw, int Pitch)> _shots = [];
|
||||
private readonly List<(int T0, uint Actor, string Kind, int X, int Y, int Z)> _objects = [];
|
||||
private readonly Dictionary<uint, int> _closedAt = [];
|
||||
private readonly Dictionary<uint, uint> _objectOwner = [];
|
||||
private readonly Dictionary<string, int> _stats = [];
|
||||
|
||||
private static int Ms(float seconds) => (int)Math.Round(seconds * 1000.0);
|
||||
private static int R(double v) => (int)Math.Round(v);
|
||||
|
||||
[GeneratedRegex(@"^/Game/Maps/([^/.]+)/\1$")]
|
||||
private static partial Regex MapPath();
|
||||
|
||||
// 스킬 · 설치물로 보는 액터 클래스 (요원 본체 *_PC_C 와 무기 · 상태는 뺀다)
|
||||
// GameObject_* (연막 · 함정 · 정찰 등), Patch_* (장판), Pawn_* (드론 · 분신), Projectile_* (날아가는 스킬), TimedBomb_C (설치된 스파이크)
|
||||
[GeneratedRegex(@"^Default__(GameObject_|Patch_|Pawn_|Projectile_|TimedBomb_C$)")]
|
||||
private static partial Regex ObjectClass();
|
||||
|
||||
public void Emit(ReplayEvent e)
|
||||
{
|
||||
switch (e)
|
||||
{
|
||||
case NetGuidExported g:
|
||||
if (_map is null && MapPath().IsMatch(g.Path)) _map = g.Path;
|
||||
break;
|
||||
case ActorSpawned s:
|
||||
if (s.ArchetypePath is { } arch)
|
||||
{
|
||||
_archetypeByActor[s.ActorNetGuid] = arch;
|
||||
Count("spawn " + Simplify(arch));
|
||||
if (s.Location is { } loc && ObjectClass().IsMatch(arch) && !arch.EndsWith("_PC_C"))
|
||||
_objects.Add((Ms(s.TimeSeconds), s.ActorNetGuid, Simplify(arch), R(loc.X), R(loc.Y), R(loc.Z)));
|
||||
}
|
||||
break;
|
||||
case ActorClosed c:
|
||||
_closedAt[c.ActorNetGuid] = Ms(c.TimeSeconds);
|
||||
break;
|
||||
case ExportGroupReceived x:
|
||||
OnExport(x);
|
||||
break;
|
||||
case RpcReceived r:
|
||||
OnRpc(r);
|
||||
break;
|
||||
case RemoteCharacterMovementReceived m:
|
||||
OnMove(m);
|
||||
break;
|
||||
case ValorantShotReceived shot:
|
||||
OnShot(shot);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnExport(ExportGroupReceived x)
|
||||
{
|
||||
switch (x.Payload)
|
||||
{
|
||||
case BombGameStateDescriptor gs when gs.HasDecoded(nameof(BombGameStateDescriptor.MatchID)) && !string.IsNullOrEmpty(gs.MatchID):
|
||||
_matchId ??= gs.MatchID;
|
||||
break;
|
||||
case BombPlayerStateDescriptor ps:
|
||||
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)
|
||||
_stateByCharacter[ps.SpawnedCharacter.NetGuid] = x.ActorNetGuid;
|
||||
if (ps.HasDecoded(nameof(BombPlayerStateDescriptor.PossessedCharacter)) && ps.PossessedCharacter.NetGuid != 0)
|
||||
_possessedByState[ps.PossessedCharacter.NetGuid] = x.ActorNetGuid;
|
||||
break;
|
||||
case GenericAgentDescriptor agent:
|
||||
if (agent.HasDecoded(nameof(GenericAgentDescriptor.PlayerState)) && agent.PlayerState.NetGuid != 0)
|
||||
_stateByCharacter.TryAdd(x.ActorNetGuid, agent.PlayerState.NetGuid);
|
||||
if (agent.HasDecoded(nameof(GenericAgentDescriptor.Owner)) && agent.Owner.NetGuid != 0)
|
||||
_objectOwner.TryAdd(x.ActorNetGuid, agent.Owner.NetGuid);
|
||||
if (agent.HasDecoded(nameof(GenericAgentDescriptor.Instigator)) && agent.Instigator.NetGuid != 0)
|
||||
_objectOwner[x.ActorNetGuid] = agent.Instigator.NetGuid;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnRpc(RpcReceived r)
|
||||
{
|
||||
var t = Ms(r.TimeSeconds);
|
||||
switch (r.Payload)
|
||||
{
|
||||
case ClientGamePhaseBeginParameters p:
|
||||
// 같은 시각에 같은 단계가 여러 컨트롤러로 올 수 있다
|
||||
if (_phases.Count == 0 || _phases[^1][1] != p.NewPhase || _phases[^1][0] != t)
|
||||
_phases.Add([t, p.NewPhase]);
|
||||
break;
|
||||
case MulticastEndRoundParameters er:
|
||||
if (_roundEnds.Count == 0 || _roundEnds[^1].NewRoundIndex != er.NewRoundNumber)
|
||||
_roundEnds.Add((t, er.NewRoundNumber));
|
||||
break;
|
||||
case MulticastNotifyKilledEnemyParameters k:
|
||||
if (!_kills.Any(q => Math.Abs(q.T - t) < 50 && q.Victim == k.KilledCharacter.NetGuid))
|
||||
_kills.Add((t, k.KillerCharacter.NetGuid, k.KilledCharacter.NetGuid));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnMove(RemoteCharacterMovementReceived m)
|
||||
{
|
||||
var t = Ms(m.TimeSeconds);
|
||||
var ch = m.ShooterCharacterNetGuidValue;
|
||||
if (_lastMoveT.TryGetValue(ch, out var last) && t - last < sampleMs) return;
|
||||
_lastMoveT[ch] = t;
|
||||
var p = m.Move.Position;
|
||||
if (!_moves.TryGetValue(ch, out var list)) _moves[ch] = list = [];
|
||||
list.Add([t, R(p.X), R(p.Y), R(p.Z), R(m.Move.Yaw), R(m.Move.Pitch)]);
|
||||
}
|
||||
|
||||
private void OnShot(ValorantShotReceived s)
|
||||
{
|
||||
var shot = s.Shot;
|
||||
if (shot.Location is not { } loc) return;
|
||||
var state = shot.FiringPlayerState?.NetGuid ?? 0;
|
||||
double yaw = 0, pitch = 0;
|
||||
if (shot.Rotation is { } rot)
|
||||
{
|
||||
yaw = rot.Yaw;
|
||||
pitch = rot.Pitch;
|
||||
}
|
||||
else if (shot.AttackVectors.Count > 0)
|
||||
{
|
||||
var v = shot.AttackVectors[0];
|
||||
yaw = Math.Atan2(v.Y, v.X) * 180 / Math.PI;
|
||||
pitch = Math.Atan2(v.Z, Math.Sqrt(v.X * v.X + v.Y * v.Y)) * 180 / Math.PI;
|
||||
}
|
||||
_shots.Add((Ms(s.TimeSeconds), state, R(loc.X), R(loc.Y), R(loc.Z), R(yaw), R(pitch)));
|
||||
}
|
||||
|
||||
private static string Simplify(string archetype) => archetype.StartsWith("Default__") ? archetype[9..] : archetype;
|
||||
|
||||
private void Count(string key) => _stats[key] = _stats.GetValueOrDefault(key) + 1;
|
||||
|
||||
public void PrintStats()
|
||||
{
|
||||
Console.WriteLine($"match {_matchId} map {_map} states {_subjectByState.Count} chars {_stateByCharacter.Count} moves {_moves.Count} kills {_kills.Count} shots {_shots.Count} objects {_objects.Count} phases {_phases.Count} roundEnds {_roundEnds.Count}");
|
||||
Console.WriteLine("stateByChar: " + string.Join(",", _stateByCharacter.Select(kv => $"{kv.Key}->{kv.Value}({(_archetypeByActor.TryGetValue(kv.Key, out var a) ? a : "?")})")));
|
||||
Console.WriteLine("moves: " + string.Join(",", _moves.OrderByDescending(kv => kv.Value.Count).Take(14).Select(kv => $"{kv.Key}:{kv.Value.Count}({(_archetypeByActor.TryGetValue(kv.Key, out var a) ? a : "?")})")));
|
||||
Console.WriteLine("states: " + string.Join(",", _subjectByState.Keys));
|
||||
foreach (var (k, v) in _stats.OrderByDescending(kv => kv.Value).Take(150)) Console.WriteLine($"{v,6} {k}");
|
||||
}
|
||||
|
||||
public ReplayFile Build(string? branch, long recordedAt, int durationMs, int hz)
|
||||
{
|
||||
// 선수 = 계정(subject) 하나. 캐릭터가 여러 번 바뀌어도(부활 등) 같은 선수로 묶는다
|
||||
var players = new List<ReplayPlayer>();
|
||||
var indexBySubject = new Dictionary<string, int>();
|
||||
var indexByCharacter = new Dictionary<uint, int>();
|
||||
int PlayerOfState(uint state)
|
||||
{
|
||||
if (!_subjectByState.TryGetValue(state, out var subject)) return -1;
|
||||
if (!indexBySubject.TryGetValue(subject, out var i))
|
||||
{
|
||||
i = players.Count;
|
||||
indexBySubject[subject] = i;
|
||||
players.Add(new ReplayPlayer { Puuid = subject });
|
||||
}
|
||||
return i;
|
||||
}
|
||||
foreach (var state in _subjectByState.Keys.OrderBy(k => k)) PlayerOfState(state);
|
||||
foreach (var (ch, state) in _possessedByState)
|
||||
if (_archetypeByActor.TryGetValue(ch, out var a) && a.EndsWith("_PC_C")) _stateByCharacter.TryAdd(ch, state);
|
||||
foreach (var (ch, state) in _stateByCharacter)
|
||||
{
|
||||
var i = PlayerOfState(state);
|
||||
if (i < 0) continue;
|
||||
indexByCharacter[ch] = i;
|
||||
if (_archetypeByActor.TryGetValue(ch, out var arch) && arch.EndsWith("_PC_C"))
|
||||
players[i].Character ??= Simplify(arch);
|
||||
}
|
||||
var merged = players.Select(_ => new List<int[]>()).ToList();
|
||||
foreach (var (ch, moves) in _moves)
|
||||
if (indexByCharacter.TryGetValue(ch, out var i)) merged[i].AddRange(moves);
|
||||
for (var i = 0; i < players.Count; i++)
|
||||
{
|
||||
var tr = players[i].Track;
|
||||
var lastT = int.MinValue / 2;
|
||||
foreach (var mv in merged[i].OrderBy(m => m[0]))
|
||||
{
|
||||
if (mv[0] - lastT < sampleMs) continue;
|
||||
lastT = mv[0];
|
||||
tr.T.Add(mv[0]); tr.X.Add(mv[1]); tr.Y.Add(mv[2]); tr.Z.Add(mv[3]); tr.Yaw.Add(mv[4]); tr.Pitch.Add(mv[5]);
|
||||
}
|
||||
}
|
||||
|
||||
// 라운드: MulticastEndRound(NewRoundNumber=k) 는 라운드 k+1(1부터) 의 시작. 단계 3=구매, 4=교전, 5=라운드 끝
|
||||
var rounds = new List<ReplayRound>();
|
||||
var starts = new List<(int T, int Num)> { (0, 1) };
|
||||
foreach (var (t, idx) in _roundEnds) starts.Add((t, idx + 1));
|
||||
for (var r = 0; r < starts.Count; r++)
|
||||
{
|
||||
var from = starts[r].T;
|
||||
var to = r + 1 < starts.Count ? starts[r + 1].T : int.MaxValue;
|
||||
int Phase(int ph) => _phases.FirstOrDefault(p => p[1] == ph && p[0] >= from && p[0] < to)?[0] ?? -1;
|
||||
var buy = Phase(3);
|
||||
rounds.Add(new ReplayRound { Num = starts[r].Num, Buy = buy >= 0 ? buy : from, Combat = Phase(4), End = Phase(5) });
|
||||
}
|
||||
|
||||
var kinds = new List<string>();
|
||||
var kindIndex = new Dictionary<string, int>();
|
||||
var objects = new List<int[]>();
|
||||
// 맵 자체 연출(예: GameObject_Infinity_Rain_*)은 뺀다
|
||||
var mapName = _map?.Split('/')[^1];
|
||||
foreach (var o in _objects)
|
||||
{
|
||||
if (mapName is not null && o.Kind.Contains("_" + mapName + "_")) continue;
|
||||
if (!kindIndex.TryGetValue(o.Kind, out var k)) { k = kinds.Count; kinds.Add(o.Kind); kindIndex[o.Kind] = k; }
|
||||
var owner = -1;
|
||||
var cur = o.Actor;
|
||||
for (var d = 0; d < 6 && _objectOwner.TryGetValue(cur, out var up); d++)
|
||||
{
|
||||
if (indexByCharacter.TryGetValue(up, out owner)) break;
|
||||
owner = -1;
|
||||
if (_stateByCharacter.ContainsKey(up)) break;
|
||||
if (_subjectByState.ContainsKey(up)) { owner = PlayerOfState(up); break; }
|
||||
cur = up;
|
||||
}
|
||||
objects.Add([o.T0, _closedAt.TryGetValue(o.Actor, out var t1) && t1 >= o.T0 ? t1 : -1, k, o.X, o.Y, o.Z, owner]);
|
||||
}
|
||||
|
||||
return new ReplayFile
|
||||
{
|
||||
MatchId = _matchId,
|
||||
Map = _map,
|
||||
Build = branch?.Replace("++Ares-Core+", ""),
|
||||
RecordedAt = recordedAt,
|
||||
DurationMs = durationMs,
|
||||
SampleMs = sampleMs,
|
||||
Players = players,
|
||||
Rounds = rounds,
|
||||
Phases = _phases,
|
||||
Kills = _kills.Select(k => new[] { k.T, indexByCharacter.GetValueOrDefault(k.Killer, -1), indexByCharacter.GetValueOrDefault(k.Victim, -1) }).ToList(),
|
||||
Shots = _shots.Select(s => new[] { s.T, PlayerOfState(s.State), s.X, s.Y, s.Z, s.Yaw, s.Pitch }).ToList(),
|
||||
Objects = objects,
|
||||
ObjectKinds = kinds,
|
||||
};
|
||||
}
|
||||
}
|
||||
69
tools/replay-extract/src/Model.cs
Normal file
69
tools/replay-extract/src/Model.cs
Normal file
@@ -0,0 +1,69 @@
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace GvrReplay;
|
||||
|
||||
// 사이트로 가는 형식. 시간은 모두 리플레이 시작부터 ms (t), 좌표는 게임 월드 단위(cm) 정수
|
||||
public sealed class ReplayFile
|
||||
{
|
||||
public string Format { get; set; } = "gvr-replay";
|
||||
public int V { get; set; } = 1;
|
||||
public string? MatchId { get; set; }
|
||||
public string? Map { get; set; }
|
||||
public string? Build { get; set; }
|
||||
/// 리플레이 녹화 시작 시각 (서버 기준 유닉스 ms). t 를 실제 시각으로 바꿀 때 recordedAt + t
|
||||
public long RecordedAt { get; set; }
|
||||
public int DurationMs { get; set; }
|
||||
public int SampleMs { get; set; }
|
||||
public List<ReplayPlayer> Players { get; set; } = [];
|
||||
public List<ReplayRound> Rounds { get; set; } = [];
|
||||
/// [t, phase] 게임 단계 바뀜 (원본 값)
|
||||
public List<int[]> Phases { get; set; } = [];
|
||||
/// [t, killer, victim] (선수 번호, 모르면 -1)
|
||||
public List<int[]> Kills { get; set; } = [];
|
||||
/// [t, player, x, y, z, yaw, pitch] 사격 위치와 방향
|
||||
public List<int[]> Shots { get; set; } = [];
|
||||
/// 스킬 · 설치물 [t0, t1, kind 번호, x, y, z, player] (t1 = 사라진 시각, 모르면 -1)
|
||||
public List<int[]> Objects { get; set; } = [];
|
||||
public List<string> ObjectKinds { get; set; } = [];
|
||||
}
|
||||
|
||||
public sealed class ReplayPlayer
|
||||
{
|
||||
public string? Puuid { get; set; }
|
||||
/// 캐릭터 클래스 (예: Wushu_PC_C). 요원 이름은 사이트가 경기 상세(match-details)로 붙인다
|
||||
public string? Character { get; set; }
|
||||
/// 이동 기록. 열 별 배열 (같은 길이): t, x, y, z, yaw(도), pitch(도)
|
||||
public PlayerTrack Track { get; set; } = new();
|
||||
}
|
||||
|
||||
public sealed class PlayerTrack
|
||||
{
|
||||
public List<int> T { get; set; } = [];
|
||||
public List<int> X { get; set; } = [];
|
||||
public List<int> Y { get; set; } = [];
|
||||
public List<int> Z { get; set; } = [];
|
||||
public List<int> Yaw { get; set; } = [];
|
||||
public List<int> Pitch { get; set; } = [];
|
||||
}
|
||||
|
||||
public sealed class ReplayRound
|
||||
{
|
||||
/// 1부터
|
||||
public int Num { get; set; }
|
||||
/// 구매 단계 시작
|
||||
public int Buy { get; set; }
|
||||
/// 교전 시작 (구매 단계 끝), 모르면 -1
|
||||
public int Combat { get; set; }
|
||||
/// 라운드 끝 (승패 확정), 모르면 -1
|
||||
public int End { get; set; }
|
||||
}
|
||||
|
||||
public static class ReplayJson
|
||||
{
|
||||
public static readonly JsonSerializerOptions Options = new()
|
||||
{
|
||||
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
||||
DefaultIgnoreCondition = JsonIgnoreCondition.Never,
|
||||
};
|
||||
}
|
||||
76
tools/replay-extract/src/Program.cs
Normal file
76
tools/replay-extract/src/Program.cs
Normal file
@@ -0,0 +1,76 @@
|
||||
// gvr-replay: 발로란트 리플레이(.vrf) → 사이트 재생기용 JSON (형식 gvr-replay v1)
|
||||
// gvr-replay <file.vrf> <out.json> [--hz 10]
|
||||
// gvr-replay <file.vrf> --stats (디버그: 액터 종류별 개수)
|
||||
// 성공하면 종료 코드 0 과 함께 stdout 마지막 줄에 {"ok":true,...} 요약을 쓴다. 실패는 1 과 {"ok":false,"error":...}
|
||||
using System.Diagnostics;
|
||||
using System.Text.Json;
|
||||
using Replay.Encoding.Archives;
|
||||
using Replay.Models.Descriptors;
|
||||
using Replay.Valorant;
|
||||
using Replay.Valorant.Events;
|
||||
|
||||
namespace GvrReplay;
|
||||
|
||||
public static class Program
|
||||
{
|
||||
public static int Main(string[] args)
|
||||
{
|
||||
if (args.Length < 2)
|
||||
{
|
||||
Console.Error.WriteLine("사용법: gvr-replay <file.vrf> <out.json> [--hz 10] | gvr-replay <file.vrf> --stats");
|
||||
return 2;
|
||||
}
|
||||
var input = args[0];
|
||||
var stats = args[1] == "--stats";
|
||||
var hz = 10;
|
||||
for (var i = 2; i < args.Length - 1; i++)
|
||||
if (args[i] == "--hz") hz = Math.Clamp(int.Parse(args[i + 1]), 1, 60);
|
||||
try
|
||||
{
|
||||
var sw = Stopwatch.StartNew();
|
||||
var collector = new Collector(1000 / hz);
|
||||
using var file = File.OpenRead(input);
|
||||
using var archive = new FBinaryArchive(file);
|
||||
var enricher = new ValorantEventEnricher(collector);
|
||||
var result = ValorantReplayReader.CreateDefault(null, enricher, ParseProfile.Default).Read(archive);
|
||||
enricher.Complete();
|
||||
var info = result.Metadata.ReplayInfo;
|
||||
if (stats)
|
||||
{
|
||||
collector.PrintStats();
|
||||
return 0;
|
||||
}
|
||||
var replay = collector.Build(
|
||||
result.Metadata.ReplayVersion.Branch,
|
||||
FDateTimeToUnixMs(info.Timestamp),
|
||||
info.LengthInMs,
|
||||
hz);
|
||||
var tmp = args[1] + ".tmp";
|
||||
using (var fs = File.Create(tmp))
|
||||
JsonSerializer.Serialize(fs, replay, ReplayJson.Options);
|
||||
File.Move(tmp, args[1], true);
|
||||
Console.WriteLine(JsonSerializer.Serialize(new
|
||||
{
|
||||
ok = true,
|
||||
matchId = replay.MatchId,
|
||||
map = replay.Map,
|
||||
build = replay.Build,
|
||||
players = replay.Players.Count,
|
||||
rounds = replay.Rounds.Count,
|
||||
kills = replay.Kills.Count,
|
||||
elapsedMs = sw.ElapsedMilliseconds,
|
||||
status = result.Status.ToString(),
|
||||
warnings = result.TotalDiagnosticCount,
|
||||
}));
|
||||
return 0;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.WriteLine(JsonSerializer.Serialize(new { ok = false, error = e.GetType().Name + ": " + e.Message }));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
/// UE FDateTime ticks (100ns, 0001-01-01 기준, UTC) → 유닉스 ms
|
||||
public static long FDateTimeToUnixMs(long ticks) => ticks <= 0 ? 0 : (ticks - 621355968000000000L) / 10000L;
|
||||
}
|
||||
Reference in New Issue
Block a user