Compare commits
26 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d2372283db | ||
|
|
977390078e | ||
|
|
673f2423d5 | ||
|
|
c86c3ee8de | ||
|
|
cec5e3537c | ||
|
|
5e756f9eb8 | ||
|
|
8782df2111 | ||
|
|
dd9564dfc2 | ||
|
|
56242cd8ca | ||
|
|
fa9929145e | ||
|
|
200dbceece | ||
|
|
0da993928e | ||
|
|
96f6957422 | ||
|
|
a5a1c8406a | ||
|
|
c36db3ef9a | ||
|
|
c539c2b9dc | ||
|
|
320cc9babe | ||
|
|
b645d7575d | ||
|
|
63d0e43196 | ||
|
|
2a9a6496d8 | ||
|
|
b1568db8ca | ||
|
|
11db2e5104 | ||
|
|
f9fbf4c6c0 | ||
|
|
9e1875b237 | ||
|
|
d0371fa0ac | ||
|
|
cfe5075f76 |
@@ -8,7 +8,7 @@
|
||||
- 설계·계획: [`docs/gemnoki-project-plan.pdf`](docs/gemnoki-project-plan.pdf), 개발 구조·인터페이스: [`docs/dev/ARCHITECTURE.md`](docs/dev/ARCHITECTURE.md)
|
||||
- 범인찾기 · 리플레이 동기화 계획서 v1.2 (결정 반영): [`docs/culprit-finder-plan.pdf`](docs/culprit-finder-plan.pdf) · 원본 · 비용 계산 · 프롬프트 초안: `docs/report/culprit/` (실제로 쓰는 프롬프트는 `site/server/prompt/`)
|
||||
- **제작 완료 보고서 (M0~M8)**: [`docs/gemnoki-final-report.pdf`](docs/gemnoki-final-report.pdf) · 단계별 테스트 기록: [`docs/dev/test-results.md`](docs/dev/test-results.md)
|
||||
- Windows 실행 파일: Gitea 릴리스 [v1.8.1](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.8.1) (`GameVoiceRecorder-1.8.1-win-x64.zip` 권장, 단일 파일 `GameVoiceRecorder-1.8.1-portable.exe`) · 바뀐 점 보고서 [`docs/gemnoki-v1.3.7-report.pdf`](docs/gemnoki-v1.3.7-report.pdf) · 처음 버전 [v1.0.0](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.0.0)
|
||||
- Windows 실행 파일: Gitea 릴리스 [v1.11.1](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.11.1) (`GameVoiceRecorder-1.11.1-win-x64.zip` 권장, 단일 파일 `GameVoiceRecorder-1.11.1-portable.exe`) · 바뀐 점 보고서 [`docs/gemnoki-v1.3.7-report.pdf`](docs/gemnoki-v1.3.7-report.pdf) · 처음 버전 [v1.0.0](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.0.0)
|
||||
|
||||
## 로그인 · 관리자 (v1.2.0~)
|
||||
|
||||
|
||||
4
app/package-lock.json
generated
4
app/package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "gvr-app",
|
||||
"version": "1.8.2",
|
||||
"version": "1.11.2",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "gvr-app",
|
||||
"version": "1.8.2",
|
||||
"version": "1.11.2",
|
||||
"license": "UNLICENSED",
|
||||
"dependencies": {
|
||||
"@discordjs/voice": "^0.19.2",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "gvr-app",
|
||||
"productName": "겜녹이",
|
||||
"version": "1.8.2",
|
||||
"version": "1.11.2",
|
||||
"description": "겜녹이 (Game Voice Recorder) - 게임 연동 디스코드 음성 기록",
|
||||
"private": true,
|
||||
"main": "dist/main.cjs",
|
||||
|
||||
@@ -6,6 +6,7 @@ import type { Culprit } from '../culprit.js';
|
||||
import { normalizePhrase, type Store, type UserRow } from '../db/db.js';
|
||||
import type { Dictionary } from '../dict/dictionary.js';
|
||||
import type { GameManager } from '../games/manager.js';
|
||||
import { HIDDEN_MODE } from '../games/modes.js';
|
||||
import type { Settings } from '../settings.js';
|
||||
import { safeJson, type Timeline, type TimelineQuery } from '../timeline.js';
|
||||
import type { Bus } from '../util/events.js';
|
||||
@@ -120,6 +121,14 @@ export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
|
||||
return { user: toUser(u, store.listAccounts()), stats: { talkMs: st.ms, count: st.n, topWords }, matches };
|
||||
});
|
||||
|
||||
// Riot 경기 기록 가져오기 취소 (v1.9.1, 사이트 경기 탭 진행 바). 받은 경기는 그대로 두고 다음 주기(30분 뒤)에 이어서 한다
|
||||
app.post<{ Body: { game?: string } }>('/api/games/history/cancel', async (req) => {
|
||||
const g = req.body?.game;
|
||||
const r = d.games.cancelHistory(g === 'valorant' || g === 'lol' ? g : undefined);
|
||||
if (r.cancelled.length) log.info(`경기 기록 가져오기 취소 (${r.cancelled.join(', ')}) · ${req.headers['x-gvr-user'] ? '사이트' : '이 PC'}`);
|
||||
return { ok: true, ...r };
|
||||
});
|
||||
|
||||
// 유저 설정 (v1.6.0, 사이트 "내 정보" · 관리 화면): 색 · 녹음 제외 · 라이엇 ID. 본인 또는 관리자만
|
||||
app.patch<{ Params: { id: string }; Body: { color?: string; excluded?: boolean; riotIds?: string[] } }>('/api/users/:id', async (req, reply) => {
|
||||
const u = store.getUser(req.params.id);
|
||||
@@ -310,9 +319,21 @@ export async function buildApi(d: ApiDeps): Promise<FastifyInstance> {
|
||||
app.get<{ Querystring: Record<string, string> }>('/api/matches', async (req) => {
|
||||
const q = req.query;
|
||||
return store
|
||||
.listMatches({ game: q.game || undefined, before: q.before ? Number(q.before) : undefined, limit: q.limit ? Math.min(Number(q.limit), 200) : 50 })
|
||||
.listMatches({
|
||||
game: q.game || undefined,
|
||||
before: q.before ? Number(q.before) : undefined,
|
||||
after: q.after ? Number(q.after) : undefined,
|
||||
limit: q.limit ? Math.min(Number(q.limit), 200) : 50,
|
||||
// 사이트 경기 탭 필터 (v1.9.0): timeline = 타임라인에 나오는 경기, voice = 목소리가 녹음된 경기
|
||||
has: q.has === 'timeline' || q.has === 'voice' ? q.has : undefined,
|
||||
// 모드 필터 (v1.11.0, 모드 이름 "경쟁전" 등) · 데스매치는 늘 뺀다
|
||||
onlyModes: q.mode ? d.games.modeKeys((name) => name === q.mode) : undefined,
|
||||
skipModes: d.games.modeKeys((name) => name === HIDDEN_MODE),
|
||||
})
|
||||
.map((m) => d.games.summary(m));
|
||||
});
|
||||
// 모드 필터 목록 (v1.11.0): 모드 이름별 경기 수
|
||||
app.get<{ Querystring: Record<string, string> }>('/api/matches/modes', async (req) => d.games.modeList(req.query.game || undefined));
|
||||
|
||||
app.get<{ Params: { id: string } }>('/api/matches/:id', async (req, reply): Promise<MatchDetail | void> => {
|
||||
const m = store.getMatch(req.params.id);
|
||||
|
||||
@@ -75,6 +75,8 @@ export class Bundles {
|
||||
const out: Group[] = [];
|
||||
for (const m of matches) {
|
||||
const list = byMatch.get(m.id) ?? [];
|
||||
// Riot 경기 기록에서 가져오기만 한 경기(녹음 없음)는 기록 묶음으로 보이지 않는다
|
||||
if (m.source === 'history' && !list.length) continue;
|
||||
const sum = this.games.summary(m);
|
||||
const label = `${m.game === 'valorant' ? '발로란트' : '롤'} · ${sum.mode} · ${sum.map.name}`;
|
||||
const score = sum.score ? ` ${sum.score.ally}:${sum.score.enemy}` : '';
|
||||
@@ -314,8 +316,8 @@ export class Bundles {
|
||||
if (s?.id) db.prepare('INSERT OR IGNORE INTO sessions(id,guild_id,channel_id,channel_name,started_at,ended_at) VALUES(?,?,?,?,?,?)').run(s.id, String(s.guild_id ?? ''), String(s.channel_id ?? ''), s.channel_name ?? null, Number(s.started_at) || 0, s.ended_at ?? null);
|
||||
for (const m of data.matches ?? []) {
|
||||
const r = db
|
||||
.prepare('INSERT OR IGNORE INTO matches(id,game,started_at,ended_at,map,mode,queue,result,detail,status,clock_offset) VALUES(?,?,?,?,?,?,?,?,?,?,?)')
|
||||
.run(m.id, m.game, m.started_at, m.ended_at ?? null, m.map ?? null, m.mode ?? null, m.queue ?? null, m.result ?? null, m.detail ?? null, m.status === 'live' ? 'complete' : (m.status ?? 'complete'), Number(m.clock_offset) || 0);
|
||||
.prepare('INSERT OR IGNORE INTO matches(id,game,started_at,ended_at,map,mode,queue,result,detail,status,clock_offset,source) VALUES(?,?,?,?,?,?,?,?,?,?,?,?)')
|
||||
.run(m.id, m.game, m.started_at, m.ended_at ?? null, m.map ?? null, m.mode ?? null, m.queue ?? null, m.result ?? null, m.detail ?? null, m.status === 'live' ? 'complete' : (m.status ?? 'complete'), Number(m.clock_offset) || 0, m.source === 'history' ? 'history' : 'live');
|
||||
res.added.matches += r.changes;
|
||||
}
|
||||
for (const r of data.rounds ?? [])
|
||||
|
||||
@@ -14,6 +14,7 @@ import type {
|
||||
import { rateLol, rateValorant } from '@gvr/shared';
|
||||
import type { EventRow, MatchRow, Store, UtteranceRow } from './db/db.js';
|
||||
import type { GameManager } from './games/manager.js';
|
||||
import { HIDDEN_MODE } from './games/modes.js';
|
||||
import { safeJson, type Timeline } from './timeline.js';
|
||||
|
||||
/**
|
||||
@@ -23,6 +24,7 @@ import { safeJson, type Timeline } from './timeline.js';
|
||||
|
||||
/** 녹음 공백 허용치: 경기 처음 · 끝 · 중간에 이보다 긴 빈 곳이 있으면 "기록 부족" */
|
||||
export const COVERAGE_GAP_MS = 60000;
|
||||
const NO_RECORDING = '녹음 기록이 없습니다';
|
||||
/** 대화가 이보다 많으면 짧은 잡담부터 줄여서 보낸다 (경기당 비용 상한, 계획서 7장) */
|
||||
export const MAX_UTTERANCES = 2500;
|
||||
|
||||
@@ -57,17 +59,22 @@ export class Culprit {
|
||||
const players: any[] = det.players || [];
|
||||
const gotResult = !det.live && players.length >= 2 && (m.game !== 'valorant' || (det.roundsDetail || []).length > 0);
|
||||
if (!gotResult) reasons.push('경기 결과를 받지 못했습니다');
|
||||
const start = realStart(m);
|
||||
const end = m.ended_at;
|
||||
const gap = this.coverageGap(start, end);
|
||||
if (gap) reasons.push(gap);
|
||||
// 녹음이 없거나 끊긴 경기도 분석한다 (v1.11.0, 앱을 켜지 않고 한 경기): 플레이 기록 · 채팅과 녹음된 대화만 쓴다
|
||||
const notes = this.recordingNotes(m);
|
||||
const pending = (
|
||||
this.store.db.prepare(`SELECT count(*) n FROM utterances WHERE match_id=? AND status='pending' AND audio_deleted=0`).get(m.id) as { n: number }
|
||||
).n;
|
||||
if (reasons.length) return { state: 'blocked', reasons };
|
||||
if (pending) return { state: 'pending', reasons: [`음성 변환 중 (${pending}문장 남음)`] };
|
||||
if (this.current(m.id)) return { state: 'done', reasons: [] };
|
||||
return { state: 'ready', reasons: [] };
|
||||
if (pending) return { state: 'pending', reasons: [`음성 변환 중 (${pending}문장 남음)`], notes };
|
||||
if (this.current(m.id)) return { state: 'done', reasons: [], notes };
|
||||
return { state: 'ready', reasons: [], notes };
|
||||
}
|
||||
|
||||
/** 녹음이 경기를 다 덮지 못하면 알림 문장 (분석은 그대로 한다) */
|
||||
private recordingNotes(m: MatchRow): string[] {
|
||||
const gap = m.ended_at ? this.coverageGap(realStart(m), m.ended_at) : null;
|
||||
if (!gap) return [];
|
||||
return [gap === NO_RECORDING ? '녹음 없음: 플레이 기록 · 채팅으로만 분석합니다' : `${gap}: 녹음된 대화만 씁니다`];
|
||||
}
|
||||
|
||||
/** 녹음(봇이 음성채널에 있던 구간)이 경기를 덮는지. 빈 곳이 1분 넘으면 이유 문장, 아니면 null */
|
||||
@@ -75,7 +82,7 @@ export class Culprit {
|
||||
const sess = this.store.db
|
||||
.prepare('SELECT started_at, ended_at FROM sessions WHERE started_at < ? AND (ended_at IS NULL OR ended_at > ?) ORDER BY started_at')
|
||||
.all(end, start) as { started_at: number; ended_at: number | null }[];
|
||||
if (!sess.length) return '녹음 기록이 없습니다';
|
||||
if (!sess.length) return NO_RECORDING;
|
||||
let cursor = start;
|
||||
let worst: { at: number; ms: number } | null = null;
|
||||
for (const s of sess) {
|
||||
@@ -93,7 +100,9 @@ export class Culprit {
|
||||
|
||||
// ---------------------------------------------------------------- 목록 · 상세
|
||||
list(opts: { game?: string; limit?: number }): CulpritMatchItem[] {
|
||||
const rows = this.store.listMatches({ game: opts.game, limit: Math.min(opts.limit ?? 50, 200) }).filter((m) => m.status !== 'live');
|
||||
const rows = this.store
|
||||
.listMatches({ game: opts.game, limit: Math.min(opts.limit ?? 50, 200), skipModes: this.games.modeKeys((name) => name === HIDDEN_MODE) })
|
||||
.filter((m) => m.status !== 'live');
|
||||
return rows.map((m) => {
|
||||
const cur = this.current(m.id);
|
||||
const elig = this.eligibility(m);
|
||||
@@ -219,6 +228,9 @@ export class Culprit {
|
||||
out.push(`# 경기 리그 오브 레전드 ${sum.mode} · ${sum.map.name} · 킬 ${score} (${resultKo}) · ${minutes}분`);
|
||||
}
|
||||
if (basic) out.push('# 이 경기는 기본 기록만 있다 (피해량 · 첫킬 · 시야 같은 추가 지표 없음)');
|
||||
const gap = m.ended_at ? this.coverageGap(realStart(m), m.ended_at) : null;
|
||||
if (gap === NO_RECORDING) out.push('# 이 경기는 음성 녹음이 없다. 모두 음성X 로 보고 플레이 기록과 채팅으로만 평가한다');
|
||||
else if (gap) out.push(`# ${gap}. 녹음이 빠진 구간의 대화는 없다`);
|
||||
if (totalUtts > utts.length) out.push(`# 대화가 많아 ${totalUtts}문장 중 짧은 말을 빼고 ${utts.length}문장만 보냄`);
|
||||
|
||||
// 참가자
|
||||
|
||||
@@ -38,6 +38,12 @@ export interface UtteranceRow {
|
||||
attempts: number;
|
||||
created_at: number;
|
||||
}
|
||||
/** 경기 모드를 가르는 칸 조합 (모드 이름은 games/modes.ts matchModeKo) */
|
||||
export interface ModeKey {
|
||||
game: string;
|
||||
queue: string | null;
|
||||
mode: string | null;
|
||||
}
|
||||
export interface MatchRow {
|
||||
id: string;
|
||||
game: 'valorant' | 'lol';
|
||||
@@ -50,6 +56,8 @@ export interface MatchRow {
|
||||
detail: string | null;
|
||||
status: string;
|
||||
clock_offset: number;
|
||||
/** live: 앱이 잡은 경기 · history: Riot 경기 기록에서 가져온 경기 */
|
||||
source: 'live' | 'history';
|
||||
}
|
||||
export interface RoundRow {
|
||||
match_id: string;
|
||||
@@ -128,6 +136,9 @@ export class Store {
|
||||
|
||||
/** 예전 DB 를 지금 스키마로 맞춘다 (스키마를 바꿀 때마다 여기에 단계 추가) */
|
||||
private migrate(): void {
|
||||
// v1.9.0: 경기 출처 (Riot 경기 기록에서 가져온 경기)
|
||||
const mcols = this.db.prepare(`PRAGMA table_info(matches)`).all() as { name: string }[];
|
||||
if (!mcols.some((c) => c.name === 'source')) this.db.exec(`ALTER TABLE matches ADD COLUMN source TEXT NOT NULL DEFAULT 'live'`);
|
||||
// v1.0 개발 중: dictionary UNIQUE 에 pack 추가 (같은 단어가 여러 묶음에 들어갈 수 있게)
|
||||
const idx = this.db.prepare(`SELECT sql FROM sqlite_master WHERE type='table' AND name='dictionary'`).get() as { sql: string } | undefined;
|
||||
if (idx && !/UNIQUE\s*\(kind,\s*word,\s*from_text,\s*pack\)/.test(idx.sql)) {
|
||||
@@ -406,13 +417,14 @@ export class Store {
|
||||
detail: null,
|
||||
status: 'live',
|
||||
clock_offset: 0,
|
||||
source: 'live',
|
||||
...(cur || {}),
|
||||
...stripUndef(m),
|
||||
} as MatchRow;
|
||||
this.db
|
||||
.prepare(
|
||||
`INSERT INTO matches(id,game,started_at,ended_at,map,mode,queue,result,detail,status,clock_offset)
|
||||
VALUES(@id,@game,@started_at,@ended_at,@map,@mode,@queue,@result,@detail,@status,@clock_offset)
|
||||
`INSERT INTO matches(id,game,started_at,ended_at,map,mode,queue,result,detail,status,clock_offset,source)
|
||||
VALUES(@id,@game,@started_at,@ended_at,@map,@mode,@queue,@result,@detail,@status,@clock_offset,@source)
|
||||
ON CONFLICT(id) DO UPDATE SET started_at=@started_at, ended_at=@ended_at, map=@map, mode=@mode, queue=@queue,
|
||||
result=@result, detail=@detail, status=@status, clock_offset=@clock_offset`,
|
||||
)
|
||||
@@ -422,9 +434,41 @@ export class Store {
|
||||
getMatch(id: string): MatchRow | undefined {
|
||||
return this.db.prepare('SELECT * FROM matches WHERE id=?').get(id) as MatchRow | undefined;
|
||||
}
|
||||
listMatches(opts: { game?: string; before?: number; limit?: number; ids?: string[] }): MatchRow[] {
|
||||
/**
|
||||
* has: timeline = 타임라인에 나오는 경기 (앱이 잡은 경기 · 기록에서 가져왔어도 대화가 붙은 경기), voice = 목소리가 녹음된 경기
|
||||
*/
|
||||
/**
|
||||
* onlyModes = 이 (게임, 큐, 모드) 조합만 · skipModes = 이 조합은 빼고 (경기 탭 모드 필터 · 데스매치 숨기기, v1.11.0).
|
||||
* after = 이 시각 이후에 시작한 경기만 (날짜 필터)
|
||||
*/
|
||||
listMatches(opts: {
|
||||
game?: string;
|
||||
before?: number;
|
||||
after?: number;
|
||||
limit?: number;
|
||||
ids?: string[];
|
||||
has?: 'timeline' | 'voice';
|
||||
onlyModes?: ModeKey[];
|
||||
skipModes?: ModeKey[];
|
||||
}): MatchRow[] {
|
||||
const where: string[] = [];
|
||||
const args: any[] = [];
|
||||
const modeCond = (keys: ModeKey[]) => {
|
||||
args.push(...keys.flatMap((k) => [k.game, k.queue, k.mode]));
|
||||
return `(${keys.map(() => '(game=? AND queue IS ? AND mode IS ?)').join(' OR ')})`;
|
||||
};
|
||||
if (opts.onlyModes) {
|
||||
if (!opts.onlyModes.length) return [];
|
||||
where.push(modeCond(opts.onlyModes));
|
||||
}
|
||||
if (opts.skipModes?.length) where.push(`NOT ${modeCond(opts.skipModes)}`);
|
||||
if (opts.after) {
|
||||
where.push('started_at>=?');
|
||||
args.push(opts.after);
|
||||
}
|
||||
const voice = `EXISTS (SELECT 1 FROM utterances u WHERE u.match_id = matches.id AND (u.noise = 0 OR u.corrected = 1))`;
|
||||
if (opts.has === 'voice') where.push(voice);
|
||||
else if (opts.has === 'timeline') where.push(`(source = 'live' OR ${voice})`);
|
||||
if (opts.game) {
|
||||
where.push('game=?');
|
||||
args.push(opts.game);
|
||||
@@ -442,6 +486,10 @@ export class Store {
|
||||
.prepare(`SELECT * FROM matches ${where.length ? 'WHERE ' + where.join(' AND ') : ''} ORDER BY started_at DESC LIMIT ?`)
|
||||
.all(...args, opts.limit ?? 50) as MatchRow[];
|
||||
}
|
||||
/** 경기 행의 (게임, 큐, 모드) 조합과 경기 수 */
|
||||
matchModeRows(): (ModeKey & { n: number })[] {
|
||||
return this.db.prepare('SELECT game, queue, mode, count(*) n FROM matches GROUP BY game, queue, mode').all() as (ModeKey & { n: number })[];
|
||||
}
|
||||
/** ts 시점에 진행 중이던 경기 */
|
||||
matchAt(ts: number): MatchRow | undefined {
|
||||
return this.db
|
||||
|
||||
@@ -82,7 +82,9 @@ CREATE TABLE IF NOT EXISTS matches (
|
||||
result TEXT,
|
||||
detail TEXT,
|
||||
status TEXT NOT NULL DEFAULT 'live',
|
||||
clock_offset INTEGER NOT NULL DEFAULT 0
|
||||
clock_offset INTEGER NOT NULL DEFAULT 0,
|
||||
-- live: 앱이 켜져 있을 때 잡은 경기 · history: Riot 경기 기록에서 가져온 경기 (v1.9.0)
|
||||
source TEXT NOT NULL DEFAULT 'live'
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS matches_started ON matches(started_at);
|
||||
|
||||
|
||||
File diff suppressed because one or more lines are too long
164
app/src/core/games/history.ts
Normal file
164
app/src/core/games/history.ts
Normal file
@@ -0,0 +1,164 @@
|
||||
import type { HistoryProgress } from '@gvr/shared';
|
||||
import type { Store } from '../db/db.js';
|
||||
import { logger } from '../util/log.js';
|
||||
|
||||
const log = logger('history');
|
||||
|
||||
/** 게임별 Riot 경기 기록 읽기 */
|
||||
export interface HistorySource {
|
||||
readonly game: 'valorant' | 'lol';
|
||||
/** 지금 가져와도 되는가 (게임 중 · 요원 선택 중이면 false) */
|
||||
idle(): boolean;
|
||||
/** 이 PC 에 로그인한 계정 (계정이 바뀌면 처음부터 다시 훑는다) */
|
||||
account(): string | null;
|
||||
/** start 번째부터 n 개 (새것부터). 경기 행 ID 로 돌려준다. 'retry' = 지금은 못 읽음 */
|
||||
page(start: number, n: number): Promise<{ ids: string[]; total: number | null } | 'retry'>;
|
||||
/** 경기 하나를 받아 저장. gone = 기록이 없음(다시 묻지 않음), retry = 나중에 */
|
||||
fetch(id: string): Promise<'ok' | 'gone' | 'retry'>;
|
||||
}
|
||||
|
||||
export interface HistoryOptions {
|
||||
pageSize: number;
|
||||
/** 최대 몇 경기 전까지 훑을지 */
|
||||
max: number;
|
||||
/** 경기 상세 요청 사이 간격 (Riot 요청 한도) */
|
||||
gapMs: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 내 Riot 경기 기록 → 경기 목록 (v1.9.0). 앱이 꺼져 있을 때 한 경기도 사이트 경기 탭에 보이게 한다.
|
||||
* 처음에는 끝까지 훑고, 그다음부터는 이미 아는 경기만 나오는 쪽까지만 본다. 게임이 시작되면 바로 멈춘다.
|
||||
*/
|
||||
export class HistorySync {
|
||||
private running = false;
|
||||
private lastAt = 0;
|
||||
private everyMs = 0;
|
||||
/** 지금 가져오는 중이면 진행 상황 (사이트 · 앱 화면 진행 바, v1.9.1) */
|
||||
private prog: HistoryProgress | null = null;
|
||||
/** 사용자가 취소함: 이번 실행만 멈추고 다음 주기에 이어서 한다 */
|
||||
private cancelled = false;
|
||||
|
||||
constructor(
|
||||
private store: Store,
|
||||
private src: HistorySource,
|
||||
private opts: HistoryOptions,
|
||||
) {}
|
||||
|
||||
/** 주기 확인: 앞 실행에서 everyMs 가 지났고 게임 중이 아니면 백그라운드로 돌린다 */
|
||||
maybeRun(everyMs: number, firstDelayMs = 60000): void {
|
||||
const now = Date.now();
|
||||
this.everyMs = everyMs;
|
||||
if (!this.lastAt) this.lastAt = now - everyMs + Math.min(firstDelayMs, everyMs);
|
||||
if (this.running || now - this.lastAt < everyMs || !this.src.idle()) return;
|
||||
this.lastAt = now;
|
||||
void this.run().catch((e) => log.warn(`${this.src.game} 경기 기록 가져오기 실패`, e));
|
||||
}
|
||||
|
||||
/** 진행 상황 (가져오는 중이 아니면 null). 남은 시간은 지금까지 한 경기에 걸린 평균으로 잰다 */
|
||||
progress(): HistoryProgress | null {
|
||||
const p = this.prog;
|
||||
if (!p) return null;
|
||||
let etaMs: number | null = null;
|
||||
if (p.phase === 'fetch' && p.done > 0 && this.fetchStartedAt) {
|
||||
const per = (Date.now() - this.fetchStartedAt) / p.done;
|
||||
etaMs = Math.round(per * (p.total - p.done));
|
||||
}
|
||||
return { ...p, etaMs };
|
||||
}
|
||||
private fetchStartedAt = 0;
|
||||
|
||||
/** 지금 가져오기 취소. 받은 경기는 그대로 두고, 다음 주기(everyMs 뒤)에 남은 것부터 이어서 한다 */
|
||||
cancel(): { cancelled: boolean; resumeAt: number | null } {
|
||||
if (!this.running || this.cancelled) return { cancelled: false, resumeAt: null };
|
||||
this.cancelled = true;
|
||||
this.prog = null;
|
||||
// 다음 실행은 취소한 때부터 한 주기 뒤 (오래 돈 실행을 취소해도 바로 다시 시작하지 않게)
|
||||
this.lastAt = Date.now();
|
||||
log.info(`${this.src.game} 경기 기록 가져오기: 사용자가 취소함`);
|
||||
return { cancelled: true, resumeAt: this.everyMs ? this.lastAt + this.everyMs : null };
|
||||
}
|
||||
|
||||
/** 멈춰야 하나 (게임 시작 · 취소) */
|
||||
private halted(): boolean {
|
||||
return this.cancelled || !this.src.idle();
|
||||
}
|
||||
|
||||
/** 마지막으로 끝까지 확인한 때 (사이트 경기 탭 안내, v1.11.0). 아직 없으면 null */
|
||||
lastDoneAt(): number | null {
|
||||
return Number(this.store.meta(this.lastKey())) || null;
|
||||
}
|
||||
private lastKey(): string {
|
||||
return `history_last:${this.src.game}`;
|
||||
}
|
||||
|
||||
private skipKey(): string {
|
||||
return `history_skip:${this.src.game}`;
|
||||
}
|
||||
private skipped(): Set<string> {
|
||||
try {
|
||||
return new Set(JSON.parse(this.store.meta(this.skipKey()) || '[]'));
|
||||
} catch {
|
||||
return new Set();
|
||||
}
|
||||
}
|
||||
|
||||
/** 한 번 훑기. 새로 저장한 경기 수 */
|
||||
async run(): Promise<number> {
|
||||
if (this.running) return 0;
|
||||
const acct = this.src.account();
|
||||
if (!acct) return 0;
|
||||
this.running = true;
|
||||
this.cancelled = false;
|
||||
try {
|
||||
const fullKey = `history_full:${this.src.game}:${acct}`;
|
||||
// 받다가 멈춘 실행 (취소 · 게임 시작 · 오류): 받은 경기 뒤쪽에 못 받은 경기가 남아 있으니 이번에는 끝까지 훑는다
|
||||
const pendingKey = `history_pending:${this.src.game}:${acct}`;
|
||||
const full = !!this.store.meta(fullKey);
|
||||
const pending = !!this.store.meta(pendingKey);
|
||||
const skip = this.skipped();
|
||||
const todo: string[] = [];
|
||||
this.prog = { phase: 'scan', first: !full, scanned: 0, done: 0, total: 0, startedAt: Date.now(), etaMs: null };
|
||||
for (let start = 0; start < this.opts.max; start += this.opts.pageSize) {
|
||||
if (this.halted()) return 0;
|
||||
const p = await this.src.page(start, this.opts.pageSize);
|
||||
if (p === 'retry' || this.cancelled) return 0;
|
||||
const fresh = p.ids.filter((id) => !skip.has(id) && !this.store.getMatch(id) && !todo.includes(id));
|
||||
todo.push(...fresh);
|
||||
this.prog = { ...this.prog, scanned: this.prog.scanned + p.ids.length, total: todo.length };
|
||||
if (!p.ids.length || p.ids.length < this.opts.pageSize || (p.total !== null && start + this.opts.pageSize >= p.total)) break;
|
||||
// 한 번 끝까지 훑은 뒤에는 아는 경기만 나오는 쪽에서 멈춘다 (지난 실행이 받다가 멈췄으면 끝까지)
|
||||
if (full && !pending && !fresh.length) break;
|
||||
}
|
||||
if (todo.length) log.info(`${this.src.game} 경기 기록: 새 경기 ${todo.length}개 가져오는 중`);
|
||||
let added = 0;
|
||||
this.fetchStartedAt = Date.now();
|
||||
if (this.prog) this.prog = { ...this.prog, phase: 'fetch', done: 0, total: todo.length };
|
||||
if (todo.length && !pending) this.store.setMeta(pendingKey, '1');
|
||||
for (const [i, id] of todo.entries()) {
|
||||
if (this.halted()) {
|
||||
log.info(`${this.src.game} 경기 기록: ${this.cancelled ? '취소해서' : '게임이 시작돼'} 멈춤 (${added}/${todo.length})`);
|
||||
return added;
|
||||
}
|
||||
const r = await this.src.fetch(id).catch(() => 'retry' as const);
|
||||
if (r === 'retry') return added;
|
||||
if (r === 'ok') added++;
|
||||
else {
|
||||
skip.add(id);
|
||||
this.store.setMeta(this.skipKey(), JSON.stringify([...skip].slice(-2000)));
|
||||
}
|
||||
if (this.prog) this.prog = { ...this.prog, done: i + 1 };
|
||||
await new Promise((res) => setTimeout(res, this.opts.gapMs));
|
||||
}
|
||||
if (this.cancelled) return added;
|
||||
// 끝(또는 max)까지 다 받았다: 다음부터는 새 경기만 본다
|
||||
this.store.setMeta(fullKey, '1');
|
||||
this.store.setMeta(this.lastKey(), String(Date.now()));
|
||||
if (this.store.meta(pendingKey)) this.store.setMeta(pendingKey, '');
|
||||
if (added) log.info(`${this.src.game} 경기 기록: ${added}개 저장`);
|
||||
return added;
|
||||
} finally {
|
||||
this.running = false;
|
||||
this.prog = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { logger } from '../util/log.js';
|
||||
import { lolObjectIcon } from './assets.js';
|
||||
import { basicAuth, findLcu, request } from './riot.js';
|
||||
import type { AdapterHost, GameAdapter } from './types.js';
|
||||
import { HistorySync } from './history.js';
|
||||
|
||||
const log = logger('lol');
|
||||
|
||||
@@ -71,8 +72,42 @@ export class LolAdapter implements GameAdapter {
|
||||
/** 게임 클라이언트 API 마지막 값 (지금 게임 상태 표시용) */
|
||||
private snap: { at: number; gameTime: number; mode: string | null; champ: string | null; champIcon: string | null; kda: string | null; extra: string | null; teamKills: { ally: number; enemy: number } | null; players: number } | null = null;
|
||||
private selfRiotId: string | null = null;
|
||||
private selfPuuid: string | null = null;
|
||||
/** 내 경기 기록 (LCU, 앱이 꺼져 있을 때 한 경기도 경기 목록에) */
|
||||
readonly history: HistorySync;
|
||||
|
||||
constructor(private host: AdapterHost) {}
|
||||
constructor(private host: AdapterHost) {
|
||||
this.history = new HistorySync(
|
||||
host.store,
|
||||
{
|
||||
game: 'lol',
|
||||
idle: () => !!this.lcu && !(this.live && !this.live.ended) && !['ChampSelect', 'GameStart', 'InProgress', 'Reconnect'].includes(this.phase ?? ''),
|
||||
account: () => this.selfPuuid,
|
||||
page: (start, n) => this.historyPage(start, n),
|
||||
fetch: (id) => this.historyFetch(id),
|
||||
},
|
||||
{ pageSize: 20, max: Number(process.env.GVR_HISTORY_MAX) || 200, gapMs: Number(process.env.GVR_HISTORY_GAP_MS) || 500 },
|
||||
);
|
||||
}
|
||||
|
||||
private async historyPage(start: number, n: number): Promise<{ ids: string[]; total: number | null } | 'retry'> {
|
||||
const r = await this.lcuGet<any>(`/lol-match-history/v1/products/lol/current-summoner/matches?begIndex=${start}&endIndex=${start + n}`);
|
||||
const games = r?.games?.games;
|
||||
if (!Array.isArray(games)) return 'retry';
|
||||
return { ids: games.filter((g: any) => g?.gameId).map((g: any) => `lol-${g.gameId}`), total: null };
|
||||
}
|
||||
|
||||
private async historyFetch(id: string): Promise<'ok' | 'gone' | 'retry'> {
|
||||
if (!this.lcu) return 'retry';
|
||||
const gameId = id.replace(/^lol-/, '');
|
||||
const game = await this.lcuGet<any>(`/lol-match-history/v1/games/${gameId}`);
|
||||
if (!this.lcu) return 'retry';
|
||||
if (!game?.participants || !game.gameCreation) return 'gone';
|
||||
const timeline = await this.lcuGet<any>(`/lol-match-history/v1/game-timelines/${gameId}`);
|
||||
this.host.historyMatch({ id, game: 'lol', startedAt: game.gameCreation, map: game.mapId ? `Map${game.mapId}` : 'Map11', mode: game.gameMode ?? null, queue: game.queueId ? String(game.queueId) : null });
|
||||
this.applyHistory(id, game, timeline, game.gameCreation);
|
||||
return 'ok';
|
||||
}
|
||||
|
||||
start(): void {
|
||||
if (this.timer) return;
|
||||
@@ -87,6 +122,10 @@ export class LolAdapter implements GameAdapter {
|
||||
status() {
|
||||
return { connected: !!this.lcu || !!this.live, inMatch: !!this.live && !this.live.ended, detail: this.lastErr || undefined };
|
||||
}
|
||||
/** 롤은 경기 중에만 (클라이언트 화면은 가볍다) */
|
||||
gameRunning(): boolean {
|
||||
return !!this.live && !this.live.ended;
|
||||
}
|
||||
|
||||
liveGame(): LiveGame {
|
||||
const enabled = this.host.settings().games.lol;
|
||||
@@ -127,6 +166,8 @@ export class LolAdapter implements GameAdapter {
|
||||
self: this.lcu || inMatch ? { name: this.selfRiotId, character: snap?.champ ?? null, characterImage: snap?.champIcon ?? null, kda: snap?.kda ?? null, extra: snap?.extra ?? null } : null,
|
||||
players: snap?.players ?? null,
|
||||
error: this.lastErr || null,
|
||||
history: this.history.progress(),
|
||||
historyAt: this.history.lastDoneAt(),
|
||||
updatedAt: Date.now(),
|
||||
};
|
||||
}
|
||||
@@ -442,6 +483,7 @@ export class LolAdapter implements GameAdapter {
|
||||
log.info('롤 클라이언트(LCU) 연결');
|
||||
const me = await this.lcuGet<any>('/lol-summoner/v1/current-summoner');
|
||||
if (me?.puuid) this.host.selfAccount(me.puuid, `${me.gameName}#${me.tagLine}`);
|
||||
this.selfPuuid = me?.puuid ?? null;
|
||||
if (me?.gameName) this.selfRiotId = `${me.gameName}#${me.tagLine ?? ''}`;
|
||||
}
|
||||
}
|
||||
@@ -459,6 +501,7 @@ export class LolAdapter implements GameAdapter {
|
||||
this.queueName = q ? (lolModeKo(q.id) ?? q.description ?? null) : null;
|
||||
}
|
||||
if (phase === 'ChampSelect' || phase === 'InProgress' || phase === 'PreEndOfGame' || phase === 'EndOfGame') await this.pollLcuChat(phase);
|
||||
this.history.maybeRun(Number(process.env.GVR_HISTORY_EVERY_MS) || 30 * 60000);
|
||||
}
|
||||
|
||||
private async pollLcuChat(phase: string): Promise<void> {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { LiveGame, MatchSummary } from '@gvr/shared';
|
||||
import type { EventRow, MatchRow, Store } from '../db/db.js';
|
||||
import type { EventRow, MatchRow, ModeKey, Store } from '../db/db.js';
|
||||
import type { Settings } from '../settings.js';
|
||||
import type { SttPipeline } from '../stt/pipeline.js';
|
||||
import type { WorkerClient } from '../stt/worker.js';
|
||||
@@ -11,7 +11,7 @@ import type { GameAssets } from './assets.js';
|
||||
import { LolAdapter } from './lol.js';
|
||||
import type { AdapterHost, GameAdapter, MatchStart } from './types.js';
|
||||
import { ValorantAdapter } from './valorant.js';
|
||||
import { lolModeKo, valModeKo } from './modes.js';
|
||||
import { HIDDEN_MODE, matchModeKo } from './modes.js';
|
||||
|
||||
const log = logger('games');
|
||||
|
||||
@@ -67,12 +67,33 @@ export class GameManager implements AdapterHost {
|
||||
return this.adapters.map((a) => a.liveGame());
|
||||
}
|
||||
|
||||
/** Riot 경기 기록 가져오기 취소 (사이트 경기 탭 · 앱 게임 연동 탭의 취소 버튼, v1.9.1). game 이 없으면 둘 다 */
|
||||
cancelHistory(game?: 'valorant' | 'lol'): { cancelled: ('valorant' | 'lol')[]; resumeAt: number | null } {
|
||||
const cancelled: ('valorant' | 'lol')[] = [];
|
||||
let resumeAt: number | null = null;
|
||||
for (const a of this.adapters) {
|
||||
if (game && a.game !== game) continue;
|
||||
const r = a.history.cancel();
|
||||
if (!r.cancelled) continue;
|
||||
cancelled.push(a.game);
|
||||
if (r.resumeAt && (!resumeAt || r.resumeAt < resumeAt)) resumeAt = r.resumeAt;
|
||||
}
|
||||
// 화면에서 진행 바가 바로 사라지게
|
||||
if (cancelled.length) {
|
||||
const live = this.live();
|
||||
this.lastLive = JSON.stringify(live.map(({ updatedAt: _u, ...rest }) => rest));
|
||||
this.bus.live({ type: 'games.state', data: live });
|
||||
}
|
||||
return { cancelled, resumeAt };
|
||||
}
|
||||
|
||||
private liveTimer: NodeJS.Timeout | null = null;
|
||||
private lastLive = '';
|
||||
/** 게임 상태가 바뀌면 사이트로 알린다 (2초마다 확인) */
|
||||
private watchLive(): void {
|
||||
if (this.liveTimer) return;
|
||||
this.liveTimer = setInterval(() => {
|
||||
void this.stt.setGameActive(this.adapters.some((a) => this.settings().games[a.game] && a.gameRunning()));
|
||||
const live = this.live();
|
||||
const key = JSON.stringify(live.map(({ updatedAt: _u, ...rest }) => rest));
|
||||
if (key === this.lastLive) return;
|
||||
@@ -103,6 +124,22 @@ export class GameManager implements AdapterHost {
|
||||
this.emitMatch(m.id);
|
||||
}
|
||||
|
||||
/** Riot 경기 기록에서 가져온 경기 (상세는 바로 이어서 matchUpdated 로 채운다). 녹음 · STT 와는 상관없다 */
|
||||
historyMatch(m: MatchStart): void {
|
||||
if (this.store.getMatch(m.id)) return;
|
||||
this.store.upsertMatch({
|
||||
id: m.id,
|
||||
game: m.game,
|
||||
started_at: m.startedAt,
|
||||
map: m.map ?? null,
|
||||
mode: m.mode ?? null,
|
||||
queue: m.queue ?? null,
|
||||
detail: m.detail ? JSON.stringify(m.detail) : null,
|
||||
status: 'pending_detail',
|
||||
source: 'history',
|
||||
});
|
||||
}
|
||||
|
||||
matchUpdated(id: string, patch: Partial<MatchRow>, opts?: { complete?: boolean }): void {
|
||||
const cur = this.store.getMatch(id);
|
||||
if (!cur) return;
|
||||
@@ -162,6 +199,41 @@ export class GameManager implements AdapterHost {
|
||||
}
|
||||
}
|
||||
|
||||
renameAccounts(names: { puuid: string; riotId: string }[]): number {
|
||||
let n = 0;
|
||||
for (const x of names) {
|
||||
if (!/^[^#]{1,32}#[^#]{1,8}$/.test(x.riotId)) continue;
|
||||
const old = this.store.listAccounts().find((a) => a.puuid === x.puuid && a.riot_id !== x.riotId);
|
||||
if (!old) continue;
|
||||
n += this.store.db.prepare('UPDATE game_accounts SET riot_id=? WHERE puuid=? AND riot_id<>?').run(x.riotId, x.puuid, x.riotId).changes;
|
||||
log.info(`Riot ID 바뀜: ${old.riot_id} → ${x.riotId}`);
|
||||
}
|
||||
if (n) this.bus.live({ type: 'users.updated', data: [] });
|
||||
return n;
|
||||
}
|
||||
|
||||
/** 모드 이름이 맞는 (게임, 큐, 모드) 조합 (경기 목록 모드 필터 · 데스매치 숨기기) */
|
||||
modeKeys(pick: (name: string, game: string) => boolean): ModeKey[] {
|
||||
return this.store
|
||||
.matchModeRows()
|
||||
.filter((r) => pick(matchModeKo(r), r.game))
|
||||
.map(({ game, queue, mode }) => ({ game, queue, mode }));
|
||||
}
|
||||
|
||||
/** 경기 탭 모드 필터 목록: 모드 이름별 경기 수, 많은 것부터. 데스매치는 경기 목록에 나오지 않아 뺀다 */
|
||||
modeList(game?: string): { game: string; mode: string; count: number }[] {
|
||||
const by = new Map<string, { game: string; mode: string; count: number }>();
|
||||
for (const r of this.store.matchModeRows()) {
|
||||
const mode = matchModeKo(r);
|
||||
if (mode === HIDDEN_MODE || (game && r.game !== game)) continue;
|
||||
const k = `${r.game}\n${mode}`;
|
||||
const cur = by.get(k) ?? { game: r.game, mode, count: 0 };
|
||||
cur.count += r.n;
|
||||
by.set(k, cur);
|
||||
}
|
||||
return [...by.values()].sort((a, b) => b.count - a.count || a.mode.localeCompare(b.mode));
|
||||
}
|
||||
|
||||
summary(m: MatchRow): MatchSummary {
|
||||
const result = safeJson<{ win: boolean | null; score: { ally: number; enemy: number } | null }>(m.result, { win: null, score: null });
|
||||
const map = m.game === 'valorant' ? this.assets.valMap(m.map) : null;
|
||||
@@ -177,11 +249,13 @@ export class GameManager implements AdapterHost {
|
||||
m.game === 'valorant'
|
||||
? { id: m.map ?? '', name: map?.name ?? m.map ?? '?', image: map?.image ?? null }
|
||||
: { id: m.map ?? 'Map11', name: '소환사의 협곡', image: this.assets.lolMapImage() },
|
||||
mode: modeKo(m),
|
||||
mode: matchModeKo(m),
|
||||
win: result.win,
|
||||
score: result.score,
|
||||
status: m.status as MatchSummary['status'],
|
||||
participants,
|
||||
source: m.source === 'history' ? 'history' : 'live',
|
||||
voice: !!this.store.db.prepare('SELECT 1 FROM utterances WHERE match_id=? AND (noise=0 OR corrected=1) LIMIT 1').get(m.id),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -190,8 +264,3 @@ export class GameManager implements AdapterHost {
|
||||
if (m) this.bus.live({ type: 'match.updated', data: this.summary(m) });
|
||||
}
|
||||
}
|
||||
|
||||
function modeKo(m: MatchRow): string {
|
||||
const q = m.queue || m.mode || '';
|
||||
return m.game === 'valorant' ? (valModeKo(q) ?? m.mode ?? '발로란트') : (lolModeKo(q) ?? m.mode ?? '리그 오브 레전드');
|
||||
}
|
||||
|
||||
@@ -32,3 +32,12 @@ export function lolModeKo(queue: string | number | null | undefined): string | n
|
||||
export function valNoRounds(queue: string | null | undefined): boolean {
|
||||
return ['deathmatch', 'hurm', 'ggteam', 'snowball'].includes((queue || '').toLowerCase());
|
||||
}
|
||||
|
||||
/** 경기 목록 · 범인찾기 목록에 보이지 않는 모드 (연습용 데스매치, v1.11.0) */
|
||||
export const HIDDEN_MODE = '데스매치';
|
||||
|
||||
/** 경기 행의 모드 이름 (경기 목록 · 모드 필터) */
|
||||
export function matchModeKo(m: { game: string; queue: string | null; mode: string | null }): string {
|
||||
const q = m.queue || m.mode || '';
|
||||
return m.game === 'valorant' ? (valModeKo(q) ?? m.mode ?? '발로란트') : (lolModeKo(q) ?? m.mode ?? '리그 오브 레전드');
|
||||
}
|
||||
|
||||
@@ -3,6 +3,7 @@ import type { EventRow, MatchRow, Store } from '../db/db.js';
|
||||
import type { Settings } from '../settings.js';
|
||||
import type { WorkerClient } from '../stt/worker.js';
|
||||
import type { GameAssets } from './assets.js';
|
||||
import type { HistorySync } from './history.js';
|
||||
|
||||
export interface MatchStart {
|
||||
id: string;
|
||||
@@ -21,6 +22,8 @@ export interface AdapterHost {
|
||||
worker: WorkerClient;
|
||||
settings(): Settings;
|
||||
matchStarted(m: MatchStart): void;
|
||||
/** Riot 경기 기록에서 가져온 경기 행 만들기 (이미 있으면 그대로) */
|
||||
historyMatch(m: MatchStart): void;
|
||||
/** 경기 정보 갱신 (상세가 채워졌을 때 등) */
|
||||
matchUpdated(id: string, patch: Partial<MatchRow>, opts?: { complete?: boolean }): void;
|
||||
matchEnded(id: string, endedAt: number): void;
|
||||
@@ -32,6 +35,8 @@ export interface AdapterHost {
|
||||
selfAccount(puuid: string, riotId: string): void;
|
||||
/** 경기 참가자 Riot ID 로 디스코드 유저 연결 갱신 */
|
||||
resolvePlayers(players: { puuid: string; riotId: string }[]): void;
|
||||
/** Riot 이름 서비스가 알려 준 지금 Riot ID 로 연결된 계정 이름을 바꾼다 (닉네임 · 태그를 바꾼 사람). 바꾼 수 */
|
||||
renameAccounts(names: { puuid: string; riotId: string }[]): number;
|
||||
}
|
||||
|
||||
export interface GameAdapter {
|
||||
@@ -39,6 +44,10 @@ export interface GameAdapter {
|
||||
start(): void;
|
||||
stop(): void;
|
||||
status(): { connected: boolean; inMatch: boolean; detail?: string };
|
||||
/** 게임이 켜져 있어 GPU 를 쓰고 있는가 (발로란트: 게임 실행 중 · 롤: 경기 중) */
|
||||
gameRunning(): boolean;
|
||||
/** 지금 게임 상태 (자세히) */
|
||||
liveGame(): LiveGame;
|
||||
/** Riot 경기 기록 가져오기 */
|
||||
readonly history: HistorySync;
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ import { logger } from '../util/log.js';
|
||||
import type { GameAssets } from './assets.js';
|
||||
import { basicAuth, readLockfile, request, riotClientLockfilePath, type Lockfile } from './riot.js';
|
||||
import type { AdapterHost, GameAdapter } from './types.js';
|
||||
import { HistorySync } from './history.js';
|
||||
|
||||
const log = logger('valorant');
|
||||
|
||||
@@ -76,8 +77,53 @@ export class ValorantAdapter implements GameAdapter {
|
||||
private detailQueue = new Map<string, { tries: number; endedAt: number; startedLocal: number }>();
|
||||
private polling = false;
|
||||
private lastErr = '';
|
||||
/** 연결된 계정 Riot ID 를 마지막으로 확인한 때 (닉네임 · 태그 바꾼 사람) */
|
||||
private namesAt = 0;
|
||||
/** 내 경기 기록 (앱이 꺼져 있을 때 한 경기도 경기 목록에) */
|
||||
readonly history: HistorySync;
|
||||
|
||||
constructor(private host: AdapterHost) {}
|
||||
constructor(private host: AdapterHost) {
|
||||
this.history = new HistorySync(
|
||||
host.store,
|
||||
{
|
||||
game: 'valorant',
|
||||
idle: () => {
|
||||
const st = this.presence?.state;
|
||||
return !!this.auth && !this.match && st !== 'INGAME' && st !== 'PREGAME';
|
||||
},
|
||||
account: () => this.auth?.puuid ?? null,
|
||||
page: (start, n) => this.historyPage(start, n),
|
||||
fetch: (id) => this.historyFetch(id),
|
||||
},
|
||||
{ pageSize: 20, max: Number(process.env.GVR_HISTORY_MAX) || 500, gapMs: Number(process.env.GVR_HISTORY_GAP_MS) || 1500 },
|
||||
);
|
||||
}
|
||||
|
||||
private async historyPage(start: number, n: number): Promise<{ ids: string[]; total: number | null } | 'retry'> {
|
||||
const a = this.auth;
|
||||
if (!a) return 'retry';
|
||||
const r = await request(`${this.pd(a)}/match-history/v1/history/${a.puuid}?startIndex=${start}&endIndex=${start + n}`, { headers: this.pvpHeaders(a), timeoutMs: 15000 });
|
||||
if (r.status !== 200 || !Array.isArray(r.data?.History)) {
|
||||
log.debug(`경기 기록 목록 실패 (${r.status})`);
|
||||
return 'retry';
|
||||
}
|
||||
return { ids: r.data.History.map((h: any) => `val-${h.MatchID}`), total: typeof r.data.Total === 'number' ? r.data.Total : null };
|
||||
}
|
||||
|
||||
private async historyFetch(id: string): Promise<'ok' | 'gone' | 'retry'> {
|
||||
const a = this.auth;
|
||||
if (!a) return 'retry';
|
||||
const r = await request(`${this.pd(a)}/match-details/v1/matches/${id.replace(/^val-/, '')}`, { headers: this.pvpHeaders(a), timeoutMs: 15000 });
|
||||
if (r.status === 404 || r.status === 400) return 'gone';
|
||||
if (r.status !== 200 || !r.data?.matchInfo) return 'retry';
|
||||
const md = r.data;
|
||||
const S: number = md.matchInfo.gameStartMillis;
|
||||
if (!S) return 'gone';
|
||||
this.host.historyMatch({ id, game: 'valorant', startedAt: S, map: md.matchInfo.mapId ?? null, mode: md.matchInfo.queueID ?? null, queue: md.matchInfo.queueID ?? null });
|
||||
await this.fillNames(a, md);
|
||||
this.applyDetails(id, md, a.puuid, S);
|
||||
return 'ok';
|
||||
}
|
||||
|
||||
start(): void {
|
||||
if (this.timer) return;
|
||||
@@ -91,6 +137,10 @@ export class ValorantAdapter implements GameAdapter {
|
||||
status() {
|
||||
return { connected: !!this.auth, inMatch: !!this.match, detail: this.lastErr || undefined };
|
||||
}
|
||||
/** 발로란트는 메뉴에서도 게임 화면을 그린다: 게임이 켜져 있으면(내 발로란트 상태가 있으면) 켜짐 */
|
||||
gameRunning(): boolean {
|
||||
return !!this.match || (!!this.auth && !!this.presence);
|
||||
}
|
||||
|
||||
liveGame(): LiveGame {
|
||||
const p = this.presence;
|
||||
@@ -136,6 +186,8 @@ export class ValorantAdapter implements GameAdapter {
|
||||
self: this.auth ? { name: this.selfName, character: m?.selfAgent ?? null, characterImage: null, kda: null, extra: null } : null,
|
||||
players: m?.players || null,
|
||||
error: this.lastErr || null,
|
||||
history: this.history.progress(),
|
||||
historyAt: this.history.lastDoneAt(),
|
||||
updatedAt: Date.now(),
|
||||
};
|
||||
}
|
||||
@@ -206,9 +258,14 @@ export class ValorantAdapter implements GameAdapter {
|
||||
if (a) {
|
||||
await this.pollPresence(a);
|
||||
if (this.match) await this.pollChat(a);
|
||||
} else if (this.match) {
|
||||
else {
|
||||
this.history.maybeRun(Number(process.env.GVR_HISTORY_EVERY_MS) || 30 * 60000);
|
||||
await this.refreshNames(a);
|
||||
}
|
||||
} else {
|
||||
this.presence = null;
|
||||
// 클라이언트가 꺼졌으면 경기도 끝난 것으로 본다
|
||||
this.endMatch();
|
||||
if (this.match) this.endMatch();
|
||||
}
|
||||
await this.pollDetails();
|
||||
this.lastErr = '';
|
||||
@@ -372,6 +429,25 @@ export class ValorantAdapter implements GameAdapter {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 디스코드 유저에 연결된 Riot 계정의 지금 Riot ID 를 이름 서비스로 확인한다 (Riot 클라이언트에 붙은 뒤 바로, 그 뒤 10분마다).
|
||||
* 닉네임이나 태그를 바꾼 사람은 연결은 그대로(puuid) 두고 표시되는 Riot ID 만 새 이름으로 바꾼다.
|
||||
* 아직 경기에서 만나지 못한 계정(riotid: 자리표시)은 puuid 를 몰라 물을 수 없다.
|
||||
*/
|
||||
private async refreshNames(a: Auth): Promise<void> {
|
||||
if (Date.now() - this.namesAt < (Number(process.env.GVR_NAMES_EVERY_MS) || 10 * 60000)) return;
|
||||
this.namesAt = Date.now();
|
||||
const puuids = [...new Set(this.host.store.listAccounts().map((x) => x.puuid))].filter((p) => p && !p.startsWith('riotid:') && !p.includes('#'));
|
||||
if (!puuids.length) return;
|
||||
try {
|
||||
const r = await request(`${this.pd(a)}/name-service/v2/players`, { method: 'PUT', headers: this.pvpHeaders(a), body: puuids, timeoutMs: 8000 });
|
||||
if (r.status !== 200 || !Array.isArray(r.data)) return void log.debug(`Riot ID 확인 실패 (${r.status})`);
|
||||
this.host.renameAccounts(r.data.filter((n: any) => n?.Subject && n.GameName && n.TagLine).map((n: any) => ({ puuid: n.Subject, riotId: `${n.GameName}#${n.TagLine}` })));
|
||||
} catch (e) {
|
||||
log.debug('Riot ID 확인 실패', e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 경기 상세에 선수 이름이 비어 오면(Riot 이 이름을 가림) 이름 서비스로 채운다. 내 이름은 로컬 채팅 세션 값으로.
|
||||
* v1.3.5 는 빈 이름을 그대로 써서 "주인 계정 자동 연결: #" 이 남았다.
|
||||
|
||||
@@ -33,6 +33,8 @@ export interface Settings {
|
||||
modelsDir: string | null;
|
||||
reprocessAfterMatch: boolean;
|
||||
gameVramReserveMb: number;
|
||||
/** 게임이 켜져 있는 동안 GPU 를 아낀다: 실시간 모델만 가볍게(빔 1) · 쉬어 가며, 정밀 모델 변환은 게임을 끈 뒤로 (v1.9.0) */
|
||||
gameSaver: boolean;
|
||||
};
|
||||
audio: {
|
||||
targetLufs: number;
|
||||
@@ -111,6 +113,7 @@ export function defaultSettings(): Settings {
|
||||
modelsDir: null,
|
||||
reprocessAfterMatch: true,
|
||||
gameVramReserveMb: 3072,
|
||||
gameSaver: true,
|
||||
},
|
||||
audio: { targetLufs: -18, denoise: false, noiseSensitivity: 0.5, silenceMs: 800, maxUtteranceSec: 30 },
|
||||
dictionary: {
|
||||
|
||||
@@ -100,6 +100,12 @@ export class SttPipeline {
|
||||
return c ? Number(c) : null;
|
||||
}
|
||||
private inMatch = false;
|
||||
/** 게임(발로란트 · 롤 경기)이 켜져 있다 (GameManager 가 2초마다 알려 줌) */
|
||||
private gameActive = false;
|
||||
/** 게임 중 GPU 아끼기: 켜져 있고 게임 중일 때 */
|
||||
private saving(): boolean {
|
||||
return this.gameActive && this.settings().stt.gameSaver !== false;
|
||||
}
|
||||
/** 두 모델을 동시에 올릴 VRAM 이 되는가 (워커 추천값) */
|
||||
private bothFit = true;
|
||||
status: SttStatus = {
|
||||
@@ -143,10 +149,46 @@ export class SttPipeline {
|
||||
this.bothFit = false;
|
||||
}
|
||||
await this.load('realtime', s.realtimeModel);
|
||||
if (this.bothFit && !this.inMatch) await this.load('precise', s.preciseModel);
|
||||
if (this.bothFit && !this.inMatch && !this.saving()) await this.load('precise', s.preciseModel);
|
||||
this.pump();
|
||||
}
|
||||
|
||||
/**
|
||||
* 게임이 켜지고 꺼질 때 (v1.9.0). 게임 중 GPU 아끼기가 켜져 있으면
|
||||
* 켜질 때 정밀 모델을 내리고(정밀 변환은 대기열에서 기다림), 꺼지면 다시 올려 밀린 정밀 변환을 한다.
|
||||
*/
|
||||
async setGameActive(on: boolean): Promise<void> {
|
||||
if (this.gameActive === on) return;
|
||||
this.gameActive = on;
|
||||
const s = this.settings().stt;
|
||||
if (on) {
|
||||
if (s.gameSaver === false) return;
|
||||
log.info('게임 켜짐: GPU 아끼기 (실시간 모델만 가볍게, 정밀 변환은 게임을 끈 뒤)');
|
||||
if (this.status.slots.precise.state === 'loaded') await this.unload('precise');
|
||||
return;
|
||||
}
|
||||
if (s.gameSaver !== false || this.queue.some((j) => j.slot === 'precise')) log.info('게임 꺼짐: 밀린 정밀 변환 시작');
|
||||
if (this.status.worker !== 'ready') return; // 워커가 켜지면 prepareModels 가 이어서 한다
|
||||
const wantPrecise = this.queue.some((j) => j.slot === 'precise') || this.bothFit;
|
||||
if (wantPrecise) await this.load('precise', s.preciseModel);
|
||||
if (this.gameActive) return; // 올리는 동안 게임이 다시 켜짐
|
||||
// 정밀 모델이 없으면(설치 안 됨 · 실패) 기다리던 정밀 변환은 버린다 (실시간 결과가 그대로 남음)
|
||||
if (this.status.slots.precise.state !== 'loaded') this.dropPrecise();
|
||||
else if (!this.bothFit && !this.queue.some((j) => j.slot === 'precise')) await this.unload('precise');
|
||||
this.pump();
|
||||
}
|
||||
|
||||
private dropPrecise(): void {
|
||||
const before = this.queue.length;
|
||||
this.queue = this.queue.filter((j) => {
|
||||
if (j.slot !== 'precise') return true;
|
||||
this.queued.delete(`precise:${j.id}`);
|
||||
return false;
|
||||
});
|
||||
this.status.queue = this.queue.length;
|
||||
if (before !== this.queue.length) log.info(`정밀 모델이 없어 정밀 변환 ${before - this.queue.length}개를 건너뜀`);
|
||||
}
|
||||
|
||||
private async installed(): Promise<Set<string>> {
|
||||
try {
|
||||
const r = await this.worker.request('models', {}, 30000);
|
||||
@@ -223,6 +265,13 @@ export class SttPipeline {
|
||||
this.inMatch = false;
|
||||
const s = this.settings().stt;
|
||||
if (!s.reprocessAfterMatch || s.preciseModel === s.realtimeModel) return;
|
||||
if (this.saving()) {
|
||||
// 게임(발로란트 메뉴 등)이 아직 켜져 있으면 정밀 변환은 대기열에서 게임이 꺼질 때까지 기다린다
|
||||
const rows = this.store.realtimeUtterancesInRange(from, to);
|
||||
log.info(`경기 종료: ${rows.length}개 발화의 정밀 변환은 게임을 끈 뒤에`);
|
||||
for (const r of rows) this.enqueue(r.id, 'precise', 10);
|
||||
return;
|
||||
}
|
||||
if (this.status.slots.precise.state !== 'loaded') await this.load('precise', s.preciseModel);
|
||||
if (this.status.slots.precise.state !== 'loaded') return;
|
||||
const rows = this.store.realtimeUtterancesInRange(from, to);
|
||||
@@ -232,6 +281,11 @@ export class SttPipeline {
|
||||
|
||||
private pickSlot(job: Job): Slot | null {
|
||||
const { realtime, precise } = this.status.slots;
|
||||
if (this.saving()) {
|
||||
// 게임 중: 정밀 변환은 기다리고, 새 발화는 실시간 모델로만
|
||||
if (job.slot === 'precise') return null;
|
||||
return realtime.state === 'loaded' ? 'realtime' : null;
|
||||
}
|
||||
if (job.slot === 'precise') return precise.state === 'loaded' ? 'precise' : null;
|
||||
// 경기 밖이고 정밀 모델이 올라와 있으면 처음부터 정밀 모델로
|
||||
if (!this.inMatch && precise.state === 'loaded' && this.queue.length < 20) return 'precise';
|
||||
@@ -255,6 +309,7 @@ export class SttPipeline {
|
||||
this.busy = true;
|
||||
this.processing = job.id;
|
||||
this.status.processing = job.id;
|
||||
const t0 = Date.now();
|
||||
this.run(job, this.pickSlot(job)!)
|
||||
.catch((e) => log.error('STT 작업 오류', e))
|
||||
.finally(() => {
|
||||
@@ -267,7 +322,9 @@ export class SttPipeline {
|
||||
} catch (e) {
|
||||
log.warn('변환 뒤 처리 실패', e);
|
||||
}
|
||||
setImmediate(() => this.pump());
|
||||
// 게임 중에는 변환한 만큼(최대 3초) 쉬고 다음 발화로: 여러 명이 연달아 말해도 GPU 를 계속 붙잡지 않는다
|
||||
if (this.saving()) setTimeout(() => this.pump(), Math.min(Date.now() - t0, 3000));
|
||||
else setImmediate(() => this.pump());
|
||||
});
|
||||
}
|
||||
|
||||
@@ -324,6 +381,8 @@ export class SttPipeline {
|
||||
target_lufs: s.audio.targetLufs,
|
||||
noise_sensitivity: s.audio.noiseSensitivity,
|
||||
denoise: s.audio.denoise,
|
||||
// 게임 중에는 빔 1 (빔 3 보다 가볍다. 경기 뒤 정밀 모델이 다시 변환한다)
|
||||
...(this.saving() && slot === 'realtime' ? { beam_size: 1 } : {}),
|
||||
},
|
||||
5 * 60000,
|
||||
);
|
||||
|
||||
@@ -173,9 +173,15 @@ export class Timeline {
|
||||
if (q.match) {
|
||||
where.push('e.match_id = ?');
|
||||
args.push(q.match);
|
||||
} else if (q.game) {
|
||||
where.push('e.game = ?');
|
||||
args.push(q.game);
|
||||
} else {
|
||||
if (q.game) {
|
||||
where.push('e.game = ?');
|
||||
args.push(q.game);
|
||||
}
|
||||
// Riot 경기 기록에서 가져오기만 한 경기(앱이 녹음하지 않은 경기)의 킬 · 라운드는 타임라인에 넣지 않는다 (경기 화면에서는 보인다)
|
||||
where.push(
|
||||
`(e.match_id IS NULL OR e.match_id NOT IN (SELECT m.id FROM matches m WHERE m.source = 'history' AND NOT EXISTS (SELECT 1 FROM utterances x WHERE x.match_id = m.id)))`,
|
||||
);
|
||||
}
|
||||
if (q.users?.length) {
|
||||
// 선택하지 않은 (디스코드에 연결된) 유저가 주인공인 이벤트만 뺀다. 라운드·오브젝트·상대 킬처럼 유저가 없는 이벤트는 남긴다.
|
||||
|
||||
@@ -5,8 +5,11 @@ import type { LiveEvent, User } from '@gvr/shared';
|
||||
export class Bus extends EventEmitter {
|
||||
/** 'users.updated' 에 실을 유저 목록. 보내는 쪽은 신호만 주고 목록은 여기서 채운다 (빈 목록이 나가면 사이트에서 모든 발화가 "알 수 없음"이 됨) */
|
||||
usersProvider: (() => User[]) | null = null;
|
||||
/** 'users.updated' 를 보낸 횟수: 앱 설정 창이 바뀐 것을 알고 유저 목록을 다시 받는다 (Riot ID 자동 갱신 등, v1.11.1) */
|
||||
usersRev = 0;
|
||||
|
||||
live(ev: LiveEvent): void {
|
||||
if (ev.type === 'users.updated') this.usersRev++;
|
||||
if (ev.type === 'users.updated' && this.usersProvider) ev = { type: 'users.updated', data: this.usersProvider() };
|
||||
this.emit('live', ev);
|
||||
}
|
||||
|
||||
@@ -69,6 +69,8 @@ export interface AppState {
|
||||
/** 지금 게임 상태 (v1.3.6~) */
|
||||
liveGames?: LiveGame[];
|
||||
counts: { utterances: number; matches: number };
|
||||
/** 유저 목록이 바뀐 횟수 (바뀌면 게임 연동 탭 Riot ID 표를 다시 받는다, v1.11.1) */
|
||||
usersRev: number;
|
||||
excludedUsers: { id: string; name: string }[];
|
||||
autoStart: boolean;
|
||||
}
|
||||
@@ -110,6 +112,8 @@ export interface GvrApi {
|
||||
users(): Promise<User[]>;
|
||||
setRiotIds(userId: string, riotIds: string[]): Promise<void>;
|
||||
setExcluded(userId: string, excluded: boolean): Promise<void>;
|
||||
/** Riot 경기 기록 가져오기 취소 (v1.9.1). game 이 없으면 둘 다. resumeAt = 다시 이어서 하는 시각 */
|
||||
cancelHistory(game?: 'valorant' | 'lol'): Promise<{ cancelled: ('valorant' | 'lol')[]; resumeAt: number | null }>;
|
||||
dictionary(): Promise<{ labels: Record<string, string>; packs: { key: string; label: string; count: number }[]; entries: { id: number; word: string; from: string | null; kind: 'hotword' | 'correction'; pack: string; source: string; enabled: boolean; hits: number }[] }>;
|
||||
addWord(word: string): Promise<void>;
|
||||
addCorrection(from: string, to: string): Promise<void>;
|
||||
|
||||
@@ -33,6 +33,7 @@ export function buildState(core: Core, opts: { dataDir: string; portable: boolea
|
||||
games: core.games.status() as AppState['games'],
|
||||
liveGames: core.games.live(),
|
||||
counts: core.store.counts(),
|
||||
usersRev: core.bus.usersRev,
|
||||
excludedUsers: core.store
|
||||
.listUsers()
|
||||
.filter((u) => u.excluded)
|
||||
@@ -244,6 +245,7 @@ export function registerIpc(ctx: IpcContext) {
|
||||
core.store.setRiotIds(userId, riotIds, true);
|
||||
core.bus.live({ type: 'users.updated', data: [] });
|
||||
},
|
||||
cancelHistory: (game?: 'valorant' | 'lol') => core.games.cancelHistory(game),
|
||||
setExcluded: (userId: string, excluded: boolean) => {
|
||||
core.store.setExcluded(userId, excluded);
|
||||
core.bus.live({ type: 'users.updated', data: [] });
|
||||
|
||||
@@ -23,6 +23,8 @@ const opt = (name: string) => argv.find((a) => a.startsWith(`--${name}=`))?.spli
|
||||
const SMOKE = flag('smoke');
|
||||
|
||||
app.setAppUserModelId('kr.tkrmagid.gvr');
|
||||
// 설정 창은 글자 · 버튼뿐이라 GPU 로 그릴 필요가 없다. 게임 · 브라우저와 GPU 를 나눠 쓰지 않게 끈다 (v1.9.0)
|
||||
app.disableHardwareAcceleration();
|
||||
if (!SMOKE && !app.requestSingleInstanceLock()) {
|
||||
app.quit();
|
||||
process.exit(0);
|
||||
|
||||
@@ -4,7 +4,7 @@ import { contextBridge, ipcRenderer } from 'electron';
|
||||
const METHODS = [
|
||||
'getState', 'updateSettings', 'setSecret', 'testBotToken', 'restartBot', 'guildMembers', 'previewTts', 'gpuInfo', 'models',
|
||||
'download', 'deleteModel', 'applyModels', 'chooseFolder', 'registerDevice', 'unregisterDevice', 'runDiagnostics', 'storageUsage',
|
||||
'runRetention', 'users', 'setRiotIds', 'setExcluded', 'dictionary', 'addWord', 'addCorrection', 'deleteDict', 'setDictEnabled',
|
||||
'runRetention', 'users', 'setRiotIds', 'setExcluded', 'cancelHistory', 'dictionary', 'addWord', 'addCorrection', 'deleteDict', 'setDictEnabled',
|
||||
'finetuneStatus', 'finetuneInstall', 'finetuneStart', 'finetuneStop', 'finetuneRollback', 'clearTrainingData', 'openExternal',
|
||||
'openPath', 'setAutoStart', 'finishWizard', 'recentLogs', 'quit',
|
||||
'authState', 'authLogin', 'authCancel', 'authLogout', 'authRecheck', 'adminUsers', 'adminAddUser', 'adminSetRole', 'adminRemoveUser', 'adminDisplayNames', 'adminSetDisplayName',
|
||||
|
||||
@@ -35,6 +35,7 @@ function defaults(): Settings {
|
||||
modelsDir: null,
|
||||
reprocessAfterMatch: true,
|
||||
gameVramReserveMb: 3072,
|
||||
gameSaver: true,
|
||||
},
|
||||
audio: { targetLufs: -18, denoise: false, noiseSensitivity: 0.5, silenceMs: 800, maxUtteranceSec: 30 },
|
||||
dictionary: {
|
||||
@@ -167,10 +168,12 @@ export function createMockGvr(): GvrApi {
|
||||
},
|
||||
{
|
||||
game: 'lol', enabled: true, connected: true, phase: '로비', inMatch: false, matchId: null, mode: '솔로 랭크', map: null, mapImage: null,
|
||||
startedAt: null, round: null, score: null, gameTimeSec: null, teamKills: null, self: { name: '하늘#KR1', character: null, characterImage: null, kda: null, extra: null }, players: null, error: null, updatedAt: now,
|
||||
startedAt: null, round: null, score: null, gameTimeSec: null, teamKills: null, self: { name: '하늘#KR1', character: null, characterImage: null, kda: null, extra: null }, players: null, error: null,
|
||||
history: q.has('nohistory') ? null : { phase: 'fetch', first: true, scanned: 140, done: 37, total: 120, startedAt: now - 40000, etaMs: 90000 }, updatedAt: now,
|
||||
},
|
||||
],
|
||||
counts: { utterances: 1824, matches: 37 },
|
||||
usersRev: 0,
|
||||
excludedUsers: noToken ? [] : [{ id: 'u4', name: '현우' }],
|
||||
autoStart: false,
|
||||
};
|
||||
@@ -250,6 +253,14 @@ export function createMockGvr(): GvrApi {
|
||||
listeners.forEach((l) => l(snap));
|
||||
};
|
||||
|
||||
// 앱이 Riot ID 를 바꾼 것 흉내 (닉네임 · 태그를 바꾼 사람): 콘솔에서 __gvrMockRename('u1', '새이름#KR9')
|
||||
(window as any).__gvrMockRename = (userId: string, riotId: string) => {
|
||||
const u = users.find((x) => x.id === userId);
|
||||
if (u?.riot[0]) u.riot[0].riotId = riotId;
|
||||
state.usersRev++;
|
||||
emit();
|
||||
};
|
||||
|
||||
// 녹음 참가자/대기열이 조금씩 바뀌는 흉내
|
||||
setInterval(() => {
|
||||
state.stt.queue = Math.random() < 0.7 ? 0 : Math.floor(Math.random() * 3);
|
||||
@@ -518,6 +529,18 @@ export function createMockGvr(): GvrApi {
|
||||
const u = users.find((x) => x.id === userId);
|
||||
if (u) u.riot = riotIds.map((r, i) => ({ puuid: `${userId}-${i}`, riotId: r }));
|
||||
},
|
||||
async cancelHistory(game) {
|
||||
await sleep(150);
|
||||
const cancelled: ('valorant' | 'lol')[] = [];
|
||||
for (const g of state.liveGames ?? []) {
|
||||
if (g.history && (!game || g.game === game)) {
|
||||
g.history = null;
|
||||
cancelled.push(g.game);
|
||||
}
|
||||
}
|
||||
emit();
|
||||
return { cancelled, resumeAt: cancelled.length ? Date.now() + 30 * 60000 : null };
|
||||
},
|
||||
async setExcluded(userId, excluded) {
|
||||
const u = users.find((x) => x.id === userId);
|
||||
if (u) u.excluded = excluded;
|
||||
|
||||
@@ -149,6 +149,10 @@ input[type='number'].input { flex: none; padding: 7px 8px; }
|
||||
.pbar i { display: block; height: 100%; background: linear-gradient(90deg, var(--accent), #ff7a85); border-radius: 5px; transition: width 0.25s; }
|
||||
.pbar.done i { background: linear-gradient(90deg, #1fb383, var(--good)); }
|
||||
.pbar.error i { background: #6b2a33; }
|
||||
.pbar.indet i { width: 35%; animation: pbar-indet 1.4s ease-in-out infinite; }
|
||||
@keyframes pbar-indet { 0% { transform: translateX(-100%); } 100% { transform: translateX(290%); } }
|
||||
.hist-row + .hist-row { margin-top: 12px; }
|
||||
.hist-top { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; }
|
||||
.prog { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 14px 16px; }
|
||||
.prog-head { display: flex; justify-content: space-between; align-items: center; gap: 10px; font-size: 13px; }
|
||||
.dl-list { display: flex; flex-direction: column; gap: 10px; margin-top: 14px; }
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useState } from 'react';
|
||||
import { GAME_NAME, liveGameRows, type LiveGame, type User } from '@gvr/shared';
|
||||
import { useEffect, useState } from 'react';
|
||||
import { GAME_NAME, historyStatus, liveGameRows, resumeText, type LiveGame, type User } from '@gvr/shared';
|
||||
import { gvr, useAction, useApp, useLoad } from '../store';
|
||||
import { Avatar, Btn, Dot, Err, FolderRow, Page, Section, Spinner, Toggle } from '../ui';
|
||||
|
||||
@@ -84,12 +84,51 @@ function LiveGames() {
|
||||
);
|
||||
}
|
||||
|
||||
/** Riot 경기 기록 가져오기 진행 바 · 취소 (v1.9.1). 게임 중이 아닐 때 30분마다 돈다 */
|
||||
function HistoryImport() {
|
||||
const { state, toast } = useApp();
|
||||
const act = useAction();
|
||||
const rows = (state.liveGames ?? []).filter((g) => g.history);
|
||||
if (!rows.length) return null;
|
||||
const cancel = async (game: LiveGame['game']) => {
|
||||
const r = await act.run(() => gvr.cancelHistory(game));
|
||||
if (r?.cancelled.length) toast(`${GAME_NAME[game]} 경기 기록 가져오기를 멈췄습니다. 받은 경기는 남고, ${resumeText(r.resumeAt)} 남은 것부터 이어서 가져옵니다`);
|
||||
};
|
||||
return (
|
||||
<Section title="Riot 경기 기록" sub="사이트 경기 탭에 지난 경기 채우기">
|
||||
{rows.map((g) => {
|
||||
const st = historyStatus(g.history!);
|
||||
return (
|
||||
<div key={g.game} className="hist-row">
|
||||
<div className="hist-top">
|
||||
<Spinner />
|
||||
<b>{GAME_NAME[g.game]}</b>
|
||||
<span>{st.title}</span>
|
||||
<span className="muted">{st.detail}</span>
|
||||
<span style={{ flex: 1 }} />
|
||||
<Btn small ghost busy={act.busy} onClick={() => cancel(g.game)}>
|
||||
취소
|
||||
</Btn>
|
||||
</div>
|
||||
<div className={`pbar${st.pct == null ? ' indet' : ''}`}>
|
||||
<i style={{ width: st.pct == null ? undefined : `${st.pct}%` }} />
|
||||
</div>
|
||||
{g.history!.first && <div className="hint">처음 한 번은 지난 경기를 끝까지 가져와서 오래 걸립니다. 게임을 켜면 바로 멈추고, 다음부터는 새 경기만 가져옵니다.</div>}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
<Err>{act.error}</Err>
|
||||
</Section>
|
||||
);
|
||||
}
|
||||
|
||||
const RIOT_RE = /^[^#]{1,16}#[^#\s]{2,5}$/;
|
||||
|
||||
function RiotRow({ u }: { u: User }) {
|
||||
const { toast } = useApp();
|
||||
const server = u.riot.map((r) => r.riotId).join(',');
|
||||
const [v, setV] = useState(u.riot.map((r) => r.riotId).join(', '));
|
||||
const [saved, setSaved] = useState(u.riot.map((r) => r.riotId).join(','));
|
||||
const [saved, setSaved] = useState(server);
|
||||
const act = useAction();
|
||||
const ids = v
|
||||
.split(',')
|
||||
@@ -97,6 +136,14 @@ function RiotRow({ u }: { u: User }) {
|
||||
.filter(Boolean);
|
||||
const bad = ids.filter((s) => !RIOT_RE.test(s));
|
||||
const dirty = ids.join(',') !== saved;
|
||||
// 앱이 Riot ID 를 바꾸면(닉네임 · 태그를 바꾼 사람, v1.11.1) 입력칸도 새 값으로. 고치는 중인 칸은 그대로 두고,
|
||||
// 고치기를 그만두면(입력을 원래대로 되돌림) 그사이 바뀐 이름을 반영한다 (v1.11.2)
|
||||
useEffect(() => {
|
||||
if (server === saved || dirty) return;
|
||||
setV(u.riot.map((r) => r.riotId).join(', '));
|
||||
setSaved(server);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [server, dirty]);
|
||||
const savedCount = saved ? saved.split(',').length : 0;
|
||||
const commit = async () => {
|
||||
if (!dirty || bad.length) return;
|
||||
@@ -172,12 +219,14 @@ function RiotKey() {
|
||||
}
|
||||
|
||||
export function GamesTab() {
|
||||
const { settings, save } = useApp();
|
||||
const { settings, save, state } = useApp();
|
||||
const g = settings.games;
|
||||
const users = useLoad(() => gvr.users());
|
||||
// 앱이 유저 목록을 바꾸면(Riot ID 자동 갱신 · 녹음 중 새 사람 등) 다시 받는다
|
||||
const users = useLoad(() => gvr.users(), [state.usersRev]);
|
||||
return (
|
||||
<Page title="게임 연동">
|
||||
<GameCards />
|
||||
<HistoryImport />
|
||||
<LiveGames />
|
||||
<Section title="리그 오브 레전드 세부 설정" className={g.lol ? '' : 'disabled'}>
|
||||
<div className="muted" style={{ marginBottom: 8 }}>
|
||||
|
||||
@@ -184,6 +184,12 @@ export function SttTab() {
|
||||
<div className="warn-text small">⚠ RTX 50 시리즈(Blackwell)에서 int8 계열은 cuBLAS 오류 사례가 있습니다. 문제가 생기면 float16으로 돌려 주세요.</div>
|
||||
)}
|
||||
<ToggleLine label="경기가 끝나면 정밀 모델로 다시 변환" on={s.reprocessAfterMatch} onChange={(v) => save({ stt: { reprocessAfterMatch: v } })} />
|
||||
<ToggleLine
|
||||
label="게임 중 GPU 아끼기"
|
||||
hint="게임이 켜져 있으면 실시간 모델만 가볍게 쉬어 가며 돌리고, 정밀 모델 변환은 게임을 끈 뒤에 합니다"
|
||||
on={s.gameSaver}
|
||||
onChange={(v) => save({ stt: { gameSaver: v } })}
|
||||
/>
|
||||
<Line label="게임용 VRAM 예약" hint="두 게임 중 큰 값 · 실측 후 조정">
|
||||
<NumInput value={s.gameVramReserveMb} min={0} max={24576} step={256} width={90} suffix="MB" onCommit={(n) => save({ stt: { gameVramReserveMb: n } })} />
|
||||
</Line>
|
||||
|
||||
@@ -49,8 +49,9 @@ test('범인찾기: 분석 가능 판정과 AI 자료', () => {
|
||||
const ctx = setup();
|
||||
const { id } = seedValorant(ctx);
|
||||
const m = ctx.store.getMatch(id)!;
|
||||
assert.deepEqual(ctx.culprit.eligibility(m), { state: 'ready', reasons: [] });
|
||||
assert.deepEqual(ctx.culprit.eligibility(m), { state: 'ready', reasons: [], notes: [] });
|
||||
const input = ctx.culprit.buildInput(m);
|
||||
assert.ok(!input.text.includes('녹음'), '녹음이 경기를 다 덮으면 녹음 안내 줄 없음');
|
||||
const lines = input.text.split('\n');
|
||||
assert.match(lines[0], /^# 경기 발로란트 .* 13:9 \(우리 팀 승리\) · 22라운드/);
|
||||
// 우리 팀이 P1~P5, 하늘은 음성O, 디스코드 계정이 없는 상대는 음성X
|
||||
@@ -88,16 +89,30 @@ test('범인찾기: 분석 가능 판정과 AI 자료', () => {
|
||||
assert.ok(u2Index > lines.findIndex((l) => l.startsWith('[u1] ')));
|
||||
});
|
||||
|
||||
test('범인찾기: 녹음이 늦게 시작 · 음성 변환 중 · 녹음 제외', () => {
|
||||
test('범인찾기: 녹음이 늦게 시작 · 녹음 없음 · 음성 변환 중 · 녹음 제외', () => {
|
||||
// 녹음이 끊긴 경기도 분석한다 (v1.11.0): 녹음된 대화만 쓰고 AI 에 알린다
|
||||
const late = setup();
|
||||
const a = seedValorant(late, { sessionStartOffsetMs: 17 * MIN });
|
||||
const e = late.culprit.eligibility(late.store.getMatch(a.id)!);
|
||||
assert.equal(e.state, 'blocked');
|
||||
assert.deepEqual(e.reasons, ['녹음이 경기 시작 12분 뒤에 시작됐습니다']);
|
||||
assert.deepEqual(e, { state: 'ready', reasons: [], notes: ['녹음이 경기 시작 12분 뒤에 시작됐습니다: 녹음된 대화만 씁니다'] });
|
||||
assert.ok(late.culprit.buildInput(late.store.getMatch(a.id)!).text.includes('\n# 녹음이 경기 시작 12분 뒤에 시작됐습니다. 녹음이 빠진 구간의 대화는 없다\n'));
|
||||
|
||||
// 앱을 켜지 않고 한 경기 (녹음 · 대화 없음): 플레이 기록 · 채팅으로만
|
||||
const none = setup();
|
||||
const n = seedValorant(none);
|
||||
none.store.db.prepare('DELETE FROM utterances').run();
|
||||
none.store.db.prepare('DELETE FROM sessions').run();
|
||||
const nm = none.store.getMatch(n.id)!;
|
||||
assert.deepEqual(none.culprit.eligibility(nm), { state: 'ready', reasons: [], notes: ['녹음 없음: 플레이 기록 · 채팅으로만 분석합니다'] });
|
||||
const ni = none.culprit.buildInput(nm);
|
||||
assert.ok(ni.text.includes('\n# 이 경기는 음성 녹음이 없다. 모두 음성X 로 보고 플레이 기록과 채팅으로만 평가한다\n'));
|
||||
assert.ok(ni.players.every((p) => !p.voice));
|
||||
assert.equal(ni.stats.utterances, 0);
|
||||
assert.ok(ni.stats.events > 0 && ni.stats.rounds > 0);
|
||||
|
||||
const pend = setup();
|
||||
const b = seedValorant(pend, { pending: true });
|
||||
assert.deepEqual(pend.culprit.eligibility(pend.store.getMatch(b.id)!), { state: 'pending', reasons: ['음성 변환 중 (1문장 남음)'] });
|
||||
assert.deepEqual(pend.culprit.eligibility(pend.store.getMatch(b.id)!), { state: 'pending', reasons: ['음성 변환 중 (1문장 남음)'], notes: [] });
|
||||
|
||||
// 녹음 제외한 사람의 대화는 보내지 않는다
|
||||
const ex = setup();
|
||||
|
||||
103
app/test/game-saver.test.ts
Normal file
103
app/test/game-saver.test.ts
Normal file
@@ -0,0 +1,103 @@
|
||||
// v1.9.0: 게임 중 GPU 아끼기 (발로란트 + 브라우저 + 겜녹이를 같이 켜면 GPU 가 100% 가까이 차던 것)
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { Store } from '../src/core/db/db.ts';
|
||||
import { Timeline } from '../src/core/timeline.ts';
|
||||
import { Bus } from '../src/core/util/events.ts';
|
||||
import { SttPipeline } from '../src/core/stt/pipeline.ts';
|
||||
|
||||
function setup(gameSaver = true) {
|
||||
const dir = fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-saver-'));
|
||||
const store = new Store(path.join(dir, 'db.sqlite'));
|
||||
store.upsertUser({ id: 'u1', name: '하늘', avatar: null });
|
||||
const t0 = Date.now() - 600000;
|
||||
store.upsertMatch({ id: 'm1', game: 'valorant', started_at: t0, status: 'live' });
|
||||
const mk = (id: string, at = Date.now()) => {
|
||||
const f = path.join(dir, 'audio', `${id}.ogg`);
|
||||
fs.mkdirSync(path.dirname(f), { recursive: true });
|
||||
fs.writeFileSync(f, Buffer.concat([Buffer.from('OggS'), Buffer.alloc(50)]));
|
||||
store.insertUtterance({ id, session_id: null, user_id: 'u1', started_at: at, ended_at: at + 1000, audio_path: f, match_id: 'm1' });
|
||||
};
|
||||
const reqs: any[] = [];
|
||||
const ops: string[] = [];
|
||||
const worker: any = Object.assign(new EventEmitter(), {
|
||||
ready: true,
|
||||
request: async (op: string, req: any) => {
|
||||
if (op === 'gpu_info') return { gpus: [{ vram_total_mb: 16303 }] }; // 두 모델을 같이 올릴 수 있는 카드
|
||||
if (op === 'models') return { models: [{ name: 'rt', installed: true }, { name: 'pr', installed: true }] };
|
||||
if (op === 'load' || op === 'unload') {
|
||||
ops.push(`${op}:${req.slot}`);
|
||||
return {};
|
||||
}
|
||||
reqs.push(req);
|
||||
await new Promise((r) => setTimeout(r, 40));
|
||||
return { text: '말', raw_text: '말', words: [], noise: false, noise_reason: null, confidence: 0.5, lufs: -30, gain_db: 0, speech_ratio: 1, duration_s: 1, model: req.slot, elapsed_ms: 40 };
|
||||
},
|
||||
});
|
||||
const settings: any = () => ({
|
||||
stt: { realtimeModel: 'rt', preciseModel: 'pr', device: 'cuda', computeType: 'float16', gameVramReserveMb: 3072, reprocessAfterMatch: true, gameSaver },
|
||||
audio: { targetLufs: -18, noiseSensitivity: 0.5, denoise: false },
|
||||
});
|
||||
const dict: any = { hotwords: () => '', corrections: () => [], candidates: () => [] };
|
||||
const stt = new SttPipeline(worker, store, dict, new Timeline(store), new Bus(), settings);
|
||||
stt.status.worker = 'ready';
|
||||
const wait = async (fn: () => boolean, ms = 5000) => {
|
||||
const t = Date.now();
|
||||
while (!fn()) {
|
||||
if (Date.now() - t > ms) throw new Error('timeout');
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
}
|
||||
};
|
||||
return { store, stt, mk, reqs, ops, wait, t0 };
|
||||
}
|
||||
|
||||
test('게임 중: 정밀 모델을 내리고, 새 발화는 실시간 모델 · 빔 1 로만, 발화 사이에 쉰다', async () => {
|
||||
const s = setup();
|
||||
await s.stt.prepareModels();
|
||||
assert.equal(s.stt.status.slots.precise.state, 'loaded', '게임 밖에서는 두 모델 모두');
|
||||
await s.stt.setGameActive(true);
|
||||
assert.equal(s.stt.status.slots.precise.state, 'empty', '게임이 켜지면 정밀 모델을 내린다');
|
||||
s.mk('a1');
|
||||
s.mk('a2');
|
||||
s.stt.enqueue('a1', 'realtime');
|
||||
s.stt.enqueue('a2', 'realtime');
|
||||
const t = Date.now();
|
||||
await s.wait(() => s.reqs.length === 2 && !s.stt.status.processing);
|
||||
assert.ok(Date.now() - t >= 75, '두 번째 발화 전에 앞 변환만큼 쉰다');
|
||||
assert.deepEqual(s.reqs.map((r) => [r.slot, r.beam_size]), [['realtime', 1], ['realtime', 1]]);
|
||||
});
|
||||
|
||||
test('경기가 끝나도 게임(메뉴)이 켜져 있으면 정밀 변환은 기다리고, 게임을 끄면 정밀 모델을 올려 한다', async () => {
|
||||
const s = setup();
|
||||
await s.stt.prepareModels();
|
||||
await s.stt.setGameActive(true);
|
||||
await s.stt.onMatchStart();
|
||||
s.mk('b1', s.t0 + 1000);
|
||||
s.stt.enqueue('b1', 'realtime');
|
||||
await s.wait(() => s.store.getUtterance('b1')!.status === 'realtime');
|
||||
await s.stt.onMatchEnd(s.t0, Date.now());
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
assert.equal(s.reqs.length, 1, '게임이 켜져 있는 동안 정밀 변환 안 함');
|
||||
assert.equal(s.stt.status.queue, 1);
|
||||
assert.equal(s.stt.status.slots.precise.state, 'empty');
|
||||
await s.stt.setGameActive(false);
|
||||
await s.wait(() => s.store.getUtterance('b1')!.status === 'precise');
|
||||
assert.equal(s.reqs[1].slot, 'precise');
|
||||
assert.equal(s.reqs[1].beam_size, undefined, '게임 밖에서는 기본 빔');
|
||||
});
|
||||
|
||||
test('게임 중 GPU 아끼기를 끄면 예전처럼 (정밀 모델 유지 · 기본 빔)', async () => {
|
||||
const s = setup(false);
|
||||
await s.stt.prepareModels();
|
||||
await s.stt.setGameActive(true);
|
||||
assert.equal(s.stt.status.slots.precise.state, 'loaded');
|
||||
await s.stt.onMatchStart();
|
||||
s.mk('c1');
|
||||
s.stt.enqueue('c1', 'realtime');
|
||||
await s.wait(() => s.reqs.length === 1);
|
||||
assert.equal(s.reqs[0].beam_size, undefined);
|
||||
});
|
||||
@@ -27,6 +27,7 @@ test('발로란트·롤 어댑터: 가짜 Riot 서버로 경기 시작→채팅
|
||||
process.env.GVR_LOL_LIVE_URL = mock.base;
|
||||
process.env.GVR_POLL_MS = '150';
|
||||
process.env.GVR_DETAIL_RETRY_MS = '100';
|
||||
process.env.GVR_NAMES_EVERY_MS = '200';
|
||||
const { Store } = await import('../src/core/db/db.ts');
|
||||
const { Timeline } = await import('../src/core/timeline.ts');
|
||||
const { GameAssets } = await import('../src/core/games/assets.ts');
|
||||
@@ -40,7 +41,7 @@ test('발로란트·롤 어댑터: 가짜 Riot 서버로 경기 시작→채팅
|
||||
const tl = new Timeline(store);
|
||||
const worker: any = Object.assign(new EventEmitter(), { request: async () => ({ lines: [] }) });
|
||||
const sttCalls: string[] = [];
|
||||
const stt: any = { onMatchStart: async () => sttCalls.push('start'), onMatchEnd: async () => sttCalls.push('end') };
|
||||
const stt: any = { onMatchStart: async () => sttCalls.push('start'), onMatchEnd: async () => sttCalls.push('end'), setGameActive: async () => undefined };
|
||||
const assets = new GameAssets(path.join(dir, 'cache'));
|
||||
(assets as any).refresh = async () => undefined; // 네트워크 없이
|
||||
assets.lol = {
|
||||
@@ -89,6 +90,18 @@ test('발로란트·롤 어댑터: 가짜 Riot 서버로 경기 시작→채팅
|
||||
assert.deepEqual(sum.score, { ally: 2, enemy: 1 });
|
||||
assert.equal(sum.win, true);
|
||||
|
||||
// ---- Riot ID 를 바꾼 사람: 연결(puuid)은 그대로, 표시되는 Riot ID 만 새 이름으로
|
||||
store.upsertUser({ id: 'friend', name: '민수', avatar: null });
|
||||
store.setAccounts('friend', [{ puuid: 'riotid:아직모름#KR1', riotId: '아직모름#KR1' }]);
|
||||
const before = live.filter((e) => e.type === 'users.updated').length;
|
||||
const revBefore = bus.usersRev;
|
||||
mock.st.names = { 'self-puuid-0001': ['새하늘', 'KR2'] };
|
||||
await until(() => store.listAccounts().some((a) => a.puuid === 'self-puuid-0001' && a.riot_id === '새하늘#KR2'), 5000, 'rename');
|
||||
assert.equal(store.userIdForPuuid('self-puuid-0001'), 'owner');
|
||||
assert.ok(live.filter((e) => e.type === 'users.updated').length > before, '사이트에 유저 목록 다시 보냄');
|
||||
assert.ok(bus.usersRev > revBefore, '앱 설정 창도 유저 목록을 다시 받게 (state.usersRev)');
|
||||
assert.ok(store.listAccounts().some((a) => a.user_id === 'friend' && a.riot_id === '아직모름#KR1'), 'puuid 모르는 계정은 그대로');
|
||||
|
||||
// ---- 롤
|
||||
mock.st.lolPhase = 'ChampSelect';
|
||||
await until(() => (gm as any).adapters[1].pendingChat.length === 1, 5000, 'champ select chat');
|
||||
|
||||
387
app/test/history.test.ts
Normal file
387
app/test/history.test.ts
Normal file
@@ -0,0 +1,387 @@
|
||||
// v1.9.0: 내 Riot 경기 기록 가져오기 (앱이 꺼져 있을 때 한 경기도 사이트 경기 탭에)
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { startMockRiot } from './mock/riot.ts';
|
||||
|
||||
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-hist-'));
|
||||
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
||||
async function until(fn: () => boolean, ms = 10000, label = 'condition') {
|
||||
const t = Date.now();
|
||||
while (!fn()) {
|
||||
if (Date.now() - t > ms) throw new Error(`timeout: ${label}`);
|
||||
await sleep(50);
|
||||
}
|
||||
}
|
||||
|
||||
test('경기 기록: 발로란트 · 롤 기록을 가져와 history 경기로 저장, 필터 · 타임라인 · 다시 훑기', async () => {
|
||||
const dir = tmp();
|
||||
const mock = await startMockRiot(path.join(dir, 'mock'));
|
||||
Object.assign(process.env, {
|
||||
GVR_RIOT_LOCKFILE: mock.lockfile,
|
||||
GVR_LCU_LOCKFILE: mock.lockfile,
|
||||
GVR_VAL_GLZ: mock.base,
|
||||
GVR_VAL_PD: mock.base,
|
||||
GVR_LOL_LIVE_URL: mock.base,
|
||||
GVR_POLL_MS: '150',
|
||||
GVR_HISTORY_EVERY_MS: '400',
|
||||
GVR_HISTORY_GAP_MS: '5',
|
||||
});
|
||||
const { Store } = await import('../src/core/db/db.ts');
|
||||
const { Timeline } = await import('../src/core/timeline.ts');
|
||||
const { GameAssets } = await import('../src/core/games/assets.ts');
|
||||
const { GameManager } = await import('../src/core/games/manager.ts');
|
||||
const { Bus } = await import('../src/core/util/events.ts');
|
||||
const { defaultSettings } = await import('../src/core/settings.ts');
|
||||
const store = new Store(path.join(dir, 'db.sqlite'));
|
||||
const tl = new Timeline(store);
|
||||
const worker: any = Object.assign(new EventEmitter(), { request: async () => ({ lines: [] }) });
|
||||
const stt: any = { onMatchStart: async () => undefined, onMatchEnd: async () => undefined, setGameActive: async () => undefined };
|
||||
const assets = new GameAssets(path.join(dir, 'cache'));
|
||||
(assets as any).refresh = async () => undefined;
|
||||
const s = defaultSettings();
|
||||
store.upsertUser({ id: 'owner', name: '하늘', avatar: null });
|
||||
const H = Date.now() - 30 * 86400000;
|
||||
// 발로란트 23경기 (두 쪽): 하나는 앱이 이미 잡은 경기, 하나는 상세가 없는 경기
|
||||
mock.st.valHistory = Array.from({ length: 23 }, (_, i) => ({ MatchID: i === 5 ? 'gone-5' : `h-${i}`, GameStartTime: H - i * 3600000 }));
|
||||
store.upsertMatch({ id: 'val-h-0', game: 'valorant', started_at: H, status: 'complete' });
|
||||
// 앱이 녹음하던 때 잡지 못한 경기: 그 시간 발화가 경기에 붙는다
|
||||
store.insertUtterance({ id: 'u1', session_id: null, user_id: 'owner', started_at: H - 3600000 + 60000, ended_at: H - 3600000 + 62000, audio_path: null, match_id: null });
|
||||
mock.st.lolHistoryList = [
|
||||
{ gameId: 9001, gameCreation: H - 100000 },
|
||||
{ gameId: 9002, gameCreation: H - 200000 },
|
||||
];
|
||||
const gm = new GameManager(store, assets, worker, stt, tl, bus(), () => s, () => 'owner');
|
||||
function bus() {
|
||||
return new Bus();
|
||||
}
|
||||
gm.start();
|
||||
try {
|
||||
await until(() => !!store.getMatch('val-h-22') && store.getMatch('val-h-22')!.status === 'complete', 15000, 'val history');
|
||||
await until(() => !!store.getMatch('lol-9002') && store.getMatch('lol-9002')!.status === 'complete', 15000, 'lol history');
|
||||
const vals = store.listMatches({ game: 'valorant', limit: 100 });
|
||||
assert.equal(vals.length, 22, '23경기 중 상세 없는 1경기 빼고');
|
||||
assert.equal(store.getMatch('val-h-0')!.source, 'live', '앱이 잡은 경기는 그대로');
|
||||
const h1 = store.getMatch('val-h-1')!;
|
||||
assert.equal(h1.source, 'history');
|
||||
assert.equal(h1.started_at, H - 3600000);
|
||||
assert.ok(store.events('val-h-1').some((e) => e.type === 'kill'), '킬 기록도 (경기 화면용)');
|
||||
assert.equal(store.getUtterance('u1')!.match_id, 'val-h-1', '그 시간 발화가 붙는다');
|
||||
assert.equal(store.getMatch('lol-9001')!.source, 'history');
|
||||
assert.ok(!store.getMatch('val-gone-5'));
|
||||
assert.ok(JSON.parse(store.meta('history_skip:valorant')!).includes('val-gone-5'));
|
||||
// 사이트 경기 탭 안내: 마지막으로 끝까지 확인한 때
|
||||
await until(() => gm.live().every((g) => typeof g.historyAt === 'number'), 5000, 'historyAt');
|
||||
|
||||
// 필터
|
||||
const ids = (has?: 'timeline' | 'voice') => store.listMatches({ limit: 100, has }).map((m) => m.id).sort();
|
||||
assert.equal(ids().length, 24);
|
||||
assert.deepEqual(ids('timeline'), ['val-h-0', 'val-h-1'], '타임라인: 앱이 잡은 경기 + 대화가 붙은 기록 경기');
|
||||
store.updateUtteranceResult('u1', { text: '가자', raw_text: '가자', words: [], noise: false, noise_reason: null, confidence: 0.9, lufs: -20, gain_db: 0, model: 'm', status: 'precise' });
|
||||
assert.deepEqual(ids('voice'), ['val-h-1']);
|
||||
const sum = gm.summary(store.getMatch('val-h-2')!);
|
||||
assert.equal(sum.source, 'history');
|
||||
assert.equal(sum.voice, false);
|
||||
assert.equal(gm.summary(store.getMatch('val-h-1')!).voice, true);
|
||||
|
||||
// 타임라인: 녹음 없는 기록 경기의 이벤트는 빼고, 그 경기를 고르면 보인다
|
||||
const page = tl.query({ limit: 500 });
|
||||
const evMatches = new Set(page.items.filter((it: any) => it.kind === 'event').map((it: any) => it.matchId));
|
||||
assert.ok(!evMatches.has('val-h-2') && !evMatches.has('lol-9001'));
|
||||
assert.ok(evMatches.has('val-h-1'), '대화가 붙은 기록 경기는 타임라인에');
|
||||
assert.ok(tl.query({ match: 'val-h-2', limit: 50 }).items.length > 0);
|
||||
|
||||
// 다시 훑기: 한 번 끝까지 본 뒤에는 첫 쪽만 (새 경기 1개)
|
||||
const before = mock.st.hits.filter((h) => h.startsWith('/match-history/')).length;
|
||||
mock.st.valHistory.unshift({ MatchID: 'h-new', GameStartTime: Date.now() - 3600000 });
|
||||
await until(() => store.getMatch('val-h-new')?.status === 'complete', 10000, 'new match');
|
||||
await sleep(100);
|
||||
const pages = mock.st.hits.filter((h) => h.startsWith('/match-history/')).length - before;
|
||||
assert.ok(pages >= 1 && pages <= 3, `다시 훑을 때는 첫 쪽만 (${pages})`);
|
||||
|
||||
// 경기 중에는 가져오지 않는다
|
||||
mock.st.valState = 'INGAME';
|
||||
await until(() => gm.status().valorant.inMatch, 5000, 'in match');
|
||||
const n = mock.st.hits.filter((h) => h.startsWith('/match-history/')).length;
|
||||
await sleep(1200);
|
||||
assert.equal(mock.st.hits.filter((h) => h.startsWith('/match-history/')).length, n);
|
||||
} finally {
|
||||
gm.stop();
|
||||
await mock.close();
|
||||
store.close();
|
||||
for (const k of ['GVR_HISTORY_EVERY_MS', 'GVR_HISTORY_GAP_MS']) delete process.env[k];
|
||||
}
|
||||
});
|
||||
|
||||
test('경기 기록: 진행 상황 (목록 확인 → 경기 받기 · 남은 시간) · 취소하면 멈추고 다음에 이어서', async () => {
|
||||
const dir = tmp();
|
||||
const { Store } = await import('../src/core/db/db.ts');
|
||||
const { HistorySync } = await import('../src/core/games/history.ts');
|
||||
const store = new Store(path.join(dir, 'db.sqlite'));
|
||||
const all = Array.from({ length: 30 }, (_, i) => `val-p-${i}`);
|
||||
let gate: (() => void) | null = null;
|
||||
const fetched: string[] = [];
|
||||
const src = {
|
||||
game: 'valorant' as const,
|
||||
idle: () => true,
|
||||
account: () => 'me',
|
||||
page: async (start: number, n: number) => {
|
||||
// 첫 쪽은 화면에서 목록 확인 중을 볼 수 있게 잠깐 멈춘다
|
||||
if (start === 0) await new Promise<void>((r) => (gate = r));
|
||||
return { ids: all.slice(start, start + n), total: all.length };
|
||||
},
|
||||
fetch: async (id: string) => {
|
||||
await sleep(15);
|
||||
store.upsertMatch({ id, game: 'valorant', started_at: Date.now(), status: 'complete' });
|
||||
fetched.push(id);
|
||||
return 'ok' as const;
|
||||
},
|
||||
};
|
||||
const h = new HistorySync(store, src, { pageSize: 10, max: 500, gapMs: 5 });
|
||||
try {
|
||||
assert.equal(h.progress(), null, '가져오는 중이 아니면 없음');
|
||||
assert.deepEqual(h.cancel(), { cancelled: false, resumeAt: null }, '돌지 않을 때 취소는 아무 일 없음');
|
||||
h.maybeRun(60000, 0);
|
||||
await until(() => !!gate, 2000, 'scan start');
|
||||
const s0 = h.progress()!;
|
||||
assert.equal(s0.phase, 'scan');
|
||||
assert.equal(s0.first, true, '처음 끝까지 훑는 중');
|
||||
assert.equal(s0.etaMs, null);
|
||||
gate!();
|
||||
await until(() => h.progress()?.phase === 'fetch' && h.progress()!.done >= 5, 5000, 'fetching');
|
||||
const p = h.progress()!;
|
||||
assert.equal(p.total, 30);
|
||||
assert.equal(p.scanned, 30);
|
||||
assert.ok(p.etaMs !== null && p.etaMs > 0 && p.etaMs < 10000, `남은 시간 (${p.etaMs})`);
|
||||
|
||||
// 취소: 진행 상황은 바로 사라지고, 루프는 다음 경기 전에 멈춘다
|
||||
const c = h.cancel();
|
||||
assert.equal(c.cancelled, true);
|
||||
assert.ok(c.resumeAt && c.resumeAt > Date.now() + 50000, '다음 주기에 이어서');
|
||||
assert.equal(h.progress(), null);
|
||||
const n = fetched.length;
|
||||
await sleep(150);
|
||||
assert.ok(fetched.length <= n + 1, `취소 뒤 더 받지 않음 (${n} → ${fetched.length})`);
|
||||
assert.ok(fetched.length < 30);
|
||||
assert.ok(!store.meta('history_full:valorant:me'), '끝까지 받지 않았으니 다음에도 끝까지 훑는다');
|
||||
|
||||
// 다음 실행: 받은 경기는 건너뛰고 남은 것만
|
||||
gate = null;
|
||||
const run = h.run();
|
||||
await until(() => !!gate, 2000, 'scan 2');
|
||||
gate!();
|
||||
const before = fetched.length;
|
||||
await run;
|
||||
assert.equal(fetched.length, 30, '남은 것부터 끝까지');
|
||||
assert.equal(new Set(fetched).size, 30, '같은 경기를 두 번 받지 않음');
|
||||
assert.ok(fetched.length - before === 30 - before);
|
||||
assert.equal(store.meta('history_full:valorant:me'), '1');
|
||||
assert.equal(h.progress(), null, '끝나면 진행 상황 없음');
|
||||
} finally {
|
||||
store.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('경기 기록: 진행 상황은 지금 게임 상태(games.state)로 나가고, 사이트에서 POST /api/games/history/cancel 로 취소', async () => {
|
||||
const dir = tmp();
|
||||
const { Store } = await import('../src/core/db/db.ts');
|
||||
const { Timeline } = await import('../src/core/timeline.ts');
|
||||
const { GameAssets } = await import('../src/core/games/assets.ts');
|
||||
const { GameManager } = await import('../src/core/games/manager.ts');
|
||||
const { Bus } = await import('../src/core/util/events.ts');
|
||||
const { buildApi } = await import('../src/core/api/server.ts');
|
||||
const { defaultSettings } = await import('../src/core/settings.ts');
|
||||
const { historyStatus, fmtEta } = await import('@gvr/shared');
|
||||
const store = new Store(path.join(dir, 'db.sqlite'));
|
||||
const bus = new Bus();
|
||||
const sent: any[] = [];
|
||||
bus.on('live', (e) => sent.push(e));
|
||||
const s = defaultSettings();
|
||||
const stt: any = { setGameActive: async () => undefined };
|
||||
const gm = new GameManager(store, new GameAssets(path.join(dir, 'cache')), Object.assign(new EventEmitter(), { request: async () => ({}) }) as any, stt, new Timeline(store), bus, () => s, () => null);
|
||||
// 롤만 가져오는 중
|
||||
let lolRunning = true;
|
||||
const fake = (game: 'valorant' | 'lol') => ({
|
||||
lastDoneAt: () => null,
|
||||
progress: () => (game === 'lol' && lolRunning ? { phase: 'fetch', first: true, scanned: 40, done: 10, total: 40, startedAt: Date.now() - 20000, etaMs: 60000 } : null),
|
||||
cancel: () => {
|
||||
if (game !== 'lol' || !lolRunning) return { cancelled: false, resumeAt: null };
|
||||
lolRunning = false;
|
||||
return { cancelled: true, resumeAt: Date.now() + 30 * 60000 };
|
||||
},
|
||||
});
|
||||
for (const a of gm.adapters) (a as any).history = fake(a.game);
|
||||
const app = await buildApi({
|
||||
store,
|
||||
timeline: new Timeline(store),
|
||||
games: gm,
|
||||
dict: {} as any,
|
||||
culprit: {} as any,
|
||||
bus,
|
||||
settings: () => s,
|
||||
trainingDir: () => dir,
|
||||
overviewExtra: () => ({ guild: null, recording: {} as any }),
|
||||
version: 'test',
|
||||
});
|
||||
try {
|
||||
const lol = gm.live().find((g) => g.game === 'lol')!;
|
||||
assert.equal(lol.history?.done, 10);
|
||||
assert.equal(gm.live().find((g) => g.game === 'valorant')!.history, null);
|
||||
assert.deepEqual(historyStatus(lol.history!), { title: '경기 기록 가져오는 중', detail: '10 / 40경기 (25%) · 약 1분 남음', pct: 25 });
|
||||
assert.equal(historyStatus({ ...lol.history!, phase: 'scan', total: 3 }).pct, null, '목록 확인 중에는 얼마나 걸릴지 모름');
|
||||
assert.equal(fmtEta(null), '남은 시간 계산 중');
|
||||
assert.equal(fmtEta(25000), '30초 남음');
|
||||
assert.equal(fmtEta(2 * 3600000 + 5 * 60000), '약 2시간 5분 남음');
|
||||
|
||||
const member = { 'x-gvr-user': encodeURIComponent(JSON.stringify({ id: 'm1', name: 'm1', avatar: null })), 'x-gvr-role': 'member' };
|
||||
const r = await app.inject({ method: 'POST', url: '/api/games/history/cancel', headers: member, payload: { game: 'lol' } });
|
||||
assert.equal(r.statusCode, 200);
|
||||
const b = r.json();
|
||||
assert.deepEqual(b.cancelled, ['lol'], '서버 멤버 누구나 취소 (다음 주기에 이어서 하니 지워지는 것 없음)');
|
||||
assert.ok(b.resumeAt > Date.now());
|
||||
const st = sent.filter((e) => e.type === 'games.state').at(-1);
|
||||
assert.ok(st, '취소하면 바로 게임 상태를 보낸다');
|
||||
assert.equal(st.data.find((g: any) => g.game === 'lol').history, null);
|
||||
const again = await app.inject({ method: 'POST', url: '/api/games/history/cancel', payload: {} });
|
||||
assert.deepEqual(again.json().cancelled, [], '이미 멈췄으면 아무 일 없음');
|
||||
} finally {
|
||||
await app.close();
|
||||
store.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('경기 기록: 끝까지 훑은 계정에서 새 경기를 받다가 취소해도, 다음 실행이 남은 경기를 모두 받는다 · 취소 뒤 한 주기 동안은 다시 시작하지 않는다', async () => {
|
||||
const dir = tmp();
|
||||
const { Store } = await import('../src/core/db/db.ts');
|
||||
const { HistorySync } = await import('../src/core/games/history.ts');
|
||||
const store = new Store(path.join(dir, 'db.sqlite'));
|
||||
// 예전 경기 20개는 이미 받았고 끝까지 훑은 계정
|
||||
const old = Array.from({ length: 20 }, (_, i) => `val-old-${i}`);
|
||||
for (const id of old) store.upsertMatch({ id, game: 'valorant', started_at: 1, status: 'complete' });
|
||||
store.setMeta('history_full:valorant:me', '1');
|
||||
// 새 경기 30개 (새것부터 = 목록 앞쪽)
|
||||
const fresh = Array.from({ length: 30 }, (_, i) => `val-new-${i}`);
|
||||
const all = [...fresh, ...old];
|
||||
const fetched: string[] = [];
|
||||
let pages = 0;
|
||||
let h!: InstanceType<typeof HistorySync>;
|
||||
const src = {
|
||||
game: 'valorant' as const,
|
||||
idle: () => true,
|
||||
account: () => 'me',
|
||||
page: async (start: number, n: number) => {
|
||||
pages++;
|
||||
return { ids: all.slice(start, start + n), total: all.length };
|
||||
},
|
||||
fetch: async (id: string) => {
|
||||
await sleep(5);
|
||||
store.upsertMatch({ id, game: 'valorant', started_at: 2, status: 'complete' });
|
||||
fetched.push(id);
|
||||
// 첫 쪽 10경기를 받은 뒤 취소
|
||||
if (fetched.length === 10) h.cancel();
|
||||
return 'ok' as const;
|
||||
},
|
||||
};
|
||||
h = new HistorySync(store, src, { pageSize: 10, max: 500, gapMs: 1 });
|
||||
try {
|
||||
assert.equal(await h.run(), 10);
|
||||
assert.equal(fetched.length, 10);
|
||||
assert.equal(store.meta('history_pending:valorant:me'), '1', '받다가 멈춤');
|
||||
|
||||
// 다음 실행: 첫 쪽은 다 아는 경기지만 멈추지 않고 끝까지 훑어 남은 20경기를 받는다
|
||||
assert.equal(await h.run(), 20, '남은 경기 모두');
|
||||
assert.deepEqual([...fetched].sort(), [...fresh].sort());
|
||||
assert.ok(!store.meta('history_pending:valorant:me'), '다 받았으면 표시를 지운다');
|
||||
|
||||
// 그다음부터는 다시 첫 쪽만
|
||||
pages = 0;
|
||||
assert.equal(await h.run(), 0);
|
||||
assert.equal(pages, 1, '아는 경기만 나오는 첫 쪽에서 멈춤');
|
||||
|
||||
// 취소한 때부터 한 주기 뒤에 이어서: 오래(주기보다 길게) 돈 실행을 취소해도 바로 다시 시작하지 않는다
|
||||
const every = 60000;
|
||||
fetched.length = 0;
|
||||
all.unshift(...Array.from({ length: 15 }, (_, i) => `val-more-${i}`));
|
||||
let gate!: () => void;
|
||||
const slowFetch = src.fetch;
|
||||
src.fetch = async (id: string) => {
|
||||
await new Promise<void>((r) => (gate = r));
|
||||
return slowFetch(id);
|
||||
};
|
||||
// 위에서 취소한 때부터 한 주기가 지나지 않았으니 maybeRun 은 아직 돌지 않는다
|
||||
h.maybeRun(every, 0);
|
||||
assert.equal((h as any).running, false, '취소 뒤 한 주기 안에는 다시 시작하지 않음');
|
||||
(h as any).lastAt = 0;
|
||||
h.maybeRun(every, 0);
|
||||
await until(() => h.progress()?.phase === 'fetch', 2000, 'fetch start');
|
||||
(h as any).lastAt -= 2 * every; // 두 주기 넘게 돈 것처럼
|
||||
const c = h.cancel();
|
||||
assert.equal(c.cancelled, true);
|
||||
assert.ok(c.resumeAt! >= Date.now() + every - 1000, `취소한 때부터 한 주기 뒤 (${c.resumeAt! - Date.now()}ms)`);
|
||||
gate();
|
||||
await until(() => !(h as any).running, 2000, 'stopped');
|
||||
pages = 0;
|
||||
h.maybeRun(every, 0);
|
||||
await sleep(50);
|
||||
assert.equal(pages, 0, '다음 확인에서 바로 다시 시작하지 않음');
|
||||
assert.equal(h.progress(), null);
|
||||
} finally {
|
||||
store.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('경기 목록: 데스매치는 빼고, 모드 · 날짜로 거른다 · 모드 목록 (v1.11.0)', async () => {
|
||||
const dir = tmp();
|
||||
const { Store } = await import('../src/core/db/db.ts');
|
||||
const { Timeline } = await import('../src/core/timeline.ts');
|
||||
const { GameAssets } = await import('../src/core/games/assets.ts');
|
||||
const { GameManager } = await import('../src/core/games/manager.ts');
|
||||
const { Culprit } = await import('../src/core/culprit.ts');
|
||||
const { Bus } = await import('../src/core/util/events.ts');
|
||||
const { buildApi } = await import('../src/core/api/server.ts');
|
||||
const { defaultSettings } = await import('../src/core/settings.ts');
|
||||
const store = new Store(path.join(dir, 'db.sqlite'));
|
||||
const bus = new Bus();
|
||||
const s = defaultSettings();
|
||||
const tl = new Timeline(store);
|
||||
const gm = new GameManager(store, new GameAssets(path.join(dir, 'cache')), Object.assign(new EventEmitter(), { request: async () => ({}) }) as any, { setGameActive: async () => undefined } as any, tl, bus, () => s, () => null);
|
||||
const DAY = 86400000;
|
||||
const T = Date.UTC(2026, 10, 20, 12);
|
||||
const add = (id: string, game: 'valorant' | 'lol', queue: string | null, at: number, mode: string | null = queue) =>
|
||||
store.upsertMatch({ id, game, started_at: at, ended_at: at + 1800000, queue, mode, status: 'complete', source: 'history' });
|
||||
add('val-comp1', 'valorant', 'competitive', T);
|
||||
add('val-dm', 'valorant', 'deathmatch', T - 1000);
|
||||
add('val-unr', 'valorant', 'unrated', T - DAY);
|
||||
add('val-comp2', 'valorant', 'competitive', T - 3 * DAY);
|
||||
add('val-prem', 'valorant', 'premier', T - 4 * DAY);
|
||||
add('val-dm-live', 'valorant', '', T - 5 * DAY, 'deathmatch'); // 큐가 비고 모드 칸에만 있는 데스매치
|
||||
add('lol-1', 'lol', '420', T - 2 * DAY, 'CLASSIC');
|
||||
const app = await buildApi({ store, timeline: tl, games: gm, dict: {} as any, culprit: new Culprit(store, tl, gm), bus, settings: () => s, trainingDir: () => dir, overviewExtra: () => ({ guild: null, recording: {} as any }), version: 'test' });
|
||||
const ids = async (qs: string) => (await app.inject({ url: `/api/matches${qs}` })).json().map((m: any) => m.id);
|
||||
try {
|
||||
assert.deepEqual(await ids(''), ['val-comp1', 'val-unr', 'lol-1', 'val-comp2', 'val-prem'], '데스매치는 목록에 없다');
|
||||
assert.deepEqual(await ids('?mode=' + encodeURIComponent('경쟁전')), ['val-comp1', 'val-comp2']);
|
||||
assert.deepEqual(await ids('?mode=' + encodeURIComponent('데스매치')), [], '데스매치는 모드로 골라도 나오지 않는다');
|
||||
assert.deepEqual(await ids('?mode=' + encodeURIComponent('없는모드')), []);
|
||||
// 날짜: after 이상 · before 미만 (사이트는 고른 날의 0시 · 다음 날 0시를 보낸다)
|
||||
assert.deepEqual(await ids(`?after=${T - 3 * DAY}&before=${T}`), ['val-unr', 'lol-1', 'val-comp2']);
|
||||
assert.deepEqual(await ids(`?game=valorant&mode=${encodeURIComponent('경쟁전')}&after=${T - DAY}`), ['val-comp1']);
|
||||
const modes = (await app.inject({ url: '/api/matches/modes' })).json();
|
||||
assert.deepEqual(modes, [
|
||||
{ game: 'valorant', mode: '경쟁전', count: 2 },
|
||||
{ game: 'lol', mode: '솔로 랭크', count: 1 },
|
||||
{ game: 'valorant', mode: '일반전', count: 1 },
|
||||
{ game: 'valorant', mode: '프리미어', count: 1 },
|
||||
]);
|
||||
assert.deepEqual((await app.inject({ url: '/api/matches/modes?game=lol' })).json(), [{ game: 'lol', mode: '솔로 랭크', count: 1 }]);
|
||||
// 범인찾기 목록에도 데스매치는 없다
|
||||
const cu = (await app.inject({ url: '/api/culprit/matches' })).json().map((x: any) => x.match.id);
|
||||
assert.ok(cu.includes('val-comp1') && !cu.includes('val-dm') && !cu.includes('val-dm-live'));
|
||||
} finally {
|
||||
await app.close();
|
||||
store.close();
|
||||
}
|
||||
});
|
||||
@@ -18,6 +18,14 @@ export interface MockState {
|
||||
lolGameId: number;
|
||||
lolHistoryReady: boolean;
|
||||
lolStart: number;
|
||||
/** 발로란트 경기 기록 (새것부터): MatchID → 경기 시작 시각 */
|
||||
valHistory: { MatchID: string; GameStartTime: number }[];
|
||||
/** 롤 경기 기록 (LCU, 새것부터) */
|
||||
lolHistoryList: { gameId: number; gameCreation: number }[];
|
||||
/** 이름 서비스: puuid → [이름, 태그] (Riot ID 를 바꾼 사람 흉내) */
|
||||
names: Record<string, [string, string]>;
|
||||
/** 요청 기록 (경로) */
|
||||
hits: string[];
|
||||
}
|
||||
|
||||
export async function startMockRiot(dir: string) {
|
||||
@@ -38,6 +46,10 @@ export async function startMockRiot(dir: string) {
|
||||
lolGameId: 7001,
|
||||
lolHistoryReady: false,
|
||||
lolStart: 0,
|
||||
valHistory: [],
|
||||
lolHistoryList: [],
|
||||
names: {},
|
||||
hits: [],
|
||||
};
|
||||
const password = 'pw-test';
|
||||
const presence = () => {
|
||||
@@ -52,7 +64,7 @@ export async function startMockRiot(dir: string) {
|
||||
};
|
||||
return Buffer.from(JSON.stringify(priv)).toString('base64');
|
||||
};
|
||||
const routes: [RegExp, (m: RegExpMatchArray, auth: string) => [number, any]][] = [
|
||||
const routes: [RegExp, (m: RegExpMatchArray, auth: string, url: URL) => [number, any]][] = [
|
||||
// ---- Riot Client local
|
||||
[/^\/entitlements\/v1\/token$/, () => [200, { accessToken: 'acc-token', token: 'ent-token', subject: SELF, issuer: 'x' }]],
|
||||
[
|
||||
@@ -69,7 +81,27 @@ export async function startMockRiot(dir: string) {
|
||||
() => [200, { MatchID: st.valMatchId, MapID: ASCENT, Players: [{ Subject: SELF, TeamID: 'Blue', CharacterID: 'add6443a-41bd-e414-f6ad-e58d267f4e95' }] }],
|
||||
],
|
||||
// ---- pd
|
||||
[/^\/match-details\/v1\/matches\/(.+)$/, (_m, auth) => (auth.startsWith('Bearer ') && st.valState !== 'INGAME' ? [200, makeValDetails(st.valStart)] : [404, {}])],
|
||||
[
|
||||
/^\/match-history\/v1\/history\/(.+)$/,
|
||||
(_m, auth, url) => {
|
||||
if (!auth.startsWith('Bearer ')) return [401, {}];
|
||||
const s = Number(url.searchParams.get('startIndex') ?? 0);
|
||||
const e = Number(url.searchParams.get('endIndex') ?? 20);
|
||||
return [200, { Subject: SELF, BeginIndex: s, EndIndex: e, Total: st.valHistory.length, History: st.valHistory.slice(s, e).map((h) => ({ ...h, QueueID: 'competitive' })) }];
|
||||
},
|
||||
],
|
||||
[
|
||||
/^\/match-details\/v1\/matches\/(.+)$/,
|
||||
(m, auth) => {
|
||||
const h = st.valHistory.find((x) => x.MatchID === m[1]);
|
||||
if (h) return m[1].startsWith('gone') ? [404, {}] : [200, { ...makeValDetails(h.GameStartTime), matchInfo: { ...makeValDetails(h.GameStartTime).matchInfo, matchId: h.MatchID } }];
|
||||
return auth.startsWith('Bearer ') && st.valState !== 'INGAME' ? [200, makeValDetails(st.valStart)] : [404, {}];
|
||||
},
|
||||
],
|
||||
[
|
||||
/^\/name-service\/v2\/players$/,
|
||||
(_m, auth) => (auth.startsWith('Bearer ') ? [200, Object.entries(st.names).map(([Subject, [GameName, TagLine]]) => ({ Subject, GameName, TagLine }))] : [401, {}]),
|
||||
],
|
||||
// ---- LoL Live Client Data
|
||||
[/^\/liveclientdata\/allgamedata$/, () => (st.lolLive ? [200, st.lolLive] : [404, {}])],
|
||||
// ---- LCU
|
||||
@@ -79,7 +111,23 @@ export async function startMockRiot(dir: string) {
|
||||
[/^\/lol-chat\/v1\/conversations$/, () => [200, st.lolPhase === 'ChampSelect' ? [{ id: 'cs1@champ-select.kr', type: 'championSelect' }] : []]],
|
||||
[/^\/lol-chat\/v1\/conversations\/(.+)\/messages$/, () => [200, [{ id: 'msg1', body: '정글 갱 갈게요', fromSummonerId: 11, timestamp: new Date(Date.now() - 5000).toISOString(), type: 'groupchat' }]]],
|
||||
[/^\/lol-summoner\/v1\/summoners\/(\d+)$/, () => [200, { gameName: '민수' }]],
|
||||
[/^\/lol-match-history\/v1\/games\/(\d+)$/, () => (st.lolHistoryReady ? [200, lolHistory()] : [404, {}])],
|
||||
[
|
||||
/^\/lol-match-history\/v1\/products\/lol\/current-summoner\/matches$/,
|
||||
(_m, _a, url) => {
|
||||
const s = Number(url.searchParams.get('begIndex') ?? 0);
|
||||
const e = Number(url.searchParams.get('endIndex') ?? 20);
|
||||
const games = st.lolHistoryList.slice(s, e);
|
||||
return [200, { games: { gameCount: games.length, gameIndexBegin: s, gameIndexEnd: e, games } }];
|
||||
},
|
||||
],
|
||||
[
|
||||
/^\/lol-match-history\/v1\/games\/(\d+)$/,
|
||||
(m) => {
|
||||
const h = st.lolHistoryList.find((x) => String(x.gameId) === m[1]);
|
||||
if (h) return [200, { ...lolHistory(), gameId: h.gameId, gameCreation: h.gameCreation }];
|
||||
return st.lolHistoryReady ? [200, lolHistory()] : [404, {}];
|
||||
},
|
||||
],
|
||||
[/^\/lol-match-history\/v1\/game-timelines\/(\d+)$/, () => (st.lolHistoryReady ? [200, lolTimeline()] : [404, {}])],
|
||||
];
|
||||
const server = https.createServer({ key: fs.readFileSync(key), cert: fs.readFileSync(cert) }, (req, res) => {
|
||||
@@ -87,7 +135,8 @@ export async function startMockRiot(dir: string) {
|
||||
for (const [re, fn] of routes) {
|
||||
const m = url.pathname.match(re);
|
||||
if (!m) continue;
|
||||
const [code, body] = fn(m, String(req.headers.authorization || ''));
|
||||
st.hits.push(url.pathname);
|
||||
const [code, body] = fn(m, String(req.headers.authorization || ''), url);
|
||||
res.writeHead(code, { 'content-type': 'application/json' });
|
||||
res.end(JSON.stringify(body));
|
||||
return;
|
||||
|
||||
@@ -78,6 +78,18 @@
|
||||
- 조준점: 녹색 점 → 발로란트 기본 (흰 선 4개 · 가운데 틈 · 검은 외곽선). 1.8.2 부터 선수 조준점 · 내 조준점 (아래).
|
||||
- 안 한 것: 총소리 · 발소리(Wwise 사운드뱅크라 따로 풀어야 함), HUD 체력 · 탄약(리플레이에 값 없음), 탄흔(맞은 자리 `hits` 로 가능), 스킨(기본 스킨만), 스킬 1인칭 동작, 재장전 중 탄창이 손으로 옮겨 가는 것(소켓 바꾸기라 탄창이 잠깐 안 보임).
|
||||
|
||||
## 맵 텍스처 1024px · 무기 스킨 (2026-11-20, 실감 5단계)
|
||||
- 맵 텍스처: `GVR_TEX` 기본 256 → 1024. 원본이 대부분 512 라 크게 늘지 않는다 (13.09 어센트: 이미지 366장 8MB → 24MB, 512px 246장 · 1024px 55장, 그래픽 메모리 추정 약 620MB, 맵 추출 최대 메모리 2.5GB · 3.7분).
|
||||
- 계기: open-aim(브라우저 에임 연습장)의 맵 · 스킨 파일을 그대로 쓰는 안을 비교했다. 맵은 11개뿐(브리즈 · 프랙처 · 팀 데스매치 없음)이고 좌표계가 달라 우리 추출 맵이 낫고, 스킨은 손으로 옮긴 20개 정도라 리플레이에 기록된 실제 스킨을 쓰기로 했다. 그 사이트 파일은 쓰지 않는다.
|
||||
- 리플레이: 총 · 칼 액터마다 `SkinDataAsset` · `SkinLevelDataAsset` · `ChromaDataAsset` · `CharmDataAsset` · `CharmLevelDataAsset` (게임 데이터 에셋 경로)가 복제된다. 파서에 무기 액터 형식이 없어 변환기 `src/Skins.cs` 가 첫 읽기 필드 목록에서 이 필드가 있는 묶음(무기 클래스)을 찾아 두 번째 읽기 (13.08 어비스: 총 · 칼 기록 5,686개 모두 스킨, 서로 다른 스킨 79개, 변환 6.8 → 7.0초).
|
||||
- 출력: `skins[]` {skin, level, chroma, charm, charmLevel} (경로의 `.Default__…_C` 는 뗌), `equips` 4번째 열 = skins 번호(-1 모름). 줍거나 떨어뜨려도 총의 스킨은 처음 주인 것 (게임과 같다). 같은 총이라도 스킨이 다르면(주운 총) 새 줄.
|
||||
- 게임 쪽 구조: 스킨 PrimaryAsset `Levels[]`(단계 PrimaryAsset → `SkinAttachment` = 단계 블루프린트) · `Chromas[]`(색상 PrimaryAsset → `EquippableSkinChroma`). 높은 단계 블루프린트는 낮은 단계의 자식 클래스라 부모 사슬을 합치면 그 단계까지의 모습. 단계: `Weapon 1P` · `Weapon 1P Cosmetic`(있으면 보이는 총은 이것, 1인칭 재질도 이것 기준) · `Magazine 1P` · `1p MaterialOverrides` · `1pMagazine MaterialOverrides` · `Weapon 3P` · `Magazine 3P` · `3p Material Overrides` · `3pMagazineMaterial Overrides`, 칼은 `NewMesh` · `3p Mesh`. 색상: `MaterialOverrides`(1인칭) · `3p Material Overrides` … (재질 칸 번호대로, 기본 색상은 비어 있다). 게임 전체 색상 약 2,969개라 미리 다 뽑지 않는다.
|
||||
- 추출 `gvr-map-extract skins <폴더> <요청 파일> [skins.json]` (`src/Skins.cs`): 열쇠 "스킨|단계|색상" 마다 `skin3p_<서명>.glb`(weapon_*.glb 형식, 512px) · `skin1p_<서명>.glb`(fpweapon_*.glb 형식, 1024px `GVR_SKIN_TEX1P`, 총 동작은 기본 무기 GN_Core_*). 서명 = 메시 · 재질 경로 해시라 모습이 같은 단계 · 색상은 파일 하나.
|
||||
- 요청 흐름: 사이트가 리플레이를 열면 없는 스킨을 `POST /site/maps3d/skins/want` → `.5 data/maps3d/skins/want.json`. 이 서버 `gvr-skins-update.timer`(3분마다 `scripts/skins-update.sh`)가 요청을 가져와(한 번에 40개) 올린 맵과 같은 매니페스트 · 매핑으로 뽑고 gltfpack + gzip 해서 `skins/` 에 올리고 `skins/index.json` 을 합친다(`skins-merge.py`). 못 뽑은 것은 `failed` (매핑 버전이 바뀌면 다시). 맵 갱신과 같은 잠금. `update.sh` 는 `skins/` 를 지우지 않는다. 시험: `scripts/test-skins.sh`.
|
||||
- 사이트 `lib/skins.ts`: 뽑아 둔 스킨이면 3인칭 손의 총(`AgentRig.setWeapon`) · 1인칭 총(`Viewmodel.set`)을 그 모델로, 아니면 기본 총. 기본 스킨(`…/Standard/…_PrimaryAsset`)은 요청하지 않는다. 처음 본 스킨은 다음에 열 때부터 보인다.
|
||||
- 13.10 전체 (2026-11-20): 맵 23개 68분 · 받은 양 2.5GB (텍스처 큰 밉을 받느라 256px 때 26분보다 길다), 맵 압축 13~56MB, 사이트 폴더 818MB. 매핑은 uedb 가 13.09 에 멈춰 있어 valorant-api.com (`/v1/version` 의 manifestId 가 라이브와 같을 때 mappingsUrl) 으로 받았다 (`update.sh`).
|
||||
- 한계: 총 장식(참) · 스킨 전용 동작 · 효과(빛나는 재질 · 단계별 VFX) · 처치 연출은 없다. 재질은 디퓨즈 텍스처만이라 빛나는 부분은 평평하다.
|
||||
|
||||
## 남은 일
|
||||
- 실제 경기로 동기화 오차 확인 (사이트 아래 줄 "킬 N개로 맞춤 (최대 오차 X초)")
|
||||
|
||||
@@ -106,3 +118,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 으로 떨어지기 직전 값)으로 정하고 (공수 교대 초기화는 뺀다: 교대 라운드 = 선수 시작 자리 중앙값이 40m 넘게 옮겨 간 라운드(13.08 실측 교대 93~109m · 평소 13m 이하), 그 앞 라운드 끝 ~ 교대 라운드 구매 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) > 위에서 (구매 · 전략 보기 · 라운드 끝). 위에서는 살아 있는 선수가 모두 들어오게 부드럽게 따라간다 (거리 = 시야각 · 화면비 · 기울기로 가장 바깥 선수가 화면 85% 에 닿는 값, `fitDistance`). 2초보다 짧은 위에서 보기 · 0.9초보다 짧은 1인칭은 앞 장면에 붙인다.
|
||||
- 13.08 어비스: 장면 265개 · 계산 15ms, 상대 팀끼리 킬 145개 중 126개를 죽인 선수 1인칭으로 (나머지는 1초 안 맞킬).
|
||||
- 시험: `site/server/test/replay-director.test.ts`, 변환기 `gvr-replay --self-test` (점수판 줄 합치기).
|
||||
|
||||
@@ -287,6 +287,44 @@ VOICE E2E PASS
|
||||
- 화면: 목 서버 + 헤드리스 크롬(playwright-core)으로 내 정보(이름 저장 · 머리글 반영 · 색 · 녹음 제외 · 되돌리기) · 관리 페이지(새 버전 링크 · 이름 바꾸기 · 앱 유저 등록) · 모바일 390px 확인, 콘솔 오류 0
|
||||
- 배포: 사이트 서버 다시 배포 (`/site/admin/overview` · `/site/profile/name` 로그인 없이 401, 컨테이너에서 Gitea 최신 릴리스 조회 확인), Windows CI (b9431c1, full) 8개 모두 PASS · 앱 버전 1.6.0 → Gitea 릴리스 v1.6.0 (v1.5.0 · v1.4.3 에 새 버전 안내)
|
||||
|
||||
## v1.11.1 — 앱 게임 연동 탭 Riot ID 표 실시간 갱신 (2026-11-21)
|
||||
|
||||
- 앱 (673f242): `Bus.usersRev`(users.updated 횟수) → `AppState.usersRev` → 게임 연동 탭이 유저 목록을 다시 받고, 고치는 중이 아닌 Riot ID 입력칸을 새 값으로. 앱 테스트 87개 PASS · 타입 검사(앱 · 렌더러) 통과. 렌더러 목(`__gvrMockRename`) + 헤드리스 크롬: 탭을 연 채 `민준#KR1` → `민준바꿈#KR9` 로 바뀜, 입력 중인 칸(서연)은 그대로
|
||||
- 배포: Windows CI (673f242, full) 8개 모두 PASS (앱 smoke 버전 1.11.1) · Gitea 릴리스 v1.11.1 (portable.exe 206,706,031 B · win-x64.zip 302,939,652 B, 올린 파일 sha256 일치) (v1.11.0 ~ v1.8.0 에 새 버전 안내)
|
||||
|
||||
## v1.11.0 — Riot ID 자동 갱신 · 녹음 없는 경기 범인찾기 · 경기 탭 모드/날짜 필터 · 데스매치 숨김 (2026-11-21)
|
||||
|
||||
- 앱 (5e756f9): Riot 클라이언트에 붙으면 바로 · 10분마다 `PUT name-service/v2/players` 로 연결 계정(puuid 아는 것)의 지금 Riot ID 확인 → `game_accounts.riot_id` 갱신 · `users.updated`. `/api/matches` 에 `mode` · `after`, 데스매치 늘 뺌, `GET /api/matches/modes`. 범인찾기 목록 데스매치 뺌, 녹음 없음 · 끊김은 막지 않고 `eligibility.notes` + AI 자료 안내 줄. `LiveGame.historyAt` (Riot 경기 기록 마지막 확인). 앱 테스트 87개 PASS (이름 바뀜 · 필터 · 모드 목록 · 녹음 없는 경기 분석 시험 추가), 타입 검사 통과
|
||||
- 사이트: 경기 탭 모드 선택 · 날짜(시작 ~ 끝) · 초기화, 예전 앱이면 사이트가 데스매치 · 모드 · 날짜를 거름, Riot 경기 기록 확인 안내, 범인찾기 녹음 없음 안내. 사이트 서버 테스트 43개 · 웹 빌드 통과, 목 서버 + 헤드리스 크롬으로 모드 목록(데스매치 없음) · 일반전 16경기만 · 11-18~11-19 거르기 확인 (콘솔 오류 없음)
|
||||
- 배포: 사이트 서버 다시 배포 (번들에 새 문구 · `/api/matches/modes` 로그인 없이 401). Windows CI (cec5e35, full) 8개 모두 PASS (앱 smoke 버전 1.11.0) · Gitea 릴리스 v1.11.0 (portable.exe 206,703,268 B · win-x64.zip 302,940,533 B, 올린 파일 sha256 일치) (v1.10.0 ~ v1.8.0 에 새 버전 안내)
|
||||
|
||||
## v1.10.0 — 3D 리플레이 무기 스킨 · 자동 시점 · Tab 점수판 · 맵 텍스처 1024px (2026-11-20)
|
||||
|
||||
- 변환기: 무기 스킨(스킨 · 단계 · 색상 · 총 장식) 두 번째 읽기 · equips 4번째 열 (96f6957), 점수판 (c36db3e · a5a1c84). 자체 시험 통과, 13.08 어비스 리플레이 스킨 79개 · 조준점 10명 (리눅스 7.0초, Windows CI 8.8초)
|
||||
- 추출기 · 자동 갱신: 맵 텍스처 1024px · `skins` 명령 · `skins-update.sh` 3분 타이머 (0da9939), 타이머 02:00~07:00 제외 (fa99291), uedb 가 늦으면 라이브 매니페스트와 같은 valorant-api.com 매핑 (56242cd). 맵 갱신 시험 18개 · 스킨 갱신 시험 5개 통과
|
||||
- 사이트: 3인칭 · 1인칭 총에 스킨, 없는 스킨 요청 (200dbce · fa99291). 사이트 서버 테스트 43개 통과 · 웹 타입 검사 통과 · 목 서버 + 헤드리스 크롬으로 홀로그램 밴달 · 이온 팬텀 · 고스트 · 홀로그램 칼 1인칭과 3인칭 손의 스킨 총 확인
|
||||
- 배포: 사이트 서버 다시 배포 (`/site/maps3d/skins` · `POST /site/maps3d/skins/want` 로그인 없이 401, 번들에 요청 코드), 맵 재추출 13.10 (매핑 valorant-api.com, 23/23 맵 68분 · 받은 양 2.5GB · 서비스 최대 메모리 약 3GB, 맵 압축 13~56MB · 폴더 818MB), 스킨 타이머 실제 요청 1개 추출 · 반영 확인 (모습 66개). Windows CI (dd9564d, full) 8개 모두 PASS (앱 smoke 버전 1.10.0 · 실제 변환 11.1초 · gzip 1.62MB) · 앱 버전 1.10.0 → Gitea 릴리스 v1.10.0 (portable.exe 206,700,418 B · win-x64.zip 302,935,640 B, 올린 파일 sha256 일치) (v1.9.1 · v1.9.0 · v1.8.2 · v1.8.1 · v1.8.0 에 새 버전 안내, 컨테이너에서 최신 릴리스 v1.10.0 조회 확인)
|
||||
|
||||
## v1.9.1 — 경기 기록 가져오기 진행 바 · 취소 (2026-11-05)
|
||||
|
||||
- 앱 · 사이트: Riot 경기 기록을 가져오는 동안 사이트 경기 탭 · 앱 게임 연동 탭에 목록 확인 중 → 받은 경기 / 받을 경기 · % · 남은 시간 진행 바와 취소 버튼 (63d0e43), 받다가 멈춘 실행(취소 · 게임 시작 · 오류)은 다음 실행이 끝까지 다시 훑고 취소하면 취소한 때부터 한 주기 뒤 재개 (b645d75). 앱 테스트 86개 PASS
|
||||
- 배포: 사이트 서버 다시 배포 (번들에 새 문구 · `POST /api/games/history/cancel` 로그인 없이 401), Windows CI (320cc9b, full) 8개 모두 PASS (실제 리플레이 crosshairs 10, 앱 smoke 버전 1.9.1 · 실제 변환 9.2초 · gzip 1.60MB) · 앱 버전 1.9.1 → Gitea 릴리스 v1.9.1 (portable.exe 206,691,291 B · win-x64.zip 302,930,242 B, 올린 파일 sha256 일치) (v1.9.0 · v1.8.2 · v1.8.1 · v1.8.0 에 새 버전 안내, 컨테이너에서 최신 릴리스 v1.9.1 조회 확인)
|
||||
|
||||
## v1.9.0 — 내 Riot 경기 기록 · 경기 탭 필터 · 게임 중 GPU 아끼기 · 리플레이 파일 없음 (2026-11-04)
|
||||
|
||||
- 앱: 게임 중이 아닐 때 30분마다 발로란트 match-history · 롤 LCU 기록을 훑어 앱이 잡지 못한 경기를 `source=history` 로 저장 (f9fbf4c) · 게임 중 GPU 아끼기 (발로란트 실행 중 · 롤 경기 중 정밀 모델 내림, 실시간 빔 1 · 발화 사이 쉼, 설정 토글 기본 켜짐, 앱 창 하드웨어 가속 끔, 9e1875b)
|
||||
- 사이트: 경기 탭 필터 (전체 / 타임라인 있는 경기 / 목소리 녹음된 경기) · 지난 경기 더 보기 (11db2e5), 3D 리플레이 '리플레이 파일 없음' · 새로고침 버튼 (d0371fa). 사이트는 앱보다 먼저 배포
|
||||
- 배포: Windows CI (b1568db, full) 8개 모두 PASS (변환기 회귀 검사 · 실제 리플레이 crosshairs 10, 앱 smoke 버전 1.9.0 · 실제 변환 11.0초 · gzip 1.60MB) · 앱 버전 1.9.0 → Gitea 릴리스 v1.9.0 (portable.exe 206,687,273 B · win-x64.zip 302,928,085 B, 올린 파일 sha256 일치) (v1.8.2 · v1.8.1 · v1.8.0 에 새 버전 안내)
|
||||
|
||||
## v1.8.2 — 3D 리플레이 선수 조준점 · 내 조준점 설정 (2026-10-29)
|
||||
|
||||
- 변환기: `BombPlayerState` 에 복제된 선수 조준점 프로필을 두 번째 읽기로 뽑아 `players[].crosshair` (`src/Crosshair.cs`). 어비스 13.08 리플레이 10명 모두, 프로필 이름 "1 4 2 0" = 불투명도 1 · 길이 4 · 두께 2 · 간격 0 으로 값 해독 확인. 두 번째 읽기 +0.4초 (리눅스 6.2초)
|
||||
- 회귀 검사 `--self-test`: 조준점 필드 자리(13.08 번호 · 2칸 밀린 패치 · 이름 어긋남) · 기본색 · 사용자 지정 색 추가, 통과
|
||||
- 사이트: 1인칭 "조준점" 버튼 · 설정 창 (선수 조준점 / 모든 선수에 내 조준점, 직접 고치기 · 발로란트 조준점 코드 가져오기 · 선수 조준점 복사). 조준점 코드 읽기 · 시각별 조준점 고르기를 esbuild 로 묶어 node 로 확인
|
||||
- 테스트: 앱 테스트 통과, 화면 타입 검사 · 빌드 통과
|
||||
- 화면: 목 서버 + 헤드리스 크롬으로 새 변환 결과 열어 하늘(1 4 2 0 흰 십자) · 상대5(빨강 굵은 십자 + 점) 선수 조준점, 코드 가져오기(초록 · 외곽선 · 점) · 모든 선수에 내 조준점 저장 확인, 콘솔 오류 0
|
||||
- 배포: 사이트 서버 다시 배포 (화면 번들에 '모든 선수에 내 조준점' 확인), Windows CI (96fb417, full) 8개 모두 PASS (변환기 실제 리플레이 crosshairs 10, 앱 smoke 실제 변환 16.3초 · gzip 1.60MB) · 앱 버전 1.8.2 → Gitea 릴리스 v1.8.2 (v1.8.1 · v1.8.0 · v1.7.0 에 새 버전 안내)
|
||||
|
||||
## v1.8.1 — 변환기: 무기 상태의 주인을 그 시각 주인으로 (2026-10-18)
|
||||
|
||||
- 고침: 무기 상태(재장전 · 사격 등)의 주인을 장비의 마지막 주인으로 정해, 무기를 넘겨받으면 넘기기 전 상태까지 새 주인 것이 되던 문제 → 인벤토리 기록 시간표에서 상태가 생긴 시각의 주인 (`EquipOwners`)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { LiveGame } from './protocol.js';
|
||||
import type { HistoryProgress, LiveGame } from './protocol.js';
|
||||
import { fmtClock } from './time.js';
|
||||
|
||||
export const GAME_NAME: Record<LiveGame['game'], string> = { valorant: '발로란트', lol: '리그 오브 레전드' };
|
||||
@@ -33,3 +33,25 @@ export function liveGameRows(g: LiveGame, now = Date.now()): [string, string][]
|
||||
if (g.error) rows.push(['오류', g.error]);
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** 남은 시간 글자: "약 3분 남음" · "40초 남음" · "남은 시간 계산 중" */
|
||||
export function fmtEta(ms: number | null): string {
|
||||
if (ms == null) return '남은 시간 계산 중';
|
||||
if (ms < 60000) return `${Math.max(1, Math.ceil(ms / 10000) * 10)}초 남음`;
|
||||
const min = Math.ceil(ms / 60000);
|
||||
return min < 60 ? `약 ${min}분 남음` : `약 ${Math.floor(min / 60)}시간 ${min % 60}분 남음`;
|
||||
}
|
||||
|
||||
/** 경기 기록 가져오기 진행 바 글자 (v1.9.1, 사이트 경기 탭 · 앱 게임 연동 탭). pct = null 이면 얼마나 걸릴지 아직 모름 */
|
||||
export function historyStatus(p: HistoryProgress): { title: string; detail: string; pct: number | null } {
|
||||
if (p.phase === 'scan')
|
||||
return { title: '경기 기록 목록 확인 중', detail: `${p.scanned}경기 확인${p.total ? ` · 새 경기 ${p.total}개` : ''}`, pct: null };
|
||||
const pct = p.total ? Math.min(100, Math.round((p.done / p.total) * 100)) : 100;
|
||||
return { title: '경기 기록 가져오는 중', detail: `${p.done} / ${p.total}경기 (${pct}%) · ${fmtEta(p.etaMs)}`, pct };
|
||||
}
|
||||
|
||||
/** 취소한 가져오기를 다시 하는 때: "약 30분 뒤" (모르면 "다음 확인 때") */
|
||||
export function resumeText(resumeAt: number | null, now = Date.now()): string {
|
||||
if (!resumeAt) return '다음 확인 때';
|
||||
return `약 ${Math.max(1, Math.ceil((resumeAt - now) / 60000))}분 뒤`;
|
||||
}
|
||||
|
||||
@@ -165,6 +165,10 @@ export interface MatchSummary {
|
||||
score: { ally: number; enemy: number } | null;
|
||||
status: 'live' | 'pending_detail' | 'complete';
|
||||
participants: string[];
|
||||
/** live: 앱이 켜져 있을 때 잡은 경기 · history: Riot 경기 기록에서 가져온 경기 (v1.9.0 앱부터, 없으면 live) */
|
||||
source?: 'live' | 'history';
|
||||
/** 목소리가 녹음된 경기 (잡음 제외, v1.9.0 앱부터) */
|
||||
voice?: boolean;
|
||||
}
|
||||
|
||||
export interface MatchPlayer {
|
||||
@@ -275,9 +279,30 @@ export interface LiveGame {
|
||||
players: number | null;
|
||||
/** 마지막 오류 (연결 실패 등) */
|
||||
error: string | null;
|
||||
/** Riot 경기 기록 가져오는 중이면 진행 상황 (v1.9.1~, 예전 앱은 없음) */
|
||||
history?: HistoryProgress | null;
|
||||
/** Riot 경기 기록을 마지막으로 끝까지 확인한 때 (v1.11.0~, 아직 한 번도 못 했으면 null) */
|
||||
historyAt?: number | null;
|
||||
updatedAt: number;
|
||||
}
|
||||
|
||||
/** Riot 경기 기록 가져오기 진행 상황 (v1.9.1~). 사이트 경기 탭 · 앱 게임 연동 탭에 진행 바로 보여 준다 */
|
||||
export interface HistoryProgress {
|
||||
/** scan = 경기 목록 훑는 중 (몇 경기를 받을지 아직 모름), fetch = 경기 하나씩 받는 중 */
|
||||
phase: 'scan' | 'fetch';
|
||||
/** 처음 끝까지 훑는 중 (오래 걸림) */
|
||||
first: boolean;
|
||||
/** 경기 목록에서 확인한 경기 수 (scan) */
|
||||
scanned: number;
|
||||
/** 받은 경기 수 / 받을 경기 수 (fetch) */
|
||||
done: number;
|
||||
total: number;
|
||||
/** 시작 시각 (PC 시계) */
|
||||
startedAt: number;
|
||||
/** 남은 시간 예상 (ms). scan 중이거나 아직 모르면 null */
|
||||
etaMs: number | null;
|
||||
}
|
||||
|
||||
/** 기록 묶음 (사이트 기록 관리, v1.3.7~): 경기 하나 또는 경기 밖 대화 한 덩어리 */
|
||||
export interface BundleInfo {
|
||||
/** match-<경기ID> 또는 talk-<첫 발화ID> */
|
||||
@@ -333,6 +358,8 @@ export interface UserProfile {
|
||||
export interface CulpritEligibility {
|
||||
state: 'ready' | 'done' | 'pending' | 'blocked';
|
||||
reasons: string[];
|
||||
/** 분석은 되지만 알려 둘 것 (녹음 없음 · 녹음이 끊김, v1.11.0 앱부터) */
|
||||
notes?: string[];
|
||||
}
|
||||
export interface CulpritPlayer {
|
||||
/** P1~P10 (우리 팀 먼저) */
|
||||
|
||||
@@ -368,7 +368,7 @@ export async function buildServer(
|
||||
});
|
||||
|
||||
// ------------------------------------------------------------------ 발로란트 맵 3D (로그인 필요)
|
||||
registerMaps3d(app, cfg.dataDir, requireSession);
|
||||
registerMaps3d(app, cfg.dataDir, requireSession, cfg.publicUrl);
|
||||
|
||||
app.get('/healthz', async () => 'ok\n');
|
||||
|
||||
|
||||
@@ -13,6 +13,13 @@ import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
|
||||
*
|
||||
* GET /site/maps3d → index.json (없으면 {maps:{}})
|
||||
* GET /site/maps3d/:dir/:f → glb · json · png · jpg (content-encoding gzip). 폴더 이름이 패치마다 바뀌므로 오래 캐시한다
|
||||
*
|
||||
* 무기 스킨 (본 것만 뽑는다, tools/map-extract/scripts/skins-update.sh 가 몇 분마다 요청을 가져가 뽑아 올린다):
|
||||
* <dataDir>/maps3d/skins/index.json {skins:{"스킨|단계|색상":{weapon, sig}}, looks:{서명:{w3p, points, w1p, points1p, gunClips}}, failed:{열쇠:이유}}
|
||||
* <dataDir>/maps3d/skins/skin3p_<서명>.glb.gz · skin1p_<서명>.glb.gz (파일 이름이 모습마다 달라 오래 캐시한다)
|
||||
* <dataDir>/maps3d/skins/want.json 사이트가 받은 요청 (아직 없는 열쇠, 시간 순 · 최대 MAX_WANT)
|
||||
* GET /site/maps3d/skins → skins/index.json (없으면 빈 목록)
|
||||
* POST /site/maps3d/skins/want {keys:[열쇠]} → 없는 것만 want.json 에 더한다
|
||||
*/
|
||||
export interface Maps3dIndex {
|
||||
version: string;
|
||||
@@ -24,7 +31,40 @@ export interface Maps3dIndex {
|
||||
/** 보내는 파일 종류: 3D (맵 · 요원 · 무기 · 스킬 모델 · 공용 애니메이션) · 스킬 목록 · 스킬 텍스처 */
|
||||
const TYPES: Record<string, string> = { '.glb': 'model/gltf-binary', '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg' };
|
||||
|
||||
export function registerMaps3d(app: FastifyInstance, dataDir: string, requireSession: (req: FastifyRequest, reply: FastifyReply) => Promise<unknown>) {
|
||||
/** 스킨 요청 열쇠 "스킨|단계|색상" (게임 데이터 에셋 경로, 단계 · 색상은 비어도 된다). 추출기 Skins.ValidKey 와 같다 */
|
||||
const SKIN_KEY = /^\/Game\/Equippables\/[A-Za-z0-9_/-]+\|(\/Game\/Equippables\/[A-Za-z0-9_/-]+)?\|(\/Game\/Equippables\/[A-Za-z0-9_/-]+)?$/;
|
||||
export const isSkinKey = (k: unknown): k is string => typeof k === 'string' && k.length < 600 && SKIN_KEY.test(k);
|
||||
const MAX_WANT = 2000;
|
||||
const MAX_WANT_PER_REQUEST = 100;
|
||||
|
||||
/** JSON 파일을 mtime 이 바뀔 때만 다시 읽는다 (없거나 깨졌으면 null) */
|
||||
function jsonFile<T>(file: string): () => T | null {
|
||||
let cache: { mtime: number; data: T | null } = { mtime: -1, data: null };
|
||||
return () => {
|
||||
let st: fs.Stats;
|
||||
try {
|
||||
st = fs.statSync(file);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (st.mtimeMs !== cache.mtime) {
|
||||
try {
|
||||
cache = { mtime: st.mtimeMs, data: JSON.parse(fs.readFileSync(file, 'utf8')) as T };
|
||||
} catch {
|
||||
cache = { mtime: st.mtimeMs, data: null };
|
||||
}
|
||||
}
|
||||
return cache.data;
|
||||
};
|
||||
}
|
||||
|
||||
export interface SkinsIndex {
|
||||
skins: Record<string, { weapon: string; sig: string }>;
|
||||
looks: Record<string, { w3p?: string; points?: Record<string, number[]>; w1p?: string; points1p?: Record<string, number[]>; gunClips?: string[] }>;
|
||||
failed?: Record<string, string>;
|
||||
}
|
||||
|
||||
export function registerMaps3d(app: FastifyInstance, dataDir: string, requireSession: (req: FastifyRequest, reply: FastifyReply) => Promise<unknown>, publicUrl?: string) {
|
||||
const root = path.join(dataDir, 'maps3d');
|
||||
let cache: { mtime: number; data: Maps3dIndex | null } = { mtime: -1, data: null };
|
||||
const index = (): Maps3dIndex | null => {
|
||||
@@ -51,6 +91,39 @@ export function registerMaps3d(app: FastifyInstance, dataDir: string, requireSes
|
||||
return index() ?? { version: null, dir: null, maps: {} };
|
||||
});
|
||||
|
||||
const skinsDir = path.join(root, 'skins');
|
||||
const skins = jsonFile<SkinsIndex>(path.join(skinsDir, 'index.json'));
|
||||
app.get('/site/maps3d/skins', async (req, reply) => {
|
||||
if (!(await requireSession(req, reply))) return;
|
||||
reply.header('cache-control', 'private, no-cache');
|
||||
return skins() ?? { skins: {}, looks: {} };
|
||||
});
|
||||
app.post<{ Body: { keys?: unknown } }>('/site/maps3d/skins/want', async (req, reply) => {
|
||||
if (!(await requireSession(req, reply))) return;
|
||||
const origin = String(req.headers.origin || '');
|
||||
if (origin && publicUrl && origin !== publicUrl) return reply.code(403).send({ error: 'bad_origin' });
|
||||
const keys = Array.isArray(req.body?.keys) ? req.body.keys.slice(0, MAX_WANT_PER_REQUEST).filter(isSkinKey) : [];
|
||||
const idx = skins();
|
||||
const file = path.join(skinsDir, 'want.json');
|
||||
let want: string[] = [];
|
||||
try {
|
||||
const w = JSON.parse(fs.readFileSync(file, 'utf8')) as unknown;
|
||||
if (Array.isArray(w)) want = w.filter(isSkinKey);
|
||||
} catch {
|
||||
/* 처음이거나 깨졌으면 새로 */
|
||||
}
|
||||
const have = new Set(want);
|
||||
const add = [...new Set(keys)].filter((k) => !have.has(k) && !idx?.skins?.[k] && !idx?.failed?.[k]);
|
||||
if (add.length === 0) return { queued: 0 };
|
||||
// 다 뽑은 것은 뺀다 (뽑는 쪽은 이 파일을 읽기만 한다)
|
||||
want = [...want.filter((k) => !idx?.skins?.[k] && !idx?.failed?.[k]), ...add].slice(-MAX_WANT);
|
||||
fs.mkdirSync(skinsDir, { recursive: true });
|
||||
fs.writeFileSync(file + '.tmp', JSON.stringify(want));
|
||||
fs.renameSync(file + '.tmp', file);
|
||||
req.log.info({ area: 'skins', add: add.length, total: want.length }, '무기 스킨 요청');
|
||||
return { queued: add.length };
|
||||
});
|
||||
|
||||
app.get<{ Params: { dir: string; file: string } }>('/site/maps3d/:dir/:file', async (req, reply) => {
|
||||
if (!(await requireSession(req, reply))) return;
|
||||
const { dir, file } = req.params;
|
||||
|
||||
@@ -51,7 +51,7 @@ async function stack() {
|
||||
const cb = await fetch(`${base}/auth/discord/callback?code=c&state=${state}`, { headers: { cookie: start.headers.getSetCookie()[0]!.split(';')[0]! }, redirect: 'manual' });
|
||||
return cb.headers.getSetCookie().find((c) => c.startsWith('gvr_sid='))!.split(';')[0]!;
|
||||
};
|
||||
return { base, store, login, close: async () => (await app.close(), dc.close()) };
|
||||
return { base, store, login, dataDir: cfg.dataDir, close: async () => (await app.close(), dc.close()) };
|
||||
}
|
||||
|
||||
test('맵 3D: 로그인 안 하면 목록 · 파일 모두 401', async () => {
|
||||
@@ -91,3 +91,39 @@ test('맵 3D: 로그인하면 목록과 glb 를 받는다 (gzip), 이상한 경
|
||||
await s.close();
|
||||
}
|
||||
});
|
||||
|
||||
test('무기 스킨: 목록 · 파일은 로그인한 사람만, 요청은 없는 것만 want.json 에 쌓인다', async () => {
|
||||
const s = await stack();
|
||||
try {
|
||||
const sk = path.join(s.dataDir, 'maps3d', 'skins');
|
||||
fs.mkdirSync(sk, { recursive: true });
|
||||
const have = '/Game/Equippables/Guns/Rifles/AK/HypeBeast/AssaultRifle_AK_HypeBeast_PrimaryAsset||';
|
||||
const bad = '/Game/Equippables/Melee/Broken/Melee_Broken_PrimaryAsset||';
|
||||
fs.writeFileSync(path.join(sk, 'index.json'), JSON.stringify({ skins: { [have]: { weapon: 'Vandal', sig: 'abc' } }, looks: { abc: { w3p: 'skin3p_abc.glb' } }, failed: { [bad]: '메시 없음' } }));
|
||||
fs.writeFileSync(path.join(sk, 'skin3p_abc.glb.gz'), zlib.gzipSync(Buffer.from('skin')));
|
||||
assert.equal((await fetch(s.base + '/site/maps3d/skins')).status, 401);
|
||||
assert.equal((await fetch(s.base + '/site/maps3d/skins/want', { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{"keys":[]}' })).status, 401);
|
||||
const cookie = await s.login();
|
||||
const idx = (await (await fetch(s.base + '/site/maps3d/skins', { headers: { cookie } })).json()) as any;
|
||||
assert.equal(idx.skins[have].sig, 'abc');
|
||||
const f = await fetch(s.base + '/site/maps3d/skins/skin3p_abc.glb', { headers: { cookie, 'accept-encoding': 'gzip' } });
|
||||
assert.equal(f.status, 200);
|
||||
assert.equal(await f.text(), 'skin');
|
||||
|
||||
const want = (keys: unknown[], origin?: string) =>
|
||||
fetch(s.base + '/site/maps3d/skins/want', { method: 'POST', headers: { cookie, 'content-type': 'application/json', ...(origin ? { origin } : {}) }, body: JSON.stringify({ keys }) });
|
||||
const k1 = '/Game/Equippables/Guns/Rifles/Carbine/SpecOps/Carbine_SpecOps_PrimaryAsset|/Game/Equippables/Guns/Rifles/Carbine/SpecOps/Levels/Carbine_SpecOps_Lv2_PrimaryAsset|';
|
||||
// 이미 있는 것 · 실패한 것 · 형식이 틀린 것은 넣지 않는다
|
||||
const r = await want([k1, have, bad, '../../etc/passwd||', 7, k1]);
|
||||
assert.equal(r.status, 200);
|
||||
assert.deepEqual(await r.json(), { queued: 1 });
|
||||
assert.deepEqual(JSON.parse(fs.readFileSync(path.join(sk, 'want.json'), 'utf8')), [k1]);
|
||||
// 같은 것을 다시 요청하면 그대로
|
||||
assert.deepEqual(await (await want([k1])).json(), { queued: 0 });
|
||||
// 다른 사이트에서 온 요청은 막는다
|
||||
assert.equal((await want([k1.replace('Lv2', 'Lv3')], 'https://evil.example')).status, 403);
|
||||
assert.deepEqual(JSON.parse(fs.readFileSync(path.join(sk, 'want.json'), 'utf8')), [k1]);
|
||||
} finally {
|
||||
await s.close();
|
||||
}
|
||||
});
|
||||
|
||||
182
site/server/test/replay-director.test.ts
Normal file
182
site/server/test/replay-director.test.ts
Normal file
@@ -0,0 +1,182 @@
|
||||
// 사이트 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, sideSwaps, teamScoreAt } from '../../web/src/lib/scoreboard.ts';
|
||||
import { fitDistance } from '../../web/src/lib/director.ts';
|
||||
import * as THREE from '../../web/node_modules/three/build/three.module.js';
|
||||
|
||||
// 선수 0·1·4 아군, 2·3·5 상대. 라운드 1: 구매 0~30초, 교전 30초~, 끝 90초. 라운드 2: 100초~ (공수 교대: 시작 자리가 100m 옮겨 감)
|
||||
const still = (n = 2000, swapAt = 100_000) => {
|
||||
const t = Array.from({ length: n }, (_, i) => i * 100);
|
||||
return { t, x: t.map((v) => (v >= swapAt ? 10_000 : 0)), y: t.map(() => 0), z: t.map(() => 100), yaw: t.map(() => 0), pitch: t.map(() => 0) };
|
||||
};
|
||||
function replay(extra: Partial<ReplayFile> = {}): 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 });
|
||||
});
|
||||
|
||||
test('점수판: 한 명만 궁 점수가 있어도 공수 교대 초기화는 궁 사용이 아니다 · 교대가 없으면 라운드 끝 0 은 사용', () => {
|
||||
// 선수 1(피닉스)만 3점을 모은 채 1라운드가 끝나고(90초) 2라운드 구매 시작(100초) 직전에 0
|
||||
const sb = [[20_000, 1, 800, 3, -1, -1, -1, -1], [99_000, 1, 800, 0, -1, -1, -1, -1]];
|
||||
const r = replay({ scoreboard: sb });
|
||||
assert.deepEqual([...sideSwaps(r)], [1]);
|
||||
const ix = boardIndex(r);
|
||||
assert.equal(ix.ultMax[1], 7); // 요원 표 (피닉스 7), 3 이 아니다
|
||||
assert.equal(boardAt(r, ix, 1, 50_000).ult, 3);
|
||||
// 같은 기록이라도 교대가 아니면(시작 자리 그대로) 쓴 것으로 본다
|
||||
const same = replay({ scoreboard: sb, players: [0, 1, 2, 3, 4, 5].map((i) => ({ puuid: `p${i}`, character: 'Phoenix_PC_C', track: still(2000, Infinity) })) });
|
||||
assert.deepEqual([...sideSwaps(same)], []);
|
||||
assert.equal(boardIndex(same).ultMax[1], 3);
|
||||
});
|
||||
|
||||
test('점수판: 마지막 라운드가 끝난 뒤에는 최종 점수', () => {
|
||||
const r = replay({ rounds: [{ num: 1, buy: 0, combat: 30_000, end: 90_000 }, { num: 2, buy: 100_000, combat: 130_000, end: 180_000 }] });
|
||||
const rounds = [{ num: 1, score: { ally: 1, enemy: 0 } }, { num: 2, score: { ally: 2, enemy: 0 } }];
|
||||
assert.deepEqual(teamScoreAt(r, rounds, 170_000), { round: 2, ally: 1, enemy: 0 });
|
||||
assert.deepEqual(teamScoreAt(r, rounds, 190_000), { round: 2, ally: 2, enemy: 0 });
|
||||
// 1라운드 끝 ~ 2라운드 구매 사이도 그 라운드 결과까지
|
||||
assert.deepEqual(teamScoreAt(r, rounds, 95_000), { round: 1, ally: 1, enemy: 0 });
|
||||
});
|
||||
|
||||
test('전략 보기 카메라: 시야각 · 화면비 · 기울기를 넣어 구한 거리면 모든 선수가 화면 안 (three.js 투영으로 확인)', () => {
|
||||
const dir: [number, number, number] = [0, 0.92 / Math.hypot(0.92, 0.42), 0.42 / Math.hypot(0.92, 0.42)];
|
||||
const cases: { pts: [number, number, number][]; aspect: number }[] = [
|
||||
{ pts: [[-35, 0, -40], [35, 0, 40]], aspect: 1 },
|
||||
{ pts: [[-45, 2, 10], [40, 8, -45], [0, 0, 48]], aspect: 16 / 9 },
|
||||
{ pts: [[-10, 0, -45], [10, 0, 45]], aspect: 0.6 },
|
||||
];
|
||||
for (const { pts, aspect } of cases) {
|
||||
const c = pts.reduce((a, p) => [a[0] + p[0] / pts.length, a[1] + p[1] / pts.length, a[2] + p[2] / pts.length], [0, 0, 0]) as [number, number, number];
|
||||
const d = fitDistance(pts, c, dir, 45, aspect);
|
||||
const cam = new THREE.PerspectiveCamera(45, aspect, 0.5, 2000);
|
||||
cam.position.set(c[0] + dir[0] * d, c[1] + dir[1] * d, c[2] + dir[2] * d);
|
||||
cam.lookAt(c[0], c[1], c[2]);
|
||||
cam.updateMatrixWorld();
|
||||
let edge = 0;
|
||||
for (const p of pts) {
|
||||
const v = new THREE.Vector3(...p).project(cam);
|
||||
assert.ok(Math.abs(v.x) <= 0.86 && Math.abs(v.y) <= 0.86, `화면 밖 ${p} → ${v.x.toFixed(3)},${v.y.toFixed(3)} (화면비 ${aspect})`);
|
||||
edge = Math.max(edge, Math.abs(v.x), Math.abs(v.y));
|
||||
}
|
||||
// 가장 짧은 거리: 가장 바깥 선수가 가장자리(0.85)에 닿는다
|
||||
assert.ok(edge > 0.84, `너무 멀다 ${edge}`);
|
||||
}
|
||||
});
|
||||
56
site/server/test/replay-skins.test.ts
Normal file
56
site/server/test/replay-skins.test.ts
Normal file
@@ -0,0 +1,56 @@
|
||||
// 사이트 3D 리플레이: 무기 스킨 찾기 (site/web/src/lib/skins.ts · replay.ts skinTracks)
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { equipAt, skinTracks, type ReplayFile, type SkinInfo } from '../../web/src/lib/replay.ts';
|
||||
import { chunks, isDefaultSkin, lookOf, missingSkins, skinKey, WANT_CHUNK } from '../../web/src/lib/skins.ts';
|
||||
|
||||
const hype: SkinInfo = {
|
||||
skin: '/Game/Equippables/Guns/Rifles/AK/HypeBeast/AssaultRifle_AK_HypeBeast_PrimaryAsset',
|
||||
level: '/Game/Equippables/Guns/Rifles/AK/HypeBeast/AssaultRifle_AK_HypeBeast_Lv4_PrimaryAsset',
|
||||
chroma: '/Game/Equippables/Guns/Rifles/AK/HypeBeast/Chromas/Blue/AssaultRifle_AK_HypeBeast_Blue_PrimaryAsset',
|
||||
};
|
||||
const knife: SkinInfo = { skin: '/Game/Equippables/Melee/Standard/Melee_Base_Standard_PrimaryAsset', level: null, chroma: '/Game/Equippables/Melee/Standard/Chromas/Standard/Melee_Base_Standard_Standard_PrimaryAsset' };
|
||||
const ghost: SkinInfo = { skin: '/Game/Equippables/Guns/Sidearms/Luger/Sovereign/Luger_Sovereign_PrimaryAsset', level: null, chroma: null };
|
||||
|
||||
test('스킨: 선수가 그 시각에 든 총의 스킨 (주운 총은 그 총의 스킨, 옛 JSON 은 -1)', () => {
|
||||
const r = {
|
||||
players: [{}, {}],
|
||||
skins: [hype, ghost],
|
||||
// 선수 0: 1초 밴달(hype) · 5초 칼(스킨 기록 없음) · 9초 주운 고스트. 선수 1: 옛 3열 줄
|
||||
equips: [[1000, 0, 0, 0], [5000, 0, 1, -1], [9000, 0, 2, 1], [2000, 1, 0]],
|
||||
} as unknown as ReplayFile;
|
||||
const tr = skinTracks(r);
|
||||
assert.equal(equipAt(tr[0], 500), -1);
|
||||
assert.equal(equipAt(tr[0], 3000), 0);
|
||||
assert.equal(equipAt(tr[0], 6000), -1);
|
||||
assert.equal(equipAt(tr[0], 9500), 1);
|
||||
assert.equal(equipAt(tr[1], 3000), -1);
|
||||
});
|
||||
|
||||
test('스킨: 뽑아 둔 것은 그 모습, 기본 스킨 · 없는 것은 null, 없는 것만 요청 목록에', () => {
|
||||
assert.equal(isDefaultSkin(knife), true);
|
||||
assert.equal(isDefaultSkin(hype), false);
|
||||
assert.equal(isDefaultSkin({ skin: '/Game/Equippables/Guns/Sidearms/Compact/Compact_Standard_PrimaryAsset', level: null, chroma: null }), true);
|
||||
const idx = {
|
||||
skins: { [skinKey(hype)]: { weapon: 'Vandal', sig: 's1' } },
|
||||
looks: { s1: { w3p: 'skin3p_s1.glb', w1p: 'skin1p_s1.glb' } },
|
||||
failed: {} as Record<string, string>,
|
||||
};
|
||||
assert.equal(lookOf(idx, hype)?.w3p, 'skin3p_s1.glb');
|
||||
assert.equal(lookOf(idx, ghost), null);
|
||||
assert.equal(lookOf(idx, knife), null);
|
||||
// 같은 스킨이 여러 번 나와도 한 번, 기본 스킨은 요청하지 않는다
|
||||
assert.deepEqual(missingSkins(idx, { skins: [hype, ghost, knife, { ...ghost }] }), [skinKey(ghost)]);
|
||||
// 뽑다 실패한 것은 다시 요청하지 않는다
|
||||
idx.failed[skinKey(ghost)] = '메시 없음';
|
||||
assert.deepEqual(missingSkins(idx, { skins: [ghost] }), []);
|
||||
assert.equal(skinKey(ghost), '/Game/Equippables/Guns/Sidearms/Luger/Sovereign/Luger_Sovereign_PrimaryAsset||');
|
||||
});
|
||||
|
||||
test('스킨 요청: 서버 한도(100개)씩 나눠 빠짐없이', () => {
|
||||
const keys = Array.from({ length: 2 * WANT_CHUNK + 1 }, (_, i) => `k${i}`);
|
||||
const parts = chunks(keys);
|
||||
assert.deepEqual(parts.map((p) => p.length), [100, 100, 1]);
|
||||
assert.deepEqual(parts.flat(), keys);
|
||||
assert.deepEqual(chunks([]), []);
|
||||
});
|
||||
@@ -580,6 +580,34 @@ function genReplayDemo(file) {
|
||||
}
|
||||
if (process.env.GVR_MOCK_REPLAY) genReplayDemo(process.env.GVR_MOCK_REPLAY);
|
||||
|
||||
// Riot 경기 기록에서 가져온 경기 (v1.9.0, 겜녹이가 꺼져 있을 때 한 경기): 녹음 · 타임라인 없음
|
||||
{
|
||||
const base = matches.find((m) => m.game === 'valorant');
|
||||
const MAPS = ['어센트', '바인드', '헤이븐', '로터스', '선셋'];
|
||||
for (let i = 0; i < 70; i++) {
|
||||
const start = NOW - (1 + i * 0.37) * 24 * 60 * MIN;
|
||||
const ally = 13;
|
||||
const enemy = (i * 5) % 12;
|
||||
const win = i % 3 !== 0;
|
||||
matches.push({
|
||||
...base,
|
||||
id: `val-hist-${i}`,
|
||||
startedAt: start,
|
||||
endedAt: start + 38 * MIN,
|
||||
map: { ...base.map, name: MAPS[i % MAPS.length] },
|
||||
mode: i % 7 === 3 ? '데스매치' : i % 4 === 0 ? '일반전' : '경쟁전',
|
||||
win,
|
||||
score: win ? { ally, enemy } : { ally: enemy, enemy: ally },
|
||||
status: 'complete',
|
||||
participants: [],
|
||||
source: 'history',
|
||||
utterances: [],
|
||||
events: [],
|
||||
replayPath: undefined,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// ── 내보내기 ─────────────────────────────────────────
|
||||
export const db = {
|
||||
users: USERS,
|
||||
|
||||
@@ -39,7 +39,22 @@ const state = {
|
||||
device: { registered: true, online: process.env.MOCK_OFFLINE !== '1', name: '하늘의 게임 PC', lastSeen: Date.now(), version: '1.0.0' },
|
||||
live: process.env.MOCK_LIVE !== '0',
|
||||
liveInterval: Number(process.env.MOCK_LIVE_INTERVAL ?? 15000),
|
||||
// 롤 경기 기록 가져오기 흉내 (v1.9.1 진행 바): 1.5초에 한 경기, MOCK_HISTORY=0 이면 끔
|
||||
hist: process.env.MOCK_HISTORY === '0' ? null : { startedAt: Date.now(), total: Number(process.env.MOCK_HISTORY_TOTAL ?? 120) },
|
||||
};
|
||||
const histProgress = () => {
|
||||
const h = state.hist;
|
||||
if (!h) return null;
|
||||
const el = Date.now() - h.startedAt;
|
||||
if (el < 4000) return { phase: 'scan', first: true, scanned: Math.floor(el / 400) * 20, done: 0, total: Math.floor(el / 400) * 12, startedAt: h.startedAt, etaMs: null };
|
||||
const done = Math.min(h.total, Math.floor((el - 4000) / 1500));
|
||||
if (done >= h.total) return (state.hist = null);
|
||||
return { phase: 'fetch', first: true, scanned: 200, done, total: h.total, startedAt: h.startedAt, etaMs: done ? (h.total - done) * 1500 : null };
|
||||
};
|
||||
const liveGames = () => [
|
||||
{ game: 'valorant', enabled: true, connected: true, phase: '경기 중', inMatch: true, matchId: 'val-demo', mode: '경쟁전', map: '어센트', mapImage: null, startedAt: Date.now() - 23 * 60000, round: 15, score: { ally: 8, enemy: 6 }, gameTimeSec: null, teamKills: null, self: { name: '하늘#KR1', character: '제트', characterImage: null, kda: null, extra: null }, players: 10, error: null, historyAt: Date.now() - 12 * 60000, updatedAt: Date.now() },
|
||||
{ game: 'lol', enabled: true, connected: !!state.hist, phase: state.hist ? '로비' : '롤 클라이언트 꺼짐', inMatch: false, matchId: null, mode: null, map: null, mapImage: null, startedAt: null, round: null, score: null, gameTimeSec: null, teamKills: null, self: null, players: null, error: null, history: histProgress(), historyAt: null, updatedAt: Date.now() },
|
||||
];
|
||||
|
||||
const json = (res, status, body, headers = {}) => {
|
||||
const s = JSON.stringify(body, (k, v) => (k.startsWith('_') ? undefined : v));
|
||||
@@ -115,7 +130,10 @@ function timeline(q) {
|
||||
return { items: page, next: items.length > limit ? enc(page[page.length - 1]) : null };
|
||||
}
|
||||
|
||||
const summary = (m) => ({ id: m.id, game: m.game, startedAt: m.startedAt, endedAt: m.endedAt, map: m.map, mode: m.mode, win: m.win, score: m.score, status: m.status, participants: m.participants });
|
||||
const summary = (m) => ({
|
||||
id: m.id, game: m.game, startedAt: m.startedAt, endedAt: m.endedAt, map: m.map, mode: m.mode, win: m.win, score: m.score, status: m.status, participants: m.participants,
|
||||
source: m.source ?? 'live', voice: m.utterances.length > 0,
|
||||
});
|
||||
|
||||
function userProfile(id) {
|
||||
const user = db.users.find((u) => u.id === id);
|
||||
@@ -200,6 +218,12 @@ async function handle(req, res) {
|
||||
const root = process.env.GVR_MOCK_MAPS3D;
|
||||
if (!root) return p === '/site/maps3d' ? json(res, 200, { version: null, dir: null, maps: {} }) : json(res, 404, { error: 'not_found' });
|
||||
if (p === '/site/maps3d') return json(res, 200, JSON.parse(fs.readFileSync(path.join(root, 'index.json'), 'utf8')));
|
||||
// 무기 스킨: <폴더>/skins/index.json (없으면 빈 목록), 요청은 받기만 한다 (뽑는 쪽이 없다)
|
||||
if (p === '/site/maps3d/skins') {
|
||||
const f = path.join(root, 'skins', 'index.json');
|
||||
return json(res, 200, fs.existsSync(f) ? JSON.parse(fs.readFileSync(f, 'utf8')) : { skins: {}, looks: {} });
|
||||
}
|
||||
if (p === '/site/maps3d/skins/want') return json(res, 200, { queued: 0 });
|
||||
const [dir, file] = p.slice('/site/maps3d/'.length).split('/').map(decodeURIComponent);
|
||||
const f = path.join(root, dir ?? '', (file ?? '') + '.gz');
|
||||
const type = { '.glb': 'model/gltf-binary', '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg' }[path.extname(file ?? '').toLowerCase()];
|
||||
@@ -300,10 +324,7 @@ async function handle(req, res) {
|
||||
recording: { active: true, channel: '발로 음성방', since: NOW - 150 * 60000, participants: db.SPEAKERS.map((u) => u.id) },
|
||||
users: db.users,
|
||||
games: { valorant: { connected: true, inMatch: false }, lol: { connected: false, inMatch: false } },
|
||||
live: [
|
||||
{ game: 'valorant', enabled: true, connected: true, phase: '경기 중', inMatch: true, matchId: 'val-demo', mode: '경쟁전', map: '어센트', mapImage: null, startedAt: Date.now() - 23 * 60000, round: 15, score: { ally: 8, enemy: 6 }, gameTimeSec: null, teamKills: null, self: { name: '하늘#KR1', character: '제트', characterImage: null, kda: null, extra: null }, players: 10, error: null, updatedAt: Date.now() },
|
||||
{ game: 'lol', enabled: true, connected: false, phase: '롤 클라이언트 꺼짐', inMatch: false, matchId: null, mode: null, map: null, mapImage: null, startedAt: null, round: null, score: null, gameTimeSec: null, teamKills: null, self: null, players: null, error: null, updatedAt: Date.now() },
|
||||
],
|
||||
live: liveGames(),
|
||||
counts: { utterances: db.utterances.length, matches: db.matches.length },
|
||||
version: '1.0.0',
|
||||
});
|
||||
@@ -335,9 +356,28 @@ async function handle(req, res) {
|
||||
const game = q.get('game');
|
||||
const before = q.get('before') ? Number(q.get('before')) : Infinity;
|
||||
const limit = Number(q.get('limit') ?? 20);
|
||||
const list = db.matches.filter((x) => (!game || x.game === game) && x.startedAt < before).sort((a, b) => b.startedAt - a.startedAt).slice(0, limit).map(summary);
|
||||
const has = q.get('has');
|
||||
const keep = (x) => (has === 'voice' ? x.utterances.length > 0 : has === 'timeline' ? x.source !== 'history' || x.utterances.length > 0 : true);
|
||||
// 모드 · 날짜 필터, 데스매치는 늘 뺀다 (v1.11.0 앱과 같게)
|
||||
const mode = q.get('mode');
|
||||
const after = q.get('after') ? Number(q.get('after')) : 0;
|
||||
const list = db.matches
|
||||
.filter((x) => (!game || x.game === game) && x.startedAt < before && x.startedAt >= after && keep(x) && x.mode !== '데스매치' && (!mode || x.mode === mode))
|
||||
.sort((a, b) => b.startedAt - a.startedAt)
|
||||
.slice(0, limit)
|
||||
.map(summary);
|
||||
return json(res, 200, list);
|
||||
}
|
||||
if (p === '/api/matches/modes') {
|
||||
const game = q.get('game');
|
||||
const by = new Map();
|
||||
for (const x of db.matches) {
|
||||
if (x.mode === '데스매치' || (game && x.game !== game)) continue;
|
||||
const k = `${x.game}\n${x.mode}`;
|
||||
by.set(k, { game: x.game, mode: x.mode, count: (by.get(k)?.count ?? 0) + 1 });
|
||||
}
|
||||
return json(res, 200, [...by.values()].sort((a, b) => b.count - a.count));
|
||||
}
|
||||
if ((m = p.match(/^\/api\/matches\/([^/]+)$/))) {
|
||||
const mt = db.matches.find((x) => x.id === decodeURIComponent(m[1]));
|
||||
if (!mt) return json(res, 404, { error: 'not_found' });
|
||||
@@ -347,7 +387,8 @@ async function handle(req, res) {
|
||||
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' });
|
||||
// 파일을 지웠다가 다시 두면 "리플레이 없음 → 내려받고 새로고침" 을 흉내 낼 수 있다
|
||||
if (!mt.replayPath || !fs.existsSync(mt.replayPath)) return json(res, 404, { error: 'replay_not_found' });
|
||||
res.writeHead(200, { 'content-type': 'application/json' });
|
||||
return fs.createReadStream(mt.replayPath).pipe(res);
|
||||
}
|
||||
@@ -416,6 +457,12 @@ async function handle(req, res) {
|
||||
}
|
||||
return json(res, 200, { bundles: out.sort((a, b) => b.from - a.from) });
|
||||
}
|
||||
if (p === '/api/games/history/cancel' && req.method === 'POST') {
|
||||
const was = !!histProgress();
|
||||
state.hist = null;
|
||||
broadcast({ type: 'games.state', data: liveGames() });
|
||||
return json(res, 200, { ok: true, cancelled: was ? ['lol'] : [], resumeAt: was ? Date.now() + 30 * 60000 : null });
|
||||
}
|
||||
if (p === '/api/bundles/delete' && req.method === 'POST') return json(res, 200, { bundles: 1, utterances: 12, files: 12 });
|
||||
if (p === '/api/bundles/export' && req.method === 'POST') {
|
||||
req.resume();
|
||||
@@ -485,10 +532,17 @@ export function startMock({ port = Number(process.env.MOCK_PORT ?? 18787) } = {}
|
||||
if (state.live && wss.clients.size) emitLive();
|
||||
}, state.liveInterval);
|
||||
const hb = setInterval(() => deviceOk() && pushStatus(), 20000);
|
||||
// 경기 기록 가져오기 진행 (앱은 2초마다 바뀌면 보낸다)
|
||||
const histTimer = setInterval(() => {
|
||||
if (!wss.clients.size) return;
|
||||
const had = !!state.hist;
|
||||
if (had) broadcast({ type: 'games.state', data: liveGames() });
|
||||
}, 2000);
|
||||
server.listen(port, '127.0.0.1', () => console.log(`[mock] http://127.0.0.1:${port} (데이터: 발화 ${db.utterances.length} · 이벤트 ${db.events.length} · 경기 ${db.matches.length} · 기준 ${fmtClock(0)})`));
|
||||
server.on('close', () => {
|
||||
clearInterval(timer);
|
||||
clearInterval(hb);
|
||||
clearInterval(histTimer);
|
||||
});
|
||||
return server;
|
||||
}
|
||||
|
||||
100
site/web/src/components/HistoryImport.tsx
Normal file
100
site/web/src/components/HistoryImport.tsx
Normal file
@@ -0,0 +1,100 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import { GAME_NAME, historyStatus, resumeText, type GameType } from '@gvr/shared';
|
||||
import { api } from '../lib/api';
|
||||
import { fmtWhen } from '../lib/format';
|
||||
import { useData } from '../store/app';
|
||||
|
||||
/**
|
||||
* Riot 경기 기록 가져오기 진행 바 (v1.9.1, 경기 탭 위). 게임 PC 앱이 게임 중이 아닐 때 30분마다 지난 경기를 받아 온다.
|
||||
* 받을 경기 수 · 남은 시간을 보여 주고 취소할 수 있다. 끝나면 onDone 으로 경기 목록을 다시 받게 한다.
|
||||
*/
|
||||
export function HistoryImport({ onDone }: { onDone: () => void }) {
|
||||
const { overview } = useData();
|
||||
const rows = (overview?.live ?? []).filter((g) => g.history);
|
||||
const [busy, setBusy] = useState<GameType | null>(null);
|
||||
const [msg, setMsg] = useState<{ text: string; bad?: boolean } | null>(null);
|
||||
// 가져오기가 끝나거나 멈추면 경기 목록을 새로
|
||||
const active = rows.map((g) => g.game).join(',');
|
||||
const prev = useRef(active);
|
||||
useEffect(() => {
|
||||
const now = active.split(',');
|
||||
if (prev.current.split(',').some((g) => g && !now.includes(g))) onDone();
|
||||
prev.current = active;
|
||||
}, [active, onDone]);
|
||||
const cancel = (game: GameType) => {
|
||||
setBusy(game);
|
||||
setMsg(null);
|
||||
api
|
||||
.cancelHistory(game)
|
||||
.then((r) => {
|
||||
if (r.cancelled.length) setMsg({ text: `${GAME_NAME[game]} 경기 기록 가져오기를 멈췄습니다. 받은 경기는 그대로 있고, ${resumeText(r.resumeAt)} 남은 것부터 이어서 가져옵니다.` });
|
||||
})
|
||||
.catch((e) => setMsg({ text: `취소하지 못했습니다: ${e instanceof Error ? e.message : String(e)}`, bad: true }))
|
||||
.finally(() => setBusy(null));
|
||||
};
|
||||
if (!rows.length && !msg) return null;
|
||||
return (
|
||||
<div className="hist-import">
|
||||
{rows.map((g) => {
|
||||
const st = historyStatus(g.history!);
|
||||
return (
|
||||
<div key={g.game} className={`hist-card ${g.game}`} role="status">
|
||||
<div className="hist-top">
|
||||
<span className="hist-dot" />
|
||||
<b>{GAME_NAME[g.game]}</b>
|
||||
<span>{st.title}</span>
|
||||
<span className="dim small">{st.detail}</span>
|
||||
<span className="hist-gap" />
|
||||
<button className="btn small" disabled={busy === g.game} onClick={() => cancel(g.game)}>
|
||||
{busy === g.game ? '멈추는 중…' : '취소'}
|
||||
</button>
|
||||
</div>
|
||||
<span className={`bar hist-bar${st.pct == null ? ' indet' : ''}`}>
|
||||
<i style={st.pct == null ? undefined : { width: `${st.pct}%` }} />
|
||||
</span>
|
||||
<div className="dim small">
|
||||
{g.history!.first ? '처음 한 번은 지난 경기를 끝까지 가져와서 오래 걸립니다. ' : ''}
|
||||
게임을 켜면 바로 멈추고, 끝나면 이 목록에 자동으로 나타납니다.
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{msg && (
|
||||
<div className={`hist-msg${msg.bad ? ' bad' : ''}`}>
|
||||
{msg.text}
|
||||
<button className="btn small" onClick={() => setMsg(null)}>
|
||||
닫기
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Riot 경기 기록을 언제 확인했는지 (v1.11.0 앱부터, 경기 탭). 앱이 꺼져 있던 때 한 경기는 이 PC 에서 Riot 클라이언트에
|
||||
* 로그인해 있어야 가져올 수 있어서, 아직 못 가져왔으면 그 방법을 알려 준다. 가져오는 중이면 위 진행 바가 대신 보인다.
|
||||
*/
|
||||
export function HistoryHint() {
|
||||
const { overview } = useData();
|
||||
const rows = (overview?.live ?? []).filter((g) => g.enabled && !g.history && g.historyAt !== undefined);
|
||||
if (!rows.length) return null;
|
||||
return (
|
||||
<div className="hist-hint dim small">
|
||||
{rows.map((g) => {
|
||||
const client = g.game === 'valorant' ? 'Riot 클라이언트' : '롤 클라이언트';
|
||||
const text =
|
||||
g.historyAt != null
|
||||
? `Riot 경기 기록 ${fmtWhen(g.historyAt)} 확인${g.connected ? ' · 30분마다 새 경기를 가져옵니다' : ` · ${client}를 켜면 그사이 한 경기를 가져옵니다`}`
|
||||
: g.connected
|
||||
? '앱이 꺼져 있던 때 한 경기를 곧 가져옵니다'
|
||||
: `앱이 꺼져 있던 때 한 경기는 아직 못 가져왔습니다. 이 PC 에서 ${client}에 로그인해 두면 자동으로 가져옵니다`;
|
||||
return (
|
||||
<div key={g.game}>
|
||||
<b>{GAME_NAME[g.game]}</b> {text}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -14,6 +14,8 @@ export function ReplayPanel({ m }: { m: MatchDetail }) {
|
||||
const [replay, setReplay] = useState<ReplayFile | null>(null);
|
||||
const [err, setErr] = useState<unknown>(null);
|
||||
const [converting, setConverting] = useState(false);
|
||||
// 새로고침을 누를 때마다 1씩 올려 리플레이를 다시 묻는다
|
||||
const [reload, setReload] = useState(0);
|
||||
useEffect(() => {
|
||||
if (!open || replay) return;
|
||||
let alive = true;
|
||||
@@ -22,7 +24,7 @@ export function ReplayPanel({ m }: { m: MatchDetail }) {
|
||||
// 처음 열면 게임 PC 가 리플레이를 변환한다 (보통 10초 안팎). 변환 중(202)이면 3초 뒤 다시 묻는다 (5분까지)
|
||||
const ask = (tries: number) =>
|
||||
api
|
||||
.replay(m.id)
|
||||
.replay(m.id, reload > 0)
|
||||
.then((r) => {
|
||||
if (!alive) return;
|
||||
if ('status' in r && r.status === 'converting') {
|
||||
@@ -46,12 +48,17 @@ export function ReplayPanel({ m }: { m: MatchDetail }) {
|
||||
alive = false;
|
||||
if (timer) clearTimeout(timer);
|
||||
};
|
||||
}, [open, m.id, replay]);
|
||||
}, [open, m.id, replay, reload]);
|
||||
const sync = useMemo(() => (replay ? computeSync(m, replay) : null), [m, replay]);
|
||||
// replay_not_found: 앱이 리플레이를 못 찾음. 다른 404: 이 앱 버전에는 리플레이 기능이 아직 없음
|
||||
const missing = err instanceof ApiError && err.status === 404 && err.code === 'replay_not_found';
|
||||
const appTooOld = err instanceof ApiError && err.status === 404 && err.code === 'Not Found'; // Fastify 기본 404 (경로 없음)
|
||||
const failed = err instanceof ApiError && err.status === 422 && err.code === 'replay_failed';
|
||||
const refresh = (
|
||||
<button className="mini-btn" onClick={() => setReload((n) => n + 1)}>
|
||||
새로고침
|
||||
</button>
|
||||
);
|
||||
return (
|
||||
<Panel
|
||||
className={`replay-panel${open ? ' open' : ''}`}
|
||||
@@ -67,15 +74,31 @@ export function ReplayPanel({ m }: { m: MatchDetail }) {
|
||||
발로란트에서 이 경기 리플레이를 내려받으면 선수 10명의 움직임을 3D로 보면서 그때 나눈 대화를 같이 들을 수 있습니다.
|
||||
</div>
|
||||
) : missing ? (
|
||||
<div className="dim small">
|
||||
이 경기 리플레이가 아직 없습니다. 발로란트 경력 탭에서 이 경기의 리플레이를 내려받으면 게임 PC 앱이 찾아서 변환합니다 (몇 초 걸림).
|
||||
<div className="replay-msg">
|
||||
<div>
|
||||
<b>리플레이 파일 없음</b>
|
||||
<div className="dim small">
|
||||
게임 PC 에 이 경기의 리플레이 파일이 없습니다. 발로란트 경력 탭에서 이 경기의 리플레이를 내려받은 뒤 새로고침을 누르면 게임 PC 앱이 찾아서
|
||||
변환합니다 (몇 초 걸림).
|
||||
</div>
|
||||
</div>
|
||||
{refresh}
|
||||
</div>
|
||||
) : appTooOld ? (
|
||||
<div className="dim small">지금 게임 PC 앱 버전은 아직 리플레이를 보내지 않습니다. 리플레이 자동 변환이 들어간 앱으로 업데이트하면 볼 수 있습니다.</div>
|
||||
<div className="replay-msg">
|
||||
<div className="dim small">지금 게임 PC 앱 버전은 아직 리플레이를 보내지 않습니다. 리플레이 자동 변환이 들어간 앱으로 업데이트하면 볼 수 있습니다.</div>
|
||||
{refresh}
|
||||
</div>
|
||||
) : failed ? (
|
||||
<div className="dim small">게임 PC 가 이 경기 리플레이를 변환하지 못했습니다. 발로란트 패치로 리플레이 형식이 바뀌었을 수 있습니다. ({(err as ApiError).detail ?? '이유 모름'})</div>
|
||||
<div className="replay-msg">
|
||||
<div className="dim small">게임 PC 가 이 경기 리플레이를 변환하지 못했습니다. 발로란트 패치로 리플레이 형식이 바뀌었을 수 있습니다. ({(err as ApiError).detail ?? '이유 모름'})</div>
|
||||
{refresh}
|
||||
</div>
|
||||
) : err ? (
|
||||
<div className="dim small">리플레이를 불러오지 못했습니다: {err instanceof Error ? err.message : String(err)}</div>
|
||||
<div className="replay-msg">
|
||||
<div className="dim small">리플레이를 불러오지 못했습니다: {err instanceof Error ? err.message : String(err)}</div>
|
||||
{refresh}
|
||||
</div>
|
||||
) : !replay || !sync ? (
|
||||
<Spinner label={converting ? '게임 PC 가 리플레이를 변환하는 중 (처음 한 번, 10초 안팎)' : '리플레이 불러오는 중'} />
|
||||
) : (
|
||||
|
||||
78
site/web/src/components/ReplayScoreboard.tsx
Normal file
78
site/web/src/components/ReplayScoreboard.tsx
Normal file
@@ -0,0 +1,78 @@
|
||||
import type { MatchDetail, MatchPlayer } from '@gvr/shared';
|
||||
import { equipLabel, type ReplayFile } from '../lib/replay';
|
||||
import { boardAt, teamScoreAt, type BoardIndex, type BoardRow } from '../lib/scoreboard';
|
||||
|
||||
interface RosterItem {
|
||||
idx: number;
|
||||
info: MatchPlayer | null;
|
||||
name: string;
|
||||
ally: boolean;
|
||||
}
|
||||
|
||||
/** 리플레이 점수판: 게임에서 Tab 을 누른 것처럼 그 시각의 팀 점수 · 궁극기 · K/D/A · 무기 · 크레딧 */
|
||||
export default function ReplayScoreboard({ m, replay, ix, roster, t }: { m: MatchDetail; replay: ReplayFile; ix: BoardIndex; roster: RosterItem[]; t: number }) {
|
||||
const rows = roster.map((r) => ({ r, b: boardAt(replay, ix, r.idx, t) }));
|
||||
// 게임처럼 전투 점수 순 (없으면 킬 순)
|
||||
const order = (a: { b: BoardRow }, c: { b: BoardRow }) => (c.b.score ?? -1) - (a.b.score ?? -1) || c.b.kills - a.b.kills || a.b.deaths - c.b.deaths;
|
||||
const ally = rows.filter((x) => x.r.ally).sort(order);
|
||||
const enemy = rows.filter((x) => !x.r.ally).sort(order);
|
||||
const sc = teamScoreAt(replay, m.rounds, t);
|
||||
const team = (list: typeof rows, side: 'a' | 'e') => (
|
||||
<tbody className={`r3d-sb-team ${side}`}>
|
||||
{list.map(({ r, b }) => (
|
||||
<tr key={r.idx} className={b.dead ? 'dead' : undefined}>
|
||||
<td className="ag">
|
||||
{r.info?.character?.icon ? <img src={r.info.character.icon} alt="" /> : <span className="ag-ph" />}
|
||||
</td>
|
||||
<td className="nm">
|
||||
<b>{r.name}</b>
|
||||
{r.info?.character?.name && <span className="muted"> {r.info.character.name}</span>}
|
||||
</td>
|
||||
<td className="ult" title={b.ult == null ? '궁극기 점수 모름' : `궁극기 ${b.ult} / ${b.ultMax}`}>
|
||||
{b.ult == null ? (
|
||||
<span className="muted">-</span>
|
||||
) : b.ult >= b.ultMax ? (
|
||||
<span className="ult-ready">궁 준비</span>
|
||||
) : (
|
||||
<span className="ult-dots" aria-label={`궁극기 ${b.ult} / ${b.ultMax}`}>
|
||||
{Array.from({ length: b.ultMax }, (_, i) => (
|
||||
<i key={i} className={i < b.ult! ? 'on' : undefined} />
|
||||
))}
|
||||
</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="num">{b.kills}</td>
|
||||
<td className="num">{b.deaths}</td>
|
||||
<td className="num">{b.assists ?? '-'}</td>
|
||||
<td className="wp">{equipLabel(b.weapon ?? undefined) ?? '-'}</td>
|
||||
<td className="num money">{b.money == null ? '-' : `${b.money.toLocaleString('ko-KR')}`}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
);
|
||||
return (
|
||||
<div className="r3d-sb" role="dialog" aria-label="점수판">
|
||||
<div className="r3d-sb-head">
|
||||
<span className="a">아군 {sc.ally}</span>
|
||||
<span className="muted">R{sc.round}</span>
|
||||
<span className="e">{sc.enemy} 상대</span>
|
||||
</div>
|
||||
<table>
|
||||
<thead>
|
||||
<tr>
|
||||
<th colSpan={2}>선수</th>
|
||||
<th>궁극기</th>
|
||||
<th className="num">K</th>
|
||||
<th className="num">D</th>
|
||||
<th className="num">A</th>
|
||||
<th>무기</th>
|
||||
<th className="num">크레딧</th>
|
||||
</tr>
|
||||
</thead>
|
||||
{team(ally, 'a')}
|
||||
{team(enemy, 'e')}
|
||||
</table>
|
||||
{!ix.has && <div className="muted small r3d-sb-note">이 리플레이는 예전 변환 결과라 크레딧 · 궁극기 · 어시스트가 없습니다. 게임 PC 앱을 1.10.0 이상으로 올리면 다음에 열 때 다시 변환합니다.</div>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -6,7 +6,8 @@ import { player } from '../store/player';
|
||||
import { settings, useSettings } from '../store/settings';
|
||||
import { useData } from '../store/app';
|
||||
import { fmtClock } from '../lib/format';
|
||||
import { equipAt, equipLabel, equipTracks, indexAt, isDead, roundAt, samplePath, samplePlayer, type ReplayFile, type ReplaySync } from '../lib/replay';
|
||||
import { equipAt, equipLabel, equipTracks, indexAt, isDead, roundAt, samplePath, samplePlayer, skinTracks, type ReplayFile, type ReplaySync } from '../lib/replay';
|
||||
import { loadSkins, lookOf, requestMissing } from '../lib/skins';
|
||||
import { findMap3d, loadMap3d, mapMaterial, worldMatrix } from '../lib/map3d';
|
||||
import { AgentRig, isGun, loadAgent, loadAnims, loadWeapon, weaponCat } from '../lib/agents3d';
|
||||
import { Viewmodel, viewmodelIndex } from '../lib/viewmodel';
|
||||
@@ -15,6 +16,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, fitDistance, 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 +45,17 @@ const REAL_LABEL_CM = 190;
|
||||
/** 위에서 볼 때 요원 몸을 이만큼 키운다 (맵 전체를 볼 때도 보이게) */
|
||||
const TOP_MODEL_SCALE = 1.8;
|
||||
|
||||
/** 카메라: 위에서 보기(돌리기) · 1인칭(고른 선수 눈) · 자유시점(WASD) */
|
||||
type CamMode = 'top' | 'fp' | 'free';
|
||||
const CAM_LABEL: Record<CamMode, string> = { top: '위에서', fp: '1인칭', free: '자유시점' };
|
||||
/** 카메라: 자동(관전처럼 장면마다 1인칭 · 위에서) · 위에서 보기(돌리기) · 1인칭(고른 선수 눈) · 자유시점(WASD) */
|
||||
type CamMode = 'auto' | 'top' | 'fp' | 'free';
|
||||
type View = Exclude<CamMode, 'auto'>;
|
||||
const CAM_LABEL: Record<CamMode, string> = { auto: '자동', top: '위에서', fp: '1인칭', free: '자유시점' };
|
||||
/** 자동 · 위에서 볼 때 카메라가 따라가는 빠르기 (1초에 남은 거리의 이만큼) */
|
||||
const AUTO_EASE = 2.2;
|
||||
/** 자동 · 위에서: 보는 곳에서 카메라 쪽 방향 (위로 많이 · 앞으로 조금, 단위 벡터) */
|
||||
const AUTO_DIR: [number, number, number] = (() => {
|
||||
const l = Math.hypot(0.92, 0.42);
|
||||
return [0, 0.92 / l, 0.42 / l];
|
||||
})();
|
||||
|
||||
type MapState = { state: 'none' | 'loading' | 'ready' | 'error'; progress?: number };
|
||||
/** 천장 자르기: 자동 · 끔 · 직접(가장 낮은 층에서 cm) */
|
||||
@@ -141,6 +153,52 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
xhairRef.current = cfg.crosshair;
|
||||
const [xOpen, setXOpen] = useState(false);
|
||||
const hasCrosshairs = useMemo(() => replay.players.some((p) => !!p.crosshair?.length), [replay]);
|
||||
// 자동 시점: 지금 장면 번호 (화면 표시 · 1인칭 조준점용)
|
||||
const [shotIdx, setShotIdx] = useState(-1);
|
||||
// 점수판 (Tab 을 누르는 동안 · 버튼으로 켜고 끔)
|
||||
const [board, setBoard] = useState(false);
|
||||
const boardIx = useMemo(() => boardIndex(replay), [replay]);
|
||||
const rootRef = useRef<HTMLDivElement>(null);
|
||||
const hoverRef = useRef(false);
|
||||
// 게임처럼 Tab 을 누르고 있는 동안 점수판. 재생기 위에 마우스가 있거나 재생기 안을 누른 뒤에만 (글 입력 중은 그대로)
|
||||
useEffect(() => {
|
||||
let held = false;
|
||||
const active = () => {
|
||||
const el = rootRef.current;
|
||||
return !!el && (hoverRef.current || el.contains(document.activeElement));
|
||||
};
|
||||
const typing = (e: KeyboardEvent) => {
|
||||
const el = e.target as HTMLElement | null;
|
||||
if (!el) return false;
|
||||
if (el.isContentEditable || el.tagName === 'TEXTAREA') return true;
|
||||
return el.tagName === 'INPUT' && !['range', 'checkbox', 'button', 'radio'].includes((el as HTMLInputElement).type);
|
||||
};
|
||||
const down = (e: KeyboardEvent) => {
|
||||
if (e.key !== 'Tab' || e.altKey || e.ctrlKey || e.metaKey || typing(e) || !active()) return;
|
||||
e.preventDefault();
|
||||
held = true;
|
||||
if (!e.repeat) setBoard(true);
|
||||
};
|
||||
const up = (e: KeyboardEvent) => {
|
||||
if (e.key !== 'Tab' || !held) return;
|
||||
e.preventDefault();
|
||||
held = false;
|
||||
setBoard(false);
|
||||
};
|
||||
const blur = () => {
|
||||
if (!held) return;
|
||||
held = false;
|
||||
setBoard(false);
|
||||
};
|
||||
window.addEventListener('keydown', down, true);
|
||||
window.addEventListener('keyup', up, true);
|
||||
window.addEventListener('blur', blur);
|
||||
return () => {
|
||||
window.removeEventListener('keydown', down, true);
|
||||
window.removeEventListener('keyup', up, true);
|
||||
window.removeEventListener('blur', blur);
|
||||
};
|
||||
}, []);
|
||||
|
||||
// 바닥(미니맵) 높이: 선수 높이의 하위 5% (떨어져 죽은 기록은 뺀다)
|
||||
const zBase = useMemo(() => {
|
||||
@@ -173,6 +231,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;
|
||||
@@ -317,6 +387,21 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
});
|
||||
let vmOn = false;
|
||||
let scopedNow = false;
|
||||
// 무기 스킨: 뽑아 둔 것만 그 스킨으로, 없는 것은 뽑아 달라고 요청한다 (다음에 열면 보인다)
|
||||
const skinByPlayer = skinTracks(replay);
|
||||
let skinIdx: Awaited<ReturnType<typeof loadSkins>> = null;
|
||||
if (replay.skins?.length) {
|
||||
// 열 때마다 새 목록 (그사이 뽑힌 스킨이 보이게)
|
||||
void loadSkins().then((ix) => {
|
||||
if (disposed || !ix) return;
|
||||
skinIdx = ix;
|
||||
void requestMissing(ix, replay);
|
||||
});
|
||||
}
|
||||
const skinLookAt = (p: number, t: number) => {
|
||||
const s = equipAt(skinByPlayer[p], t);
|
||||
return s >= 0 ? lookOf(skinIdx, replay.skins?.[s]) : null;
|
||||
};
|
||||
|
||||
// 선택한 선수 이동 경로 (최근 6초)
|
||||
const trailGeo = new THREE.BufferGeometry();
|
||||
@@ -599,7 +684,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 +744,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 +776,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 +789,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 +799,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);
|
||||
@@ -733,7 +837,7 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
const vy = q && !dead ? ((p.y - q.y) * 1000) / 150 : 0;
|
||||
const a = (p.yaw * Math.PI) / 180;
|
||||
const ek = replay.equipKinds?.[kind];
|
||||
v.rig.setWeapon(isGun(ek) ? ek : null);
|
||||
v.rig.setWeapon(isGun(ek) ? ek : null, isGun(ek) ? skinLookAt(v.idx, t) : null);
|
||||
const inp = rigInput(replay, animIx, v.idx, t, { dt: dtR, fwd: vx * Math.cos(a) + vy * Math.sin(a), right: -vx * Math.sin(a) + vy * Math.cos(a), pitch: p.pitch });
|
||||
v.rig.setShot(inp.shotMs);
|
||||
v.rig.update(inp);
|
||||
@@ -772,7 +876,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));
|
||||
@@ -934,7 +1038,7 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
const chr = replay.players[selIdx].character;
|
||||
vmOn = !!fp && !sc && !!vm && vm.has(chr, fp.kind);
|
||||
if (vmOn && vm && chr && fp) {
|
||||
vm.set(chr, fp.kind!);
|
||||
vm.set(chr, fp.kind!, skinLookAt(selIdx, t));
|
||||
vm.pose(fp.input);
|
||||
}
|
||||
// 조준점: 선수 조준점(설정에 따라) 또는 내 조준점. 저격총 줌은 조준경 가운데 점, 정조준은 정조준 조준점
|
||||
@@ -958,6 +1062,38 @@ 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 aliveN = 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 (pass === 0) aliveN = n;
|
||||
if (n) break;
|
||||
}
|
||||
if (n) {
|
||||
autoGoal.set((x0 + x1) / 2, ySum / n, (z0 + z1) / 2);
|
||||
// 시야각 · 화면비 · 기울기로 모두가 들어오는 거리 (선수 몸 · 이름표 높이만큼 위아래로 넉넉히)
|
||||
const pts: [number, number, number][] = [];
|
||||
for (const v of views) {
|
||||
if (!v.group.visible || (aliveN > 0 && isDead(replay, v.idx, t))) continue;
|
||||
const q = v.group.position;
|
||||
pts.push([q.x, q.y, q.z], [q.x, q.y + 6, q.z]);
|
||||
}
|
||||
autoDist = Math.max(36, Math.min(400, fitDistance(pts, [autoGoal.x, autoGoal.y, autoGoal.z], AUTO_DIR, camera.fov, camera.aspect)));
|
||||
}
|
||||
const k = 1 - Math.exp(-dt * AUTO_EASE);
|
||||
autoTarget.lerp(autoGoal, k);
|
||||
tmp.set(autoTarget.x + AUTO_DIR[0] * autoDist, autoTarget.y + AUTO_DIR[1] * autoDist, autoTarget.z + AUTO_DIR[2] * autoDist);
|
||||
camera.position.lerp(tmp, k);
|
||||
camera.lookAt(autoTarget);
|
||||
} else controls.update();
|
||||
if (mode !== 'fp') {
|
||||
vmOn = false;
|
||||
@@ -1035,6 +1171,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 +1186,7 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
|
||||
if (!T) return <div className="map-missing">이 경기에는 미니맵 좌표 정보가 없어 3D 리플레이를 그릴 수 없습니다</div>;
|
||||
return (
|
||||
<div className="r3d">
|
||||
<div className="r3d" ref={rootRef} onPointerEnter={() => (hoverRef.current = true)} onPointerLeave={() => (hoverRef.current = false)}>
|
||||
<div className="r3d-stage" ref={mountRef}>
|
||||
<div className="r3d-hud tl">
|
||||
<b>{rd ? `R${rd.num}` : ''}</b> <span className="mono">{clock}</span>
|
||||
@@ -1075,18 +1215,38 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{cam === 'fp' && scoped && <div className="r3d-scope" />}
|
||||
{cam === 'fp' && <canvas ref={crossRef} className="r3d-xcanvas" aria-hidden />}
|
||||
{cam === 'fp' && xOpen && (
|
||||
{fpView && scoped && <div className="r3d-scope" />}
|
||||
{fpView && <canvas ref={crossRef} className="r3d-xcanvas" aria-hidden />}
|
||||
{fpView && xOpen && (
|
||||
<CrosshairPanel
|
||||
playerName={selInfo?.name ?? null}
|
||||
player={sel != null ? crosshairAt(replay.players[sel].crosshair, ui.t) : null}
|
||||
playerName={fpWho != null ? roster[fpWho]?.name ?? null : null}
|
||||
player={fpWho != null ? crosshairAt(replay.players[fpWho].crosshair, ui.t) : null}
|
||||
hasAny={hasCrosshairs}
|
||||
onClose={() => setXOpen(false)}
|
||||
/>
|
||||
)}
|
||||
{cam === 'free' && <div className="r3d-hud bl muted small">끌기: 둘러보기 · W A S D: 이동 · Q / E: 아래 / 위 · Shift: 빠르게 (화면을 한 번 누른 뒤)</div>}
|
||||
{selInfo && cam !== 'free' && (
|
||||
{cam === 'auto' && shot && (
|
||||
<div className="r3d-hud bl r3d-auto">
|
||||
<div className="muted small">자동 · {SHOT_LABEL[shot.kind]}</div>
|
||||
{shot.pov != null ? (
|
||||
<div>
|
||||
<b className={roster[shot.pov]?.ally ? 'a' : 'e'}>{roster[shot.pov]?.name}</b>
|
||||
{roster[shot.pov]?.info?.character?.name && <span className="muted"> · {roster[shot.pov].info!.character.name}</span>} 시점
|
||||
{shot.kind === 'fight' && (shot.kills ?? 0) > 1 && <span className="muted"> · {shot.kills}킬</span>}
|
||||
{(() => {
|
||||
const w = equipLabel(replay.equipKinds?.[equipAt(equipByPlayer[shot.pov], ui.t)]);
|
||||
return w ? <div>🔫 {w}</div> : null;
|
||||
})()}
|
||||
</div>
|
||||
) : (
|
||||
<div className="muted small">살아 있는 선수가 모두 보이게 위에서 봅니다</div>
|
||||
)}
|
||||
{shot.call && <div className="r3d-call">콜 “{shot.call}”</div>}
|
||||
</div>
|
||||
)}
|
||||
{board && <ReplayScoreboard m={m} replay={replay} ix={boardIx} roster={roster} t={ui.t} />}
|
||||
{selInfo && cam !== 'free' && cam !== 'auto' && (
|
||||
<div className="r3d-hud bl">
|
||||
<b className={selInfo.ally ? 'a' : 'e'}>{selInfo.name}</b>
|
||||
{selInfo.info?.character?.name && <span className="muted"> · {selInfo.info.character.name}</span>}
|
||||
@@ -1145,13 +1305,22 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
</span>
|
||||
)}
|
||||
<span className="r3d-cams" role="group" aria-label="카메라">
|
||||
{(['top', 'fp', 'free'] as CamMode[]).map((c) => (
|
||||
<button key={c} className={`chip${cam === c ? ' on' : ''}`} onClick={() => chooseCam(c)} aria-pressed={cam === c}>
|
||||
{(['auto', 'top', 'fp', 'free'] as CamMode[]).map((c) => (
|
||||
<button
|
||||
key={c}
|
||||
className={`chip${cam === c ? ' on' : ''}`}
|
||||
onClick={() => chooseCam(c)}
|
||||
aria-pressed={cam === c}
|
||||
title={c === 'auto' ? '관전처럼 자동으로: 교전 직전에 이긴 선수 1인칭 · 교전이 없으면 위에서 전체 · 설치/해체 · 혼자 남은 선수' : undefined}
|
||||
>
|
||||
{CAM_LABEL[c]}
|
||||
</button>
|
||||
))}
|
||||
</span>
|
||||
{cam === 'fp' && (
|
||||
<button className={`chip${board ? ' on' : ''}`} onClick={() => setBoard((b) => !b)} aria-pressed={board} title="점수판: 크레딧 · 궁극기 · K/D/A (화면에서 Tab 을 누르고 있어도 됩니다)">
|
||||
점수판 (Tab)
|
||||
</button>
|
||||
{fpView && (
|
||||
<button className={`chip${xOpen ? ' on' : ''}`} onClick={() => setXOpen((o) => !o)} aria-pressed={xOpen} title="1인칭 조준점: 선수 조준점 · 내 조준점 설정">
|
||||
조준점
|
||||
</button>
|
||||
@@ -1163,7 +1332,14 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
|
||||
)}
|
||||
</div>
|
||||
<div className="r3d-foot muted">
|
||||
{cam === 'top' ? '마우스 왼쪽 끌기: 회전 · 오른쪽 끌기: 이동 · 휠: 확대 · 선수 클릭: 선택' : cam === 'fp' ? '1인칭: 고른 선수 눈높이 · 다른 선수를 누르면 그 선수로' : '자유시점: 끌어서 둘러보기 · WASD 이동'} ·{' '}
|
||||
{cam === 'auto'
|
||||
? '자동: 교전 직전에 이긴 선수 1인칭으로 넘어가고(직전 콜이 있으면 그 말부터), 교전이 없으면 위에서 전체를 봅니다'
|
||||
: cam === 'top'
|
||||
? '마우스 왼쪽 끌기: 회전 · 오른쪽 끌기: 이동 · 휠: 확대 · 선수 클릭: 선택'
|
||||
: cam === 'fp'
|
||||
? '1인칭: 고른 선수 눈높이 · 다른 선수를 누르면 그 선수로'
|
||||
: '자유시점: 끌어서 둘러보기 · WASD 이동'}{' '}
|
||||
· Tab: 점수판 ·{' '}
|
||||
{sync.matched >= 3
|
||||
? `대화 동기화: 킬 ${sync.matched}개로 맞춤 (최대 오차 ${((sync.spreadMs ?? 0) / 1000).toFixed(2)}초)`
|
||||
: '대화 동기화: 라운드 시작으로 대략 맞춤'}
|
||||
|
||||
@@ -3,6 +3,7 @@ import { GLTFLoader, type GLTF } from 'three/examples/jsm/loaders/GLTFLoader.js'
|
||||
import { MeshoptDecoder } from 'three/examples/jsm/libs/meshopt_decoder.module.js';
|
||||
import { clone as cloneSkinned } from 'three/examples/jsm/utils/SkeletonUtils.js';
|
||||
import { loadIndex } from './map3d';
|
||||
import { skinFileUrl, type SkinLook } from './skins';
|
||||
|
||||
/**
|
||||
* 요원 3D 몸 · 총 (tools/map-extract agents → 사이트 서버 /site/maps3d, 맵과 같은 폴더).
|
||||
@@ -37,8 +38,12 @@ export async function loadAgent(characterClass: string): Promise<GLTF | null> {
|
||||
return a && idx?.dir ? load(assetUrl(idx.dir, a.file)) : null;
|
||||
}
|
||||
|
||||
/** 총 (리플레이 equipKinds 이름: Vandal · Classic · Melee …). 없으면 null */
|
||||
export async function loadWeapon(name: string): Promise<GLTF | null> {
|
||||
/** 총 (리플레이 equipKinds 이름: Vandal · Classic · Melee …). 스킨 3인칭 모델이 있으면 그것 (받지 못하면 기본 스킨). 없으면 null */
|
||||
export async function loadWeapon(name: string, skin?: SkinLook | null): Promise<GLTF | null> {
|
||||
if (skin?.w3p) {
|
||||
const g = await load(skinFileUrl(skin.w3p)).catch(() => null);
|
||||
if (g) return g;
|
||||
}
|
||||
const idx = await loadIndex();
|
||||
const w = idx?.dir ? idx.weapons?.[name] : undefined;
|
||||
return w && idx?.dir ? load(assetUrl(idx.dir, w.file)) : null;
|
||||
@@ -161,6 +166,7 @@ export class AgentRig {
|
||||
/** 총구 불꽃 (사격 순간에 잠깐) */
|
||||
readonly muzzle: THREE.Sprite;
|
||||
private gunName: string | null = null;
|
||||
private gunSkin: SkinLook | null = null;
|
||||
private gunReq = 0;
|
||||
private gunTip = 60;
|
||||
private readonly tmp = new THREE.Vector3();
|
||||
@@ -198,14 +204,15 @@ export class AgentRig {
|
||||
return a;
|
||||
}
|
||||
|
||||
/** 들고 있는 총 바꾸기 (이름 없으면 맨손) */
|
||||
setWeapon(name: string | null) {
|
||||
if (name === this.gunName) return;
|
||||
/** 들고 있는 총 바꾸기 (이름 없으면 맨손, 스킨 모습이 있으면 그 스킨) */
|
||||
setWeapon(name: string | null, skin?: SkinLook | null) {
|
||||
if (name === this.gunName && (skin ?? null) === this.gunSkin) return;
|
||||
this.gunName = name;
|
||||
this.gunSkin = skin ?? null;
|
||||
const req = ++this.gunReq;
|
||||
for (const c of [...this.gunSlot.children]) if (c !== this.muzzle) this.gunSlot.remove(c);
|
||||
if (!name) return;
|
||||
void loadWeapon(name)
|
||||
void loadWeapon(name, skin)
|
||||
.then((g) => {
|
||||
if (!g || req !== this.gunReq) return;
|
||||
const gun = g.scene.clone(true);
|
||||
|
||||
@@ -42,6 +42,9 @@ export class ApiError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
/** 경기 탭 필터 */
|
||||
export type MatchHas = 'timeline' | 'voice';
|
||||
|
||||
async function request<T>(path: string, init: RequestInit = {}): Promise<T> {
|
||||
let res: Response;
|
||||
try {
|
||||
@@ -162,10 +165,17 @@ export const api = {
|
||||
hideNoise: 1,
|
||||
})}`,
|
||||
),
|
||||
matches: (o: { game?: GameType; limit?: number; before?: number } = {}) => request<MatchSummary[]>(`/api/matches${qs(o)}`),
|
||||
// has: timeline = 타임라인에 나오는 경기, voice = 목소리가 녹음된 경기 (v1.9.0 앱부터, 예전 앱은 무시하고 다 보냄)
|
||||
// mode · after (v1.11.0 앱부터): 모드 이름("경쟁전") · 이 시각 이후 시작한 경기. 데스매치는 앱이 늘 뺀다 (예전 앱은 사이트가 거름)
|
||||
matches: (o: { game?: GameType; limit?: number; before?: number; after?: number; has?: MatchHas; mode?: string } = {}) =>
|
||||
request<MatchSummary[]>(`/api/matches${qs(o)}`),
|
||||
/** 경기 탭 모드 필터 목록 (v1.11.0 앱부터, 예전 앱은 404) */
|
||||
matchModes: (game?: GameType) => request<{ game: GameType; mode: string; count: number }[]>(`/api/matches/modes${qs({ game })}`),
|
||||
match: (id: string) => request<MatchDetail>(`/api/matches/${encodeURIComponent(id)}`),
|
||||
/** 발로란트 리플레이(.vrf)에서 뽑은 재생 데이터. 없으면 404 replay_not_found, 게임 PC 가 변환 중이면 202 { status: 'converting' } */
|
||||
replay: (id: string) => request<ReplayFile | { status: 'converting' }>(`/api/matches/${encodeURIComponent(id)}/replay`),
|
||||
// fresh: 새로고침 때는 브라우저 캐시를 거치지 않는다 (방금 내려받은 리플레이가 보이게)
|
||||
replay: (id: string, fresh = false) =>
|
||||
request<ReplayFile | { status: 'converting' }>(`/api/matches/${encodeURIComponent(id)}/replay`, fresh ? { cache: 'no-cache' } : {}),
|
||||
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'),
|
||||
@@ -226,6 +236,9 @@ export const api = {
|
||||
/** 발화 지우기 (v1.4.0). noise = 잡음이라 삭제 (같은 문장을 다음부터 잡음으로) */
|
||||
deleteUtterance: (id: string, noise: boolean) =>
|
||||
request<{ ok: true; learned: string | null }>(`/api/utterances/${encodeURIComponent(id)}/delete`, { method: 'POST', body: JSON.stringify({ noise }) }),
|
||||
/** Riot 경기 기록 가져오기 취소 (v1.9.1). 받은 경기는 남고 resumeAt 에 이어서 한다 */
|
||||
cancelHistory: (game?: GameType) =>
|
||||
request<{ ok: true; cancelled: GameType[]; resumeAt: number | null }>('/api/games/history/cancel', { method: 'POST', body: JSON.stringify({ game }) }),
|
||||
noisePhrases: () => request<{ phrases: NoisePhrase[] }>('/api/noise-phrases'),
|
||||
deleteNoisePhrase: (id: number) => request<{ ok: true }>(`/api/noise-phrases/${id}`, { method: 'DELETE' }),
|
||||
};
|
||||
|
||||
301
site/web/src/lib/director.ts
Normal file
301
site/web/src/lib/director.ts
Normal file
@@ -0,0 +1,301 @@
|
||||
import { isDead, type ReplayFile } from './replay';
|
||||
|
||||
/**
|
||||
* 자동 관전 (자동 시점): 리플레이 기록(맞은 것 · 킬 · 사격 · 설치/해체)과 그때 나눈 대화로 장면을 나눈다.
|
||||
* - 교전: 킬마다 이긴 선수(죽인 선수) 1인칭. 교전이 시작되기 FIGHT_LEAD 전에 미리 넘어간다.
|
||||
* 교전 직전에 우리 팀이 말을 했으면(콜) 그 말이 시작될 때부터 보여 준다 (최대 CALL_LEAD).
|
||||
* - 스파이크 설치 · 해체: 하는 선수 1인칭
|
||||
* - 혼자 남은 선수(1 대 N): 그 선수 1인칭
|
||||
* - 교전이 없을 때: 살아 있는 선수 모두가 보이게 위에서 (전략 보기)
|
||||
* 시각(t)만으로 정해지므로 되감기 · 건너뛰기 · 배속에도 같은 장면이 나온다.
|
||||
*/
|
||||
export type ShotKind = 'fight' | 'skirmish' | 'plant' | 'defuse' | 'clutch' | 'buy' | 'overview' | 'post';
|
||||
|
||||
export interface Shot {
|
||||
t0: number;
|
||||
t1: number;
|
||||
kind: ShotKind;
|
||||
/** 1인칭으로 볼 선수 (리플레이 선수 번호). null 이면 위에서 */
|
||||
pov: number | null;
|
||||
/** 이 장면에서 pov 가 낸 킬 수 (교전) */
|
||||
kills?: number;
|
||||
/** 교전 직전 콜 (대화 글) */
|
||||
call?: string;
|
||||
}
|
||||
|
||||
export interface Talk {
|
||||
/** 리플레이 시각 (ms) */
|
||||
t0: number;
|
||||
t1: number;
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface DirectorInput {
|
||||
replay: ReplayFile;
|
||||
/** 선수별 우리 팀 여부 */
|
||||
ally: boolean[];
|
||||
/** 우리 팀 대화 (녹음된 사람은 모두 우리 팀) */
|
||||
talks: Talk[];
|
||||
}
|
||||
|
||||
/** 교전 시작 전에 미리 넘어가는 시간 */
|
||||
export const FIGHT_LEAD = 2500;
|
||||
/** 교전 직전 콜을 찾는 범위 · 콜부터 보여 줄 때 가장 이른 시각 (교전 시작 기준) */
|
||||
export const CALL_LEAD = 6000;
|
||||
/** 킬 뒤에 그 선수를 더 보여 주는 시간 */
|
||||
const FIGHT_TAIL = 1200;
|
||||
/** 같은 교전으로 보는 사격 간격 · 킬 전에 교전 시작을 찾는 범위 */
|
||||
const BURST_GAP = 1500;
|
||||
const DUEL_BACK = 8000;
|
||||
/** 다음 킬로 넘어갈 때 앞 킬 뒤로 최소 이만큼은 보여 준다 */
|
||||
const AFTER_KILL = 500;
|
||||
/** 넘어간 뒤 킬까지 이보다 짧으면 넘어가지 않는다 (무슨 일인지 볼 틈이 없음) */
|
||||
const MIN_ORIENT = 700;
|
||||
/** 1인칭 장면 사이 위에서 보기가 이보다 짧으면 앞 장면을 늘린다 · 이보다 짧은 1인칭은 앞 장면에 붙인다 */
|
||||
const MIN_OVERVIEW = 2000;
|
||||
const MIN_POV = 900;
|
||||
|
||||
type Seg = Shot;
|
||||
|
||||
export function buildDirector({ replay: r, ally, talks }: DirectorInput): Shot[] {
|
||||
const end = r.durationMs;
|
||||
const team = (p: number) => (p >= 0 ? (ally[p] ? 0 : 1) : -1);
|
||||
const rounds = r.rounds.map((rd, i) => ({ ...rd, next: r.rounds[i + 1]?.buy ?? end }));
|
||||
const roundOf = (t: number) => {
|
||||
let cur = rounds[0];
|
||||
for (const rd of rounds) if (rd.buy <= t) cur = rd;
|
||||
return cur;
|
||||
};
|
||||
const roundStart = (t: number) => roundOf(t)?.buy ?? 0;
|
||||
const hits = (r.hits ?? []).filter((h) => h[1] >= 0 && h[2] >= 0 && h[1] !== h[2] && team(h[1]) !== team(h[2])).sort((a, b) => a[0] - b[0]);
|
||||
const shotsBy: number[][] = r.players.map(() => []);
|
||||
for (const s of r.shots) if (s[1] >= 0) shotsBy[s[1]]?.push(s[0]);
|
||||
for (const a of shotsBy) a.sort((x, y) => x - y);
|
||||
const talksSorted = [...talks].filter((x) => x.text?.trim()).sort((a, b) => a.t0 - b.t0);
|
||||
|
||||
// ── 교전 (킬마다) ─────────────────────────────
|
||||
const duels: { start: number; kill: number; pov: number; call?: string; victim: number }[] = [];
|
||||
const kills = [...r.kills].sort((a, b) => a[0] - b[0]);
|
||||
for (const [tk, k, v] of kills) {
|
||||
if (k < 0 || v < 0 || k === v || team(k) === team(v)) continue;
|
||||
const floor = Math.max(roundStart(tk), tk - DUEL_BACK);
|
||||
// 둘 사이 첫 맞은 기록
|
||||
let start = tk;
|
||||
for (const h of hits) {
|
||||
if (h[0] < floor) continue;
|
||||
if (h[0] > tk) break;
|
||||
if ((h[1] === k && h[2] === v) || (h[1] === v && h[2] === k)) {
|
||||
start = Math.min(start, h[0]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
// 죽인 선수의 이어진 사격 (킬에서 거슬러 올라가며 간격 BURST_GAP 안)
|
||||
const st = shotsBy[k] ?? [];
|
||||
let j = upper(st, tk) - 1;
|
||||
let burst = tk;
|
||||
while (j >= 0 && st[j] >= floor && burst - st[j] <= BURST_GAP) burst = st[j--];
|
||||
start = Math.min(start, burst, tk - 1000);
|
||||
let from = Math.max(floor, start - FIGHT_LEAD);
|
||||
// 교전 직전 콜: 우리 팀이 낀 교전이면, 교전 시작 CALL_LEAD 안에 시작한 말부터
|
||||
let call: string | undefined;
|
||||
if (ally[k] || ally[v]) {
|
||||
const lo = start - CALL_LEAD;
|
||||
for (const x of talksSorted) {
|
||||
if (x.t0 > start) break;
|
||||
if (x.t0 >= lo && x.t1 >= lo) {
|
||||
call = x.text.trim();
|
||||
from = Math.max(roundStart(tk), Math.min(from, x.t0 - 300));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
duels.push({ start: from, kill: tk, pov: k, call, victim: v });
|
||||
}
|
||||
const segs: Seg[] = [];
|
||||
for (const d of duels) {
|
||||
const prev = segs[segs.length - 1];
|
||||
if (prev && prev.kind === 'fight' && prev.pov === d.pov && d.start <= prev.t1 + MIN_OVERVIEW) {
|
||||
// 같은 선수가 이어서 죽였다 (멀티킬): 그대로 이어 본다
|
||||
prev.t1 = Math.max(prev.t1, d.kill + FIGHT_TAIL);
|
||||
prev.kills = (prev.kills ?? 1) + 1;
|
||||
prev.call ??= d.call;
|
||||
continue;
|
||||
}
|
||||
let from = d.start;
|
||||
if (prev && from < prev.t1) {
|
||||
// 앞 장면과 겹친다: 앞 킬을 보여 준 뒤 넘어간다. 볼 틈이 없으면 넘어가지 않는다
|
||||
const prevKill = prev.t1 - FIGHT_TAIL;
|
||||
from = Math.max(from, prevKill + AFTER_KILL);
|
||||
if (d.kill - from < MIN_ORIENT) continue;
|
||||
prev.t1 = from;
|
||||
}
|
||||
segs.push({ t0: from, t1: Math.min(end, d.kill + FIGHT_TAIL), kind: 'fight', pov: d.pov, kills: 1, call: d.call });
|
||||
}
|
||||
|
||||
// ── 그 밖의 장면: 빈 곳에만 채운다 (설치 · 해체 > 킬 없는 교전 > 혼자 남은 선수) ─────────
|
||||
const fill: Seg[] = [];
|
||||
for (const [a0, a1, p, ak] of r.actions ?? []) {
|
||||
const kind = r.actionKinds?.[ak];
|
||||
if (kind !== 'Plant' && kind !== 'Defuse') continue;
|
||||
fill.push({ t0: a0 - 800, t1: (a1 >= a0 ? a1 : a0 + 4000) + 800, kind: kind === 'Plant' ? 'plant' : 'defuse', pov: p });
|
||||
}
|
||||
// 킬 없는 교전: 서로 맞힌 기록 묶음 (간격 2.5초 안). 가장 많이 맞힌 선수
|
||||
const covered = (t: number) => segs.some((s) => s.t0 <= t && t <= s.t1);
|
||||
for (let i = 0; i < hits.length; ) {
|
||||
let j = i;
|
||||
while (j + 1 < hits.length && hits[j + 1][0] - hits[j][0] <= 2500 && roundOf(hits[j + 1][0]) === roundOf(hits[i][0])) j++;
|
||||
const group = hits.slice(i, j + 1);
|
||||
i = j + 1;
|
||||
// 라운드가 끝난 뒤 쏜 것은 교전이 아니다
|
||||
const rd = roundOf(group[0][0]);
|
||||
if (rd && rd.end >= 0 && group[0][0] >= rd.end) continue;
|
||||
if (group.some((h) => covered(h[0]))) continue;
|
||||
const by = new Map<number, number>();
|
||||
for (const h of group) by.set(h[1], (by.get(h[1]) ?? 0) + 1);
|
||||
const last = group[group.length - 1][0];
|
||||
const best = [...by.entries()].filter(([p]) => !isDead(r, p, last)).sort((a, b) => b[1] - a[1])[0];
|
||||
if (!best) continue;
|
||||
fill.push({ t0: Math.max(roundStart(group[0][0]), group[0][0] - FIGHT_LEAD), t1: last + 1000, kind: 'skirmish', pov: best[0] });
|
||||
}
|
||||
// 혼자 남은 선수: 킬 뒤 한 팀이 1명이고 상대가 1명 이상이면, 라운드가 끝날 때까지 (그 선수가 죽으면 거기까지)
|
||||
for (const rd of rounds) {
|
||||
if (rd.combat < 0) continue;
|
||||
const stop = rd.end >= 0 ? rd.end : rd.next;
|
||||
let clutch: { p: number; from: number } | null = null;
|
||||
for (const [tk] of kills) {
|
||||
if (tk < rd.combat || tk >= stop) continue;
|
||||
const alive = [0, 1].map((tm) => r.players.map((_, p) => p).filter((p) => team(p) === tm && !isDead(r, p, tk + 1)));
|
||||
if (clutch && isDead(r, clutch.p, tk + 1)) {
|
||||
fill.push({ t0: clutch.from, t1: tk + FIGHT_TAIL, kind: 'clutch', pov: clutch.p });
|
||||
clutch = null;
|
||||
}
|
||||
if (!clutch) {
|
||||
for (const tm of [0, 1]) {
|
||||
if (alive[tm].length === 1 && alive[1 - tm].length >= 1) {
|
||||
clutch = { p: alive[tm][0], from: tk + FIGHT_TAIL };
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (clutch) fill.push({ t0: clutch.from, t1: stop, kind: 'clutch', pov: clutch.p });
|
||||
}
|
||||
let out = segs;
|
||||
for (const f of fill) out = paint(out, f);
|
||||
|
||||
// ── 나머지: 위에서 (구매 · 전략 보기 · 라운드 끝) ─────────
|
||||
for (const rd of rounds) {
|
||||
const combat = rd.combat >= 0 ? rd.combat : rd.buy;
|
||||
const stop = rd.end >= 0 ? rd.end : rd.next;
|
||||
out = paint(out, { t0: rd.buy, t1: combat, kind: 'buy', pov: null });
|
||||
out = paint(out, { t0: combat, t1: stop, kind: 'overview', pov: null });
|
||||
out = paint(out, { t0: stop, t1: rd.next, kind: 'post', pov: null });
|
||||
}
|
||||
out = paint(out, { t0: 0, t1: end, kind: 'overview', pov: null });
|
||||
return tidy(out.filter((s) => s.t1 > s.t0).map((s) => ({ ...s, t0: Math.max(0, s.t0), t1: Math.min(end, s.t1) })));
|
||||
}
|
||||
|
||||
/** 빈 곳에만 칠한다 (segs 는 시간 순 · 겹치지 않음) */
|
||||
function paint(segs: Seg[], c: Seg): Seg[] {
|
||||
if (c.t1 <= c.t0) return segs;
|
||||
const out: Seg[] = [];
|
||||
let cur = c.t0;
|
||||
for (const s of segs) {
|
||||
if (s.t0 > cur && cur < c.t1) out.push({ ...c, t0: cur, t1: Math.min(s.t0, c.t1) });
|
||||
out.push(s);
|
||||
cur = Math.max(cur, s.t1);
|
||||
}
|
||||
if (cur < c.t1) out.push({ ...c, t0: cur, t1: c.t1 });
|
||||
return out.sort((a, b) => a.t0 - b.t0);
|
||||
}
|
||||
|
||||
/** 깜빡이지 않게: 1인칭 사이 짧은 위에서 보기는 앞 장면을 늘리고, 짧은 1인칭은 앞 장면에 붙이고, 같은 장면은 합친다 */
|
||||
function tidy(segs: Seg[]): Shot[] {
|
||||
const out: Seg[] = [];
|
||||
for (let i = 0; i < segs.length; i++) {
|
||||
const s = { ...segs[i] };
|
||||
const prev = out[out.length - 1];
|
||||
const next = segs[i + 1];
|
||||
const len = s.t1 - s.t0;
|
||||
if (prev && s.pov == null && prev.pov != null && next?.pov != null && len < MIN_OVERVIEW) {
|
||||
prev.t1 = s.t1;
|
||||
continue;
|
||||
}
|
||||
if (prev && s.pov != null && len < MIN_POV) {
|
||||
prev.t1 = s.t1;
|
||||
continue;
|
||||
}
|
||||
if (prev && prev.kind === s.kind && prev.pov === s.pov && prev.t1 >= s.t0) {
|
||||
prev.t1 = s.t1;
|
||||
prev.kills = (prev.kills ?? 0) + (s.kills ?? 0) || undefined;
|
||||
prev.call ??= s.call;
|
||||
continue;
|
||||
}
|
||||
out.push(s);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** t 시점 장면 (번호). 없으면 -1 */
|
||||
export function shotIndexAt(shots: Shot[], t: number): number {
|
||||
let lo = 0;
|
||||
let hi = shots.length - 1;
|
||||
if (hi < 0 || t < shots[0].t0) return shots.length ? 0 : -1;
|
||||
while (lo < hi) {
|
||||
const mid = (lo + hi + 1) >> 1;
|
||||
if (shots[mid].t0 <= t) lo = mid;
|
||||
else hi = mid - 1;
|
||||
}
|
||||
return lo;
|
||||
}
|
||||
|
||||
function upper(a: number[], t: number) {
|
||||
let lo = 0;
|
||||
let hi = a.length;
|
||||
while (lo < hi) {
|
||||
const mid = (lo + hi) >> 1;
|
||||
if (a[mid] <= t) lo = mid + 1;
|
||||
else hi = mid;
|
||||
}
|
||||
return lo;
|
||||
}
|
||||
|
||||
export const SHOT_LABEL: Record<ShotKind, string> = {
|
||||
fight: '교전',
|
||||
skirmish: '교전 (킬 없음)',
|
||||
plant: '스파이크 설치',
|
||||
defuse: '스파이크 해체',
|
||||
clutch: '혼자 남음',
|
||||
buy: '구매 단계 · 전체 보기',
|
||||
overview: '전략 보기',
|
||||
post: '라운드 끝',
|
||||
};
|
||||
|
||||
type V3 = [number, number, number];
|
||||
const dot = (a: V3, b: V3) => a[0] * b[0] + a[1] * b[1] + a[2] * b[2];
|
||||
const cross = (a: V3, b: V3): V3 => [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
|
||||
const unit = (a: V3): V3 => {
|
||||
const l = Math.hypot(...a) || 1;
|
||||
return [a[0] / l, a[1] / l, a[2] / l];
|
||||
};
|
||||
|
||||
/**
|
||||
* 전략 보기 카메라 거리: 카메라를 target + dir × 거리 에 두고 target 을 볼 때 모든 점이 화면(가장자리 margin 남김) 안에 들어오는 가장 짧은 거리.
|
||||
* 카메라 공간에서 점의 깊이 = dot(q, f) + 거리 (f = -dir), 가로 · 세로 = dot(q, 오른쪽) · dot(q, 위). |가로| ≤ tan(가로 시야/2) × 깊이 를 거리로 푼다.
|
||||
* dir 은 위쪽(y) 성분이 있어야 한다 (내려다보기)
|
||||
*/
|
||||
export function fitDistance(points: V3[], target: V3, dir: V3, fovDeg: number, aspect: number, margin = 0.85): number {
|
||||
const d = unit(dir);
|
||||
const f: V3 = [-d[0], -d[1], -d[2]];
|
||||
const right = unit(cross(f, [0, 1, 0]));
|
||||
const up = cross(right, f);
|
||||
const tv = Math.tan(((fovDeg / 2) * Math.PI) / 180) * margin;
|
||||
const th = tv * aspect;
|
||||
let need = 0;
|
||||
for (const p of points) {
|
||||
const q: V3 = [p[0] - target[0], p[1] - target[1], p[2] - target[2]];
|
||||
const z = dot(q, f);
|
||||
need = Math.max(need, Math.abs(dot(q, right)) / th - z, Math.abs(dot(q, up)) / tv - z);
|
||||
}
|
||||
return need;
|
||||
}
|
||||
@@ -45,9 +45,22 @@ export interface ReplayFile {
|
||||
/** 이어지는 동작 [t0, t1, player, actionKind] (Plant · Defuse · Rope) */
|
||||
actions?: [number, number, number, number][];
|
||||
actionKinds?: string[];
|
||||
/** 들고 있는 것이 바뀐 시각 [t, player, kind] (변환기 새 버전부터. 옛 리플레이 JSON 에는 없다) */
|
||||
equips?: [number, number, number][];
|
||||
/** 들고 있는 것이 바뀐 시각 [t, player, kind, skin] (변환기 새 버전부터. 옛 리플레이 JSON 에는 없다. skin = skins 번호 · 모르면 -1, 변환기 1.10.0~) */
|
||||
equips?: [number, number, number, number?][];
|
||||
equipKinds?: string[];
|
||||
/** 무기 스킨 (게임 데이터 에셋 경로). 줍거나 떨어뜨려도 그 총의 스킨은 처음 주인 것 (변환기 1.10.0~) */
|
||||
skins?: SkinInfo[];
|
||||
/** 점수판 (게임 Tab): 선수 값이 바뀔 때마다 [t, player, 크레딧, 궁극기 점수, 킬, 데스, 어시스트, 전투 점수] (모르는 값 -1, 변환기 1.10.0~) */
|
||||
scoreboard?: number[][];
|
||||
}
|
||||
|
||||
/** 무기 스킨: 스킨 · 단계 · 색상 · 총 장식 (예: /Game/Equippables/Guns/Rifles/AK/HypeBeast/AssaultRifle_AK_HypeBeast_PrimaryAsset) */
|
||||
export interface SkinInfo {
|
||||
skin: string;
|
||||
level: string | null;
|
||||
chroma: string | null;
|
||||
charm?: string | null;
|
||||
charmLevel?: string | null;
|
||||
}
|
||||
|
||||
export interface ObjectPath {
|
||||
@@ -143,6 +156,13 @@ export function equipTracks(r: ReplayFile): [number, number][][] {
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 선수별 [t, skin] 목록 (equipTracks 와 같은 시각, equipAt 으로 찾는다. 스킨 기록이 없으면 -1) */
|
||||
export function skinTracks(r: ReplayFile): [number, number][][] {
|
||||
const out: [number, number][][] = r.players.map(() => []);
|
||||
for (const [t, p, , s] of r.equips ?? []) out[p]?.push([t, s ?? -1]);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** t 시점에 들고 있던 것 (kind 번호, 없으면 -1) */
|
||||
export function equipAt(track: [number, number][] | undefined, t: number): number {
|
||||
if (!track?.length || t < track[0][0]) return -1;
|
||||
|
||||
171
site/web/src/lib/scoreboard.ts
Normal file
171
site/web/src/lib/scoreboard.ts
Normal file
@@ -0,0 +1,171 @@
|
||||
import { indexAt, isDead, roundAt, samplePlayer, type ReplayFile } from './replay';
|
||||
|
||||
/**
|
||||
* 리플레이 점수판 (게임에서 Tab 을 누른 화면): 크레딧 · 궁극기 점수 · 킬/데스/어시 · 전투 점수.
|
||||
* 값은 변환기(1.10.0~)의 scoreboard 행 [t, 선수, 크레딧, 궁 점수, 킬, 데스, 어시, 전투 점수] (모르는 값 -1).
|
||||
* 옛 리플레이 JSON 에는 없어서 킬 · 데스만 리플레이 킬 기록으로 센다.
|
||||
*/
|
||||
const MONEY = 2;
|
||||
const ULT = 3;
|
||||
const KILLS = 4;
|
||||
const DEATHS = 5;
|
||||
const ASSISTS = 6;
|
||||
const SCORE = 7;
|
||||
|
||||
/** 요원(캐릭터 클래스 코드)별 궁극기 점수. 경기에서 궁을 쓴 기록이 있으면 그 값을 쓰고, 없을 때만 이 표 (패치로 바뀔 수 있다) */
|
||||
const ULT_COST: Record<string, number> = {
|
||||
Wushu: 8, Sarge: 8, Phoenix: 7, Hunter: 8, Thorne: 8, Pandemic: 9, Wraith: 7, Clay: 8, Vampire: 7, Breach: 8, Gumshoe: 6,
|
||||
Killjoy: 9, Guide: 8, Stealth: 8, Rift: 7, Grenadier: 8, Deadeye: 8, Sprinter: 7, BountyHunter: 8, Mage: 7, AggroBot: 8,
|
||||
Cable: 7, Sequoia: 7, Smonk: 8, Nox: 8, Cashew: 8, Terra: 8,
|
||||
};
|
||||
const DEFAULT_ULT = 8;
|
||||
|
||||
const PRIMARY = new Set(['Stinger', 'Spectre', 'Bucky', 'Judge', 'Bulldog', 'Guardian', 'Phantom', 'Vandal', 'Marshal', 'Outlaw', 'Operator', 'Ares', 'Odin']);
|
||||
const SIDEARM = new Set(['Classic', 'Shorty', 'Frenzy', 'Ghost', 'Sheriff', 'Compact Pistol']);
|
||||
|
||||
export interface BoardIndex {
|
||||
/** 선수별 행 · 행 시각 */
|
||||
rows: number[][][];
|
||||
times: number[][];
|
||||
/** 선수별 궁극기 점수 (다 모으면 궁 준비) */
|
||||
ultMax: number[];
|
||||
has: boolean;
|
||||
}
|
||||
|
||||
export function boardIndex(r: ReplayFile): BoardIndex {
|
||||
const rows: number[][][] = r.players.map(() => []);
|
||||
for (const row of r.scoreboard ?? []) rows[row[1]]?.push(row);
|
||||
for (const a of rows) a.sort((x, y) => x[0] - y[0]);
|
||||
const times = rows.map((a) => a.map((x) => x[0]));
|
||||
return { rows, times, ultMax: ultCosts(r, rows), has: rows.some((a) => a.length > 0) };
|
||||
}
|
||||
|
||||
/** 공수 교대로 시작한 라운드 번호 (rounds 의 순번): 선수들 시작 자리가 크게 바뀐 라운드 (같은 편이면 13m 안, 교대하면 90m 넘게, 13.08 어비스 실측) */
|
||||
const SWAP_CM = 4000;
|
||||
export function sideSwaps(r: ReplayFile): Set<number> {
|
||||
const out = new Set<number>();
|
||||
const spawn = (p: number, k: number) => samplePlayer(r.players[p].track, r.rounds[k].buy + 1500, r.sampleMs * 30);
|
||||
for (let k = 1; k < r.rounds.length; k++) {
|
||||
const d: number[] = [];
|
||||
for (let p = 0; p < r.players.length; p++) {
|
||||
const a = spawn(p, k - 1);
|
||||
const b = spawn(p, k);
|
||||
if (a && b) d.push(Math.hypot(a.x - b.x, a.y - b.y));
|
||||
}
|
||||
d.sort((x, y) => x - y);
|
||||
if (d.length && d[Math.floor(d.length / 2)] > SWAP_CM) out.add(k);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* 궁극기 점수: 궁을 쓴 순간(점수가 0 으로 떨어짐) 바로 앞 점수.
|
||||
* 공수 교대 초기화(교대 직전 라운드가 끝난 뒤 ~ 교대 라운드 구매 시작 3초 뒤 사이에 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 resets = [...sideSwaps(r)].map((k) => {
|
||||
const prev = r.rounds[k - 1];
|
||||
return [prev.end >= 0 ? prev.end : prev.combat >= 0 ? prev.combat : prev.buy, r.rounds[k].buy + 3000];
|
||||
});
|
||||
const used: number[][] = rows.map(() => []);
|
||||
for (const d of drops) {
|
||||
if (resets.some(([a, b]) => d.t >= a && d.t <= b)) 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 done = !!rd && rd.end >= 0 && t >= rd.end;
|
||||
const before = rounds?.filter((x) => (done ? x.num <= num : x.num < num)).sort((a, b) => b.num - a.num)[0];
|
||||
return { round: num, ally: before?.score.ally ?? 0, enemy: before?.score.enemy ?? 0 };
|
||||
}
|
||||
|
||||
function mode(a: number[]) {
|
||||
const c = new Map<number, number>();
|
||||
for (const v of a) c.set(v, (c.get(v) ?? 0) + 1);
|
||||
return [...c.entries()].sort((x, y) => y[1] - x[1] || y[0] - x[0])[0][0];
|
||||
}
|
||||
83
site/web/src/lib/skins.ts
Normal file
83
site/web/src/lib/skins.ts
Normal file
@@ -0,0 +1,83 @@
|
||||
import type { ReplayFile, SkinInfo } from './replay';
|
||||
|
||||
/**
|
||||
* 무기 스킨 3D (사이트 서버 /site/maps3d/skins, 로그인 필요).
|
||||
* 리플레이 skins 의 스킨 · 단계 · 색상으로 찾는다. 아직 없는 스킨은 요청만 해 두고 기본 스킨으로 그린다
|
||||
* (이 서버가 몇 분 안에 그 스킨만 뽑아 올리므로 다음에 열면 보인다, tools/map-extract/scripts/skins-update.sh).
|
||||
* skins[열쇠] = {weapon, sig}, looks[sig] = {w3p(3인칭 glb), w1p(1인칭 glb, 총 동작 포함), …}. 파일은 /site/maps3d/skins/<파일>
|
||||
*/
|
||||
export interface SkinLook {
|
||||
w3p?: string;
|
||||
w1p?: string;
|
||||
points?: Record<string, number[]>;
|
||||
points1p?: Record<string, number[]>;
|
||||
gunClips?: string[];
|
||||
}
|
||||
interface SkinsIndex {
|
||||
skins: Record<string, { weapon: string; sig: string }>;
|
||||
looks: Record<string, SkinLook>;
|
||||
failed?: Record<string, string>;
|
||||
}
|
||||
|
||||
export const skinKey = (s: SkinInfo) => `${s.skin}|${s.level ?? ''}|${s.chroma ?? ''}`;
|
||||
|
||||
/** 기본 스킨 (…_Standard_PrimaryAsset, 예: Melee_Base_Standard · Compact_Standard): 따로 뽑지 않고 기본 무기 모델을 쓴다 */
|
||||
export const isDefaultSkin = (s: SkinInfo) => /_Standard_PrimaryAsset$/.test(s.skin);
|
||||
|
||||
export const skinFileUrl = (file: string) => `/site/maps3d/skins/${encodeURIComponent(file)}`;
|
||||
|
||||
/** 스킨 목록. 부를 때마다 새로 받는다 (리플레이를 다시 열면 그사이 뽑힌 스킨이 보이게). 받는 중이면 그 요청을 같이 쓴다 */
|
||||
let indexP: Promise<SkinsIndex | null> | null = null;
|
||||
export function loadSkins(): Promise<SkinsIndex | null> {
|
||||
indexP ??= fetch('/site/maps3d/skins', { credentials: 'same-origin', cache: 'no-store' })
|
||||
.then((r) => (r.ok ? (r.json() as Promise<SkinsIndex>) : null))
|
||||
.catch(() => null)
|
||||
.finally(() => {
|
||||
indexP = null;
|
||||
});
|
||||
return indexP;
|
||||
}
|
||||
|
||||
/** 이 스킨의 모습 (없거나 기본 스킨이면 null) */
|
||||
export function lookOf(idx: SkinsIndex | null, s: SkinInfo | undefined | null): SkinLook | null {
|
||||
if (!idx || !s || isDefaultSkin(s)) return null;
|
||||
const e = idx.skins[skinKey(s)];
|
||||
return (e && idx.looks[e.sig]) || null;
|
||||
}
|
||||
|
||||
/** 리플레이에 나온 스킨 중 아직 없는 것 (기본 스킨 · 실패한 것은 빼고) */
|
||||
export function missingSkins(idx: SkinsIndex, r: Pick<ReplayFile, 'skins'>): string[] {
|
||||
const out = new Set<string>();
|
||||
for (const s of r.skins ?? []) {
|
||||
if (isDefaultSkin(s)) continue;
|
||||
const k = skinKey(s);
|
||||
if (!idx.skins[k] && !idx.failed?.[k]) out.add(k);
|
||||
}
|
||||
return [...out];
|
||||
}
|
||||
|
||||
/** 요청 한 번에 보내는 열쇠 수 (서버 MAX_WANT_PER_REQUEST 와 같다) */
|
||||
export const WANT_CHUNK = 100;
|
||||
|
||||
/** 열쇠를 WANT_CHUNK 개씩 나눈다 */
|
||||
export function chunks<T>(list: T[], n = WANT_CHUNK): T[][] {
|
||||
const out: T[][] = [];
|
||||
for (let i = 0; i < list.length; i += n) out.push(list.slice(i, i + n));
|
||||
return out;
|
||||
}
|
||||
|
||||
/** 없는 스킨을 뽑아 달라고 요청한다 (100개씩 나눠 전부, 실패해도 그냥 기본 스킨). 넣은 개수 */
|
||||
export async function requestMissing(idx: SkinsIndex, r: Pick<ReplayFile, 'skins'>): Promise<number> {
|
||||
let queued = 0;
|
||||
for (const keys of chunks(missingSkins(idx, r))) {
|
||||
const res = await fetch('/site/maps3d/skins/want', {
|
||||
method: 'POST',
|
||||
credentials: 'same-origin',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify({ keys }),
|
||||
}).catch(() => null);
|
||||
if (!res?.ok) break;
|
||||
queued += ((await res.json()) as { queued?: number }).queued ?? 0;
|
||||
}
|
||||
return queued;
|
||||
}
|
||||
@@ -4,6 +4,7 @@ import { MeshoptDecoder } from 'three/examples/jsm/libs/meshopt_decoder.module.j
|
||||
import { clone as cloneSkinned } from 'three/examples/jsm/utils/SkeletonUtils.js';
|
||||
import { assetUrl } from './agents3d';
|
||||
import { loadIndex } from './map3d';
|
||||
import { skinFileUrl, type SkinLook } from './skins';
|
||||
|
||||
/**
|
||||
* 1인칭 화면 팔 · 총 (tools/map-extract viewmodels → index.json viewmodels).
|
||||
@@ -120,16 +121,17 @@ export class Viewmodel {
|
||||
return !!character && !!weapon && !!this.idx.arms[character] && !!this.idx.weapons[weapon];
|
||||
}
|
||||
|
||||
/** 요원 · 무기를 바꾼다 (같으면 그대로). 받는 동안은 이전 모델을 그린다 */
|
||||
set(character: string, weapon: string) {
|
||||
const key = `${character}|${weapon}`;
|
||||
/** 요원 · 무기(· 스킨)를 바꾼다 (같으면 그대로). 받는 동안은 이전 모델을 그린다. 스킨 1인칭 모델을 받지 못하면 기본 스킨 */
|
||||
set(character: string, weapon: string, skin?: SkinLook | null) {
|
||||
const key = `${character}|${weapon}|${skin?.w1p ?? ''}`;
|
||||
if (key === this.want) return;
|
||||
this.want = key;
|
||||
const a = this.idx.arms[character];
|
||||
const w = this.idx.weapons[weapon];
|
||||
if (!a || !w) return;
|
||||
const url = (f: string) => assetUrl(this.idx.dir, f);
|
||||
void Promise.all([load(url(a.file)), load(url(w.file)), load(url(w.anim))])
|
||||
const gun = skin?.w1p ? load(skinFileUrl(skin.w1p)).catch(() => load(url(w.file))) : load(url(w.file));
|
||||
void Promise.all([load(url(a.file)), gun, load(url(w.anim))])
|
||||
.then(([ag, wg, an]) => {
|
||||
if (this.disposed || this.want !== key) return;
|
||||
this.build(ag, wg, an);
|
||||
|
||||
@@ -188,7 +188,7 @@ function MatchRow({ x, on, running, onClick }: { x: CulpritMatchItem; on: boolea
|
||||
<small>
|
||||
{m.mode} · {fmtWhen(m.startedAt)}
|
||||
{m.endedAt ? ` · ${fmtDuration(m.endedAt - m.startedAt)}` : ''}
|
||||
{x.eligibility.reasons[0] ? ` · ${x.eligibility.reasons[0]}` : ''}
|
||||
{x.eligibility.reasons[0] ? ` · ${x.eligibility.reasons[0]}` : x.eligibility.notes?.[0] ? ` · ${x.eligibility.notes[0].split(':')[0]}` : ''}
|
||||
</small>
|
||||
</span>
|
||||
<span className={`cu-score ${m.win === null ? '' : m.win ? 'win' : 'loss'}`}>{score}</span>
|
||||
@@ -236,7 +236,8 @@ function PrepPanel({ info, budget, progress, onStart, onOpen }: { info: CulpritM
|
||||
[true, m.game === 'valorant' ? '킬 · 스파이크 · 라운드 결과 이벤트' : '킬 · 오브젝트 이벤트', `${s.events}개`],
|
||||
[e.state !== 'pending' || !e.reasons[0]?.startsWith('음성 변환'), '음성 대화 (텍스트 변환 완료)', `${s.utterances}문장`],
|
||||
[true, '인게임 채팅 (팀 · 전체)', `${s.chats}개`],
|
||||
[!e.reasons.some((r) => r.startsWith('녹음')), '녹음이 경기 시작부터 끝까지 이어짐', ''],
|
||||
// 녹음이 없거나 끊겨도 분석은 된다 (v1.11.0 앱): 빠진 것만 ✕ 로 보이고 아래 안내를 단다
|
||||
[!e.reasons.some((r) => r.startsWith('녹음')) && !e.notes?.length, '녹음이 경기 시작부터 끝까지 이어짐', e.notes?.length ? '없어도 분석 가능' : ''],
|
||||
];
|
||||
return (
|
||||
<>
|
||||
@@ -261,7 +262,7 @@ function PrepPanel({ info, budget, progress, onStart, onOpen }: { info: CulpritM
|
||||
<section className="panel">
|
||||
<h4>
|
||||
<span>분석에 쓰는 기록</span>
|
||||
<span className={`cu-st ${e.state}`}>{e.state === 'ready' || e.state === 'done' ? '모두 있음' : STATE_LABEL[e.state]}</span>
|
||||
<span className={`cu-st ${e.state}`}>{e.state === 'ready' || e.state === 'done' ? (e.notes?.length ? '분석 가능' : '모두 있음') : STATE_LABEL[e.state]}</span>
|
||||
</h4>
|
||||
{checks.map(([ok, label, val]) => (
|
||||
<div key={label} className={`cu-check${ok ? '' : ' no'}`}>
|
||||
@@ -272,6 +273,7 @@ function PrepPanel({ info, budget, progress, onStart, onOpen }: { info: CulpritM
|
||||
))}
|
||||
{!s.extraStats && <div className="dim small cu-note">이 경기는 피해량 · 시야 같은 추가 지표가 없어 기본 기록으로 분석합니다.</div>}
|
||||
{e.reasons.length > 0 && <div className="cu-reason">{e.reasons.join(' · ')}</div>}
|
||||
{!!e.notes?.length && <div className="dim small cu-note">{e.notes.join(' · ')}</div>}
|
||||
<div className="dim small cu-note">음성 파일은 7일 뒤 지워져도 괜찮습니다. 분석은 텍스트로 합니다.</div>
|
||||
</section>
|
||||
<section className="panel">
|
||||
|
||||
@@ -15,7 +15,9 @@ export function toggleUser(f: Filters, users: User[], id: string): string[] {
|
||||
return all.every((x) => nextSet.includes(x)) ? [] : nextSet;
|
||||
}
|
||||
|
||||
export function MatchItem({ m, on, onClick }: { m: MatchSummary; on?: boolean; onClick?: () => void }) {
|
||||
/** tags: 경기 탭에서 녹음 · 기록만 표시 */
|
||||
export function MatchItem({ m, on, onClick, tags }: { m: MatchSummary; on?: boolean; onClick?: () => void; tags?: boolean }) {
|
||||
const voice = m.voice ?? m.participants.length > 0;
|
||||
const dur = m.endedAt ? Math.round((m.endedAt - m.startedAt) / 60000) : null;
|
||||
const res = m.win == null ? '' : m.win ? '승' : '패';
|
||||
const Tag = onClick ? 'button' : 'div';
|
||||
@@ -32,6 +34,19 @@ export function MatchItem({ m, on, onClick }: { m: MatchSummary; on?: boolean; o
|
||||
{dur != null ? ` · ${dur}분` : ''}
|
||||
{m.status === 'live' && <span className="live-dot"> · 진행 중</span>}
|
||||
</div>
|
||||
{tags && (voice || m.source === 'history') && (
|
||||
<div className="m-tags">
|
||||
{voice ? (
|
||||
<span className="m-tag voice" title="디스코드 대화가 녹음된 경기">
|
||||
🎙 녹음
|
||||
</span>
|
||||
) : (
|
||||
<span className="m-tag hist" title="겜녹이가 꺼져 있을 때 한 경기 (Riot 경기 기록에서 가져옴)">
|
||||
경기 기록만
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{res && <span className={`badge ${m.win ? 'b-win' : 'b-loss'}`}>{res}</span>}
|
||||
</Tag>
|
||||
|
||||
@@ -257,7 +257,7 @@ export function TimelinePage() {
|
||||
// 사이드바 경기 목록 · 선택한 경기 상세
|
||||
useEffect(() => {
|
||||
api
|
||||
.matches({ limit: 15, game: f.game === 'valorant' || f.game === 'lol' ? f.game : undefined })
|
||||
.matches({ limit: 15, game: f.game === 'valorant' || f.game === 'lol' ? f.game : undefined, has: 'timeline' })
|
||||
.then(setMatches)
|
||||
.catch(() => {});
|
||||
}, [f.game, epoch]);
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
import { Link, useNavigate, useParams } from 'react-router';
|
||||
import type { GameType, MatchSummary, User, UserProfile } from '@gvr/shared';
|
||||
import { api } from '../lib/api';
|
||||
import { api, type MatchHas } from '../lib/api';
|
||||
import { useStatus } from '../store/app';
|
||||
import { fmtDuration, fmtDay } from '../lib/format';
|
||||
import { dateInputToMs, dateInputValue, fmtDuration, fmtDay } from '../lib/format';
|
||||
import { sfx } from '../lib/sfx';
|
||||
import { Avatar, ErrorBox, Spinner } from '../components/common';
|
||||
import { MatchItem } from './Sidebar';
|
||||
import { HistoryHint, HistoryImport } from '../components/HistoryImport';
|
||||
|
||||
function useLoad<T>(fn: () => Promise<T>, deps: unknown[]) {
|
||||
const { epoch } = useStatus();
|
||||
@@ -50,18 +51,91 @@ export function UsersPage() {
|
||||
);
|
||||
}
|
||||
|
||||
const PAGE = 50;
|
||||
/** 목소리가 녹음된 경기 (예전 앱은 voice 가 없어 말한 사람으로 본다) */
|
||||
const hasVoice = (m: MatchSummary) => m.voice ?? m.participants.length > 0;
|
||||
const HAS_CHIPS: { has: MatchHas | null; label: string; title: string }[] = [
|
||||
{ has: null, label: '전체 경기', title: '내가 플레이한 경기 전부 (앱이 꺼져 있을 때 한 경기는 Riot 경기 기록에서 가져옴)' },
|
||||
{ has: 'timeline', label: '타임라인 있는 경기', title: '겜녹이가 켜져 있을 때 한 경기 (타임라인에서 대화 · 킬을 같이 볼 수 있음)' },
|
||||
{ has: 'voice', label: '목소리 녹음된 경기', title: '디스코드 대화가 녹음된 경기' },
|
||||
];
|
||||
|
||||
/** 경기 목록에 보이지 않는 모드 (예전 앱은 다 보내서 여기서도 거른다) */
|
||||
const HIDDEN_MODE = '데스매치';
|
||||
|
||||
export function MatchesPage() {
|
||||
const [game, setGame] = useState<GameType | null>(null);
|
||||
const [game, setGameRaw] = useState<GameType | null>(null);
|
||||
const [has, setHas] = useState<MatchHas | null>(null);
|
||||
const [mode, setMode] = useState<string | null>(null);
|
||||
// 날짜 (한국 시각): from = 시작 날 0시, to = 끝 날 23:59:59.999
|
||||
const [from, setFrom] = useState<number | undefined>(undefined);
|
||||
const [to, setTo] = useState<number | undefined>(undefined);
|
||||
// 게임을 바꾸면 그 게임에 없을 수 있는 모드는 풀어 준다
|
||||
const setGame = (g: GameType | null) => {
|
||||
setGameRaw(g);
|
||||
setMode(null);
|
||||
};
|
||||
const nav = useNavigate();
|
||||
const { data, err, retry } = useLoad<MatchSummary[]>(() => api.matches({ limit: 50, game: game ?? undefined }), [game]);
|
||||
const query = { limit: PAGE, game: game ?? undefined, has: has ?? undefined, mode: mode ?? undefined, after: from, before: to === undefined ? undefined : to + 1 };
|
||||
const { data, err, retry } = useLoad<MatchSummary[]>(() => api.matches(query), [game, has, mode, from, to]);
|
||||
// 모드 목록: 예전 앱(404)은 불러온 경기에서 만든다
|
||||
const [modeList, setModeList] = useState<{ mode: string; count: number | null }[] | null>(null);
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
api
|
||||
.matchModes(game ?? undefined)
|
||||
.then((r) => {
|
||||
if (!alive) return;
|
||||
const by = new Map<string, number>();
|
||||
for (const x of r) by.set(x.mode, (by.get(x.mode) ?? 0) + x.count);
|
||||
setModeList([...by].map(([m, count]) => ({ mode: m, count })));
|
||||
})
|
||||
.catch(() => alive && setModeList(null));
|
||||
return () => {
|
||||
alive = false;
|
||||
};
|
||||
}, [game, data]);
|
||||
// 더 보기: 지난 쪽 경기들 (필터가 바뀌면 처음부터)
|
||||
const [more, setMore] = useState<{ list: MatchSummary[]; done: boolean; busy: boolean; err: unknown }>({ list: [], done: false, busy: false, err: null });
|
||||
useEffect(() => setMore({ list: [], done: false, busy: false, err: null }), [data]);
|
||||
const all = useMemo(() => {
|
||||
const seen = new Set<string>();
|
||||
const out: MatchSummary[] = [];
|
||||
for (const m of [...(data ?? []), ...more.list]) {
|
||||
if (seen.has(m.id)) continue;
|
||||
seen.add(m.id);
|
||||
// 예전 앱은 has · 모드 · 날짜를 모르고 다 보낸다: 여기서도 거른다
|
||||
if (has === 'voice' && !hasVoice(m)) continue;
|
||||
if (m.mode === HIDDEN_MODE || (mode && m.mode !== mode)) continue;
|
||||
if ((from !== undefined && m.startedAt < from) || (to !== undefined && m.startedAt > to)) continue;
|
||||
out.push(m);
|
||||
}
|
||||
return out;
|
||||
}, [data, more.list, has, mode, from, to]);
|
||||
const modes = useMemo(() => {
|
||||
if (modeList) return modeList;
|
||||
const seen = [...new Set([...(data ?? []), ...more.list].filter((m) => !game || m.game === game).map((m) => m.mode))];
|
||||
return seen.filter((m) => m !== HIDDEN_MODE).map((m) => ({ mode: m, count: null }));
|
||||
}, [modeList, data, more.list, game]);
|
||||
const canMore = !!data && data.length >= PAGE && !more.done;
|
||||
const loadMore = () => {
|
||||
const last = more.list[more.list.length - 1] ?? data?.[data.length - 1];
|
||||
if (!last || more.busy) return;
|
||||
setMore((s) => ({ ...s, busy: true, err: null }));
|
||||
api
|
||||
.matches({ ...query, before: last.startedAt })
|
||||
.then((r) => setMore((s) => ({ list: [...s.list, ...r], done: r.length < PAGE, busy: false, err: null })))
|
||||
.catch((e) => setMore((s) => ({ ...s, busy: false, err: e })));
|
||||
};
|
||||
const filtered = !!mode || from !== undefined || to !== undefined;
|
||||
const groups = useMemo(() => {
|
||||
const g = new Map<string, MatchSummary[]>();
|
||||
for (const m of data ?? []) {
|
||||
for (const m of all) {
|
||||
const d = fmtDay(m.startedAt);
|
||||
g.set(d, [...(g.get(d) ?? []), m]);
|
||||
}
|
||||
return [...g];
|
||||
}, [data]);
|
||||
}, [all]);
|
||||
return (
|
||||
<main className="page-pad">
|
||||
<div className="page-h-row">
|
||||
@@ -78,19 +152,75 @@ export function MatchesPage() {
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="chips-wrap match-has">
|
||||
{HAS_CHIPS.map((c) => (
|
||||
<button key={c.label} className={`chip${has === c.has ? ' on-mint' : ''}`} title={c.title} onClick={() => setHas(c.has)}>
|
||||
{c.label}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<div className="match-filters">
|
||||
<select className="mf-sel" value={mode ?? ''} onChange={(e) => setMode(e.target.value || null)} aria-label="모드">
|
||||
<option value="">모든 모드</option>
|
||||
{mode && !modes.some((m) => m.mode === mode) && <option value={mode}>{mode}</option>}
|
||||
{modes.map((m) => (
|
||||
<option key={m.mode} value={m.mode}>
|
||||
{m.mode}
|
||||
{m.count !== null ? ` (${m.count})` : ''}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<div className="dates mf-dates">
|
||||
<input type="date" value={dateInputValue(from)} max={dateInputValue(to)} onChange={(e) => setFrom(dateInputToMs(e.target.value))} aria-label="시작 날짜" />
|
||||
<span className="dim">~</span>
|
||||
<input type="date" value={dateInputValue(to)} min={dateInputValue(from)} onChange={(e) => setTo(dateInputToMs(e.target.value, true))} aria-label="끝 날짜" />
|
||||
</div>
|
||||
{filtered && (
|
||||
<button
|
||||
className="link-btn"
|
||||
onClick={() => {
|
||||
setMode(null);
|
||||
setFrom(undefined);
|
||||
setTo(undefined);
|
||||
}}
|
||||
>
|
||||
모드 · 날짜 초기화
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
<HistoryImport onDone={retry} />
|
||||
<HistoryHint />
|
||||
{err != null && <ErrorBox error={err} onRetry={retry} />}
|
||||
{!data && !err && <Spinner />}
|
||||
{data && data.length === 0 && <div className="empty">경기 기록이 없습니다.</div>}
|
||||
{!data && !err && <Spinner label="경기 목록 불러오는 중" />}
|
||||
{data && all.length === 0 && (
|
||||
<div className="empty">
|
||||
{filtered
|
||||
? '고른 모드 · 날짜에 맞는 경기가 없습니다.'
|
||||
: has === 'voice'
|
||||
? '목소리가 녹음된 경기가 없습니다.'
|
||||
: has === 'timeline'
|
||||
? '타임라인이 있는 경기가 없습니다.'
|
||||
: '경기 기록이 없습니다.'}
|
||||
</div>
|
||||
)}
|
||||
{groups.map(([day, ms]) => (
|
||||
<section key={day} className="match-day">
|
||||
<h4>{day}</h4>
|
||||
<div className="match-cards">
|
||||
{ms.map((m) => (
|
||||
<MatchItem key={m.id} m={m} onClick={() => nav(`/matches/${encodeURIComponent(m.id)}`)} />
|
||||
<MatchItem key={m.id} m={m} tags onClick={() => nav(`/matches/${encodeURIComponent(m.id)}`)} />
|
||||
))}
|
||||
</div>
|
||||
</section>
|
||||
))}
|
||||
{more.err != null && <ErrorBox error={more.err} onRetry={loadMore} />}
|
||||
{canMore && (
|
||||
<div className="more-row">
|
||||
<button className="btn" onClick={loadMore} disabled={more.busy}>
|
||||
{more.busy ? '불러오는 중…' : '지난 경기 더 보기'}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2737,6 +2737,56 @@ button.match:hover {
|
||||
letter-spacing: 1px;
|
||||
margin: 20px 0 8px;
|
||||
}
|
||||
.match-has {
|
||||
margin: 4px 0 2px;
|
||||
}
|
||||
.match-filters {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
flex-wrap: wrap;
|
||||
gap: 10px;
|
||||
margin: 8px 0 2px;
|
||||
}
|
||||
.mf-sel {
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 7px;
|
||||
padding: 6px 8px;
|
||||
font-size: 12.5px;
|
||||
color: #c6d1dc;
|
||||
}
|
||||
.mf-dates input {
|
||||
flex: none;
|
||||
width: 140px;
|
||||
}
|
||||
.hist-hint {
|
||||
margin: 8px 0 2px;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.m-tags {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
margin-top: 3px;
|
||||
}
|
||||
.m-tag {
|
||||
font-size: 11px;
|
||||
padding: 0 6px;
|
||||
border-radius: 4px;
|
||||
line-height: 17px;
|
||||
}
|
||||
.m-tag.voice {
|
||||
background: #0f2e2c;
|
||||
color: #7fe9e1;
|
||||
}
|
||||
.m-tag.hist {
|
||||
background: #1a2633;
|
||||
color: var(--muted);
|
||||
}
|
||||
.more-row {
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
margin: 18px 0 8px;
|
||||
}
|
||||
.match-cards {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
|
||||
@@ -3936,6 +3986,21 @@ button.match:hover {
|
||||
}
|
||||
|
||||
/* ── 3D 리플레이 (components/ReplayViewer.tsx) ── */
|
||||
.replay-msg {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
.replay-msg b {
|
||||
display: block;
|
||||
margin-bottom: 2px;
|
||||
color: #e6edf3;
|
||||
font-size: 13px;
|
||||
}
|
||||
.replay-msg .mini-btn {
|
||||
flex: none;
|
||||
}
|
||||
.replay-panel {
|
||||
flex: none;
|
||||
}
|
||||
@@ -4033,6 +4098,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;
|
||||
@@ -4486,3 +4674,83 @@ button.match:hover {
|
||||
max-height: calc(100vh - var(--header-h) - 16px);
|
||||
}
|
||||
}
|
||||
|
||||
/* Riot 경기 기록 가져오기 진행 바 (v1.9.1, 경기 탭) */
|
||||
.hist-import {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
margin: 10px 0 4px;
|
||||
}
|
||||
.hist-card {
|
||||
border: 1px solid var(--line);
|
||||
border-left: 3px solid var(--accent);
|
||||
border-radius: 10px;
|
||||
background: var(--panel);
|
||||
padding: 10px 14px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 7px;
|
||||
}
|
||||
.hist-card.lol {
|
||||
border-left-color: var(--lol);
|
||||
}
|
||||
.hist-top {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
font-size: 13.5px;
|
||||
}
|
||||
.hist-gap {
|
||||
flex: 1;
|
||||
}
|
||||
.hist-dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: var(--mint);
|
||||
animation: hist-pulse 1.2s ease-in-out infinite;
|
||||
}
|
||||
@keyframes hist-pulse {
|
||||
50% {
|
||||
opacity: 0.3;
|
||||
}
|
||||
}
|
||||
.hist-card .btn,
|
||||
.hist-msg .btn {
|
||||
padding: 5px 12px;
|
||||
font-size: 12.5px;
|
||||
}
|
||||
.hist-bar i {
|
||||
background: var(--mint);
|
||||
}
|
||||
.hist-card.lol .hist-bar i {
|
||||
background: var(--lol);
|
||||
}
|
||||
.hist-bar.indet i {
|
||||
width: 35%;
|
||||
animation: hist-indet 1.4s ease-in-out infinite;
|
||||
}
|
||||
@keyframes hist-indet {
|
||||
0% {
|
||||
transform: translateX(-100%);
|
||||
}
|
||||
100% {
|
||||
transform: translateX(290%);
|
||||
}
|
||||
}
|
||||
.hist-msg {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 10px;
|
||||
font-size: 13px;
|
||||
padding: 8px 14px;
|
||||
border-radius: 10px;
|
||||
background: var(--panel2);
|
||||
color: var(--muted);
|
||||
}
|
||||
.hist-msg.bad {
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
#!/usr/bin/env bash
|
||||
# 맵 3D 자동 갱신을 이 리눅스 서버(.9)에 설치한다. 저장소에서: tools/map-extract/scripts/install.sh
|
||||
# - gvr-map-extract 를 빌드해 $GVR_MAPS_HOME/bin 에 둔다 (저장소 작업 폴더가 바뀌어도 타이머는 그대로 돈다)
|
||||
# - systemd 사용자 타이머 gvr-maps-update.timer (30분마다 update.sh). 메모리 6GB · CPU 3코어 상한, 봇과 다른 cgroup
|
||||
# - systemd 사용자 타이머 gvr-maps-update.timer (30분마다 update.sh, 02:00~07:00 제외). 메모리 6GB · CPU 3코어 상한, 봇과 다른 cgroup
|
||||
# - gvr-skins-update.timer (3분마다 skins-update.sh, 02:00~07:00 제외: 사이트가 요청한 무기 스킨만 뽑아 올린다, 같은 상한)
|
||||
# 코드를 고쳤으면 다시 실행하면 된다 (타이머를 꺼 뒀으면 꺼진 채로 둔다). 지금 바로 한 번 돌리기: systemctl --user start gvr-maps-update
|
||||
set -euo pipefail
|
||||
here="$(cd "$(dirname "$0")/.." && pwd)"
|
||||
@@ -21,8 +22,8 @@ mv "$GVR_MAPS_HOME/bin.new" "$GVR_MAPS_HOME/bin"
|
||||
[ -f "$GVR_MAPS_HOME/bin.old/liboodle-data-shared.so" ] && cp "$GVR_MAPS_HOME/bin.old/liboodle-data-shared.so" "$GVR_MAPS_HOME/bin/"
|
||||
rm -rf "$GVR_MAPS_HOME/bin.old"
|
||||
mkdir -p "$GVR_MAPS_HOME/scripts"
|
||||
cp "$here/scripts/update.sh" "$here/scripts/pack.py" "$here/scripts/preview.py" "$GVR_MAPS_HOME/scripts/"
|
||||
chmod +x "$GVR_MAPS_HOME/scripts/update.sh"
|
||||
cp "$here/scripts/update.sh" "$here/scripts/pack.py" "$here/scripts/preview.py" "$here/scripts/skins-update.sh" "$here/scripts/skins-merge.py" "$GVR_MAPS_HOME/scripts/"
|
||||
chmod +x "$GVR_MAPS_HOME/scripts/update.sh" "$GVR_MAPS_HOME/scripts/skins-update.sh"
|
||||
|
||||
unit="$HOME/.config/systemd/user"
|
||||
mkdir -p "$unit"
|
||||
@@ -56,18 +57,52 @@ TimeoutStartSec=2h
|
||||
EOF
|
||||
cat > "$unit/gvr-maps-update.timer" <<EOF
|
||||
[Unit]
|
||||
Description=겜녹이: 발로란트 맵 3D 자동 갱신 (30분마다)
|
||||
Description=겜녹이: 발로란트 맵 3D 자동 갱신 (30분마다, 02:00~07:00 제외)
|
||||
|
||||
[Timer]
|
||||
OnBootSec=5min
|
||||
OnUnitActiveSec=30min
|
||||
# 02:00~07:00 KST 는 돌리지 않는다 (사용자 규칙). 놓친 실행도 그 시간에 몰아서 하지 않게 Persistent 없이
|
||||
OnCalendar=*-*-* 00,01,07..23:00/30:00
|
||||
RandomizedDelaySec=2min
|
||||
Persistent=true
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
EOF
|
||||
# 무기 스킨 (요청한 것만): 맵과 같은 상한 · 잠금. 요청이 없으면 ssh 두 번으로 끝난다
|
||||
skins_was="$( [ -f "$unit/gvr-skins-update.timer" ] && (systemctl --user is-enabled gvr-skins-update.timer 2>/dev/null || true) || echo new)"
|
||||
cat > "$unit/gvr-skins-update.service" <<EOF
|
||||
[Unit]
|
||||
Description=겜녹이: 발로란트 무기 스킨 3D (사이트가 요청한 스킨만 추출 → 사이트 반영)
|
||||
After=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
Environment=GVR_MAPS_HOME=$GVR_MAPS_HOME
|
||||
Environment=DOTNET_ROOT=$DOTNET_ROOT
|
||||
Environment=PATH=$node_dir:$HOME/.dotnet:/usr/local/bin:/usr/bin:/bin
|
||||
Environment=TMPDIR=$HOME/.tmp
|
||||
ExecStart=$GVR_MAPS_HOME/scripts/skins-update.sh
|
||||
MemoryMax=6G
|
||||
MemorySwapMax=0
|
||||
CPUQuota=300%
|
||||
CPUWeight=50
|
||||
Nice=10
|
||||
TimeoutStartSec=2h
|
||||
EOF
|
||||
cat > "$unit/gvr-skins-update.timer" <<EOF
|
||||
[Unit]
|
||||
Description=겜녹이: 발로란트 무기 스킨 3D (3분마다 요청 확인, 02:00~07:00 제외)
|
||||
|
||||
[Timer]
|
||||
# 02:00~07:00 KST 는 돌리지 않는다 (사용자 규칙)
|
||||
OnCalendar=*-*-* 00,01,07..23:00/3:00
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
EOF
|
||||
systemctl --user daemon-reload
|
||||
if [ "$skins_was" = new ] || [ "$skins_was" = enabled ]; then
|
||||
systemctl --user enable --now gvr-skins-update.timer
|
||||
fi
|
||||
if [ "$timer_was" = new ] || [ "$timer_was" = enabled ]; then
|
||||
systemctl --user enable --now gvr-maps-update.timer
|
||||
echo "설치 완료: $GVR_MAPS_HOME · $(systemctl --user list-timers gvr-maps-update.timer --no-legend | head -1)"
|
||||
|
||||
65
tools/map-extract/scripts/skins-merge.py
Normal file
65
tools/map-extract/scripts/skins-merge.py
Normal file
@@ -0,0 +1,65 @@
|
||||
#!/usr/bin/env python3
|
||||
"""무기 스킨 목록 (사이트 data/maps3d/skins/index.json) 다루기. skins-update.sh 가 쓴다.
|
||||
skins-merge.py todo <index.json> <want.json> <매핑 버전> <최대 개수> → 뽑을 열쇠 (한 줄에 하나)
|
||||
skins-merge.py merge <index.json> <추출 결과 skins.json> <매핑 버전> → 합친 index.json (stdout)
|
||||
index.json = {version, updatedAt, skins:{열쇠:{weapon, sig}}, looks:{서명:{w3p, w1p, …}}, failed:{열쇠:이유}}
|
||||
failed 는 같은 매핑 버전에서만 유효하다 (패치가 바뀌면 다시 해 본다)."""
|
||||
import datetime, json, re, sys
|
||||
|
||||
KEY = re.compile(r'^/Game/Equippables/[A-Za-z0-9_/\-]+\|(/Game/Equippables/[A-Za-z0-9_/\-]+)?\|(/Game/Equippables/[A-Za-z0-9_/\-]+)?$')
|
||||
|
||||
|
||||
def load(path, default):
|
||||
try:
|
||||
with open(path) as f:
|
||||
return json.load(f)
|
||||
except (OSError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
def norm(idx, version):
|
||||
idx = idx if isinstance(idx, dict) else {}
|
||||
out = {'version': version, 'skins': dict(idx.get('skins') or {}), 'looks': dict(idx.get('looks') or {}), 'failed': dict(idx.get('failed') or {})}
|
||||
if idx.get('version') != version:
|
||||
out['failed'] = {}
|
||||
return out
|
||||
|
||||
|
||||
def todo(idx, want, version, limit):
|
||||
idx = norm(idx, version)
|
||||
seen, out = set(), []
|
||||
for k in want if isinstance(want, list) else []:
|
||||
if not isinstance(k, str) or not KEY.match(k) or k in seen or k in idx['skins'] or k in idx['failed']:
|
||||
continue
|
||||
seen.add(k)
|
||||
out.append(k)
|
||||
return out[:limit]
|
||||
|
||||
|
||||
def merge(idx, res, version):
|
||||
idx = norm(idx, version)
|
||||
res = res if isinstance(res, dict) else {}
|
||||
idx['looks'].update(res.get('looks') or {})
|
||||
for k, v in (res.get('skins') or {}).items():
|
||||
# 모습 파일이 있는 것만 (서명이 목록에 없으면 실패로)
|
||||
if v.get('sig') in idx['looks']:
|
||||
idx['skins'][k] = v
|
||||
idx['failed'].pop(k, None)
|
||||
else:
|
||||
idx['failed'][k] = '모습 없음'
|
||||
for k, why in (res.get('failed') or {}).items():
|
||||
if k not in idx['skins']:
|
||||
idx['failed'][k] = why
|
||||
idx['updatedAt'] = datetime.datetime.now(datetime.timezone.utc).isoformat()
|
||||
return idx
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
cmd = sys.argv[1]
|
||||
if cmd == 'todo':
|
||||
for k in todo(load(sys.argv[2], {}), load(sys.argv[3], []), sys.argv[4], int(sys.argv[5])):
|
||||
print(k)
|
||||
elif cmd == 'merge':
|
||||
json.dump(merge(load(sys.argv[2], {}), load(sys.argv[3], {}), sys.argv[4]), sys.stdout, ensure_ascii=False, indent=1)
|
||||
else:
|
||||
sys.exit(f'모르는 명령 {cmd}')
|
||||
60
tools/map-extract/scripts/skins-update.sh
Executable file
60
tools/map-extract/scripts/skins-update.sh
Executable file
@@ -0,0 +1,60 @@
|
||||
#!/usr/bin/env bash
|
||||
# 무기 스킨 3D: 사이트가 받은 요청(리플레이에서 본 스킨 중 아직 없는 것)을 가져와 그 스킨만 뽑아 올린다.
|
||||
# systemd 타이머 gvr-skins-update.timer 가 3분마다 실행 (install.sh). 요청이 없으면 ssh 두 번으로 끝난다.
|
||||
#
|
||||
# 1. 사이트 서버(.5) data/maps3d/skins/want.json (사이트가 쓴다) · index.json (여기서만 쓴다) 을 읽는다
|
||||
# 2. 아직 없는 열쇠만 (한 번에 SKINS_MAX 개) gvr-map-extract skins 로 뽑는다. 매니페스트 · 매핑은 지금 사이트에 올라간 맵과 같은 것
|
||||
# 3. gltfpack 압축 + gzip → skins/ 에 올리고 index.json 을 합쳐 바꿔 끼운다 (skins · looks 는 쌓이고, 뽑지 못한 것은 failed)
|
||||
# failed 는 맵 패치(매핑 버전)가 바뀌면 지운다 (새 패치에서 다시 해 본다)
|
||||
# 맵 갱신(update.sh)과 같은 잠금을 써서 동시에 돌지 않는다 (메모리 상한 공유).
|
||||
set -Eeuo pipefail
|
||||
GVR_MAPS_HOME="${GVR_MAPS_HOME:-$HOME/gvr-maps}"
|
||||
SITE_HOST="${SITE_HOST:-root@192.168.10.5}"
|
||||
SITE_DATA="${SITE_DATA:-/root/other/game-voice-recorder/data}"
|
||||
SKINS_MAX="${SKINS_MAX:-40}"
|
||||
export DOTNET_ROOT="${DOTNET_ROOT:-$HOME/.dotnet}"
|
||||
BIN="${BIN:-$GVR_MAPS_HOME/bin/gvr-map-extract}"
|
||||
STATE="$GVR_MAPS_HOME/state.json"
|
||||
log() { echo "[$(date '+%F %T')] $*"; }
|
||||
exec 9>"$GVR_MAPS_HOME/.lock"
|
||||
flock -n 9 || { log "맵 갱신 중 → 다음에"; exit 0; }
|
||||
|
||||
remote="$SITE_DATA/maps3d/skins"
|
||||
work="$GVR_MAPS_HOME/work/skins"
|
||||
rm -rf "$work"
|
||||
mkdir -p "$work/raw" "$work/out"
|
||||
ssh -o BatchMode=yes "$SITE_HOST" "cat '$remote/want.json' 2>/dev/null || echo '[]'" > "$work/want.json"
|
||||
ssh -o BatchMode=yes "$SITE_HOST" "cat '$remote/index.json' 2>/dev/null || echo '{}'" > "$work/index.json"
|
||||
|
||||
# 지금 사이트 맵과 같은 패치 (state.json published = "매핑 버전|갱신 시각|매니페스트")
|
||||
published="$(python3 -c 'import json,sys; print(json.load(open(sys.argv[1])).get("published",""))' "$STATE" 2>/dev/null || true)"
|
||||
version="${published%%|*}"
|
||||
manifest="${published##*|}"
|
||||
[ -n "$version" ] && [ -n "$manifest" ] || { log "올린 맵 패치를 모름 (state.json) → 건너뜀"; exit 0; }
|
||||
usmap="$(ls -t "$GVR_MAPS_HOME/mappings/${version}_"*.usmap 2>/dev/null | head -1)"
|
||||
[ -n "$usmap" ] || { log "매핑 $version 파일 없음 → 건너뜀"; exit 0; }
|
||||
|
||||
python3 "$GVR_MAPS_HOME/scripts/skins-merge.py" todo "$work/index.json" "$work/want.json" "$version" "$SKINS_MAX" > "$work/todo.txt"
|
||||
n="$(grep -c . "$work/todo.txt" || true)"
|
||||
[ "$n" -gt 0 ] || exit 0
|
||||
log "스킨 $n 개 뽑기 (매핑 $version)"
|
||||
GVR_USMAP="$usmap" GVR_MANIFEST="$manifest" "$BIN" skins "$work/raw" "$work/todo.txt" "$work/index.json"
|
||||
|
||||
# 압축: 뼈대 · 동작 · 노드 이름을 지킨다 (요원 · 1인칭 무기와 같음)
|
||||
for f in "$work/raw"/skin*.glb; do
|
||||
[ -e "$f" ] || continue
|
||||
b="$(basename "$f")"
|
||||
npx -y gltfpack@1.3.0 -i "$f" -o "$work/out/$b" -cc -kn -ke >/dev/null
|
||||
gzip -9 -n "$work/out/$b"
|
||||
done
|
||||
python3 "$GVR_MAPS_HOME/scripts/skins-merge.py" merge "$work/index.json" "$work/raw/skins.json" "$version" > "$work/out/index.json"
|
||||
|
||||
# 올리기: 파일 먼저, index.json 은 마지막에 바꿔 끼운다
|
||||
ssh -o BatchMode=yes "$SITE_HOST" "mkdir -p '$remote'"
|
||||
if ls "$work/out"/*.glb.gz >/dev/null 2>&1; then
|
||||
tar -C "$work/out" -cf - $(cd "$work/out" && ls *.glb.gz) | ssh -o BatchMode=yes "$SITE_HOST" "tar -xf - -C '$remote'"
|
||||
fi
|
||||
scp -q -o BatchMode=yes "$work/out/index.json" "$SITE_HOST:$remote/index.json.tmp"
|
||||
ssh -o BatchMode=yes "$SITE_HOST" "mv '$remote/index.json.tmp' '$remote/index.json'"
|
||||
log "스킨 반영: $(jq -r '"모습 \(.looks | length) · 스킨 \(.skins | length) · 실패 \(.failed | length)"' "$work/out/index.json")"
|
||||
rm -rf "$work"
|
||||
64
tools/map-extract/scripts/test-skins.sh
Executable file
64
tools/map-extract/scripts/test-skins.sh
Executable file
@@ -0,0 +1,64 @@
|
||||
#!/usr/bin/env bash
|
||||
# skins-update.sh 시험 (네트워크 · 사이트 서버 없이): 가짜 추출기 · 가짜 gltfpack(npx) · ssh/scp 를 로컬 복사로 바꿔
|
||||
# 요청 없음 → 요청한 것만 뽑아 올림 → 이미 있는 것 · 실패한 것은 다시 안 함 → 같은 모습은 파일 하나 → 패치가 바뀌면 실패한 것을 다시
|
||||
set -uo pipefail
|
||||
here="$(cd "$(dirname "$0")" && pwd)"
|
||||
T="$(mktemp -d "${TMPDIR:-/tmp}/gvr-skins-test.XXXXXX")"
|
||||
trap 'rm -rf "$T"' EXIT
|
||||
mkdir -p "$T/home/scripts" "$T/home/mappings" "$T/shim" "$T/site/maps3d/skins"
|
||||
cp "$here/skins-merge.py" "$T/home/scripts/"
|
||||
cat > "$T/shim/ssh" <<'E'
|
||||
#!/bin/bash
|
||||
while [[ "$1" == -* ]]; do shift 2; done; shift; exec bash -c "$*"
|
||||
E
|
||||
cat > "$T/shim/scp" <<'E'
|
||||
#!/bin/bash
|
||||
a=(); s=0; for x in "$@"; do [ $s = 1 ] && { s=0; continue; }; [ "$x" = -o ] && { s=1; continue; }; [[ "$x" == -* ]] && continue; a+=("${x#*:}"); done; cp "${a[0]}" "${a[1]}"
|
||||
E
|
||||
# npx -y gltfpack@… -i <in> -o <out> …: 그대로 복사
|
||||
cat > "$T/shim/npx" <<'E'
|
||||
#!/bin/bash
|
||||
while [ $# -gt 0 ]; do case "$1" in -i) i="$2"; shift 2;; -o) o="$2"; shift 2;; *) shift;; esac; done; cp "$i" "$o"
|
||||
E
|
||||
# 가짜 추출기: skins <출력> <요청> <known>. 열쇠에 Broken 이 들면 실패, Same 이면 이미 있는 모습(s0)
|
||||
cat > "$T/fakebin" <<'E'
|
||||
#!/bin/bash
|
||||
[ "$1" = skins ] || exit 2
|
||||
echo "$GVR_MANIFEST $GVR_USMAP" > "$T_LOG"
|
||||
python3 - "$2" "$3" <<'P'
|
||||
import hashlib, json, sys
|
||||
out, want = sys.argv[1], sys.argv[2]
|
||||
skins, looks, failed = {}, {}, {}
|
||||
for k in open(want).read().split():
|
||||
if 'Broken' in k: failed[k] = '메시 없음'; continue
|
||||
sig = 's0' if 'Same' in k else hashlib.sha1(k.encode()).hexdigest()[:6]
|
||||
skins[k] = {'weapon': 'Vandal', 'sig': sig}
|
||||
if sig != 's0':
|
||||
looks[sig] = {'w3p': f'skin3p_{sig}.glb', 'w1p': f'skin1p_{sig}.glb'}
|
||||
for f in looks[sig].values(): open(f'{out}/{f}', 'w').write('glb')
|
||||
json.dump({'skins': skins, 'looks': looks, 'failed': failed}, open(f'{out}/skins.json', 'w'))
|
||||
P
|
||||
E
|
||||
chmod +x "$T/shim/"* "$T/fakebin"
|
||||
echo usmap > "$T/home/mappings/V1_202610010000_br.usmap"
|
||||
echo usmap > "$T/home/mappings/V2_202611010000_br.usmap"
|
||||
echo '{"published":"V1|2026-10-01T00:00:00Z|https://x/releases/AAA.manifest"}' > "$T/home/state.json"
|
||||
R="$T/site/maps3d/skins"
|
||||
run() { PATH="$T/shim:$PATH" T_LOG="$T/ran" GVR_MAPS_HOME="$T/home" SITE_HOST=x SITE_DATA="$T/site" BIN="$T/fakebin" bash "$here/skins-update.sh" 2>&1; }
|
||||
want() { printf '%s\n' "$@" | jq -R . | jq -sc . > "$R/want.json"; }
|
||||
idx() { jq -c "$1" "$R/index.json"; }
|
||||
A='/Game/Equippables/Guns/Rifles/AK/A/A_PrimaryAsset|/Game/Equippables/Guns/Rifles/AK/A/Levels/A_Lv2_PrimaryAsset|'
|
||||
B='/Game/Equippables/Guns/Rifles/AK/Broken/B_PrimaryAsset||'
|
||||
S='/Game/Equippables/Guns/Rifles/AK/Same/S_PrimaryAsset||'
|
||||
fail=0
|
||||
ok() { if eval "$2"; then echo "ok - $1"; else echo "not ok - $1"; echo "$o" | tail -4 | sed "s|^| |"; fail=1; fi; }
|
||||
|
||||
o="$(run)"; ok "요청 없음: 아무것도 안 함" '[[ ! -e "$T/ran" && ! -e "$R/index.json" ]]'
|
||||
want "$A" "$B" 'bad||' "$A"
|
||||
o="$(run)"; ok "요청한 것만 뽑아 올림 (형식이 틀린 것은 뺌), 실패는 failed, 올린 맵과 같은 패치로" '[[ "$o" == *"스킨 2 개 뽑기"* && "$(idx ".skins | keys | length")" == 1 && "$(idx ".failed | keys")" == *Broken* && -f "$R/$(jq -r ".looks[].w3p" "$R/index.json").gz" && "$(cat "$T/ran")" == *AAA.manifest*V1_* ]]'
|
||||
rm -f "$T/ran"; o="$(run)"; ok "이미 있는 것 · 실패한 것은 다시 안 함" '[[ ! -e "$T/ran" ]]'
|
||||
jq '.looks.s0 = {"w3p":"skin3p_s0.glb"}' "$R/index.json" > "$R/i" && mv "$R/i" "$R/index.json"
|
||||
want "$A" "$B" "$S"; o="$(run)"; ok "같은 모습이 이미 있으면 파일 없이 목록만" '[[ "$(jq -r --arg k "$S" ".skins[\$k].sig" "$R/index.json")" == s0 && "$(idx ".looks | keys | length")" == 2 ]]'
|
||||
echo '{"published":"V2|2026-11-01T00:00:00Z|https://x/releases/BBB.manifest"}' > "$T/home/state.json"
|
||||
rm -f "$T/ran"; o="$(run)"; ok "패치가 바뀌면 실패한 것만 다시 해 봄 (뽑아 둔 것은 그대로)" '[[ "$o" == *"스킨 1 개 뽑기"* && "$(cat "$T/ran")" == *BBB.manifest*V2_* && "$(idx ".skins | keys | length")" == 2 && "$(idx .version)" == "\"V2\"" ]]'
|
||||
exit $fail
|
||||
@@ -47,7 +47,7 @@ E
|
||||
chmod +x "$T/shim/"* "$T/fakebin"
|
||||
echo usmap > "$T/m_br.usmap"
|
||||
echo "{\"version\":\"V1\",\"updated\":\"2026-10-17T00:00:00Z\",\"mappings\":{\"Brotli\":\"file://$T/m_br.usmap\"}}" > "$T/uedb.json"
|
||||
run() { PATH="$T/shim:$PATH" GVR_MAPS_HOME="$T/home" SITE_HOST=x SITE_DATA="$T/site" UEDB="file://$T/uedb.json" BIN="$T/fakebin" SECRETS=/nonexistent NOTIFY_CHANNEL= bash "$UPD" "$@" 2>&1; }
|
||||
run() { PATH="$T/shim:$PATH" GVR_MAPS_HOME="$T/home" SITE_HOST=x SITE_DATA="$T/site" UEDB="file://$T/uedb.json" VAPI="file://$T/vapi.json" BIN="$T/fakebin" SECRETS=/nonexistent NOTIFY_CHANNEL= bash "$UPD" "$@" 2>&1; }
|
||||
st() { python3 -c 'import json,sys; print(json.load(open(sys.argv[1])).get(sys.argv[2], ""))' "$T/home/state.json" "$1"; }
|
||||
ready() { python3 -c 'import json,sys; f=sys.argv[1]; d=json.load(open(f)); d["retryAt"]="0"; json.dump(d, open(f, "w"))' "$T/home/state.json"; }
|
||||
maps() { jq -c '.maps | keys' "$T/site/maps3d/index.json"; }
|
||||
@@ -63,7 +63,8 @@ ready; o="$(FAKE_MANIFEST=BBB FAKE_FAIL=extract run)"; ok "재실패: 알림 없
|
||||
ready; o="$(FAKE_MANIFEST=BBB FAKE_MAPS=Ascent FAKE_STAMP=2 run)"; ok "맵이 빠진 결과는 안 올림" '[[ "$o" == *"빠진 맵: /Game/Maps/Bind/Bind"* && "$(maps)" == *Bind* ]]'
|
||||
ready; mv "$T/home/scripts/pack.py" "$T/pack.bak"; o="$(FAKE_MANIFEST=BBB run)"; mv "$T/pack.bak" "$T/home/scripts/pack.py"
|
||||
ok "압축 실패도 같은 실패 처리" '[[ "$o" == *"압축 단계"* ]]'
|
||||
ready; o="$(FAKE_MANIFEST=BBB FAKE_MAPS="Ascent Bind Haven" FAKE_STAMP=3 run)"; ok "복구: 새 맵 포함해 올리고 이전 폴더 하나만 남김" '[[ "$o" == *"맵 3 개"* && "$(maps)" == *Haven* && "$(ls "$T/site/maps3d" | tr "\n" " ")" == "V1-1 V1-3 index.json " && "$(st failCount)" == 0 ]]'
|
||||
mkdir -p "$T/site/maps3d/skins" && echo '{}' > "$T/site/maps3d/skins/index.json"
|
||||
ready; o="$(FAKE_MANIFEST=BBB FAKE_MAPS="Ascent Bind Haven" FAKE_STAMP=3 run)"; ok "복구: 새 맵 포함해 올리고 이전 폴더 하나만 남김 (무기 스킨 skins/ 는 그대로)" '[[ "$o" == *"맵 3 개"* && "$(maps)" == *Haven* && "$(ls "$T/site/maps3d" | tr "\n" " ")" == "V1-1 V1-3 index.json skins " && -f "$T/site/maps3d/skins/index.json" && "$(st failCount)" == 0 ]]'
|
||||
# 요원 · 무기 추출 실패: 맵이 다 있어도 안 올리고 사이트 목록 유지, 재시도
|
||||
o="$(FAKE_MANIFEST=EEE FAKE_MAPS="Ascent Bind Haven" FAKE_FAIL=agents FAKE_STAMP=5 run)"; ok "요원 추출 전체 실패: 안 올림 · 요원 · 무기 유지 · 30분 뒤" '[[ "$o" == *"요원 추출 단계"* && "$o" == *"30분 뒤"* && "$(agents)" == "[2,1]" && "$(jq -r .dir "$T/site/maps3d/index.json")" == V1-3 ]]'
|
||||
ready; o="$(FAKE_MANIFEST=EEE FAKE_MAPS="Ascent Bind Haven" FAKE_FAIL=agents-partial FAKE_STAMP=5 run)"; ok "요원 추출 일부 실패: 안 올림 · 유지 · 간격 2배" '[[ "$o" == *"요원 추출 단계"* && "$o" == *"60분 뒤"* && "$(agents)" == "[2,1]" ]]'
|
||||
@@ -73,4 +74,8 @@ ready; o="$(FAKE_MANIFEST=EEE FAKE_MAPS="Ascent Bind Haven" FAKE_AGENTS="Wushu H
|
||||
o="$(FAKE_MANIFEST=FFF FAKE_MAPS="Ascent BIND Haven" FAKE_AGENTS="Wushu Hunter Sarge" FAKE_STAMP=7 run)"; ok "맵 경로 대소문자만 바뀐 것은 빠진 것이 아님 (사이트도 대소문자 무시)" '[[ "$o" == *"사이트 반영 완료"* && "$(maps)" == *BIND* && "$(maps)" != *Bind* ]]'
|
||||
mv "$T/uedb.json" "$T/uedb.bak"; o="$(FAKE_MANIFEST=CCC run)"; mv "$T/uedb.bak" "$T/uedb.json"; ok "uedb 장애: 확인 실패 횟수만 셈" '[[ "$o" == *"확인 실패 (1 번째"* ]]'
|
||||
o="$(FAKE_MANIFEST=DDD FAKE_MAPS=Ascent FAKE_STAMP=4 run --force)"; ok "--force 면 빠진 맵도 올림" '[[ "$(maps)" == "[\"/Game/Maps/Ascent/Ascent\"]" ]]'
|
||||
# uedb 가 새 패치를 늦게 올림: valorant-api.com 매니페스트가 라이브와 같으면 그 매핑으로, 다르면 uedb 그대로
|
||||
echo "{\"data\":{\"manifestId\":\"GGG\",\"branch\":\"release-2.00\",\"mappingsUrl\":\"file://$T/m_br.usmap\",\"buildDate\":\"2026-11-07T00:00:00Z\"}}" > "$T/vapi.json"
|
||||
o="$(FAKE_MANIFEST=HHH run)"; ok "valorant-api 매니페스트가 라이브와 다르면 uedb 매핑" '[[ "$(st published)" == V1\|*HHH* ]]'
|
||||
o="$(FAKE_MANIFEST=GGG run)"; ok "uedb 가 늦으면 라이브와 같은 valorant-api 매핑으로 올림" '[[ "$o" == *"valorant-api.com 매핑(VALORANT_2.00)"* && "$(st published)" == VALORANT_2.00\|2026-11-07* && -n "$(ls "$T/home/mappings/" | grep "^VALORANT_2.00_")" ]]'
|
||||
exit $fail
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#!/usr/bin/env bash
|
||||
# 발로란트 맵 3D 자동 갱신 (systemd 타이머가 30분마다 실행, install.sh 참고)
|
||||
#
|
||||
# 1. uedb.dev 발로란트 매핑(.usmap) 버전 · 라이브 패치 매니페스트를 본다. 지난번에 올린 것과 같으면 끝
|
||||
# 1. uedb.dev 발로란트 매핑(.usmap) 버전 · 라이브 패치 매니페스트를 본다 (uedb 가 라이브 패치보다 늦으면 valorant-api.com 매핑). 지난번에 올린 것과 같으면 끝
|
||||
# 2. 새 매핑이면 받아서 보관한다: $GVR_MAPS_HOME/mappings/ + nextcloud claude/game-voice-recorder/valorant/mappings/
|
||||
# 3. 모든 맵 · 요원 · 무기를 Riot CDN 에서 바로 뽑고(gvr-map-extract, 필요한 조각만 받음 · 디스크 거의 안 씀) 압축한다 (pack.py)
|
||||
# 4. 사이트 서버(.5) data/maps3d 에 올리고 index.json 을 바꿔 끼운다 → 사이트가 바로 새 맵을 쓴다
|
||||
@@ -14,6 +14,8 @@ GVR_MAPS_HOME="${GVR_MAPS_HOME:-$HOME/gvr-maps}"
|
||||
SITE_HOST="${SITE_HOST:-root@192.168.10.5}"
|
||||
SITE_DATA="${SITE_DATA:-/root/other/game-voice-recorder/data}"
|
||||
UEDB="${UEDB:-https://uedb.dev/svc/api/v1/valorant/mappings}"
|
||||
# 두 번째 매핑 배포처: 지금 라이브 매니페스트 · 그 패치 매핑 URL (uedb 가 새 패치를 늦게 올릴 때 쓴다)
|
||||
VAPI="${VAPI:-https://valorant-api.com/v1/version}"
|
||||
SECRETS="${SECRETS:-$HOME/.config/ejclaw/secrets.json}"
|
||||
export DOTNET_ROOT="${DOTNET_ROOT:-$HOME/.dotnet}"
|
||||
BIN="${BIN:-$GVR_MAPS_HOME/bin/gvr-map-extract}"
|
||||
@@ -83,6 +85,18 @@ updated="$(jq -r .updated <<<"$meta")"
|
||||
usmap_url="$(jq -r '.mappings.Brotli // .mappings.ZStandard' <<<"$meta")"
|
||||
[ -n "$version" ] && [ "$version" != null ] && [ -n "$usmap_url" ] && [ "$usmap_url" != null ] || { log "uedb 응답 이상: $meta"; false; }
|
||||
manifest="$("$BIN" manifest)"
|
||||
# uedb 가 새 패치 매핑을 늦게 올리면(13.10: 11-07 패치인데 11-20 에도 13.09) 옛 매핑으로 새 게임 파일을 읽게 된다.
|
||||
# valorant-api.com 이 알려 주는 매니페스트가 지금 라이브와 같고 패치 번호가 uedb 와 다르면 그쪽 매핑을 쓴다 (응답이 없거나 이상하면 uedb 그대로)
|
||||
vapi="$(curl -fsS --max-time 20 "$VAPI" 2>/dev/null || true)"
|
||||
if [ -n "$vapi" ] && [ "$(jq -r '.data.manifestId // empty' <<<"$vapi" 2>/dev/null || true)" = "$(basename "$manifest" .manifest)" ]; then
|
||||
v2="$(jq -r '.data.branch // empty' <<<"$vapi" 2>/dev/null | sed -n 's/^release-\([0-9.]*\)$/VALORANT_\1/p' || true)"
|
||||
u2="$(jq -r '.data.mappingsUrl // empty' <<<"$vapi" 2>/dev/null || true)"
|
||||
d2="$(jq -r '.data.buildDate // empty' <<<"$vapi" 2>/dev/null || true)"
|
||||
if [ -n "$v2" ] && [ -n "$u2" ] && [ -n "$d2" ] && [ "$v2" != "$version" ]; then
|
||||
log "uedb 매핑($version)이 라이브 패치와 달라 valorant-api.com 매핑($v2) 사용"
|
||||
version="$v2"; updated="$d2"; usmap_url="$u2"
|
||||
fi
|
||||
fi
|
||||
set_state "checkFails=0"
|
||||
if [ "$version|$updated|$manifest" = "$(st published)" ] && [ "$FORCE" = 0 ]; then
|
||||
log "변경 없음 ($version, $(basename "$manifest"))"
|
||||
@@ -155,8 +169,8 @@ ssh -o BatchMode=yes "$SITE_HOST" "mkdir -p '$SITE_DATA/maps3d'"
|
||||
tar -C "$out" -cf - "$dir" | ssh -o BatchMode=yes "$SITE_HOST" "tar -xf - -C '$SITE_DATA/maps3d'"
|
||||
scp -q -o BatchMode=yes "$out/index.json" "$SITE_HOST:$SITE_DATA/maps3d/index.json.tmp"
|
||||
ssh -o BatchMode=yes "$SITE_HOST" "mv '$SITE_DATA/maps3d/index.json.tmp' '$SITE_DATA/maps3d/index.json'"
|
||||
# 지금 것과 바로 전 것(이미 열어 둔 화면용)만 남긴다
|
||||
ssh -o BatchMode=yes "$SITE_HOST" "cd '$SITE_DATA/maps3d' && for d in */; do d=\${d%/}; [ \"\$d\" = '$dir' ] || [ \"\$d\" = '$prev' ] || rm -rf -- \"\$d\"; done"
|
||||
# 지금 것과 바로 전 것(이미 열어 둔 화면용)만 남긴다. skins/ 는 무기 스킨 (패치와 상관없이 쌓인다, skins-update.sh)
|
||||
ssh -o BatchMode=yes "$SITE_HOST" "cd '$SITE_DATA/maps3d' && for d in */; do d=\${d%/}; [ \"\$d\" = '$dir' ] || [ \"\$d\" = '$prev' ] || [ \"\$d\" = skins ] || rm -rf -- \"\$d\"; done"
|
||||
trap - ERR
|
||||
set_state "published=$key" "publishedAt=$(date -Is)" "dir=$dir" "failed=" "failCount=0" "retryAt=0"
|
||||
rm -rf "$raw" "$out"
|
||||
|
||||
@@ -107,8 +107,9 @@ public static class Agents
|
||||
}
|
||||
|
||||
/// <summary>스켈레탈 메시 하나를 glb 에 넣는다: 뼈 노드(참조 자세) · 피부(역바인드) · 재질별 primitive · 메시 노드(최상위).
|
||||
/// 뼈 노드 번호 · 뼈 · skin 객체 · 삼각형 수를 돌려준다 (skin 은 Write 의 extra "skins" 에 넣는다)</summary>
|
||||
public static (int[] BoneNode, MeshBoneDto[] Bones, JsonObject Skin, int Tris) Skinned(IFileProvider provider, Glb glb, TexStore tex, USkeletalMesh mesh, int lodWant, int skinIndex = 0, Func<string, bool>? skipMaterial = null)
|
||||
/// 뼈 노드 번호 · 뼈 · skin 객체 · 삼각형 수를 돌려준다 (skin 은 Write 의 extra "skins" 에 넣는다).
|
||||
/// matOverride: 재질 칸 번호 → 바꿀 재질 (무기 스킨 · 색상, null 이면 메시 재질)</summary>
|
||||
public static (int[] BoneNode, MeshBoneDto[] Bones, JsonObject Skin, int Tris) Skinned(IFileProvider provider, Glb glb, TexStore tex, USkeletalMesh mesh, int lodWant, int skinIndex = 0, Func<string, bool>? skipMaterial = null, Func<int, UMaterialInterface?>? matOverride = null)
|
||||
{
|
||||
var dto = new SkeletalMeshDto(mesh, EMeshQuality.All);
|
||||
var lod = dto.LODs[Math.Min(lodWant, dto.LODs.Count - 1)];
|
||||
@@ -188,7 +189,7 @@ public static class Agents
|
||||
{
|
||||
if (!sec.IsValid || sec.NumFaces <= 0) continue;
|
||||
UMaterialInterface? m = null;
|
||||
try { m = dto.Materials.ElementAtOrDefault(sec.MaterialIndex).Material?.Load<UMaterialInterface>(); } catch { }
|
||||
try { m = matOverride?.Invoke(sec.MaterialIndex) ?? dto.Materials.ElementAtOrDefault(sec.MaterialIndex).Material?.Load<UMaterialInterface>(); } catch { }
|
||||
var mp = m != null ? MatParams.Resolve(m) : null;
|
||||
// 반투명(눈 덧칠 · 유리 · 빛나는 껍데기) · 숨김 재질은 뺀다
|
||||
if (mp != null && (mp.BlendMode is "BLEND_Additive" or "BLEND_Translucent" or "BLEND_Modulate" || m!.Name.Contains("Hidden", StringComparison.OrdinalIgnoreCase)) || (m != null && skipMaterial?.Invoke(m.Name) == true))
|
||||
|
||||
@@ -19,12 +19,14 @@ using GvrMapExtract;
|
||||
// gvr-map-extract anims <출력 폴더> 모든 요원 공용 애니메이션 anims.glb
|
||||
// gvr-map-extract abilities <출력 폴더> [요원 · 클래스...] 스킬 재료 abilities.json + m_*.glb + t_*.png
|
||||
// gvr-map-extract viewmodels <출력 폴더> [요원...|weapons] 1인칭 팔 fparms_*.glb · 무기 fpweapon_*.glb · 팔 동작 fpanim_*.glb + viewmodels.json
|
||||
// gvr-map-extract skins <출력 폴더> <요청 파일> [skins.json] 무기 스킨 skin3p_*.glb · skin1p_*.glb + skins.json (요청 = "스킨|단계|색상" 한 줄에 하나)
|
||||
//
|
||||
// 환경변수
|
||||
// GVR_USMAP 매핑 파일 (.usmap, 필수: 13.08 부터 패키지에 형 정보가 없다). uedb.dev 에서 받는다
|
||||
// GVR_MANIFEST 매니페스트 URL (없으면 지금 라이브 패치를 Riot 설정에서 찾는다)
|
||||
// GVR_CACHE_MB 받은 조각을 메모리에 둘 크기 (기본 1500)
|
||||
// GVR_TEX 텍스처 최대 크기 (기본 256)
|
||||
// GVR_TEX 맵 텍스처 최대 크기 (기본 1024, 대부분 원본이 512 라 어센트 기준 그래픽 메모리 약 620MB)
|
||||
// GVR_SKIN_TEX1P 무기 스킨 1인칭 텍스처 최대 크기 (기본 1024, 3인칭은 GVR_AGENT_TEX 512)
|
||||
// GVR_LIGHTMAP 구운 조명 아틀라스 너비 (기본 2048, 넓이도 약 이것의 제곱 안. 0 이면 조명을 넣지 않는다)
|
||||
// GVR_OODLE Oodle 라이브러리 경로 (없으면 실행 파일 옆, 없으면 받는다)
|
||||
|
||||
@@ -102,7 +104,7 @@ switch (args[0])
|
||||
try
|
||||
{
|
||||
var r = MapScene.Build(provider, m);
|
||||
r.WriteGlb(provider, Path.Combine(outDir, m.Code + ".glb"), int.Parse(Environment.GetEnvironmentVariable("GVR_TEX") ?? "256"));
|
||||
r.WriteGlb(provider, Path.Combine(outDir, m.Code + ".glb"), int.Parse(Environment.GetEnvironmentVariable("GVR_TEX") ?? "1024"));
|
||||
r.WriteInfo(Path.Combine(outDir, m.Code + ".json"), manifestUrl, usmap);
|
||||
Console.WriteLine($"{m.Code}: 배치 {r.Placements} · 메시 {r.Meshes} · 삼각형 {r.Triangles} · 재질 {r.Materials} · 텍스처 {r.TextureCount}({r.TextureBytes >> 20}MB, 실패 {r.TextureFailed}) · {r.LightmapSummary} · 빠짐 {r.Skipped} · 실패 {r.Failed} · 받은 양 {(store.DownloadedBytes - d0) >> 20}MB · {(sw.Elapsed - t0).TotalSeconds:F0}초");
|
||||
}
|
||||
@@ -187,6 +189,10 @@ switch (args[0])
|
||||
case "abilities":
|
||||
// 요원 스킬 3D 재료: abilities.json + m_*.glb + t_*.png (Abilities.cs)
|
||||
return Abilities.Run(provider, args[1], args.Skip(2).ToList(), store);
|
||||
case "skins":
|
||||
// 무기 스킨 3D (요청한 것만): skins <출력 폴더> <요청 파일> [이미 있는 skins.json] (Skins.cs)
|
||||
return Skins.Run(provider, args[1], args[2], args.Length > 3 ? args[3] : null,
|
||||
int.Parse(Environment.GetEnvironmentVariable("GVR_SKIN_TEX1P") ?? "1024"), int.Parse(Environment.GetEnvironmentVariable("GVR_AGENT_TEX") ?? "512"));
|
||||
case "lmprobe":
|
||||
foreach (var a in args.Skip(1)) ProbeLight.Run(provider, a);
|
||||
break;
|
||||
|
||||
220
tools/map-extract/src/Skins.cs
Normal file
220
tools/map-extract/src/Skins.cs
Normal file
@@ -0,0 +1,220 @@
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.Json;
|
||||
using System.Text.Json.Nodes;
|
||||
using CUE4Parse.FileProvider;
|
||||
using CUE4Parse.UE4.Assets.Exports.Material;
|
||||
using CUE4Parse.UE4.Assets.Exports.SkeletalMesh;
|
||||
using CUE4Parse.UE4.Assets.Exports.StaticMesh;
|
||||
using Newtonsoft.Json.Linq;
|
||||
|
||||
namespace GvrMapExtract;
|
||||
|
||||
/// <summary>
|
||||
/// 무기 스킨 3D (리플레이 변환기 skins 의 스킨 · 단계 · 색상 경로로 찾는다). 사이트가 본 스킨만 요청하면 그것만 뽑는다.
|
||||
/// 스킨 PrimaryAsset: Levels[] (단계 PrimaryAsset → SkinAttachment = 단계 블루프린트), Chromas[] (색상 PrimaryAsset → EquippableSkinChroma)
|
||||
/// 단계 블루프린트: "Weapon 1P" · "Magazine 1P" · "Weapon 3P" · "Magazine 3P" · "… Material Overrides". 높은 단계는 낮은 단계의 자식 클래스라
|
||||
/// 부모 사슬을 합치면 그 단계까지의 모습이 된다 (보통 2단계부터는 효과만 더한다)
|
||||
/// 색상 블루프린트: "MaterialOverrides"(1인칭) · "3p Material Overrides"(3인칭). 재질 칸 번호대로 바꾼다 (기본 색상은 비어 있다)
|
||||
/// 결과: skin3p_<서명>.glb (weapon_*.glb 와 같은 형식: 정적 메시, 원점 = 총 뿌리) · skin1p_<서명>.glb (fpweapon_*.glb 와 같은 형식, 총 동작은 기본 무기 것).
|
||||
/// 서명 = 메시 · 재질 경로의 해시라 모습이 같은 단계 · 색상은 파일 하나를 같이 쓴다.
|
||||
/// </summary>
|
||||
public static class Skins
|
||||
{
|
||||
/// <summary>요청 열쇠 "스킨|단계|색상" (단계 · 색상은 비어 있을 수 있다). 경로는 리플레이 변환기 SkinInfo 와 같다 (".Default__…" 없이)</summary>
|
||||
public static string Key(string skin, string? level, string? chroma) => $"{skin}|{level}|{chroma}";
|
||||
|
||||
private static readonly System.Text.RegularExpressions.Regex KeyRe = new(@"^/Game/Equippables/[A-Za-z0-9_/\-]+\|(/Game/Equippables/[A-Za-z0-9_/\-]+)?\|(/Game/Equippables/[A-Za-z0-9_/\-]+)?$");
|
||||
public static bool ValidKey(string k) => k.Length < 600 && KeyRe.IsMatch(k);
|
||||
|
||||
public sealed record Look(string? Mesh1P, string? Mag1P, string?[] Mats1P, string?[] MagMats1P, string? Mesh3P, string? Mag3P, string?[] Mats3P, string?[] MagMats3P)
|
||||
{
|
||||
public string Signature()
|
||||
{
|
||||
var s = JsonSerializer.Serialize(this);
|
||||
return Convert.ToHexString(SHA1.HashData(Encoding.UTF8.GetBytes(s)))[..12].ToLowerInvariant();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// skins <출력 폴더> <요청 파일(열쇠 한 줄에 하나)> [이미 있는 skins.json]: 요청마다 모습을 찾아 파일을 만들고
|
||||
/// skins.json {skins:{열쇠:{weapon, sig}}, looks:{서명:{w3p, points, w1p, points1p, gunClips}}, failed:{열쇠:이유}}.
|
||||
/// 이미 있는 서명(known 의 looks)의 파일은 다시 만들지 않는다. 실패한 열쇠는 failed 로 (다시 요청해도 다시 하지 않게, 패치가 바뀌면 다시)
|
||||
/// </summary>
|
||||
public static int Run(IFileProvider provider, string outDir, string wantFile, string? known, int tex1p, int tex3p)
|
||||
{
|
||||
Directory.CreateDirectory(outDir);
|
||||
var have = new HashSet<string>(StringComparer.Ordinal);
|
||||
if (known != null && File.Exists(known) && JsonNode.Parse(File.ReadAllText(known))?["looks"] is JsonObject kl)
|
||||
foreach (var (sg, _) in kl) have.Add(sg);
|
||||
var skins = new JsonObject();
|
||||
var looks = new JsonObject();
|
||||
var failed = new JsonObject();
|
||||
var made = 0;
|
||||
foreach (var key in File.ReadAllLines(wantFile).Select(l => l.Trim()).Where(l => l.Length > 0).Distinct())
|
||||
{
|
||||
if (!ValidKey(key)) { failed[key] = "열쇠 형식"; continue; }
|
||||
var parts = key.Split('|');
|
||||
try
|
||||
{
|
||||
var (weapon, look) = Resolve(provider, parts[0], NullIfEmpty(parts[1]), NullIfEmpty(parts[2]));
|
||||
if (weapon is null) { failed[key] = "무기 모름"; continue; }
|
||||
var sig = look.Signature();
|
||||
var entry = new JsonObject();
|
||||
var f3 = $"skin3p_{sig}.glb";
|
||||
var f1 = $"skin1p_{sig}.glb";
|
||||
if (!have.Contains(sig))
|
||||
{
|
||||
if (Load<USkeletalMesh>(provider, look.Mesh3P) is { } m3)
|
||||
{
|
||||
var tris = Weapons.Export(provider, m3, Load<UStaticMesh>(provider, look.Mag3P), Path.Combine(outDir, f3), tex3p, Over(provider, look.Mats3P), Over(provider, look.MagMats3P));
|
||||
entry["w3p"] = f3;
|
||||
entry["points"] = Weapons.Points?.DeepClone();
|
||||
entry["tris3p"] = tris;
|
||||
}
|
||||
if (Load<USkeletalMesh>(provider, look.Mesh1P) is { } m1)
|
||||
{
|
||||
var (tris, roles, points) = Viewmodels.ExportGun(provider, m1, Load<UStaticMesh>(provider, look.Mag1P), Viewmodels.BaseGunClips(provider, weapon.Value.Blueprint),
|
||||
Path.Combine(outDir, f1), tex1p, Over(provider, look.Mats1P), Over(provider, look.MagMats1P));
|
||||
entry["w1p"] = f1;
|
||||
entry["points1p"] = points;
|
||||
entry["gunClips"] = new JsonArray(roles.Select(r => (JsonNode)r).ToArray());
|
||||
entry["tris1p"] = tris;
|
||||
}
|
||||
if (entry["w3p"] is null && entry["w1p"] is null) { failed[key] = "메시 없음"; continue; }
|
||||
have.Add(sig);
|
||||
looks[sig] = entry;
|
||||
made++;
|
||||
Console.WriteLine($"{key}: {weapon.Value.Name} {sig} 3인칭 {look.Mesh3P?.Split('.')[^1]} ({look.Mats3P.Count(x => x != null)}재질) · 1인칭 {look.Mesh1P?.Split('.')[^1]} ({look.Mats1P.Count(x => x != null)}재질)");
|
||||
}
|
||||
else Console.WriteLine($"{key}: {weapon.Value.Name} {sig} (같은 모습이 이미 있음)");
|
||||
skins[key] = new JsonObject { ["weapon"] = weapon.Value.Name, ["sig"] = sig };
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
failed[key] = $"{e.GetType().Name} {e.Message}";
|
||||
Console.WriteLine($"{key}: 실패 {e.GetType().Name} {e.Message}");
|
||||
}
|
||||
GC.Collect();
|
||||
}
|
||||
File.WriteAllText(Path.Combine(outDir, "skins.json"), new JsonObject { ["skins"] = skins, ["looks"] = looks, ["failed"] = failed }.ToJsonString(new JsonSerializerOptions { WriteIndented = true }));
|
||||
Console.WriteLine($"끝: 스킨 {skins.Count} (새 파일 {made}) · 실패 {failed.Count}");
|
||||
return 0;
|
||||
}
|
||||
|
||||
private static string? NullIfEmpty(string s) => s.Length == 0 ? null : s;
|
||||
|
||||
/// <summary>스킨 · 단계 · 색상 → 무기(기본 무기 목록 이름 · 블루프린트) · 모습(메시 · 재질 경로)</summary>
|
||||
public static ((string Name, string Blueprint)? Weapon, Look Look) Resolve(IFileProvider provider, string skin, string? level, string? chroma)
|
||||
{
|
||||
var sp = Cdo(provider, ClassPath(skin));
|
||||
// 무기: 스킨 폴더가 들어 있는 기본 무기 폴더 (가장 긴 것)
|
||||
var weapon = Weapons.List.Where(w => w.Name != "Spike")
|
||||
.Select(w => (w, dir: w.Blueprint[..(w.Blueprint.LastIndexOf('/') + 1)]))
|
||||
.Where(x => skin.StartsWith(x.dir, StringComparison.OrdinalIgnoreCase))
|
||||
.OrderByDescending(x => x.dir.Length).Select(x => ((string Name, string Blueprint)?)x.w).FirstOrDefault();
|
||||
// 단계: 요청한 단계, 없으면 1단계
|
||||
var levelPath = level ?? (sp.GetValueOrDefault("Levels") as JArray)?.Select(RefPath).FirstOrDefault(x => x != null);
|
||||
var lv = levelPath == null ? new() : Cdo(provider, ClassPath(levelPath));
|
||||
var att = RefPath(lv.GetValueOrDefault("SkinAttachment"));
|
||||
var props = att == null ? new() : Cdo(provider, att);
|
||||
Dictionary<string, JToken> ch = new();
|
||||
if (chroma != null && RefPath(Cdo(provider, ClassPath(chroma)).GetValueOrDefault("EquippableSkinChroma")) is { } cc)
|
||||
ch = Cdo(provider, cc);
|
||||
if (Environment.GetEnvironmentVariable("GVR_DEBUG") != null)
|
||||
{
|
||||
Console.Error.WriteLine($" 단계 {att}: {string.Join(", ", props.Keys)}");
|
||||
Console.Error.WriteLine($" 색상: {string.Join(", ", ch.Keys)}");
|
||||
|
||||
}
|
||||
string? P(string name) => RefPath(ch.GetValueOrDefault(name) ?? props.GetValueOrDefault(name));
|
||||
string?[] M(Func<string, bool> pick)
|
||||
{
|
||||
// 색상이 바꾸면 색상 것, 아니면 단계 것 (칸마다)
|
||||
string?[] Arr(Dictionary<string, JToken> d) => d.Where(kv => pick(kv.Key)).Select(kv => kv.Value as JArray).FirstOrDefault(a => a != null)?.Select(RefPath).ToArray() ?? [];
|
||||
var a = Arr(props);
|
||||
var b = Arr(ch);
|
||||
var n = Math.Max(a.Length, b.Length);
|
||||
return Enumerable.Range(0, n).Select(i => (i < b.Length ? b[i] : null) ?? (i < a.Length ? a[i] : null)).ToArray();
|
||||
}
|
||||
static bool Mat(string k) => k.Contains("Material", StringComparison.OrdinalIgnoreCase) && k.Contains("Override", StringComparison.OrdinalIgnoreCase);
|
||||
static bool ThirdP(string k) => k.Contains("3p", StringComparison.OrdinalIgnoreCase);
|
||||
static bool Mag(string k) => k.Contains("Magazine", StringComparison.OrdinalIgnoreCase);
|
||||
// 1인칭: 꾸밈 메시(Weapon 1P Cosmetic)가 있으면 그것이 보이는 총이다 (기본 메시는 동작만, 1인칭 재질도 꾸밈 메시 것). 칼은 NewMesh · 3p Mesh
|
||||
// 메시 없이 재질만 바꾸는 스킨(예: 쇼티 Aggrobot)은 기본 무기 메시 · 탄창에 재질만 바꾼다
|
||||
var (baseMesh3, baseMag) = weapon is { } w ? Weapons.Find(provider, w.Blueprint) : (null, null);
|
||||
var baseMesh1 = weapon is { } w1 ? Viewmodels.BaseGunMesh(provider, w1.Blueprint) : null;
|
||||
var mesh1 = P("Weapon 1P Cosmetic") ?? P("Weapon 1P") ?? P("NewMesh");
|
||||
var mesh3 = P("Weapon 3P") ?? P("3p Mesh") ?? mesh1;
|
||||
var mag1 = P("Magazine 1P") ?? (mesh1 == null ? baseMag?.GetPathName() : null);
|
||||
var mag3 = P("Magazine 3P") ?? P("Magazine 1P") ?? (mesh3 == null ? baseMag?.GetPathName() : null);
|
||||
var look = new Look(
|
||||
mesh1 ?? baseMesh1, mag1, M(k => Mat(k) && !ThirdP(k) && !Mag(k)), M(k => Mat(k) && !ThirdP(k) && Mag(k)),
|
||||
mesh3 ?? baseMesh3?.GetPathName(), mag3, M(k => Mat(k) && ThirdP(k) && !Mag(k)), M(k => Mat(k) && ThirdP(k) && Mag(k)));
|
||||
return (weapon, look);
|
||||
}
|
||||
|
||||
private static Func<int, UMaterialInterface?>? Over(IFileProvider provider, string?[] mats)
|
||||
{
|
||||
if (mats.All(m => m == null)) return null;
|
||||
var cache = new Dictionary<int, UMaterialInterface?>();
|
||||
return i =>
|
||||
{
|
||||
if (i < 0 || i >= mats.Length || mats[i] == null) return null;
|
||||
if (!cache.TryGetValue(i, out var m)) cache[i] = m = Load<UMaterialInterface>(provider, mats[i]);
|
||||
return m;
|
||||
};
|
||||
}
|
||||
|
||||
private static T? Load<T>(IFileProvider provider, string? path) where T : CUE4Parse.UE4.Assets.Exports.UObject
|
||||
{
|
||||
if (path == null) return null;
|
||||
try { return provider.LoadPackageObject<T>(path); }
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.Error.WriteLine($" 못 읽음 {path}: {e.GetType().Name} {e.Message}");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>에셋 경로(/Game/a/B_PrimaryAsset) → 클래스 경로 (/Game/a/B_PrimaryAsset.B_PrimaryAsset_C)</summary>
|
||||
private static string ClassPath(string asset) => asset.Contains('.') ? asset : asset + "." + asset[(asset.LastIndexOf('/') + 1)..] + "_C";
|
||||
|
||||
/// <summary>참조 JSON → 객체 경로 (/Game/a/B.B 또는 /Game/a/B.B_C). 소프트 참조(AssetPathName) · 하드 참조(ObjectName + ObjectPath) 둘 다</summary>
|
||||
private static string? RefPath(JToken? t)
|
||||
{
|
||||
if (t is not JObject o) return null;
|
||||
if ((string?)o["AssetPathName"] is { Length: > 0 } ap && ap != "None") return ap;
|
||||
if ((string?)o["ObjectPath"] is { Length: > 0 } op && (string?)o["ObjectName"] is { } on)
|
||||
{
|
||||
var q = on.IndexOf('\'');
|
||||
var name = q >= 0 ? on[(q + 1)..].TrimEnd('\'') : on;
|
||||
if (name.Contains(':') || name.Contains('.')) name = name.Split(':', '.')[^1];
|
||||
var pkg = op.LastIndexOf('.') is var d and > 0 ? op[..d] : op;
|
||||
return pkg + "." + name;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static readonly Dictionary<string, Dictionary<string, JToken>> CdoCache = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
/// <summary>블루프린트 클래스(/Game/a/B.B_C)의 기본 객체 속성. 부모 클래스(Super) 사슬 값 위에 자기 값 (게임 /Game 클래스만)</summary>
|
||||
private static Dictionary<string, JToken> Cdo(IFileProvider provider, string classPath, int depth = 0)
|
||||
{
|
||||
if (CdoCache.TryGetValue(classPath, out var hit)) return hit;
|
||||
var res = new Dictionary<string, JToken>(StringComparer.Ordinal);
|
||||
var dot = classPath.LastIndexOf('.');
|
||||
if (dot < 0 || depth > 16 || !classPath.StartsWith("/Game/")) return res;
|
||||
var pkg = classPath[..dot];
|
||||
var cls = classPath[(dot + 1)..];
|
||||
var ex = JArray.Parse(Newtonsoft.Json.JsonConvert.SerializeObject(provider.LoadPackage(pkg).GetExports()));
|
||||
var bp = ex.OfType<JObject>().FirstOrDefault(e => (string?)e["Name"] == cls);
|
||||
if (bp?["Super"] is JObject sup && RefPath(sup) is { } sp)
|
||||
foreach (var (k, v) in Cdo(provider, sp, depth + 1)) res[k] = v;
|
||||
if (ex.OfType<JObject>().FirstOrDefault(e => (string?)e["Name"] == "Default__" + cls)?["Properties"] is JObject props)
|
||||
foreach (var (k, v) in props)
|
||||
if (v != null) res[k] = v;
|
||||
CdoCache[classPath] = res;
|
||||
return res;
|
||||
}
|
||||
}
|
||||
@@ -87,31 +87,16 @@ public static class Viewmodels
|
||||
try
|
||||
{
|
||||
var dir = "ShooterGame/Content" + bp["/Game".Length..bp.LastIndexOf('/')] + "/S0/1P/";
|
||||
var re = new System.Text.RegularExpressions.Regex(@"/(GN|EQ)_([A-Za-z0-9]+)_S0_Skelmesh\.uasset$", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
|
||||
var mf = provider.Files.Keys.Where(k => k.StartsWith(dir + "Models/", StringComparison.OrdinalIgnoreCase) && re.IsMatch(k) && !k.Contains("Defuser", StringComparison.OrdinalIgnoreCase)).OrderBy(k => k.Length).FirstOrDefault();
|
||||
if (mf == null) { Console.WriteLine($"무기 {name}: 1인칭 모델 없음 (건너뜀)"); continue; }
|
||||
var gun = provider.LoadPackageObject<USkeletalMesh>(ObjPath(mf));
|
||||
var mp = BaseGunMesh(provider, bp);
|
||||
if (mp == null) { Console.WriteLine($"무기 {name}: 1인칭 모델 없음 (건너뜀)"); continue; }
|
||||
var gun = provider.LoadPackageObject<USkeletalMesh>(mp);
|
||||
var anims = provider.Files.Keys.Where(k => k.StartsWith(dir + "Anims/", StringComparison.OrdinalIgnoreCase) && k.EndsWith(".uasset", StringComparison.OrdinalIgnoreCase)).ToList();
|
||||
string? Find(string prefix, string[] names) =>
|
||||
names.Select(n => anims.FirstOrDefault(k => Path.GetFileNameWithoutExtension(k) is var f && f.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) && f.EndsWith("_S0_" + n, StringComparison.OrdinalIgnoreCase))).FirstOrDefault(x => x != null);
|
||||
|
||||
// 무기: 몸(뼈대) + 탄창 + 총 동작
|
||||
var (_, mag) = Weapons.Find(provider, bp);
|
||||
var glb = new Glb();
|
||||
var tex = new TexStore(provider, glb, maxTex);
|
||||
var (boneNode, bones, skin, tris) = Agents.Skinned(provider, glb, tex, gun, 0);
|
||||
if (mag != null) tris += Weapons.AttachStatic(provider, glb, tex, mag, boneNode, bones, "Magazine_Main");
|
||||
var gunClips = Clips(provider, glb, gun, boneNode, bones, GunClips.Select(c => (c.Role, Find("GN_Core_", c.Names))));
|
||||
var points = new JsonObject();
|
||||
foreach (var (key, bone) in new[] { ("muzzle", "Muzzle"), ("leftHand", "Left_Hand_Target") })
|
||||
{
|
||||
var bi = Array.FindIndex(bones, b => b.Name.Equals(bone, StringComparison.OrdinalIgnoreCase));
|
||||
if (bi < 0) continue;
|
||||
var g = CUE4Parse.UE4.Objects.Core.Math.FTransform.Identity;
|
||||
for (var i = bi; i >= 0; i = bones[i].ParentIndex) g = g * bones[i].Transform;
|
||||
points[key] = new JsonArray(g.Translation.X, g.Translation.Y, g.Translation.Z);
|
||||
}
|
||||
glb.Write(Path.Combine(outDir, WeaponFile(name)), new JsonObject { ["skins"] = new JsonArray(skin), ["animations"] = gunClips.json });
|
||||
var (tris, gunRoles, points) = ExportGun(provider, gun, mag, GunClips.Select(c => (c.Role, Find("GN_Core_", c.Names))), Path.Combine(outDir, WeaponFile(name)), maxTex);
|
||||
|
||||
// 팔 동작 (뼈 노드만)
|
||||
var armRoles = new List<string>();
|
||||
@@ -124,8 +109,8 @@ public static class Viewmodels
|
||||
armRoles = ac.roles;
|
||||
ag.Write(Path.Combine(outDir, AnimFile(name)), new JsonObject { ["animations"] = ac.json });
|
||||
}
|
||||
weapons[name] = new { file = WeaponFile(name), anim = AnimFile(name), mesh = gun.Name, triangles = tris, clips = armRoles, gunClips = gunClips.roles, points };
|
||||
Console.WriteLine($"무기 {name}: {gun.Name} 삼각형 {tris} · 팔 동작 {string.Join(',', armRoles)} · 총 동작 {string.Join(',', gunClips.roles)}");
|
||||
weapons[name] = new { file = WeaponFile(name), anim = AnimFile(name), mesh = gun.Name, triangles = tris, clips = armRoles, gunClips = gunRoles, points };
|
||||
Console.WriteLine($"무기 {name}: {gun.Name} 삼각형 {tris} · 팔 동작 {string.Join(',', armRoles)} · 총 동작 {string.Join(',', gunRoles)}");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
@@ -139,6 +124,45 @@ public static class Viewmodels
|
||||
return failed == 0 ? 0 : 1;
|
||||
}
|
||||
|
||||
/// <summary>1인칭 무기 하나: 몸(뼈대) + 탄창(Magazine_Main 뼈) + 총 동작 → glb. 삼각형 · 넣은 총 동작 · 맞출 점(총구 · 왼손)</summary>
|
||||
public static (int Tris, List<string> Roles, JsonObject Points) ExportGun(IFileProvider provider, USkeletalMesh gun, UStaticMesh? mag, IEnumerable<(string Role, string? File)> clips, string file, int maxTex,
|
||||
Func<int, CUE4Parse.UE4.Assets.Exports.Material.UMaterialInterface?>? matOverride = null, Func<int, CUE4Parse.UE4.Assets.Exports.Material.UMaterialInterface?>? magOverride = null)
|
||||
{
|
||||
var glb = new Glb();
|
||||
var tex = new TexStore(provider, glb, maxTex);
|
||||
var (boneNode, bones, skin, tris) = Agents.Skinned(provider, glb, tex, gun, 0, matOverride: matOverride);
|
||||
if (mag != null) tris += Weapons.AttachStatic(provider, glb, tex, mag, boneNode, bones, "Magazine_Main", magOverride);
|
||||
var gunClips = Clips(provider, glb, gun, boneNode, bones, clips);
|
||||
var points = new JsonObject();
|
||||
foreach (var (key, bone) in new[] { ("muzzle", "Muzzle"), ("leftHand", "Left_Hand_Target") })
|
||||
{
|
||||
var bi = Array.FindIndex(bones, b => b.Name.Equals(bone, StringComparison.OrdinalIgnoreCase));
|
||||
if (bi < 0) continue;
|
||||
var g = CUE4Parse.UE4.Objects.Core.Math.FTransform.Identity;
|
||||
for (var i = bi; i >= 0; i = bones[i].ParentIndex) g = g * bones[i].Transform;
|
||||
points[key] = new JsonArray(g.Translation.X, g.Translation.Y, g.Translation.Z);
|
||||
}
|
||||
glb.Write(file, new JsonObject { ["skins"] = new JsonArray(skin), ["animations"] = gunClips.json });
|
||||
return (tris, gunClips.roles, points);
|
||||
}
|
||||
|
||||
/// <summary>기본 스킨 1인칭 모델 경로 (<무기 폴더>/S0/1P/Models/GN|EQ_*_S0_Skelmesh, 해체기 제외). 없으면 null</summary>
|
||||
public static string? BaseGunMesh(IFileProvider provider, string blueprint)
|
||||
{
|
||||
var dir = "ShooterGame/Content" + blueprint["/Game".Length..blueprint.LastIndexOf('/')] + "/S0/1P/Models/";
|
||||
var re = new System.Text.RegularExpressions.Regex(@"/(GN|EQ)_([A-Za-z0-9]+)_S0_Skelmesh\.uasset$", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
|
||||
var mf = provider.Files.Keys.Where(k => k.StartsWith(dir, StringComparison.OrdinalIgnoreCase) && re.IsMatch(k) && !k.Contains("Defuser", StringComparison.OrdinalIgnoreCase)).OrderBy(k => k.Length).FirstOrDefault();
|
||||
return mf == null ? null : ObjPath(mf);
|
||||
}
|
||||
|
||||
/// <summary>무기 폴더(…/S0/1P/Anims)에서 총 동작 파일 (역할 → 파일, 없으면 null)</summary>
|
||||
public static IEnumerable<(string Role, string? File)> BaseGunClips(IFileProvider provider, string blueprint)
|
||||
{
|
||||
var dir = "ShooterGame/Content" + blueprint["/Game".Length..blueprint.LastIndexOf('/')] + "/S0/1P/Anims/";
|
||||
var anims = provider.Files.Keys.Where(k => k.StartsWith(dir, StringComparison.OrdinalIgnoreCase) && k.EndsWith(".uasset", StringComparison.OrdinalIgnoreCase)).ToList();
|
||||
return GunClips.Select(c => (c.Role, c.Names.Select(n => anims.FirstOrDefault(k => Path.GetFileNameWithoutExtension(k) is var f && f.StartsWith("GN_Core_", StringComparison.OrdinalIgnoreCase) && f.EndsWith("_S0_" + n, StringComparison.OrdinalIgnoreCase))).FirstOrDefault(x => x != null))).ToList();
|
||||
}
|
||||
|
||||
private static string ObjPath(string file)
|
||||
{
|
||||
var p = "/Game" + file["ShooterGame/Content".Length..^".uasset".Length];
|
||||
|
||||
@@ -80,7 +80,7 @@ public static class Weapons
|
||||
return (mesh, mag);
|
||||
}
|
||||
|
||||
public static int Export(IFileProvider provider, USkeletalMesh mesh, UStaticMesh? magazine, string file, int maxTex)
|
||||
public static int Export(IFileProvider provider, USkeletalMesh mesh, UStaticMesh? magazine, string file, int maxTex, Func<int, UMaterialInterface?>? matOverride = null, Func<int, UMaterialInterface?>? magOverride = null)
|
||||
{
|
||||
var glb = new Glb();
|
||||
var tex = new TexStore(provider, glb, maxTex);
|
||||
@@ -99,8 +99,8 @@ public static class Weapons
|
||||
nrm.AddRange([n.X, n.Y, n.Z]);
|
||||
uv.AddRange([v.Uv.U, v.Uv.V]);
|
||||
}
|
||||
var secs = lod.Sections.Where(s => s.IsValid && s.NumFaces > 0).Select(s => (s.FirstIndex, s.NumFaces, Mat: dto.Materials.ElementAtOrDefault(s.MaterialIndex).Material)).ToList();
|
||||
tris += AddPrims(provider, glb, tex, prims, pos, nrm, uv, lod.Indices, secs);
|
||||
var secs = lod.Sections.Where(s => s.IsValid && s.NumFaces > 0).Select(s => (s.FirstIndex, s.NumFaces, Mat: dto.Materials.ElementAtOrDefault(s.MaterialIndex).Material, Slot: s.MaterialIndex)).ToList();
|
||||
tris += AddPrims(provider, glb, tex, prims, pos, nrm, uv, lod.Indices, secs, matOverride);
|
||||
|
||||
// 탄창: 총 뼈 Magazine_Main 위치에
|
||||
if (magazine?.RenderData?.LODs?.FirstOrDefault(l => !l.SkipLod) is { } ml && ml.PositionVertexBuffer?.Verts is { Length: > 0 } mv && ml.IndexBuffer?.Buffer is { } mib)
|
||||
@@ -118,8 +118,8 @@ public static class Weapons
|
||||
nrm.AddRange([n.X, n.Y, n.Z]);
|
||||
uv.AddRange([it?.UV is { Length: > 0 } uu ? uu[0].U : 0, it?.UV is { Length: > 0 } uv2 ? uv2[0].V : 0]);
|
||||
}
|
||||
var msecs = ml.Sections.Select(s => (s.FirstIndex, s.NumTriangles, Mat: (FPackageIndex?)(s.MaterialIndex < magazine.StaticMaterials.Length ? magazine.StaticMaterials[s.MaterialIndex].MaterialInterface : null))).ToList();
|
||||
tris += AddPrims(provider, glb, tex, prims, pos, nrm, uv, mib.Select(x => (uint)x).ToArray(), msecs);
|
||||
var msecs = ml.Sections.Select(s => (s.FirstIndex, s.NumTriangles, Mat: (FPackageIndex?)(s.MaterialIndex < magazine.StaticMaterials.Length ? magazine.StaticMaterials[s.MaterialIndex].MaterialInterface : null), Slot: s.MaterialIndex)).ToList();
|
||||
tris += AddPrims(provider, glb, tex, prims, pos, nrm, uv, mib.Select(x => (uint)x).ToArray(), msecs, magOverride);
|
||||
}
|
||||
glb.Meshes.Add(new JsonObject { ["name"] = mesh.Name, ["primitives"] = prims });
|
||||
// 손에 쥘 때 맞출 점 (총 공간 cm): 총구 · 왼손 자리 (사이트가 오른손 = 원점, 왼손 = Left_Hand_Target 이 되게 놓는다)
|
||||
@@ -139,7 +139,7 @@ public static class Weapons
|
||||
}
|
||||
|
||||
/// <summary>정적 메시(탄창)를 뼈 노드의 자식 메시로 붙인다 (뼈 공간 그대로). 붙인 삼각형 수</summary>
|
||||
public static int AttachStatic(IFileProvider provider, Glb glb, TexStore tex, UStaticMesh sm, int[] boneNode, MeshBoneDto[] bones, string bone)
|
||||
public static int AttachStatic(IFileProvider provider, Glb glb, TexStore tex, UStaticMesh sm, int[] boneNode, MeshBoneDto[] bones, string bone, Func<int, UMaterialInterface?>? matOverride = null)
|
||||
{
|
||||
var bi = Array.FindIndex(bones, b => b.Name.Equals(bone, StringComparison.OrdinalIgnoreCase));
|
||||
if (bi < 0 || sm.RenderData?.LODs?.FirstOrDefault(l => !l.SkipLod) is not { } ml || ml.PositionVertexBuffer?.Verts is not { Length: > 0 } mv || ml.IndexBuffer?.Buffer is not { } mib) return 0;
|
||||
@@ -154,9 +154,9 @@ public static class Weapons
|
||||
nrm.AddRange([n.X, n.Y, n.Z]);
|
||||
uv.AddRange([it?.UV is { Length: > 0 } uu ? uu[0].U : 0, it?.UV is { Length: > 0 } uv2 ? uv2[0].V : 0]);
|
||||
}
|
||||
var secs = ml.Sections.Select(s => (s.FirstIndex, s.NumTriangles, Mat: (FPackageIndex?)(s.MaterialIndex < sm.StaticMaterials.Length ? sm.StaticMaterials[s.MaterialIndex].MaterialInterface : null))).ToList();
|
||||
var secs = ml.Sections.Select(s => (s.FirstIndex, s.NumTriangles, Mat: (FPackageIndex?)(s.MaterialIndex < sm.StaticMaterials.Length ? sm.StaticMaterials[s.MaterialIndex].MaterialInterface : null), Slot: s.MaterialIndex)).ToList();
|
||||
var prims = new JsonArray();
|
||||
var tris = AddPrims(provider, glb, tex, prims, pos, nrm, uv, mib.Select(x => (uint)x).ToArray(), secs);
|
||||
var tris = AddPrims(provider, glb, tex, prims, pos, nrm, uv, mib.Select(x => (uint)x).ToArray(), secs, matOverride);
|
||||
if (prims.Count == 0) return 0;
|
||||
glb.Meshes.Add(new JsonObject { ["name"] = sm.Name, ["primitives"] = prims });
|
||||
glb.Nodes.Add(new JsonObject { ["name"] = sm.Name, ["mesh"] = glb.Meshes.Count - 1 });
|
||||
@@ -166,16 +166,16 @@ public static class Weapons
|
||||
return tris;
|
||||
}
|
||||
|
||||
private static int AddPrims(IFileProvider provider, Glb glb, TexStore tex, JsonArray prims, List<float> pos, List<float> nrm, List<float> uv, uint[] indices, List<(int First, int Faces, FPackageIndex? Mat)> secs)
|
||||
private static int AddPrims(IFileProvider provider, Glb glb, TexStore tex, JsonArray prims, List<float> pos, List<float> nrm, List<float> uv, uint[] indices, List<(int First, int Faces, FPackageIndex? Mat, int Slot)> secs, Func<int, UMaterialInterface?>? matOverride)
|
||||
{
|
||||
var aPos = glb.Floats(pos.ToArray(), 3, bounds: true);
|
||||
var aNrm = glb.Floats(nrm.ToArray(), 3);
|
||||
var aUv = glb.Floats(uv.ToArray(), 2);
|
||||
var tris = 0;
|
||||
foreach (var (first, faces, matIdx) in secs)
|
||||
foreach (var (first, faces, matIdx, slot) in secs)
|
||||
{
|
||||
UMaterialInterface? m = null;
|
||||
try { m = matIdx?.Load<UMaterialInterface>(); } catch { }
|
||||
try { m = matOverride?.Invoke(slot) ?? matIdx?.Load<UMaterialInterface>(); } catch { }
|
||||
var mp = m != null ? MatParams.Resolve(m) : null;
|
||||
if (mp != null && (mp.BlendMode is "BLEND_Additive" or "BLEND_Translucent" or "BLEND_Modulate")) continue;
|
||||
var texPath = mp == null ? null : new[] { "Diffuse", "DF", "Albedo", "Base Color", "BaseColor" }.Select(n => mp.Textures.GetValueOrDefault(n)).FirstOrDefault(x => !string.IsNullOrEmpty(x))
|
||||
|
||||
@@ -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;
|
||||
@@ -49,7 +50,70 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink
|
||||
// 들고 있는 것: 장비 액터 → 이름 (총은 파서 목록 이름, 나머지는 클래스 이름), 캐릭터별 바뀐 시각
|
||||
private readonly Dictionary<uint, string> _equipName = [];
|
||||
private readonly List<(int T, uint Character, uint Equip)> _equips = [];
|
||||
private readonly List<(int T, uint State, string Name)> _shotEquips = [];
|
||||
private readonly List<(int T, uint State, string Name, uint Equip)> _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<string, int> CombatFields = new()
|
||||
{
|
||||
["AggregateKills"] = BoardKills, ["AggregateDeaths"] = BoardDeaths, ["AggregateAssists"] = BoardAssists, ["Score"] = BoardScore,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// 점수판 행: 선수 값이 바뀔 때마다 그 선수 전체 값 [t, 선수, 크레딧, 궁 점수, 킬, 데스, 어시, 전투 점수] (아직 안 온 값 -1).
|
||||
/// 같은 시각에 나눠 온 것은 한 줄로, 값이 그대로면 줄을 넣지 않는다. 선수를 모르는 기록(-1)은 건너뛴다
|
||||
/// </summary>
|
||||
public static List<int[]> BuildScoreboard(IEnumerable<(int T, int Player, int Field, int Value)> rows)
|
||||
{
|
||||
var board = new List<int[]>();
|
||||
var now = new Dictionary<int, int[]>();
|
||||
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;
|
||||
}
|
||||
|
||||
/// <summary>들고 있는 것 줄 [t, 선수, 종류, 스킨]: 시간 순, 같은 선수가 같은 종류 · 같은 스킨을 이어 들면 뺀다 (다른 스킨의 같은 총을 주우면 넣는다)</summary>
|
||||
public static List<int[]> EquipRows(IEnumerable<(int T, int P, int Kind, int Skin)> rows)
|
||||
{
|
||||
var equips = new List<int[]>();
|
||||
var last = new Dictionary<int, (int Kind, int Skin)>();
|
||||
foreach (var e in rows.OrderBy(e => e.T))
|
||||
{
|
||||
if (last.TryGetValue(e.P, out var l) && l == (e.Kind, e.Skin)) continue;
|
||||
last[e.P] = (e.Kind, e.Skin);
|
||||
equips.Add([e.T, e.P, e.Kind, e.Skin]);
|
||||
}
|
||||
return equips;
|
||||
}
|
||||
|
||||
/// <summary>파서 기본 목록에 없는 점수판 필드 (킬 · 데스 · 어시 · 전투 점수). 이름으로 찾으므로 패치로 번호가 밀려도 된다</summary>
|
||||
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 +187,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 +211,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:
|
||||
@@ -267,7 +342,7 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink
|
||||
_shots.Add((Ms(s.TimeSeconds), state, R(loc.X), R(loc.Y), R(loc.Z), R(yaw), R(pitch)));
|
||||
if (shot.Equippable is { Name: { } en })
|
||||
{
|
||||
_shotEquips.Add((Ms(s.TimeSeconds), state, en));
|
||||
_shotEquips.Add((Ms(s.TimeSeconds), state, en, shot.Equippable.NetGuid));
|
||||
if (shot.Equippable.NetGuid != 0) _equipName.TryAdd(shot.Equippable.NetGuid, en);
|
||||
}
|
||||
}
|
||||
@@ -285,7 +360,7 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink
|
||||
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)
|
||||
public ReplayFile Build(string? branch, long recordedAt, int durationMs, int hz, IReadOnlyDictionary<uint, Dictionary<string, string>>? skinsByEquip = null)
|
||||
{
|
||||
// 선수 = 계정(subject) 하나. 캐릭터가 여러 번 바뀌어도(부활 등) 같은 선수로 묶는다
|
||||
var players = new List<ReplayPlayer>();
|
||||
@@ -432,7 +507,7 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink
|
||||
actions.Add([a.T0, a.T1, pi, ak]);
|
||||
}
|
||||
|
||||
// 들고 있는 것: [t, 선수, 종류]. 같은 선수가 같은 것을 다시 들면 뺀다
|
||||
// 들고 있는 것: [t, 선수, 종류, 스킨]. 같은 선수가 같은 것(같은 스킨)을 다시 들면 뺀다
|
||||
var equipKinds = new List<string>();
|
||||
var equipKindIndex = new Dictionary<string, int>();
|
||||
int EquipKind(string name)
|
||||
@@ -440,28 +515,30 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink
|
||||
if (!equipKindIndex.TryGetValue(name, out var k)) { k = equipKinds.Count; equipKinds.Add(name); equipKindIndex[name] = k; }
|
||||
return k;
|
||||
}
|
||||
var equipRows = new List<(int T, int P, string Name)>();
|
||||
// 스킨: 장비 액터 → skins 번호 (같은 스킨 · 단계 · 색상 · 장식이면 같은 번호)
|
||||
var skins = new List<SkinInfo>();
|
||||
var skinIndex = new Dictionary<SkinInfo, int>();
|
||||
int SkinOf(uint eq)
|
||||
{
|
||||
if (skinsByEquip?.GetValueOrDefault(eq) is not { } d || SkinInfo.From(d) is not { } si) return -1;
|
||||
if (!skinIndex.TryGetValue(si, out var k)) { k = skins.Count; skins.Add(si); skinIndex[si] = k; }
|
||||
return k;
|
||||
}
|
||||
var equipRows = new List<(int T, int P, string Name, int Skin)>();
|
||||
foreach (var (t, ch, eq) in _equips)
|
||||
{
|
||||
if (!indexByCharacter.TryGetValue(ch, out var pi)) continue;
|
||||
var name = _equipName.TryGetValue(eq, out var n) ? n : _archetypeByActor.TryGetValue(eq, out var a) ? Simplify(a) : null;
|
||||
if (name != null) equipRows.Add((t, pi, name));
|
||||
if (name != null) equipRows.Add((t, pi, name, SkinOf(eq)));
|
||||
}
|
||||
// 인벤토리 기록이 없는 선수는 사격 무기로 채운다
|
||||
var hasInv = equipRows.Select(e => e.P).ToHashSet();
|
||||
foreach (var (t, st, name) in _shotEquips)
|
||||
foreach (var (t, st, name, eq) in _shotEquips)
|
||||
{
|
||||
var pi = PlayerOfState(st);
|
||||
if (pi >= 0 && !hasInv.Contains(pi)) equipRows.Add((t, pi, name));
|
||||
}
|
||||
var equips = new List<int[]>();
|
||||
var lastByPlayer = new Dictionary<int, string>();
|
||||
foreach (var e in equipRows.OrderBy(e => e.T))
|
||||
{
|
||||
if (lastByPlayer.TryGetValue(e.P, out var last) && last == e.Name) continue;
|
||||
lastByPlayer[e.P] = e.Name;
|
||||
equips.Add([e.T, e.P, EquipKind(e.Name)]);
|
||||
if (pi >= 0 && !hasInv.Contains(pi)) equipRows.Add((t, pi, name, SkinOf(eq)));
|
||||
}
|
||||
var equips = EquipRows(equipRows.Select(e => (e.T, e.P, EquipKind(e.Name), e.Skin)));
|
||||
|
||||
// 무기 · 스킬 상태: 장비 액터 → 그 시각의 선수 (인벤토리 기록, 없으면 Instigator).
|
||||
// 무기는 떨어뜨리고 주울 수 있어서 마지막 주인이 아니라 상태가 생긴 때의 주인을 쓴다
|
||||
@@ -490,9 +567,13 @@ 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,
|
||||
Skins = skins,
|
||||
EquipKinds = equipKinds,
|
||||
MatchId = _matchId,
|
||||
Map = _map,
|
||||
|
||||
@@ -41,9 +41,14 @@ public sealed class ReplayFile
|
||||
/// 이어지는 동작 [t0, t1, player, actionKind] (Plant 설치 중 · Defuse 해체 중 · Rope 줄 타기), t1 모르면 -1
|
||||
public List<int[]> Actions { get; set; } = [];
|
||||
public List<string> ActionKinds { get; set; } = [];
|
||||
/// 들고 있는 것이 바뀐 시각 [t, player, kind 번호]. 총은 영어 이름(Vandal 등), 칼은 Melee, 스파이크는 Spike, 스킬은 클래스 이름
|
||||
/// 들고 있는 것이 바뀐 시각 [t, player, kind 번호, skin 번호]. 총은 영어 이름(Vandal 등), 칼은 Melee, 스파이크는 Spike, 스킬은 클래스 이름.
|
||||
/// skin = skins 번호 (스킨 기록이 없는 것 · 스킬은 -1, 변환기 1.10.0~ 에만 4번째 열)
|
||||
public List<int[]> Equips { get; set; } = [];
|
||||
public List<string> EquipKinds { get; set; } = [];
|
||||
/// 무기 스킨 (총 · 칼). 줍거나 떨어뜨려도 그 총의 스킨은 처음 주인 것 그대로 (게임과 같다)
|
||||
public List<SkinInfo> Skins { get; set; } = [];
|
||||
/// 점수판 (게임 Tab 화면): 선수 값이 바뀔 때마다 [t, player, 크레딧, 궁극기 점수, 킬, 데스, 어시스트, 전투 점수] (아직 모르는 값 -1, 변환기 1.10.0~)
|
||||
public List<int[]> Scoreboard { get; set; } = [];
|
||||
}
|
||||
|
||||
public sealed class ReplayPlayer
|
||||
@@ -100,3 +105,15 @@ public static class ReplayJson
|
||||
DefaultIgnoreCondition = JsonIgnoreCondition.Never,
|
||||
};
|
||||
}
|
||||
|
||||
/// <summary>무기 스킨: 게임 데이터 에셋 경로 (예: /Game/Equippables/Guns/Rifles/AK/HypeBeast/AssaultRifle_AK_HypeBeast_PrimaryAsset).
|
||||
/// level = 스킨 단계, chroma = 색상, charm · charmLevel = 총 장식 (없으면 null)</summary>
|
||||
public sealed record SkinInfo(string Skin, string? Level, string? Chroma, string? Charm, string? CharmLevel)
|
||||
{
|
||||
/// <summary>리플레이 필드(이름 → 경로)에서. 스킨이 없으면 null. 경로의 ".Default__…_C" 는 뗀다</summary>
|
||||
public static SkinInfo? From(IReadOnlyDictionary<string, string> d)
|
||||
{
|
||||
string? P(string k) => d.GetValueOrDefault(k) is { Length: > 0 } v ? (v.IndexOf('.') is var i and > 0 ? v[..i] : v) : null;
|
||||
return P("SkinDataAsset") is { } skin ? new SkinInfo(skin, P("SkinLevelDataAsset"), P("ChromaDataAsset"), P("CharmDataAsset"), P("CharmLevelDataAsset")) : null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
// gvr-replay <file.vrf> <out.json> [--hz 10]
|
||||
// gvr-replay <file.vrf> --stats (디버그: 액터 종류별 개수)
|
||||
// gvr-replay <file.vrf> --fields (디버그: 복제 필드 목록 <경로\t이름>, 번호 순)
|
||||
// gvr-replay --self-test (회귀 검사: 무기 주인 시간표 · 조준점 필드 자리)
|
||||
// gvr-replay --self-test (회귀 검사: 무기 주인 시간표 · 조준점 필드 자리 · 점수판 · 들고 있는 것 · 스킨)
|
||||
// 성공하면 종료 코드 0 과 함께 stdout 마지막 줄에 {"ok":true,...} 요약을 쓴다. 실패는 1 과 {"ok":false,"error":...}
|
||||
using System.Diagnostics;
|
||||
using System.Text.Json;
|
||||
@@ -52,6 +52,39 @@ public static class Program
|
||||
var cs = Crosshair.Snapshot(0, new Dictionary<string, object> { ["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);
|
||||
}
|
||||
// 들고 있는 것: 같은 총 · 같은 스킨을 이어 들면 한 줄, 같은 총이라도 스킨이 다르면(주운 총) 새 줄
|
||||
var er = Collector.EquipRows([(3000, 0, 1, 5), (1000, 0, 1, 2), (2000, 0, 1, 2), (4000, 1, 1, 2), (5000, 0, 1, 5)]);
|
||||
Eq("들고 있는 것 줄 수", er.Count, 3);
|
||||
if (er.Count == 3)
|
||||
{
|
||||
Eq("첫 줄 스킨", er[0][3], 2);
|
||||
Eq("주운 총 스킨", er[1][3], 5);
|
||||
Eq("다른 선수", er[2][1], 1);
|
||||
}
|
||||
// 스킨 경로: ".Default__…_C" 를 떼고, 스킨이 없으면 null
|
||||
var si = SkinInfo.From(new Dictionary<string, string>
|
||||
{
|
||||
["SkinDataAsset"] = "/Game/Equippables/Guns/Rifles/AK/HypeBeast/AssaultRifle_AK_HypeBeast_PrimaryAsset.Default__AssaultRifle_AK_HypeBeast_PrimaryAsset_C",
|
||||
["ChromaDataAsset"] = "/Game/A/B_PrimaryAsset.Default__B_PrimaryAsset_C",
|
||||
});
|
||||
if (si is not { Skin: "/Game/Equippables/Guns/Rifles/AK/HypeBeast/AssaultRifle_AK_HypeBeast_PrimaryAsset", Chroma: "/Game/A/B_PrimaryAsset", Level: null })
|
||||
fails.Add($"스킨 경로: {si}");
|
||||
if (SkinInfo.From(new Dictionary<string, string> { ["ChromaDataAsset"] = "/Game/A/B" }) is not null) fails.Add("스킨 없는 기록이 스킨이 됨");
|
||||
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 +112,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")
|
||||
@@ -94,11 +127,22 @@ public static class Program
|
||||
collector.PrintStats();
|
||||
return 0;
|
||||
}
|
||||
// 무기 스킨 (두 번째 읽기). 못 읽으면 스킨 없이 (사이트는 기본 스킨)
|
||||
Dictionary<uint, Dictionary<string, string>>? skins = null;
|
||||
try
|
||||
{
|
||||
skins = SkinReader.Read(input, result);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Console.Error.WriteLine("스킨 읽기 실패: " + e.Message);
|
||||
}
|
||||
var replay = collector.Build(
|
||||
result.Metadata.ReplayVersion.Branch,
|
||||
FDateTimeToUnixMs(info.Timestamp),
|
||||
info.LengthInMs,
|
||||
hz);
|
||||
hz,
|
||||
skins);
|
||||
// 선수 조준점 (두 번째 읽기). 못 읽어도 나머지 변환은 그대로 쓴다
|
||||
var crosshairs = 0;
|
||||
try
|
||||
@@ -127,6 +171,8 @@ public static class Program
|
||||
players = replay.Players.Count,
|
||||
rounds = replay.Rounds.Count,
|
||||
kills = replay.Kills.Count,
|
||||
scoreboard = replay.Scoreboard.Count,
|
||||
skins = replay.Skins.Count,
|
||||
crosshairs,
|
||||
elapsedMs = sw.ElapsedMilliseconds,
|
||||
status = result.Status.ToString(),
|
||||
|
||||
73
tools/replay-extract/src/Skins.cs
Normal file
73
tools/replay-extract/src/Skins.cs
Normal file
@@ -0,0 +1,73 @@
|
||||
using Replay.Encoding.Archives;
|
||||
using Replay.Models.Descriptors;
|
||||
using Replay.Models.Events;
|
||||
using Replay.Unreal.Parsing;
|
||||
using Replay.Valorant;
|
||||
using Replay.Valorant.Descriptors;
|
||||
|
||||
namespace GvrReplay;
|
||||
|
||||
/// <summary>
|
||||
/// 무기 스킨. 총 · 칼 액터마다 스킨(SkinDataAsset) · 단계(SkinLevelDataAsset) · 색상(ChromaDataAsset) · 총 장식(CharmDataAsset ·
|
||||
/// CharmLevelDataAsset)이 복제된다 (값은 게임 데이터 에셋 경로). 파서에는 무기 액터 형식이 없어서, 첫 번째 읽기의 필드 목록에서
|
||||
/// 이 필드가 있는 묶음(무기 클래스)을 찾아 그 필드만 읽는 두 번째 읽기를 한다. 줍거나 떨어뜨려도 액터의 스킨은 그대로다 (게임도 같다).
|
||||
/// </summary>
|
||||
public static class SkinReader
|
||||
{
|
||||
public static readonly string[] Fields = ["SkinDataAsset", "SkinLevelDataAsset", "ChromaDataAsset", "CharmDataAsset", "CharmLevelDataAsset"];
|
||||
|
||||
/// <summary>두 번째 읽기: 무기 액터 → 필드 이름 → 에셋 경로 (마지막 값)</summary>
|
||||
public static Dictionary<uint, Dictionary<string, string>> Read(string path, ValorantReplayReadResult first)
|
||||
{
|
||||
var groups = first.ExportGroups
|
||||
.Where(g => g.PathName is { } p && g.Fields.Any(f => f.Name == "SkinDataAsset"))
|
||||
.Select(g => g.PathName!).Distinct().ToList();
|
||||
if (groups.Count == 0) return [];
|
||||
var catalog = ValorantDescriptors.CreateCatalog();
|
||||
foreach (var g in groups)
|
||||
catalog.Add(new ExportGroupDescriptor(g, ExportCategory.GameState, ExportGroupKind.Actor, fields: Fields.Select(n => new FieldDescriptor
|
||||
{
|
||||
ExportName = n,
|
||||
PropertyName = n,
|
||||
Categories = ExportCategory.GameState,
|
||||
Decoder = PrimitiveDecoders.ObjectNetGuid,
|
||||
}).ToList()));
|
||||
var sink = new Sink(groups.ToHashSet());
|
||||
var profile = new ParseProfile
|
||||
{
|
||||
EnabledCategories = ExportCategory.All,
|
||||
CaptureDiagnosticFields = true,
|
||||
IncludedPaths = [.. groups],
|
||||
};
|
||||
using var file = File.OpenRead(path);
|
||||
using var archive = new FBinaryArchive(file);
|
||||
new ValorantReplayReader(null, sink, profile, catalog).Read(archive);
|
||||
return sink.Result;
|
||||
}
|
||||
|
||||
private sealed class Sink(HashSet<string> groups) : IReplayEventSink
|
||||
{
|
||||
private readonly Dictionary<uint, string> _paths = [];
|
||||
public Dictionary<uint, Dictionary<string, string>> Result { get; } = [];
|
||||
|
||||
public void Emit(ReplayEvent e)
|
||||
{
|
||||
if (e is NetGuidExported g)
|
||||
{
|
||||
_paths[g.NetGuid] = g.Path;
|
||||
return;
|
||||
}
|
||||
if (e is not ExportGroupReceived x || x.ExportGroupPath is not { } gp || !groups.Contains(gp)) return;
|
||||
foreach (var f in x.DiagnosticFields)
|
||||
{
|
||||
if (f.Name is not { } n || Array.IndexOf(Fields, n) < 0) continue;
|
||||
if (f.Value.Kind != DecodedFieldValueKind.ObjectReference) continue;
|
||||
var r = f.Value.ObjectReferenceValue;
|
||||
var p = r.Path ?? _paths.GetValueOrDefault(r.NetGuid);
|
||||
if (!Result.TryGetValue(x.ActorNetGuid, out var d)) Result[x.ActorNetGuid] = d = [];
|
||||
if (r.NetGuid == 0 || p is null) d.Remove(n);
|
||||
else d[n] = p;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -152,6 +152,10 @@ class SttEngine:
|
||||
if noise.judge_vad(speech_ratio, speech_s, sensitivity):
|
||||
return done("vad")
|
||||
|
||||
# 앱이 게임 중에는 빔 1(가장 가벼움)을 보낸다. 없으면 슬롯 기본값
|
||||
beam = req.get("beam_size")
|
||||
beam = int(beam) if isinstance(beam, (int, float)) and 1 <= int(beam) <= 10 else BEAM.get(slot, 5)
|
||||
|
||||
hotwords = req.get("hotwords") or None
|
||||
hotwords = hotwords if isinstance(hotwords, str) and hotwords.strip() else None
|
||||
|
||||
@@ -161,7 +165,7 @@ class SttEngine:
|
||||
prep.audio,
|
||||
language="ko",
|
||||
task="transcribe",
|
||||
beam_size=BEAM.get(slot, 5),
|
||||
beam_size=beam,
|
||||
word_timestamps=True,
|
||||
vad_filter=True,
|
||||
vad_parameters={"min_silence_duration_ms": VAD_MIN_SILENCE_MS},
|
||||
|
||||
Reference in New Issue
Block a user