41 Commits

Author SHA1 Message Date
EJClaw
320cc9babe v1.9.1
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 12:39:51 +09:00
EJClaw
b645d7575d 경기 기록 가져오기 취소 · 재개 보완: 받다가 멈춘 실행(취소 · 게임 시작 · 오류)은 history_pending 으로 남겨 다음 실행이 아는 경기 쪽에서 멈추지 않고 끝까지 훑게 (끝까지 훑은 계정에서 새 경기 일부만 받고 취소하면 나머지를 영영 못 받던 것) · 취소하면 다음 실행은 취소한 때부터 한 주기 뒤 (오래 돈 실행을 취소하면 바로 다시 시작하던 것) · 테스트
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 09:58:26 +09:00
EJClaw
63d0e43196 경기 기록 가져오기 진행 바 · 취소: Riot 경기 기록을 가져오는 동안 사이트 경기 탭 · 앱 게임 연동 탭에 목록 확인 중(얼마나 걸릴지 모름) → 받은 경기 / 받을 경기 · % · 남은 시간 진행 바와 취소 버튼 (취소하면 받은 경기는 남고 다음 주기에 남은 것부터 이어서) · 진행 상황은 games.state 의 history 로 보냄 · POST /api/games/history/cancel · 끝나면 경기 목록 새로 · 목록 불러오는 중 표시 · schema.ts 사본 다시 맞춤
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 09:54:09 +09:00
EJClaw
2a9a6496d8 v1.9.0 릴리스 기록 · README 링크
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 09:33:12 +09:00
EJClaw
b1568db8ca v1.9.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 03:43:45 +09:00
EJClaw
11db2e5104 경기 탭: 내가 플레이한 경기 전부 (Riot 경기 기록 포함) · 필터 (전체 경기 / 타임라인 있는 경기 / 목소리 녹음된 경기) · 지난 경기 더 보기 · 카드에 녹음 / 경기 기록만 표시 · 타임라인 사이드바는 타임라인 있는 경기만 · 목 서버에 기록 경기 70개
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 03:43:24 +09:00
EJClaw
f9fbf4c6c0 내 Riot 경기 기록 가져오기: 발로란트 match-history · 롤 LCU 기록을 게임 중이 아닐 때 30분마다 훑어 앱이 잡지 못한 경기를 source=history 로 저장 (처음은 끝까지, 다음부터 새 경기만, 상세 없는 경기는 건너뜀) · /api/matches has=timeline|voice 필터 · 경기 요약 source · voice · 녹음 없는 기록 경기의 킬 · 라운드는 타임라인 · 기록 관리에서 뺌
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 03:40:31 +09:00
EJClaw
9e1875b237 게임 중 GPU 아끼기: 게임(발로란트 실행 중 · 롤 경기 중)이 켜져 있으면 정밀 모델을 내리고 정밀 변환은 게임을 끈 뒤로 (16GB 카드는 경기 중에도 large-v3 를 올려 두고 다음 경기 중에도 지난 경기 정밀 변환을 돌리던 것, 메뉴에서는 새 발화를 large-v3 빔 5 로 변환하던 것) · 실시간 변환은 빔 1 · 발화 사이에 변환한 만큼 쉼 · 설정 토글 · 앱 창 하드웨어 가속 끔
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 03:36:03 +09:00
EJClaw
d0371fa0ac 3D 리플레이: 리플레이 파일이 없으면 '리플레이 파일 없음'과 새로고침 버튼 (내려받은 뒤 누르면 다시 찾아 변환) · 오류 상태에도 새로고침 · 목 서버는 리플레이 파일이 없으면 404
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 03:30:39 +09:00
EJClaw
cfe5075f76 v1.8.2 릴리스 기록 · README 링크
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 21:18:34 +09:00
EJClaw
96fb41748b 1인칭 조준점: 리플레이의 선수 조준점 · 사이트 전체 내 조준점 설정 · v1.8.2
- 변환기 Crosshair.cs: BombPlayerState 에 복제된 선수 조준점 프로필(주 · 정조준 · 저격 점 · 이름)을 두 번째 읽기로 읽어 players[].crosshair (바뀐 시각마다 전체 설정). 첫 읽기 필드 목록으로 번호를 찾고 패치로 밀려도 이름이 맞는 자리를 찾는다. --fields 디버그, --self-test 에 자리 찾기 · 기본색 검사
- 사이트 lib/crosshair.ts 그리기 · 발로란트 조준점 코드 읽기, CrosshairPanel: 선수 조준점(없으면 내 조준점) / 모든 선수에 내 조준점, 직접 고치기 · 코드 가져오기 · 선수 조준점 복사
- 1인칭: 정조준 조준점 · 저격 조준경 가운데 점 · 사격/이동 오차로 벌어짐
- 앱 1.8.2 (버전이 바뀌면 리플레이를 다시 변환해 조준점이 생긴다)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 20:44:50 +09:00
EJClaw
309974087b 1인칭: 요원 · 무기를 바꿔 다시 만들 때 눈 기준점을 팔 공간 좌표로 (이전 root 변환이 섞여 1.6m 밀리던 것) · 스파이크 설치 구간에 설치 동작(activate) 재생 (설치 시작 때 스파이크를 꺼내므로 꺼내기보다 먼저)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 18:35:24 +09:00
EJClaw
1fb8821663 3D 리플레이 실감 4단계: 1인칭 팔 · 총 · 동작 · 발로란트 조준점
- 추출기 viewmodels: 요원 1인칭 팔 fparms_* (30명) · 무기 1인칭 fpweapon_* (22종, 탄창 · 총 동작) · 팔 동작 fpanim_* (대기 · 사격 · 재장전 · 꺼내기 · 정조준 · 걷기 · 스파이크 작동). Agents.Skinned 로 스켈레탈 메시 내보내기를 나눠 3인칭 요원과 같이 쓴다
- pack.py · update.sh: viewmodels 압축 · index.json viewmodels, 갱신 때 같이 뽑는다
- 사이트 lib/viewmodel.ts: 카메라 공간 장면으로 맵 위에 그린다. 꺼내기 > 재장전 > 사격(총구 불꽃) > 걷기 > 정조준 > 대기를 리플레이 시각만으로 고른다
- 1인칭: 줌(소총 1.25배 · 저격 2.5/5배 + 조준경), 조준점을 발로란트 기본 십자(흰 선 · 틈 · 외곽선)로
- 작업 노트 docs/dev/replay-3d.md

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 18:21:47 +09:00
EJClaw
88e043da28 작업 노트: 13.09 전체 반영 결과 (구운 조명 22/23 맵)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 17:58:50 +09:00
EJClaw
626878e1d8 install.sh: 알림 채널 · 토큰 파일을 환경변수로 주지 않으면 이미 설치된 값을 그대로 쓴다 (다시 설치하면 알림이 빈 값으로 덮여 꺼지던 것)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 17:48:05 +09:00
EJClaw
a69ed57a0f 맵 3D 갱신: 사이트 맵 목록 대조를 대소문자 무시로 (13.09 에서 /Game/Maps/FoxTrot → Foxtrot 로만 바뀌어 '빠진 맵'으로 올리지 않던 것, 사이트도 대소문자 무시로 찾는다) · test-update.sh 가짜 추출기에 anims · abilities 명령 (스킬 재료 단계가 생긴 뒤 시험이 깨져 있던 것) · 대소문자 시험 추가
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 17:46:25 +09:00
EJClaw
33e83256ed 라이트맵 추출 메모리: 칸 목록만 모으고 Build 에서 페이지를 하나씩 풀어 바로 줄인다 (펄 맵이 6GB 한도에서 OutOfMemory 이던 것, 고친 뒤 최대 2.7GB)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 16:41:06 +09:00
EJClaw
185e8c17bd 3D 리플레이 실감 3단계: 게임에 구워 둔 조명(라이트맵)으로 맵을 칠한다
- 추출기: 레벨 BuiltData 의 HQ 라이트맵을 메시 칸마다 풀어 irr · sh 아틀라스 두 장으로 (src/Lightmaps.cs), 조명 있는 배치는 LOD0 + 라이트맵 UV(TEXCOORD_1), ISM 은 인스턴스마다 칸
- glb: 재질 occlusionTexture(irr) · emissiveTexture(sh, 세기 0) · extras.lightmap.k. pack.py 는 맵 UV 를 실수로(-vtf, gltfpack 이 두 UV 채널을 한 범위로 양자화해서 라이트맵이 어긋나던 것)
- 사이트 map3d.ts: 색 = 텍스처 × irr × K × max(0, 1 + dot(sh, N.yzx)). 옛 glb 는 그대로
- install.sh: 꺼 둔 자동 갱신 타이머는 다시 켜지 않는다
- 조사 명령 lmprobe · 작업 노트 docs/dev/replay-3d.md

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-29 15:45:43 +09:00
EJClaw
37c898cd73 종료 보완: DB 를 닫은 뒤 온 변환 성공 응답도 버림 · 트레이와 갱신 타이머를 TrayShell 로 묶어 종료 · 없어진 트레이 처리 회귀 시험
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 23:29:24 +09:00
EJClaw
cd4b7cb16f 종료 시 'Tray is destroyed' 오류 창: 트레이 · 상태 갱신 타이머를 멈추고 트레이를 비운 뒤 없앤다 · Electron 이 먼저 없앤 트레이도 건드리지 않음 · 종료 중 STT 는 새 작업을 꺼내지 않고 워커 종료로 실패한 작업을 닫힌 DB 에 기록하지 않음 (시험 추가)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 23:25:25 +09:00
EJClaw
dc36d094e9 v1.8.1 릴리스 기록 · README 링크
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 02:25:58 +09:00
EJClaw
a6cf73dee7 변환기: 무기 상태의 주인을 그 시각 주인으로 (마지막 주인이 과거 상태까지 덮어쓰던 것) · gvr-replay --self-test 회귀 검사 · CI 에서 실행 · v1.8.1
어비스 13.08 리플레이: 상태 16,974줄 중 1,189줄의 주인이 바뀜, 그중 그 시각 들고 있던 무기와 맞는 비율 24% → 75%

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 02:11:28 +09:00
EJClaw
ac70f7ce1f v1.8.0 릴리스 기록 · README 링크
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 02:06:57 +09:00
EJClaw
735783cd10 v1.8.0: 3D 리플레이 실감 (변환기 v2 · 요원 동작 · 게임 스킬 효과)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 01:51:51 +09:00
EJClaw
4cf4de0123 스킬 효과: 게임 효과가 아무것도 그리지 않는 동안은 예전 기본 모양으로 (짧게 끝나는 연막 등) · 오멘처럼 반투명 층뿐인 연막도 돔으로 · 아군/적 전용 시스템은 보는 쪽 것만
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 01:50:27 +09:00
EJClaw
a66f79d079 스킬 효과 추출: Zone_ 클래스도 (오멘 연막 Zone_Wraith_4_Smoke · 사이퍼 덫 Zone_Gumshoe_Q_Cage)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 01:35:58 +09:00
EJClaw
73e6173a59 3D 리플레이 실감 2단계: 게임 스킬 효과 추출(Abilities.cs: Cascade 파티클 · 메시 · 텍스처 → abilities.json) · 사이트 파티클 재생기(lib/vfx.ts: 시간만으로 계산 · 연막 돔 · 장판 칸 · 투사체 꼬리 · 설치물 메시) · maps3d json/png 제공 · update.sh/pack.py 연결
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 01:33:48 +09:00
EJClaw
c94edac147 3D 리플레이 실감 1단계: 변환기 v2 (스킬 주인 · 투사체 경로 · 앉기/점프 · 무기 상태 · 맞은 자리 · 사망 모션 · 설치/해체) · 공용 애니메이션 anims.glb · 요원 동작(앉기 · 점프 · 착지 · 조준 각 · 사격 반동 · 재장전 · 던지기 · 사망) · 예광 · 작은 이름표 · 요루 분신
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-18 00:29:09 +09:00
EJClaw
5c8ba05da4 사이트 CSP connect-src 에 blob: 추가: 3D 파일 안 텍스처를 막아 요원이 흰색 · 맵 3D 가 미니맵으로 나오던 문제
- three.js GLTFLoader 는 glb 안 이미지를 blob: 주소로 fetch 해 읽는데 connect-src 가 막아 텍스처가 모두 실패했다
  (요원 흰색, 두 층 맵 재질은 텍스처 실패로 맵 전체가 실패 → 미니맵 바닥)
- CSP 를 csp.ts 하나로 모으고 vite preview 도 같은 CSP 로 열어 헤드리스 확인이 실제와 같은 제한에서 되게 함
- 맵 B 층 텍스처 하나를 못 읽어도 맵 전체를 버리지 않음
- 시험: connect-src 에 blob: 확인

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 22:30:00 +09:00
EJClaw
759334ac79 맵 3D 자동 갱신: 요원 · 무기 추출 실패나 빠진 요원 · 무기가 있으면 올리지 않고 재시도 (기존 목록 보존) · 시험 추가
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 21:00:08 +09:00
EJClaw
f584ba60b3 테스트 기록: v1.7.0 릴리스
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 20:56:03 +09:00
EJClaw
4cd6f1103f v1.7.0: 3D 리플레이 완전 3D (맵 색 · 요원 · 총 · 스킬 모양 · 1인칭/자유시점) · 작업 노트
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 20:37:47 +09:00
EJClaw
f82857f476 3D 리플레이: 스킬 종류별 모양(연막 · 장판 · 폭발 · 정찰 고리 · 설치물 · 스파이크 3D)과 요원 색
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 20:35:44 +09:00
EJClaw
86c42d99ca map-extract: __pycache__ 무시
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 20:25:32 +09:00
EJClaw
f8f585f230 3D 리플레이: 요원 3D 몸(뼈대 · 텍스처 · 공용 걷기/달리기 + 총 든 자세) · 총 22종 추출, 재생기가 원기둥 대신 요원과 손에 든 총을 그림
- map-extract agents: 요원 30명 agent_<코드>.glb (위/아래 몸 애니메이션 분리, ACL 풀기용 CUE4Parse-Natives 를 g++ 로 빌드), 무기 weapon_<이름>.glb
- pack.py: 요원 · 무기도 압축해 index.json agents · weapons
- 사이트: AgentRig (이동 방향 · 속도로 다리 애니메이션 섞기, 오른손에 총), 1인칭 · 자유시점에서 이름표 작게

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 20:25:27 +09:00
EJClaw
d87f4ade27 3D 리플레이: 1인칭 · 자유시점 카메라, 선수가 들고 있는 총 (변환기 equips · 이름표 · 킬 피드)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 19:48:48 +09:00
EJClaw
6d71abaabd 맵 3D: 재질 · 텍스처(디퓨즈 256px) · 두 층 섞기 · 법선 포함 glb, 사이트가 glb 재질로 그림
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 19:40:19 +09:00
EJClaw
1ee753bc79 테스트 기록: v1.6.0 릴리스
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 15:41:59 +09:00
EJClaw
b9431c1a15 v1.6.0: 사이트 '내 정보'(표시 이름 · 색 · 라이엇 ID · 녹음 제외) · 관리 페이지
- 사이트 오른쪽 위 내 이름 → 내 정보: 표시 이름 바꾸기/되돌리기, 색, 라이엇 ID, 녹음 제외, 로그아웃
- 관리 페이지 /admin (관리자): 게임 PC 상태 · 앱 새 버전 안내, 유저별 표시 이름 · 색 · 라이엇 ID · 녹음 제외,
  앱 등록 · 역할 · 해제(최고 관리자). /site/admin/* 는 /app/admin/* 와 같은 처리
- 서버: 표시 이름 검사(길이 · 보이지 않는 글자 · 다른 사람과 겹침), 지우면 디스코드 이름으로 되돌림,
  바뀌면 게임 PC 앱에 바로 보냄 (PUT /api/internal/names)
- 앱: PATCH /api/users/:id (본인 또는 관리자, 남의 라이엇 ID 는 관리자만), PUT /api/internal/names
- 테스트: 앱 user-settings 3개, 사이트 서버 profile-admin 3개

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 15:27:17 +09:00
EJClaw
916b35c691 테스트 기록: v1.5.0 릴리스
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 15:14:34 +09:00
EJClaw
84ba2e3e64 3D 리플레이: 사이트가 변환 실패 이유를 보여 주고 사이트 로그에 남김 · 작업 노트 v1.5.0
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-17 14:57:03 +09:00
97 changed files with 11673 additions and 395 deletions

View File

@@ -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.4.2](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.4.3) (`GameVoiceRecorder-1.4.3-win-x64.zip` 권장, 단일 파일 `GameVoiceRecorder-1.4.3-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.9.0](https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.9.0) (`GameVoiceRecorder-1.9.0-win-x64.zip` 권장, 단일 파일 `GameVoiceRecorder-1.9.0-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~)
@@ -19,6 +19,19 @@
- 앱은 시작할 때와 10분마다 등록 여부를 다시 확인한다. 등록이 해제되면 바로 잠그고 봇 · 녹음 · 사이트 연결을 멈춘다. 사이트 서버에 못 붙으면 마지막 확인 뒤 3일까지는 그대로 쓴다.
- 서버 쪽: `site/server/src/app-auth.ts` (`/auth/app/*`, `/app/me`, `/app/admin/users`), 앱 쪽: `app/src/core/auth.ts`, 권한 목록: `app/src/core/roles.ts`. 로그인 E2E: `app/scripts/login-e2e.mts`.
## v1.6.0 바뀐 점
- **내 정보** (사이트 오른쪽 위 내 이름 누르기, `site/web/src/components/UserEdit.tsx`): 표시 이름 바꾸기 · 되돌리기(디스코드 서버 별명으로), 내 색, 라이엇 ID, 녹음 제외, 내 기록 보기 · 관리 페이지 · 로그아웃
- 표시 이름은 사이트 서버에 저장하고(`PUT /site/profile/name`, 1~32자 · 보이지 않는 글자 금지 · 다른 사람 표시 이름과 겹치면 거절 · 10분에 10번) 게임 PC 앱에 바로 보낸다(`PUT /api/internal/names`, 예전 앱은 10분마다 받아 감)
- 색 · 라이엇 ID · 녹음 제외는 게임 PC 앱 기록에 저장 (`PATCH /api/users/:id`, 본인 또는 관리자. 다른 사람에게 연결된 라이엇 ID 는 본인이 가져갈 수 없음)
- **관리 페이지** `/admin` (관리자 · 최고 관리자, `site/web/src/pages/AdminPage.tsx`): 게임 PC 연결 · 앱 버전 · 새 버전 안내(Gitea 최신 릴리스), 녹음된 사람 + 앱 등록 유저 목록에서 표시 이름 · 색 · 라이엇 ID · 녹음 제외 바꾸기, 앱 등록 · 역할 · 해제(최고 관리자). 서버 `/site/admin/*` 는 앱 관리자 탭 `/app/admin/*` 와 같은 코드 (`site/server/src/app-auth.ts`). 표시 이름은 사이트에서는 관리자도 바꿀 수 있다
## v1.5.0 바뀐 점
- **3D 리플레이**: 발로란트 경력 탭에서 경기 리플레이를 내려받아 두면, 사이트 경기 화면 "3D 리플레이"를 열 때 게임 PC 앱이 `%LOCALAPPDATA%\VALORANT\Saved` 아래 `<경기 ID>.vrf` 를 찾아 변환해 보낸다 (처음 한 번 10초 안팎, 그 뒤로는 `GVR-Data/replays/<경기 ID>.json.gz` 보관본). 선수 10명이 3D 맵 위에서 움직이고 그때 대화가 같이 재생된다
- 변환기 `resources/replay/gvr-replay.exe` (`tools/replay-extract`, .NET 단일 파일). 한 번에 하나 · 낮은 우선순위로 돌린다. 실패하면 이유를 사이트에 보여 주고, 같은 파일은 다시 내려받을 때까지 다시 하지 않는다
- 앱 `app/src/core/replays.ts`, API `GET /api/matches/:id/replay` (gzip JSON, 변환 중 202) · `GET /api/replays` (찾은 리플레이 목록)
## v1.4.3 바뀐 점
- 상대 닉네임을 말로 적던 문제 (예: 말소리가 "QQQWWWQ"로 나옴): 그 경기 선수 이름을 모두 핫워드로 넣어서, 말을 못 알아들으면 Whisper 가 닉네임을 그대로 적었다. 이제

4
app/package-lock.json generated
View File

@@ -1,12 +1,12 @@
{
"name": "gvr-app",
"version": "1.5.0",
"version": "1.9.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "gvr-app",
"version": "1.5.0",
"version": "1.9.1",
"license": "UNLICENSED",
"dependencies": {
"@discordjs/voice": "^0.19.2",

View File

@@ -1,7 +1,7 @@
{
"name": "gvr-app",
"productName": "겜녹이",
"version": "1.5.0",
"version": "1.9.1",
"description": "겜녹이 (Game Voice Recorder) - 게임 연동 디스코드 음성 기록",
"private": true,
"main": "dist/main.cjs",

View File

@@ -40,6 +40,8 @@ export interface ApiDeps {
bundles?: Bundles;
/** 발로란트 리플레이 (없으면 /api/replays 없음) */
replays?: Replays;
/** 사이트 서버가 새 표시 이름을 보내 왔을 때 (녹음 파일 이름 다시 맞추기) */
onNamesChanged?: () => void;
}
const STOP = new Set(['그', '저', '이', '그냥', '아', '어', '음', '네', '응', '좀', '진짜', '근데', '나', '너', '저기', '이거', '그거', '뭐', '왜', '아니', '그래', '거', '것', '수', '게', '잠깐만']);
@@ -118,6 +120,47 @@ 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);
if (!u) return reply.code(404).send({ error: 'not_found', message: '이 PC 기록에 없는 유저입니다 (음성채널에서 한 번 녹음되면 생깁니다)' });
const admin = req.headers['x-gvr-role'] === 'admin' || !req.headers['x-gvr-user'];
if (!admin && !canDelete(req, u.id)) return reply.code(403).send({ error: 'forbidden', message: '본인 또는 관리자만 바꿀 수 있습니다' });
const b = req.body ?? {};
if (b.color !== undefined && !/^#[0-9a-fA-F]{6}$/.test(String(b.color))) return reply.code(400).send({ error: 'bad_color', message: '색은 #rrggbb 형식입니다' });
if (b.riotIds !== undefined && (!Array.isArray(b.riotIds) || b.riotIds.length > 5 || b.riotIds.some((r) => typeof r !== 'string' || r.length > 45)))
return reply.code(400).send({ error: 'bad_riot_ids', message: '라이엇 ID 는 5개까지, 이름#태그 형식입니다' });
let taken: string[] = [];
store.db.transaction(() => {
if (b.color !== undefined) store.setColor(u.id, String(b.color).toLowerCase());
if (b.excluded !== undefined) store.setExcluded(u.id, !!b.excluded);
if (b.riotIds !== undefined) taken = store.setRiotIds(u.id, b.riotIds, admin).taken;
})();
log.info(`유저 설정 바뀜 ${u.id}: ${Object.keys(b).join(', ')}${taken.length ? ` (이미 다른 사람에게 연결된 라이엇 ID ${taken.length}개 뺌)` : ''}`);
d.bus.live({ type: 'users.updated', data: [] });
return { user: toUser(store.getUser(u.id)!, store.listAccounts()), taken };
});
// 표시 이름 (v1.6.0): 사이트에서 이름을 바꾸면 사이트 서버가 바로 보낸다 (예전 앱은 10분마다 받아 감)
app.put<{ Body: { names?: Record<string, string> } }>('/api/internal/names', async (req, reply) => {
if (req.headers['x-gvr-internal'] !== '1') return reply.code(403).send({ error: 'forbidden' });
const names = req.body?.names;
if (!names || typeof names !== 'object') return reply.code(400).send({ error: 'bad_names' });
store.setDisplayNames(names);
timeline.invalidate();
d.onNamesChanged?.();
d.bus.live({ type: 'users.updated', data: [] });
return { ok: true };
});
app.get<{ Querystring: Record<string, string> }>('/api/timeline', async (req) => {
const q = req.query;
const tq: TimelineQuery = {
@@ -275,7 +318,13 @@ 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,
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,
})
.map((m) => d.games.summary(m));
});

View File

@@ -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 ?? [])

View File

@@ -50,6 +50,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 +130,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)) {
@@ -241,6 +246,10 @@ export class Store {
setExcluded(id: string, excluded: boolean): void {
this.db.prepare('UPDATE users SET excluded=?, updated_at=? WHERE id=?').run(excluded ? 1 : 0, Date.now(), id);
}
/** 사이트 · 타임라인에서 쓰는 유저 색 (#rrggbb) */
setColor(id: string, color: string): void {
this.db.prepare('UPDATE users SET color=?, updated_at=? WHERE id=?').run(color, Date.now(), id);
}
/** 유저 평소 음량 누적 평균 (최근값에 가중치) */
updateGainProfile(id: string, lufs: number): void {
const u = this.getUser(id);
@@ -252,6 +261,29 @@ export class Store {
listAccounts(): { user_id: string; puuid: string; riot_id: string }[] {
return this.db.prepare('SELECT * FROM game_accounts').all() as any[];
}
/**
* 라이엇 ID (이름#태그) 목록으로 연결 계정을 바꾼다. 이미 연결된 것은 puuid 를 그대로 두고, 새것은 riotid: 로 두었다가
* 경기에서 만나면 실제 puuid 로 바뀐다. 다른 사람에게 연결된 라이엇 ID 는 넣지 않고 돌려준다 (관리자는 allowTaken 으로 같이 연결)
*/
setRiotIds(userId: string, riotIds: string[], allowTaken = false): { taken: string[] } {
const all = this.listAccounts();
const cur = all.filter((a) => a.user_id === userId);
const taken: string[] = [];
const seen = new Set<string>();
const next: { puuid: string; riot_id: string }[] = [];
for (const raw of riotIds) {
const r = raw.trim();
if (!/^[^#]{1,32}#[^#]{1,8}$/.test(r) || seen.has(r.toLowerCase())) continue;
seen.add(r.toLowerCase());
if (!allowTaken && all.some((a) => a.user_id !== userId && a.riot_id.toLowerCase() === r.toLowerCase())) {
taken.push(r);
continue;
}
next.push(cur.find((a) => a.riot_id.toLowerCase() === r.toLowerCase()) ?? { puuid: `riotid:${r}`, riot_id: r });
}
this.setAccounts(userId, next.map((a) => ({ puuid: a.puuid, riotId: a.riot_id })));
return { taken };
}
setAccounts(userId: string, accounts: { puuid: string; riotId: string }[]): void {
const tx = this.db.transaction(() => {
this.db.prepare('DELETE FROM game_accounts WHERE user_id=?').run(userId);
@@ -379,13 +411,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`,
)
@@ -395,9 +428,15 @@ 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 = 목소리가 녹음된 경기
*/
listMatches(opts: { game?: string; before?: number; limit?: number; ids?: string[]; has?: 'timeline' | 'voice' }): MatchRow[] {
const where: string[] = [];
const args: any[] = [];
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);

View File

@@ -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

View File

@@ -0,0 +1,155 @@
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();
}
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');
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;
}
}
}

View File

@@ -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,7 @@ 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(),
updatedAt: Date.now(),
};
}
@@ -442,6 +482,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 +500,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> {

View File

@@ -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;
@@ -182,6 +219,8 @@ export class GameManager implements AdapterHost {
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),
};
}

View File

@@ -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;
@@ -39,6 +42,10 @@ export interface GameAdapter {
start(): void;
stop(): void;
status(): { connected: boolean; inMatch: boolean; detail?: string };
/** 게임이 켜져 있어 GPU 를 쓰고 있는가 (발로란트: 게임 실행 중 · 롤: 경기 중) */
gameRunning(): boolean;
/** 지금 게임 상태 (자세히) */
liveGame(): LiveGame;
/** Riot 경기 기록 가져오기 */
readonly history: HistorySync;
}

View File

@@ -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,51 @@ export class ValorantAdapter implements GameAdapter {
private detailQueue = new Map<string, { tries: number; endedAt: number; startedLocal: number }>();
private polling = false;
private lastErr = '';
/** 내 경기 기록 (앱이 꺼져 있을 때 한 경기도 경기 목록에) */
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 +135,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 +184,7 @@ 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(),
updatedAt: Date.now(),
};
}
@@ -206,9 +255,11 @@ 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);
} else {
this.presence = null;
// 클라이언트가 꺼졌으면 경기도 끝난 것으로 본다
this.endMatch();
if (this.match) this.endMatch();
}
await this.pollDetails();
this.lastErr = '';

View File

@@ -106,6 +106,7 @@ export async function startCore(opts: CoreOptions) {
trainingDir: () => paths().training,
version: opts.version,
replays,
onNamesChanged: () => audioNames.refreshAll(),
bundles: new Bundles(store, games, () => paths().audio, opts.version, (ids) => ids.forEach((id) => audioNames.refresh(id))),
overviewExtra: () => ({
guild: bot.state.guild,
@@ -188,6 +189,7 @@ export async function startCore(opts: CoreOptions) {
relay.stop();
retention.stop();
games.stop();
stt.stop();
await bot.stop();
await worker.stop();
await api.close();

View File

@@ -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: {

View File

@@ -81,6 +81,8 @@ export class SttPipeline {
private queued = new Set<string>();
private busy = false;
private processing: string | null = null;
/** 앱 종료 중: 새 작업을 꺼내지 않고, 워커가 끊겨 실패한 작업은 DB(곧 닫힘)에 기록하지 않는다. 남은 발화는 다음 시작 때 다시 처리 */
private stopped = false;
/** 한 발화의 변환이 끝났을 때 (녹음 파일 이름 맞추기) */
onDone: ((id: string) => void) | null = null;
/** 예전 녹음 고치기가 끝났을 때 */
@@ -98,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 = {
@@ -141,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);
@@ -221,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);
@@ -230,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';
@@ -238,8 +294,13 @@ export class SttPipeline {
return null;
}
/** 종료 시작 (워커 · DB 를 닫기 전에 부른다) */
stop(): void {
this.stopped = true;
}
private pump(): void {
if (this.busy || !this.worker.ready) return;
if (this.stopped || this.busy || !this.worker.ready) return;
const idx = this.queue.findIndex((j) => this.pickSlot(j) !== null);
if (idx < 0) return;
const job = this.queue.splice(idx, 1)[0];
@@ -248,18 +309,22 @@ 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(() => {
this.busy = false;
this.processing = null;
this.status.processing = null;
if (this.stopped) return;
try {
if (!this.isBusy(job.id)) this.onDone?.(job.id);
} 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());
});
}
@@ -316,10 +381,13 @@ 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,
);
} catch (e: any) {
if (this.stopped) return;
const attempts = this.store.bumpAttempt(u.id);
this.status.lastError = e.message;
log.warn(`STT 실패 (${u.id}, ${attempts}회): ${e.message}`);
@@ -331,6 +399,8 @@ export class SttPipeline {
} else this.enqueue(u.id, job.slot, job.prio + 2);
return;
}
// 종료 중에 결과가 왔으면 버린다 (DB 가 이미 닫혔을 수 있다. 발화는 다음 시작 때 다시 처리)
if (this.stopped) return;
// 변환하는 동안 사이트에서 지운 발화: 결과를 버린다
if (!this.store.getUtterance(u.id)) return;
// 사이트에서 "잡음이라 삭제"한 문장과 같으면 잡음으로 (v1.4.0)

View File

@@ -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) {
// 선택하지 않은 (디스코드에 연결된) 유저가 주인공인 이벤트만 뺀다. 라운드·오브젝트·상대 킬처럼 유저가 없는 이벤트는 남긴다.

View File

@@ -110,6 +110,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>;

View File

@@ -241,13 +241,10 @@ export function registerIpc(ctx: IpcContext) {
return core.store.listUsers().map((u) => toUser(u, acc));
},
setRiotIds: (userId: string, riotIds: string[]) => {
const cur = core.store.listAccounts().filter((a) => a.user_id === userId);
const next = riotIds
.map((r) => r.trim())
.filter((r) => /^.+#.+$/.test(r))
.map((r) => cur.find((a) => a.riot_id.toLowerCase() === r.toLowerCase()) ?? { puuid: `riotid:${r}`, riot_id: r });
core.store.setAccounts(userId, next.map((a) => ({ puuid: a.puuid, riotId: a.riot_id })));
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: [] });

View File

@@ -12,6 +12,7 @@ import { Finetuner } from './finetune.js';
import type { AuthView } from './api-types.js';
import { buildState, registerIpc } from './ipc.js';
import { brandDir, rendererDir, replayToolPath, resolveDataDir, resourcesDir, workerCommand } from './paths.js';
import { TrayShell } from './tray-shell.js';
// 인증서 검증을 끄는 환경변수(NODE_TLS_REJECT_UNAUTHORIZED=0)는 무시한다. fuses 로 막지 못하는 변수라 가장 먼저 지운다
hardenTlsEnv();
@@ -22,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);
@@ -33,7 +36,7 @@ let ft: Finetuner | null = null;
let settings: SettingsStore | null = null;
let auth: AppAuth | null = null;
let win: BrowserWindow | null = null;
let tray: Tray | null = null;
const trayShell = new TrayShell<Tray>();
let quitting = false;
const dataDir = resolveDataDir(opt('data-dir'));
@@ -148,6 +151,7 @@ function closeSplash(): void {
}
function updateTray(): void {
const tray = trayShell.get();
if (!tray) return;
if (!core) {
tray.setImage(trayImage('off'));
@@ -168,6 +172,7 @@ function updateTray(): void {
}
function buildTrayMenu(): void {
const tray = trayShell.get();
if (!tray) return;
if (!core) {
tray.setContextMenu(
@@ -203,7 +208,8 @@ async function quit(): Promise<void> {
} catch (e) {
log.error('종료 중 오류', e);
}
tray?.destroy();
// 트레이 갱신 타이머가 app.exit 사이에 한 번 더 돌면 'Tray is destroyed' 오류 창이 뜬다
trayShell.dispose();
app.exit(0);
}
@@ -376,25 +382,26 @@ app.whenReady().then(async () => {
if (starting) await starting;
},
});
tray = new Tray(trayImage('off'));
const tray = new Tray(trayImage('off'));
tray.on('click', () => openWindow());
trayShell.set(tray);
refreshShell();
a.on('change', onAuthChange);
// 시작할 때 확인 → 10분마다 다시 확인 (등록 해제되면 바로 잠김). 서버에 못 붙어 막힌 상태면 1분마다 다시 시도
let lastCheck = Date.now();
const first = a.check();
setInterval(() => {
trayShell.every(15000, () => {
const st = a.state.status;
if ((st === 'ok' && Date.now() - lastCheck > 10 * 60000) || (st === 'error' && Date.now() - lastCheck > 60000) || (st === 'ok' && a.state.offline && Date.now() - lastCheck > 60000)) {
lastCheck = Date.now();
void a.check().then(syncNames);
}
}, 15000);
setInterval(() => {
});
trayShell.every(1500, () => {
updateTray();
buildTrayMenu();
pushState();
}, 1500);
});
splashText('로그인 확인 중…');
await first;
if (a.ok) splashText('녹음 · 음성 인식 엔진 시작 중…');

View File

@@ -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',

View File

@@ -0,0 +1,31 @@
/** 트레이 아이콘과 그 갱신 타이머. 종료할 때 타이머를 먼저 멈추고 트레이를 없앤다 (v1.8.2: 'Tray is destroyed' 오류 창) */
export interface TrayLike {
isDestroyed(): boolean;
destroy(): void;
}
export class TrayShell<T extends TrayLike> {
private tray: T | null = null;
private timers: NodeJS.Timeout[] = [];
set(tray: T): void {
this.tray = tray;
}
/** 쓸 수 있는 트레이 (없거나, 종료했거나, Windows 로그오프 등으로 Electron 이 먼저 없앴으면 null) */
get(): T | null {
return this.tray && !this.tray.isDestroyed() ? this.tray : null;
}
every(ms: number, fn: () => void): void {
this.timers.push(setInterval(fn, ms));
}
dispose(): void {
for (const t of this.timers) clearInterval(t);
this.timers = [];
const tray = this.get();
this.tray = null;
tray?.destroy();
}
}

View File

@@ -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,7 +168,8 @@ 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 },
@@ -518,6 +520,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;

View File

@@ -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; }

View File

@@ -1,5 +1,5 @@
import { useState } from 'react';
import { GAME_NAME, liveGameRows, type LiveGame, type User } from '@gvr/shared';
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,6 +84,44 @@ 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 }) {
@@ -178,6 +216,7 @@ export function GamesTab() {
return (
<Page title="게임 연동">
<GameCards />
<HistoryImport />
<LiveGames />
<Section title="리그 오브 레전드 세부 설정" className={g.lol ? '' : 'disabled'}>
<div className="muted" style={{ marginBottom: 8 }}>

View File

@@ -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>

103
app/test/game-saver.test.ts Normal file
View 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);
});

View File

@@ -40,7 +40,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 = {

331
app/test/history.test.ts Normal file
View File

@@ -0,0 +1,331 @@
// 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'));
// 필터
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') => ({
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();
}
});

View File

@@ -18,6 +18,12 @@ export interface MockState {
lolGameId: number;
lolHistoryReady: boolean;
lolStart: number;
/** 발로란트 경기 기록 (새것부터): MatchID → 경기 시작 시각 */
valHistory: { MatchID: string; GameStartTime: number }[];
/** 롤 경기 기록 (LCU, 새것부터) */
lolHistoryList: { gameId: number; gameCreation: number }[];
/** 요청 기록 (경로) */
hits: string[];
}
export async function startMockRiot(dir: string) {
@@ -38,6 +44,9 @@ export async function startMockRiot(dir: string) {
lolGameId: 7001,
lolHistoryReady: false,
lolStart: 0,
valHistory: [],
lolHistoryList: [],
hits: [],
};
const password = 'pw-test';
const presence = () => {
@@ -52,7 +61,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 +78,23 @@ 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, {}];
},
],
// ---- LoL Live Client Data
[/^\/liveclientdata\/allgamedata$/, () => (st.lolLive ? [200, st.lolLive] : [404, {}])],
// ---- LCU
@@ -79,7 +104,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 +128,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;

View File

@@ -0,0 +1,142 @@
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';
import { WorkerError } from '../src/core/stt/worker.ts';
import { TrayShell } from '../src/main/tray-shell.ts';
test('앱 종료: 변환 중이던 작업이 워커 종료로 실패해도 닫힌 DB 를 건드리지 않고, 남은 작업을 꺼내지 않는다', async () => {
const dir = fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-stop-'));
const store = new Store(path.join(dir, 'db.sqlite'));
store.upsertUser({ id: 'u1', name: '하늘', avatar: null });
for (const id of ['s1', 's2']) {
const f = path.join(dir, `${id}.ogg`);
fs.writeFileSync(f, Buffer.concat([Buffer.from('OggS'), Buffer.alloc(50)]));
store.insertUtterance({ id, session_id: null, user_id: 'u1', started_at: Date.now(), ended_at: Date.now() + 1000, audio_path: f, match_id: null });
}
const transcribing: string[] = [];
let fail: ((e: Error) => void) | null = null;
const worker: any = Object.assign(new EventEmitter(), {
ready: true,
request: async (op: string, req: any) => {
if (op === 'models') return { models: [{ name: 'm', installed: true }] };
if (op !== 'transcribe') return {};
transcribing.push(path.basename(req.path, '.ogg'));
return new Promise((_, rej) => (fail = rej));
},
});
const settings: any = () => ({ stt: { realtimeModel: 'm', preciseModel: 'm' }, 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);
await stt.load('realtime', 'm');
const done: string[] = [];
stt.onDone = (id) => {
done.push(id);
store.getUtterance(id); // 실제 앱의 녹음 파일 이름 맞추기도 DB 를 읽는다
};
stt.enqueue('s1', 'realtime');
stt.enqueue('s2', 'realtime');
assert.deepEqual(transcribing, ['s1']);
// core.stop 순서: stt.stop → 워커 종료 → DB 닫기 → (워커 프로세스 종료 이벤트로) 변환 요청 실패
stt.stop();
store.close();
fail!(new WorkerError('worker_exit', '워커 종료'));
await new Promise((r) => setTimeout(r, 50));
assert.deepEqual(done, [], '종료 중에는 변환 뒤 처리를 하지 않는다');
assert.deepEqual(transcribing, ['s1']);
assert.equal(stt.status.queue, 1, '종료 중에는 다음 작업을 꺼내지 않는다 (다음 시작 때 다시 처리)');
});
test('앱 종료: DB 를 닫은 뒤 변환 성공 응답이 와도 닫힌 DB 를 건드리지 않는다', async () => {
const dir = fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-stop-'));
const store = new Store(path.join(dir, 'db.sqlite'));
store.upsertUser({ id: 'u1', name: '하늘', avatar: null });
const f = path.join(dir, 's1.ogg');
fs.writeFileSync(f, Buffer.concat([Buffer.from('OggS'), Buffer.alloc(50)]));
store.insertUtterance({ id: 's1', session_id: null, user_id: 'u1', started_at: Date.now(), ended_at: Date.now() + 1000, audio_path: f, match_id: null });
let ok: ((r: unknown) => void) | null = null;
const worker: any = Object.assign(new EventEmitter(), {
ready: true,
request: async (op: string) => {
if (op === 'models') return { models: [{ name: 'm', installed: true }] };
if (op !== 'transcribe') return {};
return new Promise((res) => (ok = res));
},
});
const settings: any = () => ({ stt: { realtimeModel: 'm', preciseModel: 'm' }, 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);
await stt.load('realtime', 'm');
const errors: unknown[] = [];
const done: string[] = [];
stt.onDone = (id) => done.push(id);
// run() 의 오류는 pump 의 catch 가 log.error 로만 남기므로, DB 접근을 감시한다
const prepare = (store as any).db.prepare.bind((store as any).db);
(store as any).db.prepare = (sql: string) => {
try {
return prepare(sql);
} catch (e) {
errors.push(e);
throw e;
}
};
stt.enqueue('s1', 'realtime');
stt.stop();
store.close();
ok!({ text: '가자', raw_text: '가자', words: [], noise: false, noise_reason: null, confidence: 0.9, lufs: -20, gain_db: 0, speech_ratio: 1, duration_s: 1, model: 'm', elapsed_ms: 1 });
await new Promise((r) => setTimeout(r, 50));
assert.deepEqual(errors, [], '닫힌 DB 에 접근하지 않는다');
assert.deepEqual(done, []);
});
test('트레이: 종료하면 갱신 타이머가 멈추고 트레이를 한 번만 없앤다 · 이미 없어진 트레이는 건드리지 않는다', (t) => {
t.mock.timers.enable({ apis: ['setInterval'] });
const fake = () => {
const tr = { destroyed: false, destroys: 0, updates: 0, isDestroyed: () => tr.destroyed, destroy: () => ((tr.destroyed = true), tr.destroys++) };
return tr;
};
// 갱신 함수는 main.ts 의 updateTray 처럼 shell.get() 으로 트레이를 얻는다 (없어진 트레이에 쓰면 Electron 이 던지는 것을 흉내)
const shell = new TrayShell<ReturnType<typeof fake>>();
let ticks = 0;
const update = () => {
ticks++;
const tr = shell.get();
if (!tr) return;
if (tr.destroyed) throw new Error('Tray is destroyed');
tr.updates++;
};
const a = fake();
shell.set(a);
shell.every(1500, update);
t.mock.timers.tick(3000);
assert.equal(a.updates, 2);
shell.dispose();
assert.equal(a.destroys, 1);
assert.equal(shell.get(), null);
t.mock.timers.tick(3000);
assert.equal(a.updates, 2, '종료 뒤에는 갱신하지 않는다');
assert.equal(ticks, 2, '종료하면 갱신 타이머가 멈춘다');
shell.dispose();
assert.equal(a.destroys, 1, '두 번 없애지 않는다');
// Windows 로그오프 등으로 Electron 이 트레이를 먼저 없앤 경우
const b = fake();
const shell2 = new TrayShell<ReturnType<typeof fake>>();
shell2.set(b);
shell2.every(1500, () => {
const tr = shell2.get();
if (tr?.destroyed) throw new Error('Tray is destroyed');
});
b.destroyed = true;
assert.equal(shell2.get(), null);
assert.doesNotThrow(() => t.mock.timers.tick(1500));
shell2.dispose();
assert.equal(b.destroys, 0, '이미 없어진 트레이는 다시 없애지 않는다');
});

View File

@@ -0,0 +1,82 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { Store } from '../src/core/db/db.ts';
import { buildApi } from '../src/core/api/server.ts';
import { Timeline } from '../src/core/timeline.ts';
import { Bus } from '../src/core/util/events.ts';
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-uset-'));
const as = (id: string, role: 'admin' | 'member' = 'member') => ({ 'x-gvr-user': encodeURIComponent(JSON.stringify({ id, name: id, avatar: null })), 'x-gvr-role': role });
async function setup() {
const dir = tmp();
const store = new Store(path.join(dir, 'db.sqlite'));
const bus = new Bus();
bus.usersProvider = () => store.listUsers().map((u) => ({ id: u.id, name: u.name, color: u.color, avatar: u.avatar, excluded: !!u.excluded, riot: [] }));
const live: any[] = [];
bus.on('live', (e) => live.push(e));
store.upsertUser({ id: 'u1', name: '하늘', avatar: null });
store.upsertUser({ id: 'u2', name: '민수', avatar: null });
store.setAccounts('u2', [{ puuid: 'p2', riotId: '민수#KR1' }]);
let renamed = 0;
const app = await buildApi({
store,
timeline: new Timeline(store),
games: {} as any,
dict: {} as any,
culprit: {} as any,
bus,
settings: () => ({}) as any,
trainingDir: () => path.join(dir, 'training'),
overviewExtra: () => ({ guild: null, recording: {} as any }),
version: 'test',
onNamesChanged: () => renamed++,
});
return { store, app, live, renamed: () => renamed };
}
test('유저 설정: 본인은 색 · 녹음 제외 · 라이엇 ID 를 바꾸고, 바뀌면 사이트에 실시간으로 알린다', async () => {
const s = await setup();
const r = await s.app.inject({ method: 'PATCH', url: '/api/users/u1', headers: as('u1'), payload: { color: '#45D39A', excluded: true, riotIds: ['하늘#KR1', ' 하늘#KR1 ', '별빛#0001'] } });
assert.equal(r.statusCode, 200);
const u = r.json().user;
assert.equal(u.color, '#45d39a');
assert.equal(u.excluded, true);
assert.deepEqual(u.riot.map((x: any) => x.riotId), ['하늘#KR1', '별빛#0001'], '같은 ID 는 한 번만');
assert.equal(s.live.at(-1).type, 'users.updated');
assert.ok(s.live.at(-1).data.length >= 2, '실제 유저 목록을 보낸다');
// 이미 연결된 puuid 는 그대로 둔다
s.store.setAccounts('u1', [{ puuid: 'p1', riotId: '하늘#KR1' }]);
await s.app.inject({ method: 'PATCH', url: '/api/users/u1', headers: as('u1'), payload: { riotIds: ['하늘#KR1'] } });
assert.deepEqual(s.store.listAccounts().filter((a) => a.user_id === 'u1'), [{ user_id: 'u1', puuid: 'p1', riot_id: '하늘#KR1' }]);
});
test('유저 설정: 다른 사람 것은 관리자만, 남의 라이엇 ID 는 본인이 가져갈 수 없다, 형식 검사', async () => {
const s = await setup();
assert.equal((await s.app.inject({ method: 'PATCH', url: '/api/users/u2', headers: as('u1'), payload: { excluded: true } })).statusCode, 403);
assert.equal(s.store.getUser('u2')!.excluded, 0);
const taken = await s.app.inject({ method: 'PATCH', url: '/api/users/u1', headers: as('u1'), payload: { riotIds: ['민수#KR1', '하늘#KR1'] } });
assert.deepEqual(taken.json().taken, ['민수#KR1']);
assert.deepEqual(taken.json().user.riot.map((x: any) => x.riotId), ['하늘#KR1']);
// 관리자는 다른 사람 설정도 바꾼다
const adm = await s.app.inject({ method: 'PATCH', url: '/api/users/u2', headers: as('u1', 'admin'), payload: { excluded: true, color: '#ff4655' } });
assert.equal(adm.statusCode, 200);
assert.equal(s.store.getUser('u2')!.excluded, 1);
assert.equal((await s.app.inject({ method: 'PATCH', url: '/api/users/u1', headers: as('u1'), payload: { color: 'red' } })).statusCode, 400);
assert.equal((await s.app.inject({ method: 'PATCH', url: '/api/users/u1', headers: as('u1'), payload: { riotIds: ['a#1', 'b#2', 'c#3', 'd#4', 'e#5', 'f#6'] } })).statusCode, 400);
assert.equal((await s.app.inject({ method: 'PATCH', url: '/api/users/nobody', headers: as('nobody'), payload: { excluded: true } })).statusCode, 404);
});
test('표시 이름: 사이트 서버(내부 요청)만 보낼 수 있고, 받으면 이름 · 녹음 파일 이름을 맞추고 알린다', async () => {
const s = await setup();
const bad = await s.app.inject({ method: 'PUT', url: '/api/internal/names', headers: as('u1', 'admin'), payload: { names: { u1: '해커' } } });
assert.equal(bad.statusCode, 403);
const ok = await s.app.inject({ method: 'PUT', url: '/api/internal/names', headers: { ...as('server'), 'x-gvr-internal': '1' }, payload: { names: { u1: '하늘별' } } });
assert.equal(ok.statusCode, 200);
assert.equal(s.store.getUser('u1')!.name, '하늘별');
assert.equal(s.renamed(), 1);
assert.equal(s.live.at(-1).type, 'users.updated');
});

View File

@@ -23,10 +23,63 @@
- 천장 자르기: 자동(고른 선수 · 없으면 가장 높은 산 선수 몸 중심 + 380cm 위를 자름) · 없음 · 직접(슬라이더).
- 자동 갱신: `scripts/install.sh` 가 `~/gvr-maps` 에 설치, `gvr-maps-update.timer` 30분마다 `update.sh`: uedb 매핑(버전 · 갱신 시각) 또는 라이브 매니페스트가 바뀌면 매핑을 받아 `~/gvr-maps/mappings/` + nextcloud `claude/game-voice-recorder/valorant/mappings/` 에 보관 → 전체 추출 → .5 `data/maps3d` 에 올리고 index.json 교체 (이전 폴더 1개만 남김). 어느 단계든 실패하면 이전 맵 유지, 같은 조합은 30분 · 1 · 2 · 4 · 6시간 간격으로 재시도 (첫 실패 · 성공 때 이 방 채널에 한 줄 알림, uedb/패치 확인 자체는 6번 연속 실패 때 알림). 지금 사이트에 있는 맵이 하나라도 새 결과에 없으면 올리지 않는다 (추출기도 맵 찾기 중 레벨 읽기 실패를 실패로 친다). 강제(대기 · 누락 검사 무시): `~/gvr-maps/scripts/update.sh --force`. 시험: `scripts/test-update.sh`.
## 앱 (v1.5.0)
- `app/src/core/replays.ts`: `%LOCALAPPDATA%\VALORANT\Saved` 아래(깊이 3, Logs · Crashes · Config 제외) `<경기 ID>.vrf` → 사이트가 열 때 `gvr-replay.exe <vrf> <tmp.json>` (낮은 우선순위, 한 번에 하나, 3분 제한) → gzip → `GVR-Data/replays/<경기 ID>.json.gz` + `.src`(크기:수정시각:앱 버전). 실패는 메모리에 기억 (파일이 바뀌거나 앱을 다시 켜면 다시)
- `GET /api/matches/:id/replay`: 15초 안에 끝나면 200 (content-encoding gzip), 아니면 202 `{status:'converting'}` → 사이트가 3초마다 다시. 중계는 content-encoding 이 있으면 바이너리 조각 (`relay/client.ts`)
- 빌드: win-ci `replay_build` 단계 (.NET 10 SDK `C:\win-ci\dotnet`, `dotnet publish -r win-x64` 단일 파일 38MB) → electron-builder extraResources `replay/`. 호스트 `~/win-ci/serve/gvr-test.vrf`(13.08 어비스 경기) 가 있으면 변환기 · 포터블 앱 smoke(`GVR_SMOKE_VRF`) 둘 다 실제 변환
- 리눅스 실측(13.08, 73.8MB vrf): 5.5초, 최대 메모리 347MB, gzip 1.4MB
## 완전 3D (2026-10-17, v1.7.0)
- 맵 색: `MapScene` 이 재질마다 primitive 하나 (법선 · UV, 디퓨즈 텍스처 256px JPEG/PNG(알파), `DiffuseColor` 색). 두 층 재질(`BaseEnv_Blend_*`, Diffuse A/B)은 정점 색 R 로 섞는다 (`extras.blend`, 사이트 `map3d.ts` 셰이더). UE 왼손 → glTF 앞면에 맞춰 삼각형을 뒤집는다. 어비스 압축 12MB.
- 요원: `gvr-map-extract agents <폴더>` → `agent_<코드>.glb` (요원 블루프린트 `Characters/<코드>/<코드>_PC` 의 3인칭 메시 LOD1, 512px 텍스처, 뼈대 + 공용 애니메이션 `ub_rifle`(Core_Rifle_Idle 위 몸) · `lb_idle/run*/walk*`(아래 몸, Skeleton·Root 는 회전만)). 애니메이션은 ACL 압축이라 CUE4Parse-Natives(ACL 만)를 g++ 로 빌드해 실행 파일 옆에 둔다 (`install.sh`). 30명 46초, 압축 6.4MB.
- 무기: `weapon_<이름>.glb` (기본 스킨 몸 + 탄창, 원점 = 손잡이, 총구 +X). 사이트는 손목(R_Hand) 에 붙이고 보는 방향(pitch)으로 돌린다 (공용 애니메이션은 R_WeaponPoint 를 움직이지 않아 손과 떨어져 있다). 22종 1.5MB.
- 변환기: `equips` [t, 선수, 종류] / `equipKinds` (총 영어 이름 · Melee · Spike · 스킬 클래스). 사이트 이름표 "🔫 밴달", 킬 피드에 무기. 옛 리플레이 JSON 에는 없다 (앱 v1.7.0 부터).
- 재생기: 카메라 위에서 / 1인칭(고른 선수 눈 + 60cm, pitch) / 자유시점(WASD · Q/E · Shift, 끌어서 둘러보기). 요원은 이동 방향 · 속도로 아래 몸 애니메이션을 섞는다. 스킬은 `lib/abilities.ts` 가 클래스 이름으로 연막(요원 색 구) · 장판 · 폭발 · 정찰 고리 · 설치물 · 스파이크로 나눈다.
- 한계: 스킬 효과(파티클) · 벽 스킬 방향 · 앉기 · 점프 자세 · 스킨은 없다. 리플레이 위치는 10Hz 라 빠른 움직임은 보간이다.
## 스킬 효과 (2026-10-18, 실감 2단계)
- 추출: `gvr-map-extract abilities <폴더>` (`src/Abilities.cs`) → `abilities.json` + `m_*.glb`(스킬 · 투사체 · 설치물 메시, 파티클 메시) + `t_*.png`(256px, 큰 것 512px). 13.08 전체: 스킬 클래스 217 · 파티클 시스템 520 · 메시 373 · 텍스처 1054, 받은 양 341MB · 3.9분 · 최대 메모리 1.7GB, gzip 합계 약 40MB (json 0.8MB).
- 발로란트 효과는 전부 Cascade `ParticleSystem` 이다 (Niagara 0개). 이미터마다 모양(sprite · mesh · decal · ribbon) · 재질 · 분포 표(구운 FRawDistribution) 를 그대로 옮긴다. 형식 설명은 `Abilities.cs` 머리말.
- 클래스(리플레이 objectKinds) → 블루프린트 → FXC 효과 묶음 · 패치 · 투사체 컴포넌트에서 역할(loop · intro · outro · warn · trail · explode · patch · decal) 별 시스템(아군 · 적 따로).
- `update.sh` 가 맵 · 요원 · 애니메이션 다음에 돌리고 `pack.py` 가 `abilities/` 를 gzip 해 index.json `abilities` 로 올린다.
- 사이트 `lib/vfx.ts`: 입자 상태를 "켜진 뒤 지난 시간" 만으로 계산 (입자마다 고정 난수) → 되감기 · 배속에도 같은 장면. 이미터 종류별로 인스턴스 사각형 · 인스턴스 메시 · 바닥에 눕힌 사각형 · 지나간 길(리본).
- 재질 그래프는 쿡된 파일에 없다(매개변수 · 텍스처만). 이름 점수로 색 · 알파 텍스처를 고르고, 텍스처 채널 상관으로 색 그림 · 흑백/묶음 마스크(R)를 가린다. UE 반투명처럼 (HDR 색 × 불투명도) 를 미리 곱한 알파로 더하고 채널마다 0.8 위를 눌러 불꽃이 주황 · 노랑이 된다.
- 연막 돔(불투명 · 마스크 큰 구)은 요원별 색(`DOME`) + noise + 가장자리 빛(게임 팀 색). 돔 위 반투명 층은 돔 색으로 옅게.
- 장판(CellularPatch): 게임처럼 반지름 안 칸마다 불 효과 하나, 가운데서 SpreadSpeed 로 번진다. 그을음은 반지름 크기.
- 뺀 것: 벽 너머 표시 · HUD · 1인칭 · 사거리 표시 · 팀 구별 층(FoF) · beam · 화면 아이콘 메시. 데이터가 예상과 다른 이미터는 그 이미터만 끈다.
- 효과가 없는 클래스는 예전 종류별 모양, 날아가는 모습이 없는 투사체(요루 섬광 등)는 예전 빛 구 + 터지는 효과. 요루 분신 · 스파이크는 원래 그리던 것 + 효과.
- 개발 확인: 효과 하나만 따로 그리는 판(`~/.tmp/gvr/vfxHarness.ts` 를 `site/web/src/dev/` 에 잠시 두고 vite dev 에서 `import('/src/dev/vfxHarness.ts')`). 저장소에는 넣지 않았다.
- 한계: 재질 그래프 근사라 색 · 무늬가 게임과 조금 다르다. 리본 · beam 일부, 화면 효과(섬광 눈부심 등)는 없다. 오멘 연막처럼 추출기가 클래스를 못 찾은 것은 예전 모양.
## 구운 조명 (2026-10-29, 실감 3단계)
- 계기: aim.sheepu.dev(브라우저 발로란트 에임 연습장)의 맵이 게임처럼 보이는 이유를 보니 게임이 구워 둔 라이트맵(밝기 + SH 방향)을 그대로 쓴다. 우리 맵은 텍스처 × 장면 조명(하늘빛 + 해)이라 평평했다. 그 사이트 파일은 쓰지 않고 우리 추출기로 게임 파일에서 직접 뽑는다.
- 게임 쪽: 레벨마다 `<레벨>_BuiltData` (UMapBuildDataRegistry). 컴포넌트 `LODData[0].MapBuildDataId` → FMeshMapBuildData → FLightMap2D (텍스처 · ScaleVectors/AddVectors · CoordinateScale/Bias), ISM 은 인스턴스마다 `PerInstanceLightmapData[i].LightmapUVBias` (HISM 은 `InstanceReorderTable`). 라이트맵 UV 채널은 메시 `LightMapCoordinateIndex`, LOD0 에만 있다 (구운 조명이 있는 배치는 LOD0, 삼각형은 거의 같다: 어센트 233만 → 235만).
- HQ_Lightmap 텍스처(DXT5 1024²)는 위 절반 = 계수 0(UVW² · 로그 밝기), 아래 절반 = 계수 1(SH 방향 xyz · 밝기 나머지). 푸는 식은 UE `LightmapCommon.ush` GetLightMapColorHQ 와 같다. 햇빛 그림자까지 다 구워져 있다 (정적 조명).
- 추출기 `src/Lightmaps.cs`: 메시가 차지한 칸마다 그 메시 범위로 풀어 irr(L·UVW·L0, sRGB/K) · sh(방향/L0, ±2) 두 장으로 → 칸 밖은 이웃 값으로 채움 → 1/2 씩 줄여 선반 쌓기 아틀라스(너비 `GVR_LIGHTMAP` 기본 2048, 넓이 약 그 제곱 안). 조명 없는 배치는 (0,0) 기본 칸(맵 평균 밝기).
- glb: 모든 재질에 `occlusionTexture`(irr) · `emissiveTexture`(sh, 세기 0) 를 TEXCOORD_1 로, `extras.lightmap.k`. gltfpack 이 쓰지 않는 UV 채널을 버리지 않게 텍스처가 그 채널을 가리켜야 한다. 옛 사이트는 aoMap 으로만 써서(어두워지기만) 깨지지 않는다.
- pack.py 는 맵을 `-vtf`(UV 실수) 로: gltfpack 은 재질마다 TEXCOORD_0(반복, 수십 단위) · TEXCOORD_1 을 한 범위로 양자화해서 정수로 줄이면 라이트맵이 몇 텍셀씩 어긋난다.
- 13.09 실측: 어센트 페이지 72 → 1864×1360(1/4) 2.5MB, 어비스 116 → 1864×2176(1/4) 3.4MB. 맵 압축 크기 어센트 14.7 → 18.8MB, 어비스 12.1 → 17.4MB.
- 메모리: 배치를 모으는 동안은 칸 목록만 두고 Build 에서 페이지를 하나씩 풀어 바로 줄인다. 처음(모든 페이지를 원래 크기로 들고 있던 것)에는 페이지 200개 넘는 펄(Pitt)이 서비스 한도 6GB 에서 OutOfMemory 였다. 고친 뒤 펄 최대 2.7GB.
- 사이트 `lib/map3d.ts` `installShader`: 색 = 텍스처 × irr × K × max(0, 1 + dot(sh, N.yzx)) (N 은 glb 법선 = UE 월드 법선 그대로), 0.8 위는 살짝 눌러 하얗게 날지 않게. 장면 조명은 맵에 쓰지 않는다 (요원 · 효과는 그대로 장면 조명).
- 조사 명령: `gvr-map-extract lmprobe <레벨.umap>` (빌드 데이터 · 텍스처 · 연결 통계, `GVR_LM_DUMP=<폴더>` 면 라이트맵 png).
- 13.09 전체 (2026-10-29 반영): 맵 23개 중 22개에 조명 (아이스박스 Port 는 BuiltData 에 라이트맵이 없어 예전 장면 조명), 아틀라스 1.2~4.7MB, 사이트 폴더 303 → 403MB. 맵 추출 26분 · 서비스 최대 메모리 5.9GB(스킬 재료 단계 포함).
- 한계: 1/4 로 줄여 그림자 가장자리가 흐리다. 움직이는 것(요원)은 구운 조명을 받지 않는다 (볼륨 라이트맵은 아직 안 씀). 어비스 낭떠러지처럼 게임에서 어두운 곳은 그대로 어둡다.
## 1인칭 팔 · 총 · 조준점 (2026-10-29, 실감 4단계)
- 계기: aim.sheepu.dev 훈련 화면(밴달 + 피닉스 팔 1인칭, 흰 십자 조준점, 탄흔 · 총소리)을 보고 우리 1인칭에 없던 것을 게임 파일에서 직접 뽑았다 (그 사이트 파일은 쓰지 않음).
- 추출 `gvr-map-extract viewmodels <폴더>` (`src/Viewmodels.cs`, 13.09 전체 39초 · 최대 1.1GB):
- `fparms_<코드>.glb` 요원 1인칭 팔 `Characters/<코드>/S0/1P/Models/FP_<코드>[_New]_S0_Skelmesh` (30명, 브리치는 `_New`). 팔 메시에 같이 든 스킬 · 3인칭 조각(재질 AB_ · ABTP_ · CS_ · TP_)은 뺀다 (네온 칼날 모양, 소바 활 장갑 등).
- `fpweapon_<이름>.glb` 무기 1인칭 `<무기 폴더>/S0/1P/Models/(GN|EQ)_*_S0_Skelmesh` + 탄창(Magazine_Main 뼈 자식) + `GN_Core_*_S0_{Fire,Reload,Equip}` → gun_fire · gun_reload · gun_equip (22종, 칼 · 스파이크 포함).
- `fpanim_<이름>.glb` 팔 동작(뼈 노드만, 공용 뼈대 `FP_Core_Retarget_Skelmesh`): `FP_Core_*_S0_` IdlePose|Idle · Fire|FireAdd · Reload · Equip · AltIdlePose(정조준) · WalkAdd · Activate(스파이크). 덧셈 동작은 CUE4Parse 가 기준 자세에 더해 준다.
- 압축 합계 7.4MB, index.json `viewmodels`. update.sh 가 anims 다음에 돌린다.
- 사이트 `lib/viewmodel.ts`: 맵과 따로 장면 하나(카메라 공간, 깊이를 지우고 맵 위에 그림). 무기 뿌리 = 팔 뼈 MasterWeapon × 회전 (0.5,−0.5,0.5,0.5) (총구 → 팔 앞, 탄창 → 아래가 되는 축 맞춤, 모든 총 같음). 눈 = 팔 Camera 뼈(대기 자세).
- 자세는 시각만으로: 꺼내기(equips) > 재장전(states ReloadState) > 사격(shots, 60ms 총구 불꽃) > 걷기(0.2초에 30cm 넘게 움직임) > 정조준(ZoomState*) > 대기. 죽었거나 스킬 · 맨손이면 숨긴다.
- 줌: 소총 등 1.25배, 저격총 2.5배(2단 5배) + 조준경 테두리(검은 원 · 가는 십자선), 저격 줌 중에는 팔 · 총을 숨긴다.
- 조준점: 녹색 점 → 발로란트 기본 (흰 선 4개 · 가운데 틈 · 검은 외곽선). 1.8.2 부터 선수 조준점 · 내 조준점 (아래).
- 안 한 것: 총소리 · 발소리(Wwise 사운드뱅크라 따로 풀어야 함), HUD 체력 · 탄약(리플레이에 값 없음), 탄흔(맞은 자리 `hits` 로 가능), 스킨(기본 스킨만), 스킬 1인칭 동작, 재장전 중 탄창이 손으로 옮겨 가는 것(소켓 바꾸기라 탄창이 잠깐 안 보임).
## 남은 일
1. 앱: `%LOCALAPPDATA%\VALORANT\Saved` 아래 `<matchId>.vrf` 찾기 → `gvr-replay.exe` 실행 → `GVR-Data/replays/<matchId>.json.gz` → `GET /api/matches/:id/replay` (content-encoding gzip, 사이트는 /api/* 그대로 중계)
2. 빌드: win-ci 에 .NET SDK 설치 · `dotnet publish -r win-x64` 단일 파일 → electron-builder extraResources `replay/`
3. 실제 경기로 동기화 오차 확인 (사이트 아래 줄 "킬 N개로 맞춤 (최대 오차 X초)")
- 실제 경기로 동기화 오차 확인 (사이트 아래 줄 "킬 N개로 맞춤 (최대 오차 X초)")
## 완전 3D (맵 · 캐릭터 · 총 · 효과) 조사 (2026-10-17)
- 게임 파일: Riot CDN 에서 바로 받을 수 있다 (게임 PC 불필요). 매니페스트는
@@ -43,3 +96,13 @@
- 보관: nextcloud `claude/game-voice-recorder/valorant/13.08/` (nextcloud 에서는 `claude/` 폴더 안만 다룬다, 사용자 규칙) (abyss-13.08.tar.gz = glb · scene.json · 미리보기 · usmap · 도구 사본, usmap 단독). 계정은 secrets `nextcloud.192.168.10.10`.
- 실험은 반드시 `systemd-run --user --scope -p MemoryMax=6G -p MemorySwapMax=0` 안에서.
- 디스크: .9 는 150GB 이상 비워 둔다 (사용자 요청). 게임 파일은 다시 받을 수 있으므로 지웠다. 큰 결과물은 nextcloud(.10:8080)로 (로그인 정보 필요).
## 선수 조준점 · 내 조준점 (2026-10-29, v1.8.2)
- 리플레이에 있다: `BombPlayerState` 에 선수마다 조준점 프로필이 복제된다 (관전자에게 보이는 조준점). 파서 형식에는 없어서 `gvr-replay <vrf> --fields` 로 필드 이름을 보고 찾았다.
- 13.08 번호: 39~85 주 조준점, 86~132 정조준, 133~179 (값이 온 적 없음), 180~197 저격 조준경(가운데 점 색 · 크기 · 불투명도 · 표시) · `bUsePrimaryCrosshairForADS` · `bUseAdvancedOptions` · `ProfileName`.
- 묶음 안 순서: 색 BGRA · 사용자 지정 색 BGRA · bUseCustomColor · 외곽선(켬 · 두께 · 색 · 불투명도) · 가운데 점(크기 · 불투명도 · 켬) · … · 안쪽 선 12개 · 바깥쪽 선 12개 (두께 · 길이 · 세로 길이 · 간격 · 세로 따로 · 이동 오차 · 사격 오차 · 최소 오차 · 불투명도 · 켬 · 사격 배율 · 이동 배율).
- 기본값과 다를 때만 오고(색 흰색 255 · 숫자 0 · 끔), 바뀐 것만 다시 온다. 확인: 프로필 이름 "1 4 2 0" 선수 = 불투명도 1 · 길이 4 · 두께 2 · 간격 0, "점" 선수들 = 가운데 점만. 저격 점은 10명 모두 빨강(게임 기본).
- 변환기 `src/Crosshair.cs`: 첫 읽기의 필드 목록에서 기준 번호를 찾고(이름이 모두 맞는 자리, 패치로 밀리면 ±80 안에서 찾음, 못 찾으면 조준점 없이 변환) 이 필드만 읽는 두 번째 읽기 (`IncludedPaths`, 어비스 리플레이 +0.4초). 출력 `players[].crosshair` = 바뀐 시각마다 전체 설정 (`t · name · primary · ads · sniper · adsFromPrimary · advanced`, color 는 실제 보이는 색).
- 사이트 `lib/crosshair.ts` (그리기 · 발로란트 조준점 코드 읽기) · `components/CrosshairPanel.tsx`: 1인칭 "조준점" 버튼 → 선수 조준점(없으면 내 조준점) / 모든 선수에 내 조준점, 내 조준점 직접 고치기 · 코드 가져오기 · 선수 조준점 복사. 설정은 브라우저 `gvr.settings.v1` `crosshair`.
- 정조준(저격총 아님) 중에 고급 설정 + 정조준 조준점 따로면 ads, 저격 줌은 조준경 가운데 점. 사격 오차 · 이동 오차 켠 선은 쏜 뒤 0.35초 · 걷는 동안 벌어진다 (총마다 다른 실제 퍼짐이 아니라 대략).
- 옛 리플레이 JSON 에는 없다. 앱은 버전이 바뀌면 다시 변환하므로 1.8.2 로 올리면 다음에 열 때 생긴다.

View File

@@ -272,3 +272,54 @@ VOICE E2E PASS
- 테스트: 워커 `test_hotword_echo.py` 이름 되풀이 3개, 앱 `name-echo.test.ts` 3개(판정 · 핫워드에 영문 닉네임 빠짐 · 예전 발화 다시 보기 한 번만)
- 실제 모델(faster-whisper small, CPU): 실제 말소리 · 키보드 · 잡음 파일에 영문 닉네임 핫워드를 넣어도 정상, 결과 전체를 선수 이름으로 준 경우 되풀이로 잡고 이름 없이 다시 변환해 실제 말을 돌려줌
- 배포: Windows CI (010d247, full) 7개 모두 PASS · 앱 버전 1.4.3 → Gitea 릴리스 v1.4.3 (v1.4.2 에 새 버전 안내). 사이트 서버는 바뀐 것 없음
## v1.5.0 — 3D 리플레이: 앱이 리플레이를 찾아 변환 (2026-10-17)
- 앱 `replays.ts`: `%LOCALAPPDATA%\VALORANT\Saved` 아래 `<경기 ID>.vrf` → 사이트가 열 때 `gvr-replay.exe` 로 변환 → `GVR-Data/replays/<경기 ID>.json.gz`. API `GET /api/matches/:id/replay` (gzip, 변환 중 202, 실패 422) · `GET /api/replays`
- 테스트: 앱 73(새 `replays.test.ts` 7개: 찾기 · 변환 후 보관본 · 실패 기억과 다시 내려받으면 다시 · 202 → 200 · 변환기 없음 · 중계 gzip 바이너리 · 실제 리눅스 변환기로 13.08 리플레이) · 사이트 서버 27 통과, 타입 검사 · 화면 빌드 통과
- Windows CI (adc1c66, full) 8개 모두 PASS: 새 `replay_build` (.NET 10.0.402, gvr-replay.exe 36.3MB, 13.08 어비스 리플레이 6.8초 변환), `app_smoke` 에서 포터블 앱 안 변환기로 같은 리플레이 9.1초 변환(gzip 1.39MB)
- 배포: 사이트 서버 다시 배포 (화면 번들에 '변환하는 중' 확인), 앱 버전 1.5.0 → Gitea 릴리스 v1.5.0 (v1.4.3 에 새 버전 안내)
## v1.6.0 — 사이트 내 정보 · 관리 페이지 (2026-10-17)
- 사이트: 머리글 내 이름 → 내 정보 (표시 이름 · 색 · 라이엇 ID · 녹음 제외 · 로그아웃), `/admin` 관리 페이지 (게임 PC · 새 버전 안내 · 유저별 설정 · 앱 등록/역할/해제)
- 테스트: 앱 76 (새 `user-settings.test.ts` 3개) · 사이트 서버 30 (새 `profile-admin.test.ts` 3개) 통과, 타입 검사 · 화면 빌드 통과
- 화면: 목 서버 + 헤드리스 크롬(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.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`)
- 회귀 검사: `gvr-replay --self-test` (넘기기 전 · 넘긴 순간 · 뒤 · 첫 기록 전 · 기록 없음 · 순서 섞임 · 모르는 선수). 옛 동작(마지막 주인)으로 바꾸면 3개 실패하는 것 확인. Windows CI `replay_build` 에서 실행
- 어비스 13.08 리플레이: 상태 16,974줄 중 1,189줄의 주인이 바뀜. 그중 그 시각 그 선수가 같은 무기를 들고 있던 비율 24% → 75%
- Windows CI (a6cf73d, full) 8개 모두 PASS (self-test 통과 포함) → Gitea 릴리스 v1.8.1 (v1.8.0 · v1.7.0 에 새 버전 안내)
## v1.8.0 — 3D 리플레이 실감: 게임 스킬 효과 · 요원 동작 · 투사체 경로 (2026-10-18)
- 스킬 효과 추출기(`abilities`): 13.08 스킬 클래스 219 · 파티클 시스템 526 · 메시 377 · 텍스처 1064, 3.8분, 최대 메모리 1.7GB, 압축 41.8MB. 맵 · 요원 · 애니메이션과 함께 강제 갱신 13.9분 (서비스 최대 메모리 5.6GB, 상한 6GB) → .5 `data/maps3d/VALORANT_13.08-202610171648` (index.json `anims` · `abilities`)
- 테스트: 앱 76 · 사이트 서버 30 통과, 타입 검사 · 화면 빌드 통과
- 화면: 효과 하나씩 그리는 판 + 목 서버(사이트와 같은 CSP 미리보기, 오류 0)로 브림스톤 · 오멘 · 아스트라 · 클로브 · 제트 연막, 브림스톤 · 피닉스 장판, 피닉스 · 케이오 · 브리치 · 스카이 섬광, 소바 화살 · 브림스톤 몰리 꼬리, 체임버 덫 · 소바 드론 · 킬조이 포탑/알람봇 · 사이퍼 덫 확인. 바이퍼 연막 · 세이지 벽처럼 효과를 못 뽑은 것은 예전 기본 모양
- 배포: 사이트 서버 다시 배포 (화면 번들에 vfx 코드 확인), Windows CI (735783c, full) 8개 모두 PASS (변환기 어비스 리플레이 7.0초, 앱 smoke 실제 변환 8.3초 · gzip 1.60MB) · 앱 버전 1.8.0 → Gitea 릴리스 v1.8.0 (v1.7.0 에 새 버전 안내)
## v1.7.0 — 3D 리플레이 완전 3D: 맵 색 · 요원 · 총 · 스킬 모양 · 1인칭/자유시점 (2026-10-17)
- 맵 추출기: 재질 · 텍스처(256px) · 두 층 섞기 · 법선. 22개 맵 9.7분, 받은 양 961MB, 압축 합계 약 255MB (맵당 4~19MB). 요원 30명 · 총 22종 0.9분 (압축 6.4MB · 1.5MB). 갱신 서비스 최대 메모리 5.7GB (상한 6GB)
- 변환기: `equips` · `equipKinds` (13.08 어비스 리플레이: 6,539줄, 총 이름 전부 풀림, 5.9초)
- 테스트: 앱 76 · 사이트 서버 30 통과, 타입 검사 · 화면 빌드 통과
- 화면: 목 서버 + 헤드리스 크롬으로 어비스(텍스처) · 어센트 · 로터스 맵, 요원 몸 · 손에 든 총(밴달 · 클래식 · 오퍼레이터 · 칼), 1인칭 · 자유시점, 연막 색 · 장판 확인
- 배포: 사이트 서버 다시 배포 (화면 번들에 '자유시점' 확인), 맵 3D 강제 갱신으로 .5 `data/maps3d` 에 맵 22 · 요원 30 · 무기 22 반영, Windows CI (4cd6f11, full) 8개 모두 PASS (앱 smoke 실제 리플레이 변환 8.5초, gzip 1.42MB) · 앱 버전 1.7.0 → Gitea 릴리스 v1.7.0 (v1.6.0 에 새 버전 안내)

View File

@@ -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))}분 뒤`;
}

View File

@@ -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,28 @@ export interface LiveGame {
players: number | null;
/** 마지막 오류 (연결 실패 등) */
error: string | null;
/** Riot 경기 기록 가져오는 중이면 진행 상황 (v1.9.1~, 예전 앱은 없음) */
history?: HistoryProgress | 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> */

View File

@@ -28,7 +28,17 @@ const sha = (s: string) => crypto.createHash('sha256').update(s).digest();
export function registerAppAuth(
app: FastifyInstance,
deps: { cfg: Config; store: ServerStore; discord: DiscordApi; secure: boolean; onRevoke?: (by: { userId?: string; token?: string }) => void },
deps: {
cfg: Config;
store: ServerStore;
discord: DiscordApi;
secure: boolean;
onRevoke?: (by: { userId?: string; token?: string }) => void;
/** 사이트 로그인 세션 (사이트 관리 화면 /site/admin/*). app.ts 가 나중에 넣는다 */
siteSession?: (req: FastifyRequest, reply: FastifyReply) => Promise<{ user: { id: string } } | null>;
/** 표시 이름이 바뀌었을 때 (게임 PC 앱에 바로 보낸다) */
onNamesChanged?: (id: string, name: string | null) => void;
},
) {
const { cfg, store, discord, secure } = deps;
const revoke = (by: { userId?: string; token?: string }) => deps.onRevoke?.(by);
@@ -186,64 +196,109 @@ export function registerAppAuth(
if (!(await auth(req, reply))) return;
return { names: store.displayNames() };
});
app.put<{ Body: { id?: string; name?: string | null } }>('/app/admin/names', async (req, reply) => {
const a = await need(req, reply, 'superadmin');
if (!a) return;
const id = String(req.body?.id ?? '').trim();
const name = String(req.body?.name ?? '').trim().slice(0, 32);
if (!SNOWFLAKE.test(id)) return reply.code(400).send({ error: 'bad_id', message: '디스코드 아이디는 17~20자리 숫자입니다' });
store.setDisplayName(id, name || null);
req.log.info({ by: a.id, user: id, set: !!name }, '표시 이름 변경');
return { names: store.displayNames() };
});
app.get('/app/admin/users', async (req, reply) => {
if (!(await need(req, reply, 'admin'))) return;
return { users: rows() };
});
app.post<{ Body: { id?: string; role?: string } }>('/app/admin/users', async (req, reply) => {
const a = await need(req, reply, 'superadmin');
if (!a) return;
const id = String(req.body?.id ?? '').trim();
const r = role(req.body?.role ?? 'user');
if (!SNOWFLAKE.test(id)) return reply.code(400).send({ error: 'bad_id', message: '디스코드 아이디는 17~20자리 숫자입니다' });
if (!r) return reply.code(400).send({ error: 'bad_role', message: '역할은 관리자 또는 유저입니다' });
if (cfg.superAdmins.includes(id)) return reply.code(400).send({ error: 'fixed', message: '최고 관리자는 이미 등록되어 있습니다' });
let du: DiscordUser | null;
try {
du = await fetchDiscordUser(cfg, id);
} catch (e) {
req.log.warn(e, '디스코드 계정 조회 실패');
return reply.code(502).send({ error: 'discord_error', message: '디스코드에서 계정을 확인하지 못했습니다. 잠시 뒤 다시 시도해 주세요' });
// 관리 API 는 두 곳에서 부른다: 앱 관리자 탭(/app/admin/*, 앱 토큰) · 사이트 관리 화면(/site/admin/*, 사이트 로그인 v1.6.0~)
const siteNeed = async (req: FastifyRequest, reply: FastifyReply, level: 'admin' | 'superadmin') => {
const s = deps.siteSession ? await deps.siteSession(req, reply) : null;
if (!s) {
if (!reply.sent) reply.code(401).send({ error: 'unauthorized' });
return null;
}
if (!du) return reply.code(404).send({ error: 'unknown_user', message: '디스코드에 없는 아이디입니다' });
if ((du as any).bot) return reply.code(400).send({ error: 'bot', message: '봇 계정은 등록할 수 없습니다' });
store.upsertAppUser({ id, name: du.global_name || du.username, avatar: avatarUrl(du), role: r, addedBy: a.id });
req.log.info({ by: a.id, user: id, role: r }, '앱 유저 등록');
return { users: rows() };
});
// 쓰기 요청은 같은 사이트에서 온 것만 (CSRF)
const origin = String(req.headers.origin || '');
if (req.method !== 'GET' && origin && origin !== cfg.publicUrl) {
reply.code(403).send({ error: 'bad_origin' });
return null;
}
const r = siteRole(s.user.id);
const ok = r && (level === 'superadmin' ? r === 'superadmin' : r !== 'user');
if (!ok) {
reply.code(403).send({ error: 'forbidden', message: level === 'superadmin' ? '유저 등록 · 역할 바꾸기는 최고 관리자만 할 수 있습니다' : '관리자만 볼 수 있습니다' });
return null;
}
return { id: s.user.id, role: r };
};
for (const [prefix, who] of [
['/app/admin', need],
['/site/admin', siteNeed],
] as const) {
// 표시 이름: 앱에서는 최고 관리자만 (v1.2~), 사이트 관리 화면에서는 관리자도 (v1.6.0)
app.put<{ Body: { id?: string; name?: string | null } }>(`${prefix}/names`, async (req, reply) => {
const a = await who(req, reply, prefix === '/app/admin' ? 'superadmin' : 'admin');
if (!a) return;
const id = String(req.body?.id ?? '').trim();
if (!SNOWFLAKE.test(id)) return reply.code(400).send({ error: 'bad_id', message: '디스코드 아이디는 17~20자리 숫자입니다' });
const v = checkName(req.body?.name, id);
if ('error' in v) return reply.code(400).send({ error: 'bad_name', message: v.error });
store.setDisplayName(id, v.name);
req.log.info({ by: a.id, user: id, set: !!v.name }, '표시 이름 변경');
deps.onNamesChanged?.(id, v.name);
return { names: store.displayNames() };
});
app.patch<{ Params: { id: string }; Body: { role?: string } }>('/app/admin/users/:id', async (req, reply) => {
const a = await need(req, reply, 'superadmin');
if (!a) return;
const r = role(req.body?.role);
if (!r) return reply.code(400).send({ error: 'bad_role', message: '역할은 관리자 또는 유저입니다' });
if (cfg.superAdmins.includes(req.params.id)) return reply.code(400).send({ error: 'fixed', message: '최고 관리자는 바꿀 수 없습니다' });
if (!store.setAppUserRole(req.params.id, r)) return reply.code(404).send({ error: 'not_found', message: '등록되지 않은 아이디입니다' });
req.log.info({ by: a.id, user: req.params.id, role: r }, '앱 유저 역할 변경');
return { users: rows() };
});
app.get(`${prefix}/users`, async (req, reply) => {
if (!(await who(req, reply, 'admin'))) return;
return { users: rows(), names: store.displayNames() };
});
app.delete<{ Params: { id: string } }>('/app/admin/users/:id', async (req, reply) => {
const a = await need(req, reply, 'superadmin');
if (!a) return;
if (cfg.superAdmins.includes(req.params.id)) return reply.code(400).send({ error: 'fixed', message: '최고 관리자는 지울 수 없습니다' });
if (!store.removeAppUser(req.params.id)) return reply.code(404).send({ error: 'not_found', message: '등록되지 않은 아이디입니다' });
revoke({ userId: req.params.id });
req.log.info({ by: a.id, user: req.params.id }, '앱 유저 등록 해제');
return { users: rows() };
});
app.post<{ Body: { id?: string; role?: string } }>(`${prefix}/users`, async (req, reply) => {
const a = await who(req, reply, 'superadmin');
if (!a) return;
const id = String(req.body?.id ?? '').trim();
const r = role(req.body?.role ?? 'user');
if (!SNOWFLAKE.test(id)) return reply.code(400).send({ error: 'bad_id', message: '디스코드 아이디는 17~20자리 숫자입니다' });
if (!r) return reply.code(400).send({ error: 'bad_role', message: '역할은 관리자 또는 유저입니다' });
if (cfg.superAdmins.includes(id)) return reply.code(400).send({ error: 'fixed', message: '최고 관리자는 이미 등록되어 있습니다' });
let du: DiscordUser | null;
try {
du = await fetchDiscordUser(cfg, id);
} catch (e) {
req.log.warn(e, '디스코드 계정 조회 실패');
return reply.code(502).send({ error: 'discord_error', message: '디스코드에서 계정을 확인하지 못했습니다. 잠시 뒤 다시 시도해 주세요' });
}
if (!du) return reply.code(404).send({ error: 'unknown_user', message: '디스코드에 없는 아이디입니다' });
if ((du as any).bot) return reply.code(400).send({ error: 'bot', message: '봇 계정은 등록할 수 없습니다' });
store.upsertAppUser({ id, name: store.nameOf(id, du.global_name || du.username), avatar: avatarUrl(du), role: r, addedBy: a.id });
req.log.info({ by: a.id, user: id, role: r }, '앱 유저 등록');
return { users: rows() };
});
app.patch<{ Params: { id: string }; Body: { role?: string } }>(`${prefix}/users/:id`, async (req, reply) => {
const a = await who(req, reply, 'superadmin');
if (!a) return;
const r = role(req.body?.role);
if (!r) return reply.code(400).send({ error: 'bad_role', message: '역할은 관리자 또는 유저입니다' });
if (cfg.superAdmins.includes(req.params.id)) return reply.code(400).send({ error: 'fixed', message: '최고 관리자는 바꿀 수 없습니다' });
if (!store.setAppUserRole(req.params.id, r)) return reply.code(404).send({ error: 'not_found', message: '등록되지 않은 아이디입니다' });
req.log.info({ by: a.id, user: req.params.id, role: r }, '앱 유저 역할 변경');
return { users: rows() };
});
app.delete<{ Params: { id: string } }>(`${prefix}/users/:id`, async (req, reply) => {
const a = await who(req, reply, 'superadmin');
if (!a) return;
if (cfg.superAdmins.includes(req.params.id)) return reply.code(400).send({ error: 'fixed', message: '최고 관리자는 지울 수 없습니다' });
if (!store.removeAppUser(req.params.id)) return reply.code(404).send({ error: 'not_found', message: '등록되지 않은 아이디입니다' });
revoke({ userId: req.params.id });
req.log.info({ by: a.id, user: req.params.id }, '앱 유저 등록 해제');
return { users: rows() };
});
}
/**
* 표시 이름 확인: 빈 값이면 지우기(디스코드 이름으로), 아니면 1~32자 · 제어 문자 없음 · 다른 사람의 표시 이름과 겹치지 않음
* (같은 이름이 둘이면 기록 · 범인 분석에서 누가 누군지 알 수 없다)
*/
function checkName(raw: unknown, id: string): { name: string | null } | { error: string } {
if (raw === null || raw === undefined) return { name: null };
const name = String(raw).normalize('NFC').replace(/\s+/g, ' ').trim();
if (!name) return { name: null };
if ([...name].length > 32) return { error: '이름은 32자까지입니다' };
if (/[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u2028-\u202e\u2066-\u2069\ufeff]/.test(name)) return { error: '이름에 쓸 수 없는 글자가 있습니다' };
const key = name.toLowerCase();
for (const [other, n] of Object.entries(store.displayNames())) if (other !== id && n.toLowerCase() === key) return { error: '다른 사람이 이미 쓰는 이름입니다' };
return { name };
}
const siteRole = (id: string): AppRole | null => roleOf(id) ?? (cfg.owners.includes(id) ? 'admin' : null);
/** 겜녹이 봇 중계 연결 확인: 살아 있는 앱 토큰 + 등록된 아이디 */
const verifyToken = (token: string): { userId: string; role: AppRole } | null => {
@@ -252,7 +307,7 @@ export function registerAppAuth(
return s && r ? { userId: s.userId, role: r } : null;
};
return { completeLogin, verifyToken, roleOf };
return { completeLogin, verifyToken, roleOf, siteRole, checkName };
}
const esc = (s: string) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);

View File

@@ -9,8 +9,9 @@ import { registerAppAuth } from './app-auth.js';
import { BotBroker, type BotSource } from './bot-broker.js';
import { registerCulprit, type ModelCall } from './culprit.js';
import type { KnowledgeAuto } from './culprit-prompt.js';
import { avatarUrl, DiscordApi } from './discord.js';
import { avatarUrl, DiscordApi, fetchDiscordUser } from './discord.js';
import { registerMaps3d } from './maps3d.js';
import { contentSecurityPolicy } from './csp.js';
import { RateLimiter } from './rate-limit.js';
import { RelayHub } from './relay.js';
import { SiteLog } from './site-log.js';
@@ -46,26 +47,20 @@ export async function buildServer(
await app.register(cookie, { secret: cfg.sessionSecret });
const secure = cfg.publicUrl.startsWith('https://');
let broker: BotBroker | null = null;
const appAuth = registerAppAuth(app, { cfg, store, discord, secure, onRevoke: (by) => broker?.kick(by) });
const appAuth = registerAppAuth(app, {
cfg,
store,
discord,
secure,
onRevoke: (by) => broker?.kick(by),
siteSession: (req, reply) => requireSession(req, reply),
onNamesChanged: (id, name) => (name ? pushNames() : void restoreName(id).then(pushNames)),
});
if (opts.botSource) broker = new BotBroker(opts.botSource, appAuth.verifyToken, app.log.child({ area: 'bot' }), opts.botRecheckMs);
// 보안 헤더. HSTS · X-Frame-Options · Referrer-Policy 는 앞단 프록시(NPMplus)가 붙인다 (http → https 이동도 프록시)
// CSP: 이 사이트의 스크립트만 실행, 접속은 이 사이트로만 (XSS 가 생겨도 기록을 바깥으로 보내지 못하게)
// 'wasm-unsafe-eval': 맵 3D 압축 풀기(meshopt, WebAssembly)만 허용. 자바스크립트 eval 은 여전히 막힌다
const wsOrigin = cfg.publicUrl.replace(/^http/, 'ws');
const csp = [
"default-src 'self'",
"script-src 'self' 'wasm-unsafe-eval'",
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data: blob: https://cdn.discordapp.com",
"media-src 'self' blob: data:",
"font-src 'self' data:",
`connect-src 'self' ${wsOrigin}`,
"object-src 'none'",
"base-uri 'self'",
"form-action 'self'",
"frame-ancestors 'none'",
].join('; ');
// CSP 내용과 이유는 csp.ts
const csp = contentSecurityPolicy(cfg.publicUrl.replace(/^http/, 'ws'));
app.addHook('onSend', async (_req, reply, payload) => {
reply.header('content-security-policy', csp);
reply.header('x-content-type-options', 'nosniff');
@@ -214,7 +209,78 @@ export async function buildServer(
app.get('/auth/me', async (req, reply) => {
const s = await requireSession(req, reply);
if (!s) return;
return { user: s.user, isOwner: cfg.owners.includes(s.user.id), canViewLogs: canViewLogs(s.user.id) };
return { user: s.user, isOwner: cfg.owners.includes(s.user.id), canViewLogs: canViewLogs(s.user.id), role: appAuth.siteRole(s.user.id) };
});
// ------------------------------------------------------------------ 내 정보 · 표시 이름 (v1.6.0)
/** 표시 이름을 게임 PC 앱에 바로 보낸다 (v1.6.0 앱. 예전 앱은 10분마다 받아 간다) */
function pushNames(): void {
if (!hub.status().online) return;
hub
.request('PUT', '/api/internal/names', { 'x-gvr-internal': '1', 'content-type': 'application/json', accept: 'application/json' }, { id: 'server', name: '사이트 서버', avatar: null }, JSON.stringify({ names: store.displayNames() }), 10000)
.then((r) => r.status >= 400 && app.log.info({ area: 'names', status: r.status }, '게임 PC 앱이 표시 이름을 바로 받지 못함 (예전 앱은 10분 안에 받아 감)'))
.catch(() => undefined);
}
/** 표시 이름을 지우면 디스코드 이름(서버 별명 → 전역 이름 → 아이디)으로 되돌린다 */
async function restoreName(id: string): Promise<void> {
try {
let nick: string | null = null;
for (const g of allowedGuilds()) {
const m = await discord.memberOf(g, id);
if (m?.nick) nick = m.nick;
if (m) break;
}
const u = nick ? null : await fetchDiscordUser(cfg, id);
const name = nick || u?.global_name || u?.username;
if (name) store.restoreDiscordName(id, name);
} catch (e) {
app.log.warn({ area: 'names', err: String(e) }, '디스코드 이름 다시 받기 실패');
}
}
// 관리 화면 머리: 게임 PC 상태 + 최신 앱 릴리스 (Gitea, 1시간 보관). 새 버전이 있으면 관리자에게 알린다
let latest: { at: number; v: { version: string; url: string; publishedAt: string | null } | null } = { at: 0, v: null };
async function latestRelease() {
if (!cfg.releasesApi || Date.now() - latest.at < 3600000) return latest.v;
latest.at = Date.now();
try {
const r = await fetch(cfg.releasesApi, { signal: AbortSignal.timeout(5000), headers: { accept: 'application/json' } });
if (r.ok) {
const j: any = await r.json();
if (typeof j.tag_name === 'string') latest.v = { version: j.tag_name.replace(/^v/, ''), url: String(j.html_url ?? ''), publishedAt: j.published_at ?? null };
}
} catch {
/* 다음에 다시 */
latest.at = Date.now() - 3300000;
}
return latest.v;
}
app.get('/site/admin/overview', async (req, reply) => {
const s = await requireSession(req, reply);
if (!s) return;
const r = appAuth.siteRole(s.user.id);
if (!r || r === 'user') return reply.code(403).send({ error: 'forbidden', message: '관리자만 볼 수 있습니다' });
const dev = store.device();
return { device: { ...hub.status(), guildId: dev?.guildId ?? null }, latest: await latestRelease(), role: r, serverVersion: cfg.version };
});
const nameLimit = new RateLimiter(10, 10 * 60000);
app.get('/site/profile', async (req, reply) => {
const s = await requireSession(req, reply);
if (!s) return;
return { user: s.user, customName: store.displayNames()[s.user.id] ?? null, role: appAuth.siteRole(s.user.id) };
});
app.put<{ Body: { name?: string | null } }>('/site/profile/name', async (req, reply) => {
const s = await requireSession(req, reply);
if (!s) return;
const origin = String(req.headers.origin || '');
if (origin && origin !== cfg.publicUrl) return reply.code(403).send({ error: 'bad_origin' });
if (!nameLimit.hit(s.user.id)) return reply.code(429).send({ error: 'rate_limited', message: '이름을 너무 자주 바꿨습니다. 10분 뒤 다시 해 주세요' });
const v = appAuth.checkName(req.body?.name, s.user.id);
if ('error' in v) return reply.code(400).send({ error: 'bad_name', message: v.error });
store.setDisplayName(s.user.id, v.name);
if (!v.name) await restoreName(s.user.id);
req.log.info({ user: s.user.id, set: !!v.name }, '내 표시 이름 변경');
pushNames();
return { user: s.user, customName: v.name };
});
// ------------------------------------------------------------------ 상태 · 관리

View File

@@ -20,6 +20,8 @@ export interface Config {
/** 테스트용: 디스코드 API 주소 바꾸기 */
discordApi: string;
assetUpstream: Record<string, string>;
/** 최신 앱 릴리스 (Gitea API, 관리 화면에서 새 버전 안내) */
releasesApi?: string;
/** 범인찾기 (Claude API). apiKey 가 없으면 꺼진다 (없으면 CULPRIT_DEFAULTS) */
culprit?: {
apiKey: string | null;
@@ -59,6 +61,7 @@ export function loadConfig(env = process.env): Config {
webDir: env.WEB_DIR || path.resolve('../web/dist'),
version: env.GVR_VERSION || '1.0.0',
discordApi: env.DISCORD_API || 'https://discord.com/api/v10',
releasesApi: env.RELEASES_API || 'https://git.tkrmagid.kr/api/v1/repos/tkrmagid/game_voice_recorder/releases/latest',
assetUpstream: {
valmedia: 'https://media.valorant-api.com/',
ddragon: 'https://ddragon.leagueoflegends.com/',

22
site/server/src/csp.ts Normal file
View File

@@ -0,0 +1,22 @@
/**
* 사이트 CSP. 이 사이트의 스크립트만 실행, 접속은 이 사이트로만 (XSS 가 생겨도 기록을 바깥으로 보내지 못하게).
* 사이트 서버(app.ts)와 화면 미리보기(site/web vite preview)가 같은 값을 쓴다 → 헤드리스 확인도 실제와 같은 제한에서 한다.
* 'wasm-unsafe-eval': 맵 3D 압축 풀기(meshopt, WebAssembly)만 허용. 자바스크립트 eval 은 여전히 막힌다
* connect-src blob: 3D 파일(glb) 안 텍스처를 three.js 가 blob: 주소로 fetch 해 읽는다 (페이지가 만든 blob 만, 바깥 접속은 아님).
* 없으면 텍스처를 못 읽어 요원이 흰색, 맵 3D 는 통째로 실패해 미니맵으로 나온다
*/
export function contentSecurityPolicy(wsOrigin: string): string {
return [
"default-src 'self'",
"script-src 'self' 'wasm-unsafe-eval'",
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data: blob: https://cdn.discordapp.com",
"media-src 'self' blob: data:",
"font-src 'self' data:",
`connect-src 'self' blob: ${wsOrigin}`,
"object-src 'none'",
"base-uri 'self'",
"form-action 'self'",
"frame-ancestors 'none'",
].join('; ');
}

View File

@@ -9,9 +9,10 @@ import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify';
*
* <dataDir>/maps3d/index.json {version, dir, updatedAt, maps:{<맵 경로>:{code,file,bytes,triangles}}}
* <dataDir>/maps3d/<dir>/<code>.glb.gz meshopt 압축 glb 를 gzip 한 것. 위치는 UE 월드 좌표(cm)
* <dataDir>/maps3d/<dir>/abilities.json.gz · m_*.glb.gz · t_*.png.gz 스킬 목록 · 모델 · 텍스처 (모두 gzip)
*
* GET /site/maps3d → index.json (없으면 {maps:{}})
* GET /site/maps3d/:dir/:f → glb (content-encoding gzip). 폴더 이름이 패치마다 바뀌므로 오래 캐시한다
* GET /site/maps3d/:dir/:f → glb · json · png · jpg (content-encoding gzip). 폴더 이름이 패치마다 바뀌므로 오래 캐시한다
*/
export interface Maps3dIndex {
version: string;
@@ -20,6 +21,9 @@ export interface Maps3dIndex {
maps: Record<string, { code: string; file: string; bytes: number; triangles: number }>;
}
/** 보내는 파일 종류: 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>) {
const root = path.join(dataDir, 'maps3d');
let cache: { mtime: number; data: Maps3dIndex | null } = { mtime: -1, data: null };
@@ -50,10 +54,11 @@ export function registerMaps3d(app: FastifyInstance, dataDir: string, requireSes
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;
if (!/^[\w.-]+$/.test(dir) || !/^[\w.-]+\.glb$/.test(file) || dir.includes('..')) return reply.code(404).send({ error: 'not_found' });
const type = TYPES[path.extname(file).toLowerCase()];
if (!/^[\w.-]+$/.test(dir) || !/^[\w.-]+$/.test(file) || !type || dir.includes('..')) return reply.code(404).send({ error: 'not_found' });
const gz = path.join(root, dir, file + '.gz');
if (!fs.existsSync(gz)) return reply.code(404).send({ error: 'not_found' });
reply.header('cache-control', 'private, max-age=31536000, immutable').type('model/gltf-binary');
reply.header('cache-control', 'private, max-age=31536000, immutable').type(type);
if (/\bgzip\b/.test(String(req.headers['accept-encoding'] ?? ''))) {
reply.header('content-encoding', 'gzip').header('content-length', fs.statSync(gz).size);
return reply.send(fs.createReadStream(gz));

View File

@@ -212,6 +212,15 @@ export class ServerStore {
} else delete this.d.displayNames[id];
this.save(true);
}
/** 표시 이름을 지운 뒤 디스코드에서 다시 받은 이름으로 세션 · 앱 유저 이름을 되돌린다 (예전 표시 이름이 남지 않게) */
restoreDiscordName(id: string, name: string): void {
if (this.d.displayNames[id]) return;
for (const s of this.d.sessions) if (s.user.id === id) s.user.name = name;
const u = this.appUser(id);
if (u) u.name = name;
if (this.d.appSeen[id]) this.d.appSeen[id].name = name;
this.save(true);
}
// ---- 앱 유저 등록 · 앱 로그인 토큰
appUsers(): AppUser[] {

View File

@@ -38,6 +38,9 @@ async function stack() {
const dir = path.join(cfg.dataDir, 'maps3d', 'V1-1');
fs.mkdirSync(dir, { recursive: true });
fs.writeFileSync(path.join(dir, 'Ascent.glb.gz'), zlib.gzipSync(Buffer.from('glTF-test')));
fs.writeFileSync(path.join(dir, 'abilities.json.gz'), zlib.gzipSync(Buffer.from('{"classes":{}}')));
fs.writeFileSync(path.join(dir, 't_Smoke.png.gz'), zlib.gzipSync(Buffer.from('png-test')));
fs.writeFileSync(path.join(dir, 'secret.txt.gz'), zlib.gzipSync(Buffer.from('no')));
fs.writeFileSync(path.join(cfg.dataDir, 'maps3d', 'index.json'), JSON.stringify({ version: 'V1', dir: 'V1-1', updatedAt: 'x', maps: { '/Game/Maps/Ascent/Ascent': { code: 'Ascent', file: 'Ascent.glb', bytes: 1, triangles: 1 } } }));
const { app, store } = await buildServer(cfg);
await app.listen({ host: '127.0.0.1', port: 0 });
@@ -72,6 +75,16 @@ test('맵 3D: 로그인하면 목록과 glb 를 받는다 (gzip), 이상한 경
assert.equal(r.status, 200);
assert.equal(r.headers.get('content-encoding'), 'gzip');
assert.equal(await r.text(), 'glTF-test'); // fetch 가 gzip 을 풀어 준다
// 스킬 목록 · 텍스처도 같은 폴더에서 (gzip, 종류에 맞는 content-type)
const j = await fetch(s.base + '/site/maps3d/V1-1/abilities.json', { headers: { cookie, 'accept-encoding': 'gzip' } });
assert.equal(j.status, 200);
assert.match(j.headers.get('content-type') ?? '', /application\/json/);
assert.deepEqual(await j.json(), { classes: {} });
const t = await fetch(s.base + '/site/maps3d/V1-1/t_Smoke.png', { headers: { cookie, 'accept-encoding': 'gzip' } });
assert.equal(t.status, 200);
assert.equal(t.headers.get('content-type'), 'image/png');
// 정해진 종류(glb · json · png · jpg)가 아니면 404
assert.equal((await fetch(s.base + '/site/maps3d/V1-1/secret.txt', { headers: { cookie } })).status, 404);
assert.equal((await fetch(s.base + '/site/maps3d/V1-1/..%2Findex.json', { headers: { cookie } })).status, 404);
assert.equal((await fetch(s.base + '/site/maps3d/V1-1/Nope.glb', { headers: { cookie } })).status, 404);
} finally {

View File

@@ -0,0 +1,132 @@
// 사이트 "내 정보" (표시 이름) · 관리 화면 API (v1.6.0)
import { test } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import http from 'node:http';
import os from 'node:os';
import path from 'node:path';
import { buildServer } from '../src/app.ts';
import type { Config } from '../src/config.ts';
const SUPER = '293719842274541579';
const ADMIN = '111111111111111111';
const MEMBER = '222222222222222222';
const OTHER = '333333333333333333';
const tmp = () => fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), 'gvr-profile-'));
const NICK: Record<string, string> = { [SUPER]: '사금향', [ADMIN]: '관리', [MEMBER]: '멤버닉', [OTHER]: '다른' };
async function fakeDiscord() {
const srv = http.createServer((req, res) => {
const u = new URL(req.url!, 'http://x');
res.setHeader('content-type', 'application/json');
const m = /^\/guilds\/111\/members\/(\d+)$/.exec(u.pathname);
if (m && NICK[m[1]!]) return res.end(JSON.stringify({ nick: NICK[m[1]!], avatar: null }));
const usr = /^\/users\/(\d+)$/.exec(u.pathname);
if (usr && NICK[usr[1]!]) return res.end(JSON.stringify({ id: usr[1], username: 'u' + usr[1], global_name: NICK[usr[1]!], avatar: null }));
if (u.pathname === '/releases/latest') return res.end(JSON.stringify({ tag_name: 'v1.6.0', html_url: 'https://git.example/releases/tag/v1.6.0', published_at: '2026-10-17T00:00:00Z' }));
res.statusCode = 404;
res.end('{}');
});
await new Promise<void>((r) => srv.listen(0, '127.0.0.1', () => r()));
return { url: `http://127.0.0.1:${(srv.address() as any).port}`, close: () => srv.close() };
}
async function stack() {
const dc = await fakeDiscord();
const cfg: Config = {
port: 0, host: '127.0.0.1', publicUrl: 'https://gvr.example', clientId: 'cid', clientSecret: 's', botToken: 'bot',
allowedGuilds: ['111'], owners: [SUPER], superAdmins: [SUPER], sessionSecret: 'x'.repeat(32), dataDir: tmp(), webDir: '/nonexistent',
version: 'test', discordApi: dc.url, assetUpstream: {}, releasesApi: `${dc.url}/releases/latest`,
};
const { app, store } = await buildServer(cfg);
store.upsertAppUser({ id: ADMIN, name: '관리', avatar: null, role: 'admin', addedBy: SUPER });
await app.listen({ host: '127.0.0.1', port: 0 });
const base = `http://127.0.0.1:${(app.server.address() as any).port}`;
const cookieOf = (id: string) => {
const s = store.createSession({ id, name: NICK[id]!, avatar: null });
return `gvr_sid=${app.signCookie(s.token)}`;
};
const as = (id: string) => {
const cookie = cookieOf(id);
const call = async (method: string, p: string, body?: unknown, origin = 'https://gvr.example') => {
const r = await fetch(base + p, { method, headers: { cookie, ...(body !== undefined ? { 'content-type': 'application/json', origin } : {}) }, body: body === undefined ? undefined : JSON.stringify(body) });
return { status: r.status, json: (await r.json().catch(() => null)) as any };
};
return { get: (p: string) => call('GET', p), put: (p: string, b: unknown, o?: string) => call('PUT', p, b, o), post: (p: string, b: unknown) => call('POST', p, b), patch: (p: string, b: unknown) => call('PATCH', p, b), del: (p: string) => call('DELETE', p, {}) };
};
return { store, as, close: async () => (await app.close(), dc.close()) };
}
test('내 정보: 누구나 자기 표시 이름을 바꾸고, 지우면 디스코드 별명으로 돌아간다', async () => {
const s = await stack();
try {
const me = s.as(MEMBER);
assert.deepEqual((await me.get('/site/profile')).json, { user: { id: MEMBER, name: '멤버닉', avatar: null }, customName: null, role: null });
const r = await me.put('/site/profile/name', { name: ' 하늘 별 ' });
assert.equal(r.status, 200);
assert.equal(r.json.user.name, '하늘 별');
assert.equal((await me.get('/auth/me')).json.user.name, '하늘 별');
assert.equal(s.store.displayNames()[MEMBER], '하늘 별');
// 지우기 → 디스코드 서버 별명
const back = await me.put('/site/profile/name', { name: '' });
assert.equal(back.status, 200);
assert.equal(back.json.customName, null);
assert.equal((await me.get('/auth/me')).json.user.name, '멤버닉');
assert.equal(s.store.displayNames()[MEMBER], undefined);
} finally {
await s.close();
}
});
test('내 정보: 다른 사람 이름 · 너무 긴 이름 · 보이지 않는 글자 · 다른 사이트에서 온 요청은 막는다', async () => {
const s = await stack();
try {
assert.equal((await s.as(OTHER).put('/site/profile/name', { name: '하늘' })).status, 200);
const me = s.as(MEMBER);
const dup = await me.put('/site/profile/name', { name: '하늘' });
assert.equal(dup.status, 400);
assert.match(dup.json.message, /이미 쓰는 이름/);
assert.equal((await me.put('/site/profile/name', { name: '가'.repeat(33) })).status, 400);
assert.equal((await me.put('/site/profile/name', { name: '하​늘' })).status, 400);
assert.equal((await me.put('/site/profile/name', { name: '별' }, 'https://evil.example')).status, 403);
assert.equal(s.store.displayNames()[MEMBER], undefined);
} finally {
await s.close();
}
});
test('관리 화면: 관리자는 목록 · 남의 표시 이름, 등록 · 역할 · 해제는 최고 관리자만, 일반 멤버는 못 들어온다', async () => {
const s = await stack();
try {
const member = s.as(MEMBER);
const admin = s.as(ADMIN);
const sup = s.as(SUPER);
assert.equal((await member.get('/site/admin/users')).status, 403);
assert.equal((await member.get('/site/admin/overview')).status, 403);
assert.equal((await member.put('/site/admin/names', { id: OTHER, name: 'x' })).status, 403);
const list = await admin.get('/site/admin/users');
assert.equal(list.status, 200);
assert.deepEqual(list.json.users.map((u: any) => [u.id, u.role]), [[SUPER, 'superadmin'], [ADMIN, 'admin']]);
const ov = await admin.get('/site/admin/overview');
assert.equal(ov.json.role, 'admin');
assert.equal(ov.json.latest.version, '1.6.0');
assert.equal(ov.json.device.registered, false);
const named = await admin.put('/site/admin/names', { id: MEMBER, name: '지호' });
assert.equal(named.status, 200);
assert.equal(named.json.names[MEMBER], '지호');
assert.equal((await member.get('/auth/me')).json.user.name, '지호', '로그인해 있는 세션 이름도 바뀐다');
assert.equal((await admin.post('/site/admin/users', { id: MEMBER, role: 'user' })).status, 403);
const added = await sup.post('/site/admin/users', { id: MEMBER, role: 'user' });
assert.equal(added.status, 200);
assert.equal(added.json.users.find((u: any) => u.id === MEMBER).name, '지호', '등록할 때도 표시 이름으로');
assert.equal((await sup.patch(`/site/admin/users/${MEMBER}`, { role: 'admin' })).json.users.find((u: any) => u.id === MEMBER).role, 'admin');
assert.equal((await sup.patch(`/site/admin/users/${SUPER}`, { role: 'user' })).status, 400);
assert.equal((await sup.del(`/site/admin/users/${MEMBER}`)).status, 200);
assert.equal((await member.get('/site/admin/users')).status, 403);
} finally {
await s.close();
}
});

View File

@@ -63,7 +63,7 @@ test('보안 헤더: CSP 는 이 사이트 스크립트 · 접속만 허용하
const csp = r.headers.get('content-security-policy') ?? '';
assert.match(csp, /default-src 'self'/);
assert.match(csp, /script-src 'self' 'wasm-unsafe-eval'(;|$)/); // WebAssembly(맵 3D 압축 풀기)만, eval 은 안 됨
assert.match(csp, /connect-src 'self' wss:\/\/gvr\.example/);
assert.match(csp, /connect-src 'self' blob: wss:\/\/gvr\.example(;|$)/); // blob: = 3D 파일 안 텍스처 (없으면 요원 흰색 · 맵 3D 실패)
assert.match(csp, /frame-ancestors 'none'/);
assert.equal(r.headers.get('x-content-type-options'), 'nosniff');
} finally {

View File

@@ -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 % 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,

View File

@@ -21,11 +21,40 @@ const here = path.dirname(fileURLToPath(import.meta.url));
const ASSET_DIR = path.resolve(here, '../../../docs/report/mock/assets');
const ME = { id: '310482915522101248', name: '하늘', avatar: null };
let m0;
/** 표시 이름: 목에서는 유저 목록 이름도 같이 바꾼다 (실제로는 게임 PC 앱이 받아서 바꿈) */
function setName(id, n) {
const u = db.users.find((x) => x.id === id);
if (u) u._orig ??= u.name;
if (n) state.names[id] = n;
else delete state.names[id];
if (u) u.name = n || u._orig;
broadcast({ type: 'users.updated', data: db.users });
}
const state = {
names: {},
regs: [
{ id: ME.id, name: ME.name, avatar: null, role: 'superadmin', fixed: true, addedBy: null, addedAt: null, lastSeenAt: Date.now() - 3600000, lastVersion: '1.5.0' },
],
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, 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(), updatedAt: Date.now() },
];
const json = (res, status, body, headers = {}) => {
const s = JSON.stringify(body, (k, v) => (k.startsWith('_') ? undefined : v));
@@ -101,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);
@@ -188,8 +220,9 @@ async function handle(req, res) {
if (p === '/site/maps3d') return json(res, 200, JSON.parse(fs.readFileSync(path.join(root, 'index.json'), 'utf8')));
const [dir, file] = p.slice('/site/maps3d/'.length).split('/').map(decodeURIComponent);
const f = path.join(root, dir ?? '', (file ?? '') + '.gz');
if (!/^[\w.-]+$/.test(dir ?? '') || !/^[\w.-]+\.glb$/.test(file ?? '') || !fs.existsSync(f)) return json(res, 404, { error: 'not_found' });
res.writeHead(200, { 'content-type': 'model/gltf-binary', 'content-encoding': 'gzip', 'content-length': fs.statSync(f).size });
const type = { '.glb': 'model/gltf-binary', '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg' }[path.extname(file ?? '').toLowerCase()];
if (!/^[\w.-]+$/.test(dir ?? '') || !/^[\w.-]+$/.test(file ?? '') || !type || !fs.existsSync(f)) return json(res, 404, { error: 'not_found' });
res.writeHead(200, { 'content-type': type, 'content-encoding': 'gzip', 'content-length': fs.statSync(f).size });
return fs.createReadStream(f).pipe(res);
}
@@ -241,7 +274,35 @@ async function handle(req, res) {
if (p === '/auth/me') {
if (!sess) return json(res, 401, { error: 'unauthorized' });
if (sess === 'nm') return json(res, 403, { error: 'not_member' });
return json(res, 200, { user: ME, isOwner: true, canViewLogs: true });
return json(res, 200, { user: { ...ME, name: state.names[ME.id] ?? ME.name }, isOwner: true, canViewLogs: true, role: 'superadmin' });
}
// 내 정보 · 관리 화면 (v1.6.0)
if (p === '/site/profile') return json(res, 200, { user: { ...ME, name: state.names[ME.id] ?? ME.name }, customName: state.names[ME.id] ?? null, role: 'superadmin' });
if (p === '/site/profile/name' && req.method === 'PUT') {
const b = JSON.parse((await readBody(req)) || '{}');
const n = String(b.name ?? '').trim();
if (n && Object.entries(state.names).some(([id, x]) => id !== ME.id && x === n)) return json(res, 400, { error: 'bad_name', message: '다른 사람이 이미 쓰는 이름입니다' });
setName(ME.id, n);
return json(res, 200, { user: { ...ME, name: state.names[ME.id] ?? ME.name }, customName: state.names[ME.id] ?? null });
}
if (p === '/site/admin/overview') return json(res, 200, { device: { ...deviceStatus(), guildId: '1200000000000000000' }, latest: { version: '1.6.0', url: 'https://git.tkrmagid.kr/tkrmagid/game_voice_recorder/releases/tag/v1.6.0', publishedAt: null }, role: 'superadmin', serverVersion: '1.0.0' });
if (p === '/site/admin/users' && req.method === 'GET') return json(res, 200, { users: state.regs, names: state.names });
if (p === '/site/admin/names' && req.method === 'PUT') {
const b = JSON.parse((await readBody(req)) || '{}');
setName(String(b.id), String(b.name ?? '').trim());
return json(res, 200, { names: state.names });
}
if (p === '/site/admin/users' && req.method === 'POST') {
const b = JSON.parse((await readBody(req)) || '{}');
const u = db.users.find((x) => x.id === b.id);
state.regs.push({ id: b.id, name: u?.name ?? b.id, avatar: null, role: b.role, fixed: false, addedBy: ME.id, addedAt: Date.now(), lastSeenAt: null, lastVersion: null });
return json(res, 200, { users: state.regs });
}
if ((m0 = p.match(/^\/site\/admin\/users\/(\d+)$/))) {
const b = req.method === 'PATCH' ? JSON.parse((await readBody(req)) || '{}') : {};
if (req.method === 'PATCH') state.regs = state.regs.map((r) => (r.id === m0[1] ? { ...r, role: b.role } : r));
if (req.method === 'DELETE') state.regs = state.regs.filter((r) => r.id !== m0[1]);
return json(res, 200, { users: state.regs });
}
if (p.startsWith('/api/')) {
@@ -257,10 +318,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',
});
@@ -273,6 +331,16 @@ async function handle(req, res) {
return json(res, 200, db.users);
}
let m;
if ((m = p.match(/^\/api\/users\/([^/]+)$/)) && req.method === 'PATCH') {
const u = db.users.find((x) => x.id === decodeURIComponent(m[1]));
if (!u) return json(res, 404, { error: 'not_found', message: '이 PC 기록에 없는 유저입니다' });
const b = JSON.parse((await readBody(req)) || '{}');
if (b.color) u.color = b.color;
if (b.excluded !== undefined) u.excluded = !!b.excluded;
if (b.riotIds) u.riot = b.riotIds.map((r) => ({ puuid: `riotid:${r}`, riotId: r }));
broadcast({ type: 'users.updated', data: db.users });
return json(res, 200, { user: u, taken: [] });
}
if ((m = p.match(/^\/api\/users\/([^/]+)$/))) {
const prof = userProfile(decodeURIComponent(m[1]));
return prof ? json(res, 200, prof) : json(res, 404, { error: 'not_found' });
@@ -282,7 +350,9 @@ 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);
const list = db.matches.filter((x) => (!game || x.game === game) && x.startedAt < before && keep(x)).sort((a, b) => b.startedAt - a.startedAt).slice(0, limit).map(summary);
return json(res, 200, list);
}
if ((m = p.match(/^\/api\/matches\/([^/]+)$/))) {
@@ -294,7 +364,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);
}
@@ -363,6 +434,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();
@@ -432,10 +509,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;
}

View File

@@ -18,6 +18,7 @@ import { CulpritPage } from './pages/CulpritPage';
import { MatchesPage, UserPage, UsersPage } from './pages/UserPages';
import { LogsPage } from './pages/LogsPage';
import { RecordsPage } from './pages/RecordsPage';
import { AdminPage } from './pages/AdminPage';
import { installErrorReporting } from './lib/report';
import { useLocation } from 'react-router';
@@ -75,6 +76,7 @@ function Shell() {
<Route path="/dictionary" element={<DictionaryPage />} />
<Route path="/culprit" element={<CulpritPage />} />
<Route path="/culprit/:id" element={<CulpritPage />} />
<Route path="/admin" element={<AdminPage />} />
<Route path="*" element={<Navigate to="/" replace />} />
</Routes>
</div>

View File

@@ -0,0 +1,166 @@
import { useEffect, useRef, useState } from 'react';
import { settings, useSettings } from '../store/settings';
import { CROSS_COLORS, DEFAULT_CROSSHAIR, drawCrosshair, parseCrosshairCode, prepCanvas, type CrossLines, type CrossSet, type CrosshairAt, type CrosshairProfile } from '../lib/crosshair';
/** 조준점 미리보기 (어두운 바탕) */
function Preview({ set }: { set: CrossSet }) {
const ref = useRef<HTMLCanvasElement>(null);
useEffect(() => {
const g = ref.current && prepCanvas(ref.current);
if (g) drawCrosshair(g.ctx, g.cx, g.cy, set);
}, [set]);
return <canvas ref={ref} className="r3d-xprev" aria-label="조준점 미리보기" />;
}
function Range({ label, value, min, max, step, onChange }: { label: string; value: number; min: number; max: number; step: number; onChange: (v: number) => void }) {
return (
<label className="r3d-xrow">
<span>{label}</span>
<input type="range" min={min} max={max} step={step} value={value} onChange={(e) => onChange(Number(e.target.value))} />
<span className="mono">{step < 1 ? value.toFixed(2) : value}</span>
</label>
);
}
function Check({ label, value, onChange }: { label: string; value: boolean; onChange: (v: boolean) => void }) {
return (
<label className="r3d-xcheck">
<input type="checkbox" checked={value} onChange={(e) => onChange(e.target.checked)} /> {label}
</label>
);
}
function LinesEdit({ title, l, maxOffset, onChange }: { title: string; l: CrossLines; maxOffset: number; onChange: (l: CrossLines) => void }) {
const up = (p: Partial<CrossLines>) => onChange({ ...l, ...p, ...(p.length != null ? { vLength: p.length } : {}) });
return (
<fieldset className="r3d-xset">
<legend>
<Check label={title} value={l.on} onChange={(on) => up({ on })} />
</legend>
{l.on && (
<>
<Range label="불투명도" value={l.opacity} min={0} max={1} step={0.05} onChange={(opacity) => up({ opacity })} />
<Range label="길이" value={l.length} min={0} max={20} step={1} onChange={(length) => up({ length })} />
<Range label="두께" value={l.thickness} min={0} max={10} step={1} onChange={(thickness) => up({ thickness })} />
<Range label="간격" value={l.offset} min={0} max={maxOffset} step={1} onChange={(offset) => up({ offset })} />
<Check label="이동 오차" value={l.moveError} onChange={(moveError) => up({ moveError })} />
<Check label="사격 오차" value={l.fireError} onChange={(fireError) => up({ fireError })} />
</>
)}
</fieldset>
);
}
/**
* 1인칭 조준점 설정: 선수 조준점을 쓸지, 사이트 전체에 쓰는 내 조준점 (직접 고치기 · 발로란트 조준점 코드 가져오기).
* 설정은 이 브라우저에 저장한다
*/
export default function CrosshairPanel({ playerName, player, hasAny, onClose }: { playerName: string | null; player: CrosshairAt | null; hasAny: boolean; onClose: () => void }) {
const cfg = useSettings().crosshair;
const mine = cfg.mine;
const [code, setCode] = useState(cfg.code ?? '');
const [err, setErr] = useState<string | null>(null);
const save = (p: Partial<typeof cfg>) => settings.set({ crosshair: { ...cfg, ...p } });
const setMine = (m: CrosshairProfile, c?: string) => save({ mine: m, code: c });
// 직접 고치면 정조준 조준점도 같이 (발로란트 '정조준에도 주 조준점')
const upSet = (p: Partial<CrossSet>) => {
const primary = { ...mine.primary, ...p };
setMine({ ...mine, primary, ads: primary, adsFromPrimary: true });
};
const presetIdx = CROSS_COLORS.findIndex((c) => c.hex === mine.primary.color.toLowerCase());
const importCode = () => {
const p = parseCrosshairCode(code);
if (!p) {
setErr('조준점 코드 형식이 아닙니다 (예: 0;P;c;5;h;0;0l;4;0o;2;0a;1;0f;0;1b;0)');
return;
}
setErr(null);
setMine(p, code.trim());
};
const s = mine.primary;
return (
<div className="r3d-xpanel" role="dialog" aria-label="조준점 설정">
<div className="r3d-xhead">
<b>조준점</b>
<button className="chip" onClick={onClose} aria-label="닫기">
✕
</button>
</div>
<label className="r3d-xcheck">
<input type="radio" name="xmode" checked={cfg.usePlayer} onChange={() => save({ usePlayer: true })} /> 선수 조준점 (리플레이에 없으면 내 조준점)
</label>
<label className="r3d-xcheck">
<input type="radio" name="xmode" checked={!cfg.usePlayer} onChange={() => save({ usePlayer: false })} /> 모든 선수에 내 조준점
</label>
{player ? (
<div className="r3d-xplayer">
<Preview set={player.primary} />
<div>
<div className="small">
{playerName ?? '이 선수'} 조준점{player.name ? <span className="muted"> · {player.name}</span> : null}
</div>
<button className="chip" onClick={() => setMine({ primary: player.primary, ads: player.ads, sniper: player.sniper, adsFromPrimary: player.adsFromPrimary, advanced: player.advanced })}>
내 조준점으로 복사
</button>
</div>
</div>
) : (
<div className="muted small">
{hasAny ? '이 선수는 조준점 기록이 없어 내 조준점을 씁니다.' : '이 리플레이에는 선수 조준점 기록이 없어 내 조준점을 씁니다. 게임 PC 앱을 1.8.2 이상으로 올리면 리플레이를 열 때 다시 변환해 기록이 생깁니다.'}
</div>
)}
<div className="r3d-xmine">
<div className="r3d-xhead">
<b className="small">내 조준점</b>
<button className="chip" onClick={() => setMine(DEFAULT_CROSSHAIR)} title="발로란트 기본 조준점으로">
기본값
</button>
</div>
<Preview set={s} />
<div className="r3d-xcode">
<input value={code} onChange={(e) => setCode(e.target.value)} placeholder="발로란트 조준점 코드 붙여넣기" aria-label="조준점 코드" onKeyDown={(e) => e.key === 'Enter' && importCode()} />
<button className="chip" onClick={importCode}>
가져오기
</button>
</div>
{err && <div className="small r3d-xerr">{err}</div>}
<label className="r3d-xrow">
<span>색</span>
<select value={presetIdx >= 0 ? presetIdx : -1} onChange={(e) => Number(e.target.value) >= 0 && upSet({ color: CROSS_COLORS[Number(e.target.value)].hex })}>
{CROSS_COLORS.map((c, i) => (
<option key={c.hex} value={i}>
{c.name}
</option>
))}
<option value={-1}>사용자 지정</option>
</select>
<input type="color" value={s.color} onChange={(e) => upSet({ color: e.target.value })} aria-label="사용자 지정 색" />
</label>
<fieldset className="r3d-xset">
<legend>
<Check label="외곽선" value={s.outline} onChange={(outline) => upSet({ outline })} />
</legend>
{s.outline && (
<>
<Range label="불투명도" value={s.outlineOpacity} min={0} max={1} step={0.05} onChange={(outlineOpacity) => upSet({ outlineOpacity })} />
<Range label="두께" value={s.outlineThickness} min={1} max={6} step={1} onChange={(outlineThickness) => upSet({ outlineThickness })} />
</>
)}
</fieldset>
<fieldset className="r3d-xset">
<legend>
<Check label="가운데 점" value={s.dot} onChange={(dot) => upSet({ dot })} />
</legend>
{s.dot && (
<>
<Range label="불투명도" value={s.dotOpacity} min={0} max={1} step={0.05} onChange={(dotOpacity) => upSet({ dotOpacity })} />
<Range label="두께" value={s.dotSize} min={1} max={6} step={1} onChange={(dotSize) => upSet({ dotSize })} />
</>
)}
</fieldset>
<LinesEdit title="안쪽 선" l={s.inner} maxOffset={20} onChange={(inner) => upSet({ inner })} />
<LinesEdit title="바깥쪽 선" l={s.outer} maxOffset={40} onChange={(outer) => upSet({ outer })} />
</div>
</div>
);
}

View File

@@ -6,7 +6,8 @@ import { settings, useSettings, type SfxKind } from '../store/settings';
import { sfx, SFX_LABEL } from '../lib/sfx';
import { resumeAudio } from '../lib/audio';
import { Avatar, Brand } from './common';
import { IGear, ILogout, ISearch } from './Icons';
import { IGear, ISearch } from './Icons';
import { ProfilePopover } from './UserEdit';
import { GAME_NAME, liveGameLine, liveGameRows } from '@gvr/shared';
function SettingsPopover({ onClose }: { onClose: () => void }) {
@@ -165,10 +166,11 @@ export function SearchBox() {
}
export function Header() {
const { auth, logout } = useAuth();
const { overview } = useData();
const { auth } = useAuth();
const { overview, userById } = useData();
const { device, locked, conn } = useStatus();
const [open, setOpen] = useState(false);
const [profile, setProfile] = useState(false);
const me = auth.status === 'ok' ? auth.me.user : null;
const rec = overview?.recording;
const nav = [
@@ -178,6 +180,7 @@ export function Header() {
['/users', '유저'],
['/dictionary', '단어사전'],
['/culprit', '🔍 범인찾기'],
...(auth.status === 'ok' && auth.me.canViewLogs ? ([['/admin', '🛡️ 관리']] as const) : []),
] as const;
return (
<header className="topbar">
@@ -211,14 +214,13 @@ export function Header() {
</button>
<AnimatePresence>{open && <SettingsPopover onClose={() => setOpen(false)} />}</AnimatePresence>
{me && (
<div className="me">
<Avatar name={me.name} src={me.avatar} color="#5865f2" size={26} />
<button className="me me-btn" onClick={() => setProfile((o) => !o)} aria-expanded={profile} title="내 정보 · 표시 이름 · 색 · 로그아웃">
<Avatar name={me.name} src={me.avatar} color={userById(me.id)?.color ?? '#5865f2'} size={26} />
<span className="me-nm">{me.name}</span>
<button className="icon-btn" onClick={logout} title="로그아웃" aria-label="로그아웃">
<ILogout width={16} height={16} />
</button>
</div>
<span className="me-caret">▾</span>
</button>
)}
<AnimatePresence>{profile && <ProfilePopover onClose={() => setProfile(false)} />}</AnimatePresence>
</div>
</header>
);

View File

@@ -0,0 +1,71 @@
import { useEffect, useRef, useState } from 'react';
import { GAME_NAME, historyStatus, resumeText, type GameType } from '@gvr/shared';
import { api } from '../lib/api';
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>
);
}

View File

@@ -2,6 +2,7 @@ import { lazy, Suspense, useEffect, useMemo, useState } from 'react';
import type { MatchDetail } from '@gvr/shared';
import { api, ApiError } from '../lib/api';
import { computeSync, type ReplayFile } from '../lib/replay';
import { reportClient } from '../lib/report';
import { Panel, Spinner } from './common';
// three.js 는 크므로 3D 리플레이를 열 때만 받는다
@@ -13,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;
@@ -21,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') {
@@ -37,18 +40,25 @@ export function ReplayPanel({ m }: { m: MatchDetail }) {
if (!alive) return;
setConverting(false);
setErr(e);
// 변환 실패 이유는 게임 PC 에만 남으므로 사이트 로그에도 남긴다
if (e instanceof ApiError && e.status === 422) reportClient('warn', `리플레이 변환 실패 ${m.id}: ${e.detail ?? e.code}`);
});
void ask(0);
return () => {
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' : ''}`}
@@ -64,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 가 이 경기 리플레이를 변환하지 못했습니다. 발로란트 패치로 리플레이 형식이 바뀌었을 수 있습니다 (게임 PC 앱 로그에 이유가 남습니다).</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초 안팎)' : '리플레이 불러오는 중'} />
) : (

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,234 @@
// 유저 설정 고치기 (v1.6.0): 머리글 "내 정보" 와 관리 화면이 같이 쓴다
// - 표시 이름: 사이트 서버에 저장 (디스코드 이름 대신 보일 이름, 게임 PC 앱에 바로 전달)
// - 색 · 녹음 제외 · 라이엇 ID: 게임 PC 앱 기록에 저장 (앱 v1.6.0~)
import { useEffect, useRef, useState } from 'react';
import { Link } from 'react-router';
import { motion } from 'framer-motion';
import type { User } from '@gvr/shared';
import { api, ApiError } from '../lib/api';
import { sfx } from '../lib/sfx';
import { useAuth, useData } from '../store/app';
import { Avatar } from './common';
import { ILogout } from './Icons';
/** 타임라인에서 잘 보이는 색들 (어두운 배경) */
export const USER_COLORS = ['#ff4655', '#ff8a3d', '#f2b23a', '#c8e04a', '#45d39a', '#14c1b7', '#3db8ff', '#5b8cff', '#9a7bff', '#d46bff', '#ff6fb1', '#c9d1dc'];
/** 오류를 사람이 읽을 말로 */
export function errText(e: unknown): string {
if (e instanceof ApiError) {
if (e.status === 404 && e.code === 'Not Found') return '게임 PC 앱이 아직 이 기능을 모릅니다. 앱을 v1.6.0 이상으로 업데이트해 주세요';
if (e.status === 503 && e.code === 'device_offline') return '게임 PC 가 꺼져 있어 저장하지 못했습니다';
if (e.status === 504) return '게임 PC 가 답하지 않습니다. 잠시 뒤 다시 해 주세요';
if (e.detail) return e.detail;
if (e.status === 0) return '서버에 연결하지 못했습니다';
return `저장하지 못했습니다 (${e.status} ${e.code})`;
}
return e instanceof Error ? e.message : String(e);
}
/** 표시 이름 입력: 저장 · 디스코드 이름으로 되돌리기 */
export function NameEditor({ value, custom, onSave, placeholder }: { value: string; custom: boolean; onSave: (name: string) => Promise<void>; placeholder?: string }) {
const [v, setV] = useState(value);
const [busy, setBusy] = useState(false);
const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
useEffect(() => setV(value), [value]);
const save = async (name: string) => {
setBusy(true);
setMsg(null);
try {
await onSave(name);
setMsg({ ok: true, text: name ? '저장했습니다' : '디스코드 이름으로 되돌렸습니다' });
sfx('click');
} catch (e) {
setMsg({ ok: false, text: errText(e) });
} finally {
setBusy(false);
}
};
return (
<div className="ue-block">
<form
className="ue-row"
onSubmit={(e) => {
e.preventDefault();
if (v.trim() && v.trim() !== value) void save(v.trim());
}}
>
<input className="ue-input" value={v} maxLength={32} placeholder={placeholder ?? '표시 이름'} onChange={(e) => setV(e.target.value)} aria-label="표시 이름" />
<button className="btn sm primary" disabled={busy || !v.trim() || v.trim() === value}>
저장
</button>
{custom && (
<button type="button" className="btn sm" disabled={busy} onClick={() => void save('')} title="표시 이름을 지우고 디스코드 서버 별명으로 보이게">
되돌리기
</button>
)}
</form>
{msg && <div className={`ue-msg${msg.ok ? ' ok' : ' bad'}`}>{msg.text}</div>}
</div>
);
}
/** 색 · 녹음 제외 · 라이엇 ID (게임 PC 앱에 저장) */
export function AppUserEditor({ user, self }: { user: User; self: boolean }) {
const { reloadUsers } = useData();
const [riot, setRiot] = useState(user.riot.map((r) => r.riotId).join(', '));
const [busy, setBusy] = useState(false);
const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
const riotNow = user.riot.map((r) => r.riotId).join(', ');
useEffect(() => setRiot(riotNow), [riotNow]);
const colorRef = useRef<HTMLInputElement>(null);
const patch = async (p: { color?: string; excluded?: boolean; riotIds?: string[] }, okText: string) => {
setBusy(true);
setMsg(null);
try {
const r = await api.updateUser(user.id, p);
reloadUsers();
setMsg(r.taken.length ? { ok: false, text: `다른 사람에게 연결된 라이엇 ID 는 빼고 저장했습니다: ${r.taken.join(', ')}` } : { ok: true, text: okText });
sfx('click');
} catch (e) {
setMsg({ ok: false, text: errText(e) });
} finally {
setBusy(false);
}
};
const riotIds = riot
.split(/[,\n]/)
.map((x) => x.trim())
.filter(Boolean);
const riotBad = riotIds.filter((r) => !/^[^#]{1,32}#[^#]{1,8}$/.test(r));
return (
<div className="ue-block">
<div className="ue-label">색</div>
<div className="ue-colors" role="radiogroup" aria-label="유저 색">
{USER_COLORS.map((c) => (
<button
key={c}
className={`ue-sw${user.color.toLowerCase() === c ? ' on' : ''}`}
style={{ background: c }}
role="radio"
aria-checked={user.color.toLowerCase() === c}
aria-label={c}
disabled={busy}
onClick={() => void patch({ color: c }, '색을 바꿨습니다')}
/>
))}
<button className="ue-sw custom" title="다른 색 고르기" aria-label="다른 색 고르기" disabled={busy} onClick={() => colorRef.current?.click()}>
+
</button>
<input ref={colorRef} type="color" className="ue-hidden" defaultValue={user.color} onChange={(e) => void patch({ color: e.target.value }, '색을 바꿨습니다')} />
</div>
<div className="ue-label">라이엇 ID</div>
<form
className="ue-row"
onSubmit={(e) => {
e.preventDefault();
if (!riotBad.length) void patch({ riotIds }, '라이엇 ID 를 저장했습니다');
}}
>
<input className="ue-input" value={riot} placeholder="이름#태그 (여러 개는 쉼표로)" onChange={(e) => setRiot(e.target.value)} aria-label="라이엇 ID" />
<button className="btn sm" disabled={busy || riot.trim() === riotNow || riotBad.length > 0 || riotIds.length > 5}>
저장
</button>
</form>
{riotBad.length > 0 && <div className="ue-msg bad">이름#태그 형식이 아닙니다: {riotBad.join(', ')}</div>}
<div className="ue-hint">경기 기록의 선수와 연결됩니다. 새로 넣은 ID 는 다음 경기에서 확인됩니다.</div>
<label className="ue-check">
<input type="checkbox" checked={user.excluded} disabled={busy} onChange={(e) => void patch({ excluded: e.target.checked }, e.target.checked ? '앞으로 녹음하지 않습니다' : '다시 녹음합니다')} />
<span>
<b>녹음 제외</b>
<span className="ue-hint">{self ? '켜면 앞으로 내 목소리를 녹음하지 않습니다 (이미 녹음된 기록은 그대로).' : '켜면 앞으로 이 사람 목소리를 녹음하지 않습니다.'}</span>
</span>
</label>
{msg && <div className={`ue-msg${msg.ok ? ' ok' : ' bad'}`}>{msg.text}</div>}
</div>
);
}
/** 머리글 오른쪽 위 내 이름을 누르면 나오는 "내 정보" */
export function ProfilePopover({ onClose }: { onClose: () => void }) {
const { auth, logout, refreshMe } = useAuth();
const { userById } = useData();
const ref = useRef<HTMLDivElement>(null);
const [custom, setCustom] = useState<boolean | null>(null);
useEffect(() => {
const down = (e: PointerEvent) => {
if (ref.current && !ref.current.contains(e.target as Node) && !(e.target as HTMLElement).closest('.me-btn')) onClose();
};
const key = (e: KeyboardEvent) => e.key === 'Escape' && onClose();
document.addEventListener('pointerdown', down);
document.addEventListener('keydown', key);
return () => {
document.removeEventListener('pointerdown', down);
document.removeEventListener('keydown', key);
};
}, [onClose]);
useEffect(() => {
let alive = true;
fetch('/site/profile', { credentials: 'include' })
.then((r) => (r.ok ? r.json() : null))
.then((p) => alive && p && setCustom(!!p.customName))
.catch(() => undefined);
return () => {
alive = false;
};
}, []);
if (auth.status !== 'ok') return null;
const me = auth.me.user;
const u = userById(me.id);
const admin = auth.me.canViewLogs;
const roleLabel = auth.me.role === 'superadmin' ? '최고 관리자' : auth.me.role === 'admin' ? '관리자' : auth.me.role === 'user' ? '앱 유저' : admin ? '관리자' : '서버 멤버';
return (
<motion.div
ref={ref}
className="popover profile-pop"
initial={{ opacity: 0, y: -6, scale: 0.98 }}
animate={{ opacity: 1, y: 0, scale: 1 }}
exit={{ opacity: 0, y: -6, scale: 0.98 }}
transition={{ duration: 0.16 }}
role="dialog"
aria-label="내 정보"
>
<div className="pp-head">
<Avatar name={me.name} src={me.avatar} color={u?.color ?? '#5865f2'} size={40} />
<div>
<b style={u ? { color: u.color } : undefined}>{me.name}</b>
<div className="dim small">
{roleLabel} · <span className="mono">{me.id}</span>
</div>
</div>
</div>
<h5>표시 이름</h5>
<NameEditor
value={me.name}
custom={!!custom}
onSave={async (name) => {
const r = await api.setMyName(name);
setCustom(!!r.customName);
await refreshMe();
}}
/>
<div className="ue-hint">사이트 · 게임 PC 기록 · 범인 분석에서 디스코드 이름 대신 보입니다.</div>
<h5>녹음 기록 설정</h5>
{u ? <AppUserEditor user={u} self /> : <div className="ue-hint">아직 녹음된 적이 없습니다. 음성채널에서 한 번 녹음되면 색 · 라이엇 ID · 녹음 제외를 바꿀 수 있습니다.</div>}
<div className="pp-links">
{u && (
<Link to={`/users/${me.id}`} className="mini-btn" onClick={onClose}>
내 기록 보기
</Link>
)}
{admin && (
<Link to="/admin" className="mini-btn" onClick={onClose}>
🛡️ 관리 페이지
</Link>
)}
<button className="mini-btn" onClick={logout}>
<ILogout width={13} height={13} /> 로그아웃
</button>
</div>
</motion.div>
);
}

View File

@@ -0,0 +1,75 @@
/**
* 리플레이 스킬 · 설치물 (변환기 objectKinds: GameObject_Sarge_4_Smoke_… 같은 게임 클래스 이름) → 3D 모양 · 색.
* 게임의 효과(파티클)는 그대로 옮길 수 없어서 종류별로 비슷한 모양을 그린다:
* smoke 연막(요원 색 구), fire 장판(바닥 원), burst 폭발 · 섬광(커지며 사라지는 구), pulse 정찰 · 소리(퍼지는 고리),
* projectile 날아가는 것(작은 빛 구), device 설치물 · 함정 · 드론(작은 다이아몬드), spike 스파이크(총 모델 대신 스파이크 3D)
*/
export type AbilityShape = 'smoke' | 'fire' | 'burst' | 'pulse' | 'projectile' | 'device' | 'spike';
export interface AbilityLook {
shape: AbilityShape;
/** 0xRRGGBB */
color: number;
/** 게임 단위(cm) 반지름 */
radiusCm: number;
/** 사라진 시각을 모를 때 보여 줄 시간 (ms) */
defaultMs: number;
/** 요원 코드 (Sarge 등), 모르면 null */
agent: string | null;
}
/** 요원 코드(게임 내부 이름) → 대표 색. 연막 · 장판은 게임에서 보이는 색에 가깝게 */
const AGENT_COLOR: Record<string, number> = {
Sarge: 0xd9a066, // 브림스톤: 주황빛 연막
Wraith: 0x5a3f8f, // 오멘: 짙은 보라
Rift: 0x9a5fd6, // 아스트라: 보라
Smonk: 0xe48ac6, // 클로브: 분홍
Wushu: 0xe9f2ff, // 제트: 흰 바람
Mage: 0x2fa9c9, // 하버: 물
Pandemic: 0x41c25a, // 바이퍼: 초록 독
Phoenix: 0xff7a2f, // 피닉스: 불
Hunter: 0x4fb3ff, // 소바: 정찰
Deadeye: 0xd9b25a, // 체임버: 금색
Killjoy: 0xffd23f, // 킬조이: 노랑
Gumshoe: 0xd7dde6, // 사이퍼: 흰 철사
Thorne: 0x4fe0c9, // 세이지: 청록
Clay: 0xff8a3d, // 레이즈
Breach: 0xff9a3d, // 브리치
Vampire: 0xc23fd6, // 레이나
Stealth: 0x4f6fff, // 요루: 파랑
Guide: 0x7ad65a, // 스카이
BountyHunter: 0x6b3f8f, // 페이드
Grenadier: 0x7fd6ff, // 케이오
AggroBot: 0xb6f04a, // 게코
Sprinter: 0x3fd0ff, // 네온
Cable: 0x9fe8ff, // 데드록
Sequoia: 0xb07cff, // 아이소
Nox: 0x7d8cff, // 바이스
Cashew: 0xffb347, // 테호
Terra: 0xff6fa8, // 웨이레이
Pine: 0x9ad4ff,
Iris: 0xffc0f0,
};
const DEFAULT_COLOR = 0x9fffe0;
/** 클래스 이름에서 요원 코드: GameObject_<요원>_… / Projectile_<요원>_… / Ability_Q_<요원>_… */
export function abilityAgent(kind: string): string | null {
const parts = kind.split('_');
for (const p of parts.slice(1, 4)) if (AGENT_COLOR[p] != null) return p;
return null;
}
export function abilityLook(kind: string): AbilityLook {
const agent = abilityAgent(kind);
const color = agent ? AGENT_COLOR[agent] : DEFAULT_COLOR;
const k = kind.toLowerCase();
const base = { color, agent };
if (kind === 'TimedBomb_C') return { ...base, shape: 'spike', color: 0xff2d3d, radiusCm: 40, defaultMs: 45000 };
if (/^projectile_/.test(k)) return { ...base, shape: 'projectile', radiusCm: /flash/.test(k) ? 25 : 18, defaultMs: 3000 };
// 연막: 관리자 · 생성기는 실제 연막이 아니다
if (/smoke|cloud|nebula|dome/.test(k) && !/manager|spawner|projectile/.test(k)) return { ...base, shape: 'smoke', radiusCm: 450, defaultMs: 15000 };
if (/^patch_|molotov|fire|acid|slow|snakebite|nanoswarm|paint/.test(k)) return { ...base, shape: 'fire', radiusCm: /slow/.test(k) ? 550 : 450, defaultMs: 7000 };
if (/explosion|explode|blast|flash|stun|concuss|beam|strike|decay/.test(k)) return { ...base, shape: 'burst', radiusCm: /strike|beam/.test(k) ? 700 : 400, defaultMs: 1200 };
if (/sonar|ping|reveal|recon|scan|pulse|alarm/.test(k)) return { ...base, shape: 'pulse', radiusCm: 1500, defaultMs: 2500 };
return { ...base, shape: 'device', radiusCm: 30, defaultMs: 12000 };
}

View File

@@ -0,0 +1,385 @@
import * as THREE from 'three';
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';
/**
* 요원 3D 몸 · 총 (tools/map-extract agents → 사이트 서버 /site/maps3d, 맵과 같은 폴더).
* 좌표는 게임(UE) 그대로: cm, 발 = 원점 근처, 앞 = +X (애니메이션의 Root 회전 포함).
* 애니메이션: 요원 glb 안의 기본(ub_rifle · lb_idle/run/walk) + 공용 anims.glb (tools/map-extract anims:
* 앉기 · 점프 · 착지 · 무기별 자세 · 재장전 · 꺼내기 · 던지기 · 칼 · 해체 · 죽음). 공용 애니메이션은 뼈 이름으로 붙이고,
* 이동 트랙은 (요원 참조 자세 − 공용 파일 참조 자세)만큼 옮긴다 (요원마다 키가 달라서).
* 위 몸(ub_*) · 아래 몸(lb_*)을 따로 섞고, 죽으면 온몸(fb_*) 하나만.
*/
const cache = new Map<string, Promise<GLTF>>();
function load(url: string): Promise<GLTF> {
let p = cache.get(url);
if (!p) {
const loader = new GLTFLoader();
loader.setMeshoptDecoder(MeshoptDecoder);
p = loader.loadAsync(url);
p.catch(() => cache.delete(url)); // 실패하면 다음에 다시
cache.set(url, p);
}
return p;
}
export function assetUrl(dir: string, file: string) {
return `/site/maps3d/${encodeURIComponent(dir)}/${encodeURIComponent(file)}`;
}
/** 리플레이 캐릭터 클래스(Wushu_PC_C)의 몸. 없으면 null */
export async function loadAgent(characterClass: string): Promise<GLTF | null> {
const idx = await loadIndex();
const a = idx?.dir ? idx.agents?.[characterClass] : undefined;
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> {
const idx = await loadIndex();
const w = idx?.dir ? idx.weapons?.[name] : undefined;
return w && idx?.dir ? load(assetUrl(idx.dir, w.file)) : null;
}
/** 공용 애니메이션. 없으면 null (요원 glb 안의 기본 애니메이션만 쓴다) */
export async function loadAnims(): Promise<GLTF | null> {
const idx = await loadIndex();
return idx?.dir && idx.anims ? load(assetUrl(idx.dir, idx.anims.file)).catch(() => null) : null;
}
/** 손에 든 것의 자세 종류 */
export type WeaponCat = 'rifle' | 'pistol' | 'sniper' | 'knife' | 'ability';
const PISTOLS = new Set(['Classic', 'Shorty', 'Frenzy', 'Ghost', 'Sheriff', 'Compact Pistol']);
const SNIPERS = new Set(['Marshal', 'Outlaw', 'Operator']);
/** 리플레이 equipKinds 이름 → 자세 종류 */
export function weaponCat(kind: string | undefined | null): WeaponCat {
if (!kind) return 'ability';
if (kind === 'Melee') return 'knife';
if (PISTOLS.has(kind)) return 'pistol';
if (SNIPERS.has(kind)) return 'sniper';
if (/^(Ability_|Equippable_)|Unarmed|Spike|Bomb_Defuser/.test(kind)) return 'ability';
return 'rifle';
}
/** 손에 3D 총을 그릴 것 (스킬 · 맨손 · 해체기는 없음) */
export function isGun(kind: string | undefined | null): kind is string {
return !!kind && !/^(Ability_|Equippable_)|Unarmed|Bomb_Defuser/.test(kind);
}
/** 경기 기록 사망 모션 이름 (TP_Core_Death_Head_Front_SM_Montage) → 공용 애니메이션 이름 (fb_Head_Front_SM) */
export function deathClipName(montage: string | undefined | null): string {
const m = montage?.match(/^TP_Core_Death_(.+?)(_Montage)?$/);
return m ? `fb_${m[1]}` : 'fb_Body_Front_LG';
}
/** 애니메이션이 만든 속도 (cm/s): 이보다 빠르면 빨리 돌린다 */
const RUN_CM_S = 540;
const WALK_CM_S = 300;
const CROUCH_CM_S = 200;
/** 한 프레임의 몸 상태 (뷰어가 리플레이에서 계산해 넣는다). 시간은 모두 리플레이 기준이라 되감기 · 멈춤에도 같은 자세 */
export interface RigInput {
/** 지난 프레임부터 리플레이 시간 (초, 되감으면 0) */
dt: number;
/** 몸 기준 이동 속도 (cm/s, UE: 앞 +X · 오른쪽 +Y) */
fwd: number;
right: number;
/** 위아래 보는 각 (도) */
pitch: number;
crouch: boolean;
/** 공중에 뜬 지 (ms, 땅이면 null) · 내려앉은 지 (ms, 오래됐으면 null) */
airMs: number | null;
landMs: number | null;
cat: WeaponCat;
/** 위 몸 한 번 동작 (재장전 · 꺼내기 · 던지기 · 칼 · 해체): 공용 애니메이션 이름과 시작한 지 (ms). loop 면 반복 */
overlay: { clip: string; ms: number; loop?: boolean } | null;
/** 죽음: 온몸 애니메이션 이름과 죽은 지 (ms) */
death: { clip: string; ms: number } | null;
}
/** 공용 애니메이션을 이 요원 뼈 길이에 맞춘 복제본 (요원 glb 하나당 한 번) */
const retargeted = new WeakMap<object, Map<string, THREE.AnimationClip>>();
function sharedClips(model: THREE.Object3D, agent: GLTF, anims: GLTF | null): Map<string, THREE.AnimationClip> {
const out = new Map<string, THREE.AnimationClip>();
for (const c of agent.animations) out.set(c.name, c);
if (!anims) return out;
let cached = retargeted.get(agent);
if (!cached) {
cached = new Map();
const offset = new Map<string, THREE.Vector3>();
const delta = (bone: string) => {
let d = offset.get(bone);
if (!d) {
const mine = model.getObjectByName(bone);
const core = anims.scene.getObjectByName(bone);
d = mine && core ? mine.position.clone().sub(core.position) : new THREE.Vector3();
offset.set(bone, d);
}
return d;
};
const has = new Set<string>();
model.traverse((o) => has.add(o.name));
for (const c of anims.animations) {
// 이 요원에게 없는 뼈(눈꺼풀 · 카메라 등)는 뺀다
const own = c.tracks.filter((tr) => has.has(tr.name.slice(0, tr.name.lastIndexOf('.'))));
const tracks = own.map((tr) => {
if (!tr.name.endsWith('.position')) return tr;
const d = delta(tr.name.slice(0, -'.position'.length));
if (!d.lengthSq()) return tr;
const t2 = tr.clone();
const v = t2.values;
for (let i = 0; i < v.length; i += 3) {
v[i] += d.x;
v[i + 1] += d.y;
v[i + 2] += d.z;
}
return t2;
});
cached.set(c.name, new THREE.AnimationClip(c.name, c.duration, tracks));
}
retargeted.set(agent, cached);
}
for (const [n, c] of cached) out.set(n, c); // 공용이 있으면 공용 (ub_rifle 등 같은 이름은 공용 자세가 게임과 같다)
return out;
}
/** 선수 한 명의 몸 (복제본) · 애니메이션 · 손에 든 총 */
export class AgentRig {
/** UE 좌표(cm) 공간의 선수 자리. 뷰어가 위치 · yaw 를 넣는다 */
readonly root = new THREE.Group();
private readonly model: THREE.Object3D;
private readonly mixer: THREE.AnimationMixer;
private readonly clips: Map<string, THREE.AnimationClip>;
private readonly actions = new Map<string, THREE.AnimationAction>();
private readonly hand: THREE.Object3D | null;
private readonly gunSlot = new THREE.Group();
/** 총구 불꽃 (사격 순간에 잠깐) */
readonly muzzle: THREE.Sprite;
private gunName: string | null = null;
private gunReq = 0;
private gunTip = 60;
private readonly tmp = new THREE.Vector3();
/** 사격 반동 (0~1, 줄어든다) */
private kick = 0;
private shotMs: number | null = null;
constructor(gltf: GLTF, anims: GLTF | null) {
this.model = cloneSkinned(gltf.scene);
this.model.traverse((o) => {
const m = o as THREE.Mesh;
if (m.isMesh) m.frustumCulled = false;
});
this.root.add(this.model);
this.root.add(this.gunSlot);
this.muzzle = new THREE.Sprite(new THREE.SpriteMaterial({ map: muzzleTexture(), color: 0xffd38a, blending: THREE.AdditiveBlending, depthWrite: false, transparent: true }));
this.muzzle.scale.setScalar(26);
this.muzzle.visible = false;
this.gunSlot.add(this.muzzle);
this.mixer = new THREE.AnimationMixer(this.model);
this.clips = sharedClips(this.model, gltf, anims);
// R_WeaponPoint 는 공용 애니메이션이 움직이지 않아 손에서 떨어져 있다 → 손목(R_Hand) 기준
this.hand = this.model.getObjectByName('R_Hand') ?? null;
}
private action(name: string): THREE.AnimationAction | null {
let a = this.actions.get(name);
if (a) return a;
const c = this.clips.get(name);
if (!c) return null;
a = this.mixer.clipAction(c);
a.play();
a.setEffectiveWeight(0);
this.actions.set(name, a);
return a;
}
/** 들고 있는 총 바꾸기 (이름 없으면 맨손) */
setWeapon(name: string | null) {
if (name === this.gunName) return;
this.gunName = name;
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)
.then((g) => {
if (!g || req !== this.gunReq) return;
const gun = g.scene.clone(true);
gun.traverse((o) => {
const m = o as THREE.Mesh;
if (m.isMesh) m.frustumCulled = false;
});
gun.position.x = 7; // 손목 → 손바닥 (총 원점 = 손잡이)
if (name === 'Melee') gun.rotation.y = Math.PI / 2; // 칼은 날이 +Z → 앞(+X)으로
const box = new THREE.Box3().setFromObject(gun);
this.gunTip = Number.isFinite(box.max.x) ? box.max.x : 60;
this.gunSlot.add(gun);
})
.catch(() => {});
}
/** 마지막 사격에서 지난 시간 (ms, 없으면 null): 반동 · 총구 불꽃 */
setShot(ms: number | null) {
this.shotMs = ms != null && ms >= 0 ? ms : null;
this.kick = this.shotMs != null && this.shotMs < 90 ? 1 - this.shotMs / 90 : 0;
}
/** 이 애니메이션이 있는지 (뷰어가 대신 할 것을 고를 때) */
has(name: string) {
return this.clips.has(name);
}
update(inp: RigInput) {
const set = (name: string, w: number, opts?: { time?: number; scale?: number }) => {
const a = w > 0.001 ? this.action(name) : this.actions.get(name);
if (!a) return w > 0.001 ? false : true;
a.setEffectiveWeight(w);
if (opts?.time != null) {
a.paused = true;
a.time = Math.min(opts.time, a.getClip().duration - 1e-3);
} else {
a.paused = false;
a.setEffectiveTimeScale(opts?.scale ?? 1);
}
return true;
};
const zero = new Set(this.actions.keys());
const use = (name: string, w: number, opts?: { time?: number; scale?: number }) => {
if (w <= 0.001) return;
if (set(name, w, opts)) zero.delete(name);
};
if (inp.death && this.clips.has(inp.death.clip)) {
// 죽음: 온몸 한 번 (끝 자세로 누워 있다)
use(inp.death.clip, 1, { time: inp.death.ms / 1000 });
} else if (inp.death) {
use('fb_Body_Front_LG', 1, { time: inp.death.ms / 1000 });
} else {
this.lowerBody(inp, use);
this.upperBody(inp, use);
}
for (const n of zero) this.actions.get(n)?.setEffectiveWeight(0);
this.mixer.update(inp.dt);
// 총: 오른손 자리에, 몸 앞(+X)을 보는 방향 + 위아래 각, 사격하면 뒤로 살짝
this.muzzle.visible = this.kick > 0.55 && this.gunName != null && this.gunName !== 'Melee';
if (this.muzzle.visible) {
this.muzzle.position.set(this.gunTip + 6, 0, 2);
this.muzzle.material.rotation = Math.random() * Math.PI;
}
if (this.hand && this.gunSlot.children.length > 1) {
this.root.updateWorldMatrix(true, true);
this.hand.getWorldPosition(this.tmp);
this.root.worldToLocal(this.tmp);
this.gunSlot.position.copy(this.tmp);
const pr = (-THREE.MathUtils.clamp(inp.pitch, -80, 80) * Math.PI) / 180;
this.gunSlot.rotation.set(0, pr - this.kick * 0.12, 0);
this.gunSlot.translateX(-this.kick * 4);
}
this.gunSlot.visible = !inp.death;
}
private lowerBody(inp: RigInput, use: (n: string, w: number, o?: { time?: number; scale?: number }) => void) {
const has = (n: string) => this.clips.has(n);
// 공중: 뛴 처음 0.45초는 점프 동작, 그 뒤는 떨어지는 자세
if (inp.airMs != null && (has('lb_fall') || has('lb_jump'))) {
const jumpW = has('lb_jump') ? 1 - THREE.MathUtils.smoothstep(inp.airMs, 300, 500) : 0;
if (jumpW > 0) use('lb_jump', jumpW, { time: inp.airMs / 1000 });
if (1 - jumpW > 0) use(has('lb_fall') ? 'lb_fall' : 'lb_jump', 1 - jumpW, has('lb_fall') ? undefined : { time: 0.45 });
return;
}
const speed = Math.hypot(inp.fwd, inp.right);
const moving = THREE.MathUtils.smoothstep(speed, 40, 140);
const sum = Math.abs(inp.fwd) + Math.abs(inp.right) || 1;
const dir = (n: number) => (moving * Math.max(0, n)) / sum;
// 내려앉음: 0.35초 동안 착지 동작을 섞는다
const landW = inp.landMs != null && has('lb_land') ? 1 - THREE.MathUtils.smoothstep(inp.landMs, 150, 450) : 0;
const rest = 1 - landW;
if (landW > 0) use('lb_land', landW, { time: inp.landMs! / 1000 });
const crouch = inp.crouch && has('lb_crouch');
let g: string;
let base: number;
if (crouch) {
g = 'lb_crouch';
base = CROUCH_CM_S;
use('lb_crouch', rest * (1 - moving));
} else {
g = speed > 400 ? 'lb_run' : 'lb_walk';
base = speed > 400 ? RUN_CM_S : WALK_CM_S;
use('lb_idle', rest * (1 - moving));
}
const scale = THREE.MathUtils.clamp(speed / base, 0.6, 1.5);
use(`${g}N`, rest * dir(inp.fwd), { scale });
use(`${g}S`, rest * dir(-inp.fwd), { scale });
use(`${g}E`, rest * dir(inp.right), { scale });
use(`${g}W`, rest * dir(-inp.right), { scale });
}
private upperBody(inp: RigInput, use: (n: string, w: number, o?: { time?: number; scale?: number }) => void) {
const has = (n: string) => this.clips.has(n);
let ow = 0;
if (inp.overlay && has(inp.overlay.clip)) {
const dur = this.clips.get(inp.overlay.clip)!.duration * 1000;
const ms = inp.overlay.loop ? inp.overlay.ms % dur : inp.overlay.ms;
if (inp.overlay.loop || ms < dur) {
// 들어갈 때 · 끝날 때 0.12초씩 섞는다
ow = inp.overlay.loop ? THREE.MathUtils.smoothstep(inp.overlay.ms, 0, 120) : Math.min(THREE.MathUtils.smoothstep(ms, 0, 120), 1 - THREE.MathUtils.smoothstep(ms, dur - 150, dur));
use(inp.overlay.clip, ow, { time: ms / 1000 });
}
}
const cat = inp.cat;
let pose = `ub_${cat}${inp.crouch ? 'Crouch' : ''}`;
if (!has(pose)) pose = `ub_${cat}`;
if (!has(pose)) pose = 'ub_rifle';
let rest = 1 - ow;
// 사격: 반동 자세 (쏜 뒤 0.35초 동안 줄어든다)
const fire = `ub_${cat}Fire`;
if (rest > 0 && this.shotMs != null && this.shotMs < 350 && has(fire)) {
const fw = rest * (1 - THREE.MathUtils.smoothstep(this.shotMs, 120, 350));
use(fire, fw, { time: this.shotMs / 1000 });
rest -= fw;
}
// 조준 각: 위(+90°) · 아래(-90°) 자세를 비율로 섞는다 (게임의 AimOffset)
const up = THREE.MathUtils.clamp(inp.pitch / 90, 0, 1);
const down = THREE.MathUtils.clamp(-inp.pitch / 90, 0, 1);
const hasUp = has(`${pose}Up`) && has(`${pose}Down`);
if (hasUp) {
use(`${pose}Up`, rest * up);
use(`${pose}Down`, rest * down);
use(pose, rest * (1 - up - down));
} else use(pose, rest);
}
dispose() {
this.mixer.stopAllAction();
this.gunSlot.clear();
}
}
let muzzleTex: THREE.Texture | null = null;
/** 총구 불꽃 (가운데가 밝은 별 모양) */
function muzzleTexture() {
if (muzzleTex) return muzzleTex;
const c = document.createElement('canvas');
c.width = c.height = 64;
const g = c.getContext('2d')!;
const rg = g.createRadialGradient(32, 32, 0, 32, 32, 32);
rg.addColorStop(0, 'rgba(255,255,240,1)');
rg.addColorStop(0.25, 'rgba(255,210,120,0.9)');
rg.addColorStop(1, 'rgba(255,120,20,0)');
g.fillStyle = rg;
g.beginPath();
for (let i = 0; i < 12; i++) {
const a = (i / 12) * Math.PI * 2;
const r = i % 2 ? 12 : 32;
g.lineTo(32 + Math.cos(a) * r, 32 + Math.sin(a) * r);
}
g.fill();
muzzleTex = new THREE.CanvasTexture(c);
muzzleTex.colorSpace = THREE.SRGBColorSpace;
return muzzleTex;
}

View File

@@ -15,6 +15,8 @@ import type {
BundleInfo,
BundleImportResult,
NoisePhrase,
AppRole,
AppUserRow,
} from '@gvr/shared';
import { reportClient } from './report';
@@ -33,11 +35,16 @@ export class ApiError extends Error {
constructor(
public status: number,
public code: string,
/** 서버가 함께 보낸 설명 (있으면) */
public detail?: string,
) {
super(`${status} ${code}`);
}
}
/** 경기 탭 필터 */
export type MatchHas = 'timeline' | 'voice';
async function request<T>(path: string, init: RequestInit = {}): Promise<T> {
let res: Response;
try {
@@ -54,8 +61,11 @@ async function request<T>(path: string, init: RequestInit = {}): Promise<T> {
return (await res.json()) as T;
}
let code = 'error';
let detail: string | undefined;
try {
code = ((await res.json()) as { error?: string }).error ?? code;
const b = (await res.json()) as { error?: string; message?: string };
code = b.error ?? code;
if (typeof b.message === 'string') detail = b.message;
} catch {
/* 본문 없음 */
}
@@ -64,7 +74,7 @@ async function request<T>(path: string, init: RequestInit = {}): Promise<T> {
else if (res.status === 503 && code === 'device_offline') emit('device_offline');
// 게임 PC 쪽 오류 · 시간 초과는 사이트 로그에도 남긴다 (게임 PC 꺼짐은 서버가 이미 남김)
else if (res.status >= 500) reportClient('error', `요청 실패 ${res.status} ${code}: ${init.method ?? 'GET'} ${path.split('?')[0]}`);
throw new ApiError(res.status, code);
throw new ApiError(res.status, code, detail);
}
export interface Me {
@@ -72,6 +82,16 @@ export interface Me {
isOwner: boolean;
/** 사이트 로그를 볼 수 있는지 (관리자 · 최고 관리자, v1.3.6~) */
canViewLogs?: boolean;
/** 앱 역할 (등록 안 된 멤버는 null, v1.6.0~) */
role?: AppRole | null;
}
/** 관리 화면 머리 (v1.6.0) */
export interface AdminOverview {
device: DeviceStatus & { guildId: string | null };
latest: { version: string; url: string; publishedAt: string | null } | null;
role: AppRole;
serverVersion: string;
}
export interface StatusResponse {
device: DeviceStatus;
@@ -114,6 +134,17 @@ export const api = {
/** 관리자(OWNER_DISCORD_IDS) 전용: 게임 PC 1회용 등록 코드 (10분) */
registrationCode: () => request<{ code: string; expiresAt: number }>('/admin/registration-code', { method: 'POST' }),
status: () => request<StatusResponse>('/api/status'),
// 내 정보 · 관리 화면 (v1.6.0)
setMyName: (name: string) => request<{ user: Me['user']; customName: string | null }>('/site/profile/name', { method: 'PUT', body: JSON.stringify({ name }) }),
/** 색 · 녹음 제외 · 라이엇 ID (게임 PC 앱 v1.6.0~, 본인 또는 관리자) */
updateUser: (id: string, patch: { color?: string; excluded?: boolean; riotIds?: string[] }) =>
request<{ user: User; taken: string[] }>(`/api/users/${encodeURIComponent(id)}`, { method: 'PATCH', body: JSON.stringify(patch) }),
adminOverview: () => request<AdminOverview>('/site/admin/overview'),
adminUsers: () => request<{ users: AppUserRow[]; names: Record<string, string> }>('/site/admin/users'),
adminSetName: (id: string, name: string) => request<{ names: Record<string, string> }>('/site/admin/names', { method: 'PUT', body: JSON.stringify({ id, name }) }),
adminAddUser: (id: string, role: 'admin' | 'user') => request<{ users: AppUserRow[] }>('/site/admin/users', { method: 'POST', body: JSON.stringify({ id, role }) }),
adminSetRole: (id: string, role: 'admin' | 'user') => request<{ users: AppUserRow[] }>(`/site/admin/users/${encodeURIComponent(id)}`, { method: 'PATCH', body: JSON.stringify({ role }) }),
adminRemoveUser: (id: string) => request<{ users: AppUserRow[] }>(`/site/admin/users/${encodeURIComponent(id)}`, { method: 'DELETE' }),
overview: () => request<Overview>('/api/overview'),
users: () => request<User[]>('/api/users'),
user: (id: string) => request<UserProfile>(`/api/users/${encodeURIComponent(id)}`),
@@ -134,10 +165,13 @@ 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 앱부터, 예전 앱은 무시하고 다 보냄)
matches: (o: { game?: GameType; limit?: number; before?: number; has?: MatchHas } = {}) => request<MatchSummary[]>(`/api/matches${qs(o)}`),
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'),
@@ -198,6 +232,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' }),
};

View File

@@ -0,0 +1,230 @@
/**
* 발로란트 조준점: 리플레이의 선수 조준점(변환기 players[].crosshair) · 사이트 전체 조준점 설정 · 조준점 코드 · 그리기.
* 크기는 발로란트 설정 값 그대로 화면 픽셀로 그린다.
*/
export interface CrossLines {
on: boolean;
length: number;
/** 세로 길이 (따로 쓰지 않으면 length 와 같다) */
vLength: number;
thickness: number;
offset: number;
opacity: number;
moveError: boolean;
fireError: boolean;
moveScale: number;
fireScale: number;
}
export interface CrossSet {
/** 보이는 색 #rrggbb */
color: string;
outline: boolean;
outlineThickness: number;
outlineOpacity: number;
dot: boolean;
dotSize: number;
dotOpacity: number;
inner: CrossLines;
outer: CrossLines;
}
export interface SniperDot {
color: string;
dot: boolean;
dotSize: number;
dotOpacity: number;
}
export interface CrosshairProfile {
primary: CrossSet;
ads: CrossSet;
sniper: SniperDot;
/** 정조준에도 주 조준점 */
adsFromPrimary: boolean;
advanced: boolean;
}
/** 리플레이 기록: t(ms) 부터 이 설정 */
export interface CrosshairAt extends CrosshairProfile {
t: number;
name: string;
}
/** 발로란트 색 목록 (조준점 코드 c 번호 순, 8 = 사용자 지정) */
export const CROSS_COLORS: { name: string; hex: string }[] = [
{ name: '흰색', hex: '#ffffff' },
{ name: '초록색', hex: '#00ff00' },
{ name: '연두색', hex: '#7fff00' },
{ name: '황록색', hex: '#dfff00' },
{ name: '노란색', hex: '#ffff00' },
{ name: '청록색', hex: '#00ffff' },
{ name: '분홍색', hex: '#ff00ff' },
{ name: '빨간색', hex: '#ff0000' },
];
const INNER: CrossLines = { on: true, length: 6, vLength: 6, thickness: 2, offset: 3, opacity: 0.8, moveError: false, fireError: true, moveScale: 1, fireScale: 1 };
const OUTER: CrossLines = { on: true, length: 2, vLength: 2, thickness: 2, offset: 10, opacity: 0.35, moveError: true, fireError: true, moveScale: 1, fireScale: 1 };
const SET: CrossSet = { color: '#ffffff', outline: true, outlineThickness: 1, outlineOpacity: 0.5, dot: false, dotSize: 2, dotOpacity: 1, inner: INNER, outer: OUTER };
/** 발로란트 기본 조준점 */
export const DEFAULT_CROSSHAIR: CrosshairProfile = {
primary: SET,
ads: SET,
sniper: { color: '#ff0000', dot: true, dotSize: 1, dotOpacity: 0.75 },
adsFromPrimary: true,
advanced: false,
};
/** t 시점 선수 조준점 (그 전이면 첫 기록, 기록이 없으면 null) */
export function crosshairAt(list: CrosshairAt[] | null | undefined, t: number): CrosshairAt | null {
if (!list?.length) return null;
let c = list[0];
for (const x of list) {
if (x.t > t) break;
c = x;
}
return c;
}
/** 지금 쓸 조준점 묶음: 정조준(저격총 아님) 중이고 정조준 조준점을 따로 쓰면 ads */
export function crossFor(p: CrosshairProfile, ads: boolean): CrossSet {
return ads && p.advanced && !p.adsFromPrimary ? p.ads : p.primary;
}
const num = (v: string | undefined, d: number) => {
const n = v == null ? NaN : Number(v);
return Number.isFinite(n) ? n : d;
};
/**
* 발로란트 조준점 코드 (설정 → 조준점 → 프로필 내보내기, 예: 0;P;c;5;h;0;0l;4;0o;2;0a;1;0f;0;1b;0) → 설정.
* 코드에 없는 값은 발로란트 기본값. 형식이 아니면 null
*/
export function parseCrosshairCode(code: string): CrosshairProfile | null {
const tok = code.trim().split(';').map((s) => s.trim());
if (tok.length < 1 || !/^\d+$/.test(tok[0])) return null;
const sec: Record<'G' | 'P' | 'A' | 'S', Record<string, string>> = { G: {}, P: {}, A: {}, S: {} };
let cur: keyof typeof sec = 'G';
for (let i = 1; i < tok.length; i++) {
const k = tok[i];
if (k === 'P' || k === 'A' || k === 'S') {
cur = k;
continue;
}
if (!k) continue;
if (i + 1 >= tok.length) return null;
sec[cur][k] = tok[++i];
}
const color = (s: Record<string, string>, d: string) => {
const c = num(s.c, -1);
if ((c === 8 || s.b === '1') && /^[0-9a-fA-F]{6}/.test(s.u ?? '')) return `#${s.u.slice(0, 6).toLowerCase()}`;
return CROSS_COLORS[c]?.hex ?? d;
};
const lines = (s: Record<string, string>, p: '0' | '1', d: CrossLines): CrossLines => {
const length = num(s[p + 'l'], d.length);
return {
on: s[p + 'b'] !== '0' && (s[p + 'b'] === '1' || d.on),
length,
vLength: s[p + 'g'] === '1' ? num(s[p + 'v'], length) : length,
thickness: num(s[p + 't'], d.thickness),
offset: num(s[p + 'o'], d.offset),
opacity: num(s[p + 'a'], d.opacity),
moveError: s[p + 'm'] != null ? s[p + 'm'] === '1' : d.moveError,
fireError: s[p + 'f'] != null ? s[p + 'f'] === '1' : d.fireError,
moveScale: num(s[p + 's'], d.moveScale),
fireScale: num(s[p + 'e'], d.fireScale),
};
};
const set = (s: Record<string, string>): CrossSet => ({
color: color(s, SET.color),
outline: s.h != null ? s.h === '1' : SET.outline,
outlineThickness: num(s.t, SET.outlineThickness),
outlineOpacity: num(s.o, SET.outlineOpacity),
dot: s.d != null ? s.d === '1' : SET.dot,
dotSize: num(s.z, SET.dotSize),
dotOpacity: num(s.a, SET.dotOpacity),
inner: lines(s, '0', INNER),
outer: lines(s, '1', OUTER),
});
const S = sec.S;
const sd = DEFAULT_CROSSHAIR.sniper;
return {
primary: set(sec.P),
ads: set(sec.A),
sniper: {
color: color(S, sd.color),
dot: S.d != null ? S.d === '1' : sd.dot,
dotSize: num(S.s, sd.dotSize),
dotOpacity: num(S.o, sd.dotOpacity),
},
adsFromPrimary: sec.G.p !== '0',
advanced: sec.G.s === '1',
};
}
/** 사격 · 이동으로 벌어지는 정도 (픽셀): fire 0..1 (막 쏨 = 1), move 0..1 */
export interface Spread {
fire: number;
move: number;
}
const FIRE_PX = 6;
const MOVE_PX = 4;
function rgba(hex: string, a: number) {
const n = parseInt(hex.slice(1, 7), 16);
return `rgba(${(n >> 16) & 255},${(n >> 8) & 255},${n & 255},${Math.max(0, Math.min(1, a))})`;
}
/** (cx, cy) 를 가운데로 조준점을 그린다. 크기는 CSS 픽셀 (ctx 는 devicePixelRatio 로 미리 늘려 둔다) */
export function drawCrosshair(ctx: CanvasRenderingContext2D, cx: number, cy: number, s: CrossSet, spread: Spread = { fire: 0, move: 0 }) {
const rects: [number, number, number, number, number][] = [];
const line = (l: CrossLines) => {
if (!l.on || l.opacity <= 0 || l.thickness <= 0) return;
const gap = l.offset + (l.fireError ? spread.fire * FIRE_PX * l.fireScale : 0) + (l.moveError ? spread.move * MOVE_PX * l.moveScale : 0);
const th = l.thickness;
if (l.length > 0) {
rects.push([cx - gap - l.length, cy - th / 2, l.length, th, l.opacity]);
rects.push([cx + gap, cy - th / 2, l.length, th, l.opacity]);
}
if (l.vLength > 0) {
rects.push([cx - th / 2, cy - gap - l.vLength, th, l.vLength, l.opacity]);
rects.push([cx - th / 2, cy + gap, th, l.vLength, l.opacity]);
}
};
line(s.outer);
line(s.inner);
if (s.dot && s.dotSize > 0 && s.dotOpacity > 0) rects.push([cx - s.dotSize / 2, cy - s.dotSize / 2, s.dotSize, s.dotSize, s.dotOpacity]);
// 픽셀 경계에 맞춘다 (두께 1 · 2 선이 흐려지지 않게)
const px = rects.map(([x, y, w, h, a]) => [Math.round(x), Math.round(y), Math.max(1, Math.round(w)), Math.max(1, Math.round(h)), a] as const);
if (s.outline && s.outlineThickness > 0 && s.outlineOpacity > 0) {
const o = s.outlineThickness;
ctx.fillStyle = rgba('#000000', s.outlineOpacity);
for (const [x, y, w, h] of px) ctx.fillRect(x - o, y - o, w + o * 2, h + o * 2);
}
for (const [x, y, w, h, a] of px) {
ctx.fillStyle = rgba(s.color, a);
ctx.fillRect(x, y, w, h);
}
}
/** 저격총 조준경 가운데 점 */
export function drawSniperDot(ctx: CanvasRenderingContext2D, cx: number, cy: number, d: SniperDot) {
if (!d.dot || d.dotSize <= 0 || d.dotOpacity <= 0) return;
ctx.fillStyle = rgba(d.color, d.dotOpacity);
ctx.beginPath();
ctx.arc(cx, cy, Math.max(1, d.dotSize * 2), 0, Math.PI * 2);
ctx.fill();
}
/** 캔버스를 화면 크기 · devicePixelRatio 에 맞추고 지운 뒤 가운데 좌표 */
export function prepCanvas(c: HTMLCanvasElement): { ctx: CanvasRenderingContext2D; cx: number; cy: number } | null {
const ctx = c.getContext('2d');
if (!ctx) return null;
const dpr = window.devicePixelRatio || 1;
const w = c.clientWidth;
const h = c.clientHeight;
if (c.width !== Math.round(w * dpr) || c.height !== Math.round(h * dpr)) {
c.width = Math.round(w * dpr);
c.height = Math.round(h * dpr);
}
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, w, h);
return { ctx, cx: Math.floor(w / 2), cy: Math.floor(h / 2) };
}

View File

@@ -10,10 +10,17 @@ interface Index {
dir: string | null;
version: string | null;
maps: Record<string, { code: string; file: string; bytes: number; triangles: number }>;
/** 요원 몸 (리플레이 캐릭터 클래스 → glb), 무기 (equipKinds 이름 → glb). 옛 index 에는 없다 */
agents?: Record<string, { code: string; file: string; bytes: number }>;
weapons?: Record<string, { file: string; bytes: number }>;
/** 모든 요원 공용 애니메이션 (앉기 · 점프 · 무기별 자세 · 재장전 · 죽음 …). 옛 index 에는 없다 */
anims?: { file: string; bytes: number } | null;
/** 스킬 모델 · 파티클 · 텍스처 (abilities.json). 옛 index 에는 없다 */
abilities?: { file: string; bytes: number } | null;
}
let indexP: Promise<Index | null> | null = null;
function loadIndex(): Promise<Index | null> {
export function loadIndex(): Promise<Index | null> {
indexP ??= fetch('/site/maps3d', { credentials: 'same-origin' })
.then((r) => (r.ok ? (r.json() as Promise<Index>) : null))
.catch(() => null)
@@ -40,22 +47,73 @@ export async function findMap3d(mapUrl: string): Promise<Map3dInfo | null> {
return hit ? { url: `/site/maps3d/${encodeURIComponent(idx.dir)}/${encodeURIComponent(hit.file)}`, bytes: hit.bytes, triangles: hit.triangles, version: idx.version } : null;
}
/** glb 를 받아 메시 하나로. onProgress: 0~1 */
export function loadMap3d(url: string, material: THREE.Material, onProgress?: (p: number) => void): Promise<THREE.Object3D> {
/**
* glb 를 받아 장면 하나로. onProgress: 0~1
* 재질이 든 glb(텍스처 · 색)는 그 재질에 천장 자르기만 붙이고, 재질이 없는 옛 glb 는 fallback(높이 색) 재질을 쓴다.
* 두 층 재질(extras.blend = {texture, tint})은 정점 색 R 로 A 층(기본 텍스처) · B 층을 섞는다.
* 구운 조명(extras.lightmap = {k}): 추출기가 aoMap(irr) · emissiveMap(sh) 자리에 TEXCOORD_1 로 넣어 둔 아틀라스로
* 색 = 텍스처 × irr × K × max(0, 1 + dot(sh, N.yzx)) (N 은 UE 월드 법선, tools/map-extract/src/Lightmaps.cs). 장면 조명은 쓰지 않는다.
*/
export function loadMap3d(url: string, clip: THREE.Plane, fallback: () => THREE.Material, onProgress?: (p: number) => void): Promise<THREE.Object3D> {
const loader = new GLTFLoader();
loader.setMeshoptDecoder(MeshoptDecoder);
return new Promise((resolve, reject) => {
loader.load(
url,
(gltf) => {
const hasMats = !!gltf.parser.json.materials?.length;
const fb = hasMats ? null : fallback();
const pending: Promise<unknown>[] = [];
const done = new Map<THREE.Material, THREE.Material>();
gltf.scene.traverse((o) => {
const mesh = o as THREE.Mesh;
if (mesh.isMesh) {
mesh.material = material;
mesh.frustumCulled = false;
if (!mesh.isMesh) return;
mesh.frustumCulled = false;
if (fb) {
mesh.material = fb;
return;
}
const src = mesh.material as THREE.MeshStandardMaterial;
const blend = src.userData?.blend as { texture?: number; tint?: number[] } | undefined;
const lm = src.userData?.lightmap as { k?: number } | undefined;
// 정점 색은 색칠이 아니라 두 층 섞는 비율이다
const col = mesh.geometry.getAttribute('color');
if (col) {
mesh.geometry.setAttribute('blendCol', col);
mesh.geometry.deleteAttribute('color');
}
let mat = done.get(src);
if (!mat) {
const m = src.clone() as THREE.MeshStandardMaterial;
m.vertexColors = false;
// 게임(UE) 좌표를 그대로 쓰고 행렬로 옮기므로 면 방향이 뒤집혀 보일 수 있다 → 양면
m.side = THREE.DoubleSide;
m.clippingPlanes = [clip];
m.clipShadows = true;
m.roughness = 1;
m.metalness = 0;
if (m.map) m.map.anisotropy = 4;
if (m.transparent) m.depthWrite = false;
const shader: ShaderParts = {};
if (lm?.k && m.aoMap && m.emissiveMap) {
shader.lightmap = { k: lm.k };
for (const t of [m.aoMap, m.emissiveMap]) {
t.colorSpace = THREE.NoColorSpace; // 셰이더에서 직접 푼다
t.anisotropy = 4;
}
} else {
// 조명 없는 재질에 붙은 조명 텍스처는 쓰지 않는다
m.aoMap = null;
m.emissiveMap = null;
}
const ready = blend ? blendLayer(gltf.parser, blend).then((b) => void (shader.blend = b)) : Promise.resolve();
pending.push(ready.then(() => installShader(m, shader)));
done.set(src, m);
mat = m;
}
mesh.material = mat;
});
resolve(gltf.scene);
void Promise.all(pending).then(() => resolve(gltf.scene), reject);
},
(e) => onProgress?.(e.total ? e.loaded / e.total : 0),
reject,
@@ -63,6 +121,86 @@ export function loadMap3d(url: string, material: THREE.Material, onProgress?: (p
});
}
interface ShaderParts {
blend?: { texB: THREE.Texture | null; tintB: THREE.Color };
lightmap?: { k: number };
}
/** B 층 텍스처 · 색 (셰이더에서 정점 색 R 로 섞는다) */
async function blendLayer(parser: { getDependency: (type: string, i: number) => Promise<unknown> }, b: { texture?: number; tint?: number[] }) {
let texB: THREE.Texture | null = null;
if (b.texture != null) {
// 텍스처 하나를 못 읽어도 맵 전체를 버리지 않고 B 층 색만 쓴다
texB = (await parser.getDependency('texture', b.texture).catch(() => null)) as THREE.Texture | null;
if (texB) {
texB.colorSpace = THREE.SRGBColorSpace;
texB.anisotropy = 4;
}
}
const tintB = new THREE.Color().setRGB(b.tint?.[0] ?? 1, b.tint?.[1] ?? 1, b.tint?.[2] ?? 1, THREE.SRGBColorSpace);
return { texB, tintB };
}
/** 두 층 섞기 · 구운 조명을 셰이더에 넣는다 */
function installShader(m: THREE.MeshStandardMaterial, parts: ShaderParts) {
const { blend, lightmap } = parts;
if (!blend && !lightmap) return;
const md = m as unknown as { defines?: Record<string, string> };
md.defines = { ...(md.defines ?? {}) };
if (blend) {
md.defines.GVR_BLEND = '';
if (blend.texB) md.defines.GVR_BLEND_MAP = '';
}
if (lightmap) md.defines.GVR_LIGHTMAP = '';
// 같은 프로그램을 나눠 쓰도록 (uniform 값만 재질마다 다름)
m.customProgramCacheKey = () => `gvr:${blend ? (blend.texB ? 'bm' : 'b') : ''}:${lightmap ? 'l' : ''}`;
m.onBeforeCompile = (sh) => {
if (blend) {
sh.uniforms.mapB = { value: blend.texB };
sh.uniforms.tintB = { value: blend.tintB };
sh.vertexShader = sh.vertexShader
.replace('#include <common>', '#include <common>\nattribute vec4 blendCol;\nvarying float vBlend;\nvarying vec2 vUvB;')
.replace('#include <uv_vertex>', '#include <uv_vertex>\nvBlend = blendCol.r;\nvUvB = uv;');
sh.fragmentShader = sh.fragmentShader
.replace('#include <common>', '#include <common>\nuniform sampler2D mapB;\nuniform vec3 tintB;\nvarying float vBlend;\nvarying vec2 vUvB;')
.replace(
'#include <map_fragment>',
`#include <map_fragment>
#ifdef GVR_BLEND_MAP
vec3 layerB = texture2D(mapB, vUvB).rgb * tintB;
#else
vec3 layerB = tintB;
#endif
diffuseColor.rgb = mix(layerB, diffuseColor.rgb, vBlend);`,
);
}
if (lightmap) {
sh.uniforms.lmK = { value: lightmap.k };
sh.vertexShader = sh.vertexShader
.replace('#include <common>', '#include <common>\nvarying vec3 vUeN;')
.replace('#include <beginnormal_vertex>', '#include <beginnormal_vertex>\nvUeN = objectNormal;');
sh.fragmentShader = sh.fragmentShader
.replace('#include <common>', '#include <common>\nuniform float lmK;\nvarying vec3 vUeN;')
.replace(
'#include <opaque_fragment>',
`{
// 구운 조명 (UE HQ 라이트맵을 추출기가 풀어 둔 값): irr 는 sRGB, sh 는 ±2 → 0~1
vec3 lmIrr = texture2D(aoMap, vAoMapUv).rgb;
lmIrr = mix(lmIrr / 12.92, pow((lmIrr + 0.055) / 1.055, vec3(2.4)), step(vec3(0.04045), lmIrr));
vec3 lmSh = texture2D(emissiveMap, vEmissiveMapUv).rgb * 4.0 - 2.0;
vec3 n = normalize(vUeN);
float lmDir = max(0.0, 1.0 + dot(lmSh, n.yzx));
vec3 lit = diffuseColor.rgb * lmIrr * (lmK * lmDir);
// 밝은 곳이 하얗게 날아가지 않게 살짝 누른다
outgoingLight = lit / (1.0 + max(lit - 0.8, 0.0));
}
#include <opaque_fragment>`,
);
}
};
m.needsUpdate = true;
}
/** UE 월드 좌표(cm) → 3D 리플레이 화면 좌표. ReplayViewer 의 toWorld 와 같은 식을 행렬로 */
export function worldMatrix(T: { xMultiplier: number; yMultiplier: number; xScalarToAdd: number; yScalarToAdd: number }, S: number, zBase: number, vex: number) {
const h = Math.abs(T.xMultiplier) * S * vex;

View File

@@ -1,9 +1,13 @@
import type { KillData, MatchDetail } from '@gvr/shared';
import type { CrosshairAt } from './crosshair';
/** tools/replay-extract (gvr-replay v1) 출력. t 는 리플레이 시작부터 ms, 좌표는 게임 월드 단위 */
/**
* tools/replay-extract (gvr-replay v1 · v2) 출력. t 는 리플레이 시작부터 ms, 좌표는 게임 월드 단위(cm).
* v2 는 v1 열을 그대로 두고 뒤에 열 · 필드를 더했다 (옛 JSON 은 없는 필드 → 빈 것으로 본다).
*/
export interface ReplayFile {
format: 'gvr-replay';
v: 1;
v: 1 | 2;
matchId: string | null;
map: string | null;
build: string | null;
@@ -11,16 +15,145 @@ export interface ReplayFile {
recordedAt: number;
durationMs: number;
sampleMs: number;
players: { puuid: string | null; character: string | null; track: { t: number[]; x: number[]; y: number[]; z: number[]; yaw: number[]; pitch: number[] } }[];
players: {
puuid: string | null;
character: string | null;
track: { t: number[]; x: number[]; y: number[]; z: number[]; yaw: number[]; pitch: number[]; f?: number[] };
/** 조준점 설정이 바뀐 시각마다 전체 설정 (변환기 1.8.2~, 옛 JSON 은 없다) */
crosshair?: CrosshairAt[] | null;
}[];
rounds: { num: number; buy: number; combat: number; end: number }[];
phases: [number, number][];
/** [t, killer, victim] */
kills: [number, number, number][];
/** [t, killer, victim, deathAnim(v2, deathAnims 번호 · -1)] */
kills: [number, number, number, number?][];
/** 죽는 모션 이름 (TP_Core_Death_Head_Front_SM_Montage …) */
deathAnims?: string[];
/** [t, player, x, y, z, yaw, pitch] */
shots: [number, number, number, number, number, number, number][];
/** [t0, t1, kind, x, y, z, owner] */
objects: [number, number, number, number, number, number, number][];
/** [t0, t1, kind, x, y, z, owner, yaw(v2), pitch(v2)]. 날아가는 것은 t1 = 부딪힌 시각 (v2) */
objects: [number, number, number, number, number, number, number, number?, number?][];
objectKinds: string[];
/** 움직이는 스킬 경로 (투사체 비행 · 드론 · 분신), o = objects 번호 */
objectPaths?: ObjectPath[];
/** 무기 · 스킬 상태 [t, player, equipKind, stateKind] */
states?: [number, number, number, number][];
stateKinds?: string[];
/** 맞은 것 [t, attacker, victim, ox, oy, oz, ix, iy, iz, 부위(1 머리 2 몸 3 다리), 죽였으면 1] */
hits?: number[][];
/** 스파이크 설치 [t, player, x, y, z] */
plants?: number[][];
/** 이어지는 동작 [t0, t1, player, actionKind] (Plant · Defuse · Rope) */
actions?: [number, number, number, number][];
actionKinds?: string[];
/** 들고 있는 것이 바뀐 시각 [t, player, kind] (변환기 새 버전부터. 옛 리플레이 JSON 에는 없다) */
equips?: [number, number, number][];
equipKinds?: string[];
}
export interface ObjectPath {
o: number;
t: number[];
x: number[];
y: number[];
z: number[];
/** 드론 · 분신만 */
yaw: number[];
}
/** 움직임 상태 비트 (track.f) */
export const MOVE_CROUCH = 1;
export const MOVE_WALK = 2;
export const MOVE_AIR = 4;
export const MOVE_FLY = 8;
/** 표본 배열 t 에서 t 이하 마지막 번호 (없으면 -1) */
export function indexAt(T: ArrayLike<number>, t: number): number {
if (!T.length || t < T[0]) return -1;
let lo = 0;
let hi = T.length - 1;
while (lo < hi) {
const mid = (lo + hi + 1) >> 1;
if (T[mid] <= t) lo = mid;
else hi = mid - 1;
}
return lo;
}
/** t 시점 움직임 상태 비트 (옛 리플레이는 0) */
export function moveFlagsAt(tr: ReplayFile['players'][number]['track'], t: number): number {
if (!tr.f) return 0;
const i = indexAt(tr.t, t);
return i < 0 ? 0 : tr.f[i] ?? 0;
}
/** 경로 위 t 시점 위치 (앞뒤 표본을 Catmull-Rom 으로 부드럽게). 경로 밖이면 null */
export function samplePath(p: ObjectPath, t: number): { x: number; y: number; z: number; yaw: number | null; vx: number; vy: number; vz: number } | null {
const T = p.t;
if (T.length < 2 || t < T[0] || t > T[T.length - 1]) return null;
const i = Math.min(indexAt(T, t), T.length - 2);
const j = i + 1;
const h = i > 0 ? i - 1 : i;
const k2 = j < T.length - 1 ? j + 1 : j;
const span = T[j] - T[i] || 1;
const u = (t - T[i]) / span;
const cr = (a: number[]) => {
const p0 = a[h], p1 = a[i], p2 = a[j], p3 = a[k2];
const m1 = ((p2 - p0) / (T[j] - T[h] || 1)) * span;
const m2 = ((p3 - p1) / (T[k2] - T[i] || 1)) * span;
const u2 = u * u, u3 = u2 * u;
return (2 * u3 - 3 * u2 + 1) * p1 + (u3 - 2 * u2 + u) * m1 + (-2 * u3 + 3 * u2) * p2 + (u3 - u2) * m2;
};
let yaw: number | null = null;
if (p.yaw.length === T.length) {
let d = p.yaw[j] - p.yaw[i];
if (d > 180) d -= 360;
if (d < -180) d += 360;
yaw = p.yaw[i] + d * u;
}
return { x: cr(p.x), y: cr(p.y), z: cr(p.z), yaw, vx: (p.x[j] - p.x[i]) / span * 1000, vy: (p.y[j] - p.y[i]) / span * 1000, vz: (p.z[j] - p.z[i]) / span * 1000 };
}
/** 선수별 무기 · 스킬 상태 [t, equipKind, stateName] (시간 순) */
export function stateTracks(r: ReplayFile): [number, number, string][][] {
const out: [number, number, string][][] = r.players.map(() => []);
for (const [t, p, ek, sk] of r.states ?? []) out[p]?.push([t, ek, r.stateKinds?.[sk] ?? '']);
return out;
}
const WEAPON_KO: Record<string, string> = {
Classic: '클래식', Shorty: '쇼티', Frenzy: '프렌지', Ghost: '고스트', Sheriff: '셰리프', 'Compact Pistol': '밴딧',
Stinger: '스팅어', Spectre: '스펙터', Bucky: '버키', Judge: '저지', Bulldog: '불독', Guardian: '가디언', Phantom: '팬텀', Vandal: '밴달',
Marshal: '마셜', Outlaw: '아웃로', Operator: '오퍼레이터', Ares: '아레스', Odin: '오딘',
Melee: '칼', Spike: '스파이크', Unarmed: '맨손', Headhunter: '헤드헌터', 'Tour de Force': '투르 드 포스', Bomb_Defuser_C: '스파이크 해체',
};
/** 들고 있는 것 이름 (한국어). 스킬은 "스킬", 모르면 null */
export function equipLabel(kind: string | undefined): string | null {
if (!kind) return null;
if (WEAPON_KO[kind]) return WEAPON_KO[kind];
if (/^Ability_/.test(kind)) return '스킬';
if (/Unarmed/.test(kind)) return null;
return null;
}
/** 선수별 [t, kind] 목록 (시간 순) */
export function equipTracks(r: ReplayFile): [number, number][][] {
const out: [number, number][][] = r.players.map(() => []);
for (const [t, p, k] of r.equips ?? []) out[p]?.push([t, k]);
return out;
}
/** t 시점에 들고 있던 것 (kind 번호, 없으면 -1) */
export function equipAt(track: [number, number][] | undefined, t: number): number {
if (!track?.length || t < track[0][0]) return -1;
let lo = 0;
let hi = track.length - 1;
while (lo < hi) {
const mid = (lo + hi + 1) >> 1;
if (track[mid][0] <= t) lo = mid;
else hi = mid - 1;
}
return track[lo][1];
}
/**
@@ -98,7 +231,7 @@ export function samplePlayer(tr: ReplayFile['players'][number]['track'], t: numb
}
const i = lo;
const j = Math.min(i + 1, T.length - 1);
if (t - T[i] > gapMs) return { x: tr.x[i], y: tr.y[i], z: tr.z[i], yaw: tr.yaw[i], pitch: tr.pitch[i], stale: true };
if (t - T[i] > gapMs) return { x: tr.x[i], y: tr.y[i], z: tr.z[i], yaw: tr.yaw[i], pitch: signedDeg(tr.pitch[i]), stale: true };
const span = T[j] - T[i];
const k = j === i || span > gapMs || span <= 0 ? 0 : Math.min(1, Math.max(0, (t - T[i]) / span));
let dy = tr.yaw[j] - tr.yaw[i];
@@ -109,11 +242,17 @@ export function samplePlayer(tr: ReplayFile['players'][number]['track'], t: numb
y: tr.y[i] + (tr.y[j] - tr.y[i]) * k,
z: tr.z[i] + (tr.z[j] - tr.z[i]) * k,
yaw: tr.yaw[i] + dy * k,
pitch: tr.pitch[i] + (tr.pitch[j] - tr.pitch[i]) * k,
pitch: signedDeg(tr.pitch[i]) + (signedDeg(tr.pitch[j]) - signedDeg(tr.pitch[i])) * k,
stale: false,
};
}
/** 게임 각도(0~360) → -180~180 (아래를 보면 음수) */
function signedDeg(a: number) {
const v = ((a % 360) + 360) % 360;
return v > 180 ? v - 360 : v;
}
/** t 가 속한 라운드 (구매 단계 시작 기준) */
export function roundAt(r: ReplayFile, t: number) {
let cur = r.rounds[0] ?? null;

View File

@@ -0,0 +1,120 @@
import { deathClipName, weaponCat, type RigInput } from './agents3d';
import { equipAt, indexAt, MOVE_AIR, MOVE_CROUCH, MOVE_FLY, roundAt, type ReplayFile } from './replay';
/**
* 리플레이 기록 → 요원 몸 동작 (agents3d RigInput). 모두 t 하나로 정해지므로 되감기 · 멈춤 · 배속에도 같은 자세다.
* 공중 · 착지: track.f 공중 비트가 이어진 구간
* 위 몸 한 번 동작: 해체 · 설치(이어지는 동작) > 던지기(이 선수 투사체가 생김) > 재장전 · 칼 휘두르기(무기 상태) > 꺼내기(들고 있는 것이 바뀜)
* 죽음: 이 라운드에서 죽은 킬 (사망 모션 이름)
*/
export interface AnimIndex {
equips: [number, number][][];
/** 선수별 [t, equipKind, state] */
states: [number, number, string][][];
/** 선수별 던진 시각 (Projectile_* 생김) */
throws: number[][];
/** 선수별 이어지는 동작 [t0, t1, kind] */
actions: [number, number, string][][];
/** 선수별 사격 시각 */
shots: number[][];
/** states · equips 의 시각만 (찾기용) */
stateT: number[][];
equipT: number[][];
}
export function buildAnimIndex(r: ReplayFile, equips: [number, number][][]): AnimIndex {
const n = r.players.length;
const states: AnimIndex['states'] = Array.from({ length: n }, () => []);
for (const [t, p, ek, sk] of r.states ?? []) states[p]?.push([t, ek, r.stateKinds?.[sk] ?? '']);
const throws: number[][] = Array.from({ length: n }, () => []);
for (const o of r.objects) if (o[6] >= 0 && /^Projectile_/.test(r.objectKinds[o[2]] ?? '')) throws[o[6]]?.push(o[0]);
for (const a of throws) a.sort((x, y) => x - y);
const actions: AnimIndex['actions'] = Array.from({ length: n }, () => []);
for (const [t0, t1, p, k] of r.actions ?? []) actions[p]?.push([t0, t1 < 0 ? t0 + 7000 : t1, r.actionKinds?.[k] ?? '']);
const shots: number[][] = Array.from({ length: n }, () => []);
for (const s of r.shots) if (s[1] >= 0) shots[s[1]]?.push(s[0]);
return { equips, states, throws, actions, shots, stateT: states.map((a) => a.map((x) => x[0])), equipT: equips.map((a) => a.map((x) => x[0])) };
}
function lastBefore(a: number[], t: number): number | null {
const i = indexAt(a, t);
return i < 0 ? null : a[i];
}
/** 공중에 뜬 지 · 내려앉은 지 (ms) */
export function airState(tr: ReplayFile['players'][number]['track'], t: number): { airMs: number | null; landMs: number | null; crouch: boolean } {
const f = tr.f;
if (!f) return { airMs: null, landMs: null, crouch: false };
const i = indexAt(tr.t, t);
if (i < 0) return { airMs: null, landMs: null, crouch: false };
const air = (k: number) => (f[k] & (MOVE_AIR | MOVE_FLY)) !== 0;
const crouch = (f[i] & MOVE_CROUCH) !== 0;
if (air(i)) {
let k = i;
while (k > 0 && air(k - 1) && tr.t[k] - tr.t[k - 1] < 400) k--;
return { airMs: t - tr.t[k], landMs: null, crouch };
}
// 바로 전에 공중이었으면 착지
let k = i;
while (k > 0 && !air(k - 1) && tr.t[i] - tr.t[k - 1] < 600) k--;
if (k > 0 && air(k - 1)) return { airMs: null, landMs: t - tr.t[k], crouch };
return { airMs: null, landMs: null, crouch };
}
export function rigInput(
r: ReplayFile,
ix: AnimIndex,
p: number,
t: number,
base: { dt: number; fwd: number; right: number; pitch: number },
): RigInput & { shotMs: number | null } {
const tr = r.players[p].track;
const air = airState(tr, t);
const ek = equipAt(ix.equips[p], t);
const kind = r.equipKinds?.[ek];
const cat = weaponCat(kind);
let crouch = air.crouch;
let overlay: RigInput['overlay'] = null;
// 이어지는 동작 (해체 · 설치): 앉아서 손
for (const [a0, a1, k] of ix.actions[p]) {
if (a0 <= t && t <= a1 && (k === 'Defuse' || k === 'Plant')) {
crouch = true;
overlay = { clip: 'ub_defuse', ms: t - a0, loop: true };
}
}
if (!overlay) {
const th = lastBefore(ix.throws[p], t + 300);
// 던지는 동작은 손을 놓는 때(투사체가 생긴 때)보다 0.3초 먼저 시작한다
if (th != null && t - (th - 300) < 1500) overlay = { clip: 'ub_throw', ms: t - (th - 300) };
}
if (!overlay) {
const st = ix.states[p];
const i = indexAt(ix.stateT[p], t);
if (i >= 0) {
const [ts, sek, name] = st[i];
if (sek === ek && name === 'ReloadState') overlay = { clip: cat === 'pistol' ? 'ub_reloadPistol' : cat === 'sniper' ? 'ub_reloadSniper' : 'ub_reloadRifle', ms: t - ts };
else if (sek === ek && /^AnimTriggeredState/.test(name) && t - ts < 1500) overlay = { clip: /Alt/.test(name) ? 'ub_knifeAlt' : name.endsWith('2') ? 'ub_knifeAttack2' : 'ub_knifeAttack', ms: t - ts };
}
}
if (!overlay) {
const eq = ix.equips[p];
const i = indexAt(ix.equipT[p], t);
if (i >= 0 && t - eq[i][0] < 1500) {
const clip = cat === 'ability' ? 'ub_equipAbility' : cat === 'knife' ? 'ub_equipKnife' : cat === 'pistol' ? 'ub_equipPistol' : cat === 'sniper' ? 'ub_equipSniper' : 'ub_equipRifle';
overlay = { clip, ms: t - eq[i][0] };
}
}
// 죽음: 이 라운드에서 죽은 킬
let death: RigInput['death'] = null;
const rd = roundAt(r, t);
if (rd) {
for (const k of r.kills) {
if (k[2] !== p || k[0] < rd.buy || k[0] > t) continue;
death = { clip: deathClipName(k[3] != null && k[3] >= 0 ? r.deathAnims?.[k[3]] : null), ms: t - k[0] };
}
}
const sh = lastBefore(ix.shots[p], t);
return { ...base, crouch, airMs: air.airMs, landMs: air.landMs, cat, overlay, death, shotMs: sh == null ? null : t - sh };
}

1830
site/web/src/lib/vfx.ts Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,237 @@
import * as THREE from 'three';
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 { assetUrl } from './agents3d';
import { loadIndex } from './map3d';
/**
* 1인칭 화면 팔 · 총 (tools/map-extract viewmodels → index.json viewmodels).
* arms[캐릭터 클래스] 요원 1인칭 팔 (뼈대는 모든 요원 공용, Camera 뼈 = 눈)
* weapons[무기 이름] 무기 1인칭 모델(총 동작 gun_*) + 그 무기를 든 팔 동작(idle · fire · reload · equip · ads · walk · activate)
* 좌표는 게임(UE) cm. 무기 뿌리는 팔 뼈 MasterWeapon 에 GUN_Q 만큼 돌려 붙인다 (총 몸의 앞 = 팔의 앞, 탄창 = 아래).
* 자세는 시각(ms)만으로 정한다 (되감기 · 멈춤 · 배속에도 같은 자세).
*/
export interface VmIndex {
arms: Record<string, { code: string; file: string }>;
weapons: Record<string, { file: string; anim: string; clips: string[]; gunClips: string[]; points?: { muzzle?: number[] } }>;
}
const GUN_Q = new THREE.Quaternion(0.5, -0.5, 0.5, 0.5);
/** UE(cm, X 앞 · Y 오른쪽 · Z 위) → 카메라 공간(m, -Z 앞 · X 오른쪽 · Y 위) */
const UE_TO_VIEW = new THREE.Matrix4().set(0, 0.01, 0, 0, 0, 0, 0.01, 0, -0.01, 0, 0, 0, 0, 0, 0, 1);
const cache = new Map<string, Promise<GLTF>>();
function load(url: string): Promise<GLTF> {
let p = cache.get(url);
if (!p) {
const loader = new GLTFLoader();
loader.setMeshoptDecoder(MeshoptDecoder);
p = loader.loadAsync(url);
p.catch(() => cache.delete(url));
cache.set(url, p);
}
return p;
}
export async function viewmodelIndex(): Promise<(VmIndex & { dir: string }) | null> {
const idx = (await loadIndex()) as { dir: string | null; viewmodels?: VmIndex | null } | null;
return idx?.dir && idx.viewmodels ? { ...idx.viewmodels, dir: idx.dir } : null;
}
/** 지금 자세를 정하는 입력 (모두 ms, 없으면 null) */
export interface VmInput {
/** 이 무기를 꺼낸 지 */
equipMs: number | null;
/** 마지막 사격 뒤 */
shotMs: number | null;
/** 재장전 시작 뒤 */
reloadMs: number | null;
/** 정조준(줌) 중 */
ads: boolean;
/** 걷는 중이면 걸은 시간 (반복 동작 위치) */
walkMs: number | null;
/** 스파이크 설치 시작 뒤 (설치하는 동안만) */
activateMs?: number | null;
}
function findBone(root: THREE.Object3D, name: string): THREE.Object3D | null {
let b: THREE.Object3D | null = null;
root.traverse((o) => {
if (!b && o.name === name) b = o;
});
return b;
}
function prep(root: THREE.Object3D) {
root.traverse((o) => {
const m = o as THREE.Mesh;
if (!m.isMesh) return;
m.frustumCulled = false;
const mat = m.material as THREE.MeshStandardMaterial;
mat.side = THREE.DoubleSide;
});
}
/**
* 1인칭 팔 + 무기. scene 을 따로 두고 카메라 공간에서 그린다 (맵보다 앞에, 깊이 따로).
* set() 으로 요원 · 무기를 바꾸고(받는 동안은 이전 것), pose() 로 자세를 정한 뒤 render().
*/
export class Viewmodel {
readonly scene = new THREE.Scene();
readonly camera = new THREE.PerspectiveCamera(70, 1, 0.01, 20);
private root = new THREE.Group();
private arms: THREE.Object3D | null = null;
private armsMixer: THREE.AnimationMixer | null = null;
private gunMixer: THREE.AnimationMixer | null = null;
private armClips = new Map<string, THREE.AnimationClip>();
private gunClips = new Map<string, THREE.AnimationClip>();
private flash: THREE.Sprite;
private muzzle: THREE.Object3D | null = null;
private want = '';
private have = '';
private disposed = false;
constructor(private readonly idx: VmIndex & { dir: string }) {
this.root.matrixAutoUpdate = false;
this.scene.add(this.root);
this.scene.add(new THREE.HemisphereLight(0xffffff, 0x8a8f99, 2.2));
const sun = new THREE.DirectionalLight(0xfff4e0, 1.6);
sun.position.set(0.4, 1, 0.6);
this.scene.add(sun);
// 총구 불꽃 (사격 직후 잠깐)
const c = document.createElement('canvas');
c.width = c.height = 64;
const g = c.getContext('2d')!;
const grd = g.createRadialGradient(32, 32, 0, 32, 32, 32);
grd.addColorStop(0, 'rgba(255,250,220,1)');
grd.addColorStop(0.3, 'rgba(255,200,90,0.85)');
grd.addColorStop(1, 'rgba(255,120,20,0)');
g.fillStyle = grd;
g.fillRect(0, 0, 64, 64);
this.flash = new THREE.Sprite(new THREE.SpriteMaterial({ map: new THREE.CanvasTexture(c), blending: THREE.AdditiveBlending, depthTest: false, transparent: true }));
this.flash.scale.setScalar(0.12);
this.flash.visible = false;
this.scene.add(this.flash);
}
/** 이 요원 · 무기에 1인칭 모델이 있는지 */
has(character: string | null | undefined, weapon: string | null | undefined): boolean {
return !!character && !!weapon && !!this.idx.arms[character] && !!this.idx.weapons[weapon];
}
/** 요원 · 무기를 바꾼다 (같으면 그대로). 받는 동안은 이전 모델을 그린다 */
set(character: string, weapon: string) {
const key = `${character}|${weapon}`;
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))])
.then(([ag, wg, an]) => {
if (this.disposed || this.want !== key) return;
this.build(ag, wg, an);
this.have = key;
})
.catch(() => undefined);
}
private build(ag: GLTF, wg: GLTF, an: GLTF) {
if (this.arms) this.root.remove(this.arms);
const arms = cloneSkinned(ag.scene);
const gun = cloneSkinned(wg.scene);
prep(arms);
prep(gun);
const attach = findBone(arms, 'MasterWeapon');
if (attach) {
gun.quaternion.copy(GUN_Q);
attach.add(gun);
}
this.root.add(arms);
this.arms = arms;
this.muzzle = findBone(gun, 'Muzzle');
this.armsMixer = new THREE.AnimationMixer(arms);
this.gunMixer = new THREE.AnimationMixer(gun);
this.armClips = new Map(an.animations.map((c) => [c.name, c]));
this.gunClips = new Map(wg.animations.map((c) => [c.name, c]));
// 눈 = 팔 Camera 뼈 (대기 자세)
this.play(this.armsMixer, this.armClips.get('idle'), 0, false);
arms.updateMatrixWorld(true);
// 팔 공간 좌표로 (root 에 이전 요원 · 무기의 변환이 남아 있어도 같은 값)
const cam = findBone(arms, 'Camera');
const cp = cam ? arms.worldToLocal(new THREE.Vector3().setFromMatrixPosition(cam.matrixWorld)) : new THREE.Vector3(0, 0, 166);
this.root.matrix.copy(UE_TO_VIEW).multiply(new THREE.Matrix4().makeTranslation(-cp.x, -cp.y, -cp.z));
this.root.matrixWorldNeedsUpdate = true;
}
get ready() {
return this.have !== '' && this.have === this.want;
}
private play(mixer: THREE.AnimationMixer, clip: THREE.AnimationClip | undefined, ms: number, loop: boolean) {
mixer.stopAllAction();
if (!clip) return false;
const a = mixer.clipAction(clip);
a.reset();
a.setLoop(loop ? THREE.LoopRepeat : THREE.LoopOnce, Infinity);
a.clampWhenFinished = true;
a.play();
const d = Math.max(clip.duration, 1e-3);
a.time = loop ? (ms / 1000) % d : Math.min(ms / 1000, d);
mixer.update(0);
return true;
}
/** 시각만으로 자세: 스파이크 설치 > 꺼내기 > 재장전 > 사격 > 걷기 > 정조준 > 대기 (설치 시작 때 스파이크를 꺼내므로 설치가 먼저) */
pose(i: VmInput) {
if (!this.armsMixer || !this.gunMixer) return;
const dur = (n: string) => (this.armClips.get(n)?.duration ?? 0) * 1000;
let role = 'idle';
let ms = 0;
let loop = false;
if (i.activateMs != null && this.armClips.has('activate')) [role, ms] = ['activate', i.activateMs];
else if (i.equipMs != null && i.equipMs < dur('equip')) [role, ms] = ['equip', i.equipMs];
else if (i.reloadMs != null && i.reloadMs < dur('reload')) [role, ms] = ['reload', i.reloadMs];
else if (i.shotMs != null && i.shotMs < dur('fire')) [role, ms] = ['fire', i.shotMs];
else if (i.walkMs != null && this.armClips.has('walk') && !i.ads) [role, ms, loop] = ['walk', i.walkMs, true];
else if (i.ads && this.armClips.has('ads')) role = 'ads';
if (!this.play(this.armsMixer, this.armClips.get(role), ms, loop)) this.play(this.armsMixer, this.armClips.get('idle'), 0, false);
if (!this.play(this.gunMixer, this.gunClips.get('gun_' + role), ms, false)) this.gunMixer.stopAllAction();
// 총구 불꽃: 사격 뒤 60ms
const on = i.shotMs != null && i.shotMs < 60 && role === 'fire' && !!this.muzzle;
this.flash.visible = on;
if (on) {
this.root.updateMatrixWorld(true);
this.flash.position.setFromMatrixPosition(this.muzzle!.matrixWorld);
this.flash.material.rotation = (i.shotMs! * 7) % (Math.PI * 2);
}
}
/** 맵을 그린 뒤 깊이만 지우고 그 위에 그린다 */
render(renderer: THREE.WebGLRenderer, fov: number, aspect: number) {
if (!this.arms) return;
if (this.camera.fov !== fov || this.camera.aspect !== aspect) {
this.camera.fov = fov;
this.camera.aspect = aspect;
this.camera.updateProjectionMatrix();
}
const clip = renderer.localClippingEnabled;
const auto = renderer.autoClear;
renderer.localClippingEnabled = false;
renderer.autoClear = false;
renderer.clearDepth();
renderer.render(this.scene, this.camera);
renderer.autoClear = auto;
renderer.localClippingEnabled = clip;
}
dispose() {
this.disposed = true;
this.armsMixer?.stopAllAction();
this.gunMixer?.stopAllAction();
this.flash.material.map?.dispose();
this.flash.material.dispose();
}
}

View File

@@ -0,0 +1,299 @@
// 관리 페이지 (v1.6.0, 관리자 · 최고 관리자)
// - 게임 PC: 연결 · 앱 버전 · 새 버전 안내
// - 유저: 표시 이름 · 색 · 녹음 제외 · 라이엇 ID (녹음된 사람), 앱 등록 · 역할 · 해제 (최고 관리자)
import { useCallback, useEffect, useMemo, useState } from 'react';
import { Link } from 'react-router';
import type { AppUserRow, User } from '@gvr/shared';
import { api, type AdminOverview } from '../lib/api';
import { fmtDay } from '../lib/format';
import { useAuth, useData } from '../store/app';
import { Avatar, ErrorBox, Panel, Spinner } from '../components/common';
import { AppUserEditor, errText, NameEditor } from '../components/UserEdit';
const ROLE: Record<string, string> = { superadmin: '최고 관리자', admin: '관리자', user: '앱 유저' };
/** "1.4.1" < "1.5.0" */
export function olderVersion(a: string | null | undefined, b: string | null | undefined): boolean {
if (!a || !b) return false;
const pa = a.split('.').map((x) => parseInt(x, 10) || 0);
const pb = b.split('.').map((x) => parseInt(x, 10) || 0);
for (let i = 0; i < Math.max(pa.length, pb.length); i++) if ((pa[i] ?? 0) !== (pb[i] ?? 0)) return (pa[i] ?? 0) < (pb[i] ?? 0);
return false;
}
const when = (t: number | null) => (t ? `${fmtDay(t)} ${new Date(t).toLocaleTimeString('ko-KR', { hour12: false, hour: '2-digit', minute: '2-digit' })}` : '—');
interface Row {
id: string;
name: string;
avatar: string | null;
/** 녹음 기록에 있는 사람 (게임 PC 앱) */
user: User | null;
/** 앱 등록 (사이트 서버) */
reg: AppUserRow | null;
}
export function AdminPage() {
const { auth } = useAuth();
const { users } = useData();
const [ov, setOv] = useState<AdminOverview | null>(null);
const [regs, setRegs] = useState<AppUserRow[] | null>(null);
const [names, setNames] = useState<Record<string, string>>({});
const [err, setErr] = useState<unknown>(null);
const [open, setOpen] = useState<string | null>(null);
const [q, setQ] = useState('');
const load = useCallback(() => {
setErr(null);
Promise.all([api.adminOverview(), api.adminUsers()])
.then(([o, u]) => {
setOv(o);
setRegs(u.users);
setNames(u.names ?? {});
})
.catch(setErr);
}, []);
useEffect(load, [load]);
const sup = ov?.role === 'superadmin';
const rows = useMemo<Row[]>(() => {
const m = new Map<string, Row>();
for (const u of users) m.set(u.id, { id: u.id, name: u.name, avatar: u.avatar, user: u, reg: null });
for (const r of regs ?? []) {
const cur = m.get(r.id);
if (cur) cur.reg = r;
else m.set(r.id, { id: r.id, name: r.name, avatar: r.avatar, user: null, reg: r });
}
const order = (r: Row) => (r.reg?.role === 'superadmin' ? 0 : r.reg?.role === 'admin' ? 1 : r.reg ? 2 : 3);
const k = q.trim().toLowerCase();
return [...m.values()]
.filter((r) => !k || r.name.toLowerCase().includes(k) || r.id.includes(k) || r.user?.riot.some((x) => x.riotId.toLowerCase().includes(k)))
.sort((a, b) => order(a) - order(b) || a.name.localeCompare(b.name, 'ko'));
}, [users, regs, q]);
if (auth.status !== 'ok' || !auth.me.canViewLogs)
return (
<main className="page-pad">
<h2 className="page-h h">관리</h2>
<div className="dim">관리자만 볼 수 있습니다.</div>
</main>
);
if (err) return <main className="page-pad"><ErrorBox error={err} onRetry={load} /></main>;
if (!ov || !regs) return <main className="page-pad"><Spinner /></main>;
const dev = ov.device;
const outdated = olderVersion(dev.version, ov.latest?.version);
return (
<main className="page-pad admin-page">
<div className="page-h-row">
<h2 className="page-h h">🛡️ 관리</h2>
<div className="chips-wrap">
<a className="mini-btn" href="/logs">
📄 사이트 로그
</a>
<button className="mini-btn" onClick={load}>
새로고침
</button>
</div>
</div>
<Panel title="게임 PC">
<div className="adm-dev">
<div>
<span className={`dot-st ${dev.online ? 'on' : 'off'}`} /> <b>{dev.name ?? '등록된 PC 없음'}</b>
<span className="dim small"> · {dev.online ? '연결됨' : dev.lastSeen ? `마지막 연결 ${when(dev.lastSeen)}` : '연결 안 됨'}</span>
</div>
<div>
앱 <b className="mono">{dev.version ?? '?'}</b>
{ov.latest && (
<span className="dim small">
{' '}
· 최신 <span className="mono">{ov.latest.version}</span>
</span>
)}
{outdated && ov.latest && (
<a className="adm-update" href={ov.latest.url} target="_blank" rel="noreferrer">
새 버전 v{ov.latest.version} 받기 →
</a>
)}
</div>
{outdated && <div className="ue-hint">게임 PC 앱이 최신이 아닙니다. 색 · 녹음 제외 · 라이엇 ID 바꾸기와 3D 리플레이는 최신 앱에서 됩니다.</div>}
</div>
</Panel>
<Panel
title={`유저 ${rows.length}명`}
right={<input className="ue-input adm-search" value={q} placeholder="이름 · 아이디 · 라이엇 ID 찾기" onChange={(e) => setQ(e.target.value)} aria-label="유저 찾기" />}
>
<div className="ue-hint adm-note">
표시 이름은 디스코드 이름 대신 사이트 · 게임 PC 기록 · 범인 분석에 보입니다 (관리자). 앱 등록 · 역할 바꾸기 · 등록 해제는 최고 관리자만 할 수 있습니다.
</div>
<div className="adm-list">
{rows.map((r) => (
<AdminUserRow
key={r.id}
r={r}
custom={!!names[r.id]}
sup={sup}
open={open === r.id}
onToggle={() => setOpen((o) => (o === r.id ? null : r.id))}
onNames={setNames}
onRegs={setRegs}
/>
))}
</div>
{sup && <AddUser onRegs={setRegs} />}
</Panel>
</main>
);
}
function AdminUserRow({
r,
custom,
sup,
open,
onToggle,
onNames,
onRegs,
}: {
r: Row;
custom: boolean;
sup: boolean;
open: boolean;
onToggle: () => void;
onNames: (n: Record<string, string>) => void;
onRegs: (u: AppUserRow[]) => void;
}) {
const { reloadUsers } = useData();
const { auth, refreshMe } = useAuth();
const [msg, setMsg] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const act = async (fn: () => Promise<{ users: AppUserRow[] }>) => {
setBusy(true);
setMsg(null);
try {
onRegs((await fn()).users);
} catch (e) {
setMsg(errText(e));
} finally {
setBusy(false);
}
};
const role = r.reg?.role ?? null;
return (
<div className={`adm-row${open ? ' open' : ''}`}>
<button className="adm-sum" onClick={onToggle} aria-expanded={open}>
<Avatar user={r.user} name={r.name} src={r.avatar} size={30} />
<span className="adm-nm">
<b style={r.user ? { color: r.user.color } : undefined}>{r.name}</b>
{custom && <span className="badge b-name">표시 이름</span>}
{r.user?.excluded && <span className="badge b-excl">녹음 제외</span>}
<span className="dim small mono">{r.id}</span>
</span>
<span className="adm-role">{role ? <span className={`badge b-role ${role}`}>{ROLE[role]}</span> : <span className="dim small">앱 미등록</span>}</span>
<span className="adm-seen dim small">{r.reg?.lastSeenAt ? `앱 ${when(r.reg.lastSeenAt)}${r.reg.lastVersion ? ` · v${r.reg.lastVersion}` : ''}` : r.user ? '녹음 기록 있음' : ''}</span>
<span className="adm-caret">{open ? '▴' : '▾'}</span>
</button>
{open && (
<div className="adm-body">
<div className="ue-label">표시 이름</div>
<NameEditor
value={r.name}
custom={custom}
onSave={async (name) => {
const res = await api.adminSetName(r.id, name);
onNames(res.names);
// 게임 PC 앱이 이름을 받아 유저 목록을 다시 보낸다. 조금 기다렸다가 다시 받는다
window.setTimeout(reloadUsers, 1500);
if (auth.status === 'ok' && auth.me.user.id === r.id) await refreshMe();
const regs = await api.adminUsers().catch(() => null);
if (regs) onRegs(regs.users);
}}
/>
{r.user ? (
<AppUserEditor user={r.user} self={false} />
) : (
<div className="ue-hint">이 PC 녹음 기록에 없는 사람입니다. 음성채널에서 한 번 녹음되면 색 · 라이엇 ID · 녹음 제외를 바꿀 수 있습니다.</div>
)}
{r.user && (
<Link className="mini-btn" to={`/users/${r.id}`}>
기록 보기
</Link>
)}
{sup && role !== 'superadmin' && (
<div className="adm-acts">
<div className="ue-label">앱 사용 (게임 PC 앱 로그인)</div>
{role ? (
<>
<button className="btn sm" disabled={busy} onClick={() => void act(() => api.adminSetRole(r.id, role === 'admin' ? 'user' : 'admin'))}>
{role === 'admin' ? '관리자 → 앱 유저로' : '앱 유저 → 관리자로'}
</button>
<button
className="btn sm danger"
disabled={busy}
onClick={() => {
if (window.confirm(`${r.name} 님의 앱 등록을 해제할까요? 그 사람의 겜녹이 앱이 바로 잠깁니다.`)) void act(() => api.adminRemoveUser(r.id));
}}
>
등록 해제
</button>
</>
) : (
<>
<button className="btn sm" disabled={busy} onClick={() => void act(() => api.adminAddUser(r.id, 'user'))}>
앱 유저로 등록
</button>
<button className="btn sm" disabled={busy} onClick={() => void act(() => api.adminAddUser(r.id, 'admin'))}>
관리자로 등록
</button>
</>
)}
</div>
)}
{msg && <div className="ue-msg bad">{msg}</div>}
</div>
)}
</div>
);
}
function AddUser({ onRegs }: { onRegs: (u: AppUserRow[]) => void }) {
const [id, setId] = useState('');
const [role, setRole] = useState<'user' | 'admin'>('user');
const [busy, setBusy] = useState(false);
const [msg, setMsg] = useState<{ ok: boolean; text: string } | null>(null);
const ok = /^\d{17,20}$/.test(id.trim());
return (
<form
className="adm-add"
onSubmit={(e) => {
e.preventDefault();
if (!ok) return;
setBusy(true);
setMsg(null);
api
.adminAddUser(id.trim(), role)
.then((r) => {
onRegs(r.users);
setMsg({ ok: true, text: '등록했습니다. 그 사람은 이제 겜녹이 앱에 로그인할 수 있습니다' });
setId('');
})
.catch((e) => setMsg({ ok: false, text: errText(e) }))
.finally(() => setBusy(false));
}}
>
<div className="ue-label">디스코드 아이디로 앱 유저 등록</div>
<div className="ue-row">
<input className="ue-input mono" value={id} inputMode="numeric" placeholder="디스코드 아이디 (17~20자리 숫자)" onChange={(e) => setId(e.target.value)} aria-label="디스코드 아이디" />
<select className="ue-input adm-sel" value={role} onChange={(e) => setRole(e.target.value as 'user' | 'admin')} aria-label="역할">
<option value="user">앱 유저</option>
<option value="admin">관리자</option>
</select>
<button className="btn sm primary" disabled={busy || !ok}>
등록
</button>
</div>
{msg && <div className={`ue-msg${msg.ok ? ' ok' : ' bad'}`}>{msg.text}</div>}
</form>
);
}

View File

@@ -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>

View File

@@ -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]);

View File

@@ -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 { sfx } from '../lib/sfx';
import { Avatar, ErrorBox, Spinner } from '../components/common';
import { MatchItem } from './Sidebar';
import { HistoryImport } from '../components/HistoryImport';
function useLoad<T>(fn: () => Promise<T>, deps: unknown[]) {
const { epoch } = useStatus();
@@ -50,18 +51,53 @@ 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: '디스코드 대화가 녹음된 경기' },
];
export function MatchesPage() {
const [game, setGame] = useState<GameType | null>(null);
const [has, setHas] = useState<MatchHas | null>(null);
const nav = useNavigate();
const { data, err, retry } = useLoad<MatchSummary[]>(() => api.matches({ limit: 50, game: game ?? undefined }), [game]);
const { data, err, retry } = useLoad<MatchSummary[]>(() => api.matches({ limit: PAGE, game: game ?? undefined, has: has ?? undefined }), [game, has]);
// 더 보기: 지난 쪽 경기들 (필터가 바뀌면 처음부터)
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;
out.push(m);
}
return out;
}, [data, more.list, has]);
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({ limit: PAGE, game: game ?? undefined, has: has ?? undefined, 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 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 +114,39 @@ 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>
<HistoryImport onDone={retry} />
{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">
{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>
);
}

View File

@@ -6,7 +6,7 @@ import { makeUnknownUserCheck } from '../lib/unknown-users';
// ── 로그인 ───────────────────────────────────────────
type AuthState = { status: 'loading' } | { status: 'anon' } | { status: 'not_member' } | { status: 'ok'; me: Me };
const AuthCtx = createContext<{ auth: AuthState; logout: () => void }>({ auth: { status: 'loading' }, logout: () => {} });
const AuthCtx = createContext<{ auth: AuthState; logout: () => void; refreshMe: () => Promise<void> }>({ auth: { status: 'loading' }, logout: () => {}, refreshMe: async () => {} });
export function AuthProvider({ children }: { children: ReactNode }) {
const [auth, setAuth] = useState<AuthState>({ status: 'loading' });
@@ -28,7 +28,12 @@ export function AuthProvider({ children }: { children: ReactNode }) {
const logout = useCallback(() => {
void api.logout().finally(() => setAuth({ status: 'anon' }));
}, []);
return <AuthCtx.Provider value={{ auth, logout }}>{children}</AuthCtx.Provider>;
// 내 표시 이름을 바꾼 뒤 머리글 이름을 다시 받는다
const refreshMe = useCallback(async () => {
const r = await api.me().catch(() => null);
if (r?.ok) setAuth({ status: 'ok', me: r.me });
}, []);
return <AuthCtx.Provider value={{ auth, logout, refreshMe }}>{children}</AuthCtx.Provider>;
}
export const useAuth = () => useContext(AuthCtx);
@@ -123,8 +128,10 @@ interface DataValue {
overview: Overview | null;
users: User[];
userById: (id: string | undefined | null) => User | undefined;
/** 유저 목록 다시 받기 (유저 설정을 바꾼 뒤) */
reloadUsers: () => void;
}
const DataCtx = createContext<DataValue>({ overview: null, users: [], userById: () => undefined });
const DataCtx = createContext<DataValue>({ overview: null, users: [], userById: () => undefined, reloadUsers: () => {} });
export function DataProvider({ children }: { children: ReactNode }) {
const { epoch, locked } = useStatus();
@@ -163,6 +170,6 @@ export function DataProvider({ children }: { children: ReactNode }) {
if (e.type === 'games.state') setOverview((o) => (o ? { ...o, live: e.data } : o));
});
const userById = useCallback((id: string | undefined | null) => (id ? map.get(id) : undefined), [map]);
return <DataCtx.Provider value={{ overview, users, userById }}>{children}</DataCtx.Provider>;
return <DataCtx.Provider value={{ overview, users, userById, reloadUsers }}>{children}</DataCtx.Provider>;
}
export const useData = () => useContext(DataCtx);

View File

@@ -1,4 +1,5 @@
import { useSyncExternalStore } from 'react';
import { DEFAULT_CROSSHAIR, type CrosshairProfile } from '../lib/crosshair';
export type SfxKind = 'click' | 'play' | 'kill' | 'round' | 'chime';
export interface Settings {
@@ -10,6 +11,8 @@ export interface Settings {
normalize: boolean;
/** 녹음 재생 음량 0..2 (1 = 원래 크기) */
playVolume: number;
/** 3D 리플레이 1인칭 조준점: usePlayer 면 리플레이에 있는 선수 조준점(없으면 mine), 아니면 항상 mine */
crosshair: { usePlayer: boolean; mine: CrosshairProfile; code?: string };
/** 기본값을 바꾼 횟수 (예전에 저장한 설정을 한 번만 새 기본값으로 맞춘다) */
defaultsRev?: number;
}
@@ -24,6 +27,7 @@ const DEFAULTS: Settings = {
continuous: true,
normalize: true,
playVolume: 1,
crosshair: { usePlayer: true, mine: DEFAULT_CROSSHAIR },
defaultsRev: 1,
};
@@ -32,7 +36,7 @@ function load(): Settings {
const raw = localStorage.getItem(KEY);
if (!raw) return DEFAULTS;
const v = JSON.parse(raw) as Partial<Settings>;
const out = { ...DEFAULTS, ...v, sfx: { ...DEFAULTS.sfx, ...(v.sfx ?? {}) } };
const out = { ...DEFAULTS, ...v, sfx: { ...DEFAULTS.sfx, ...(v.sfx ?? {}) }, crosshair: { ...DEFAULTS.crosshair, ...(v.crosshair ?? {}) } };
// 예전 사이트는 설정을 하나만 바꿔도 효과음 켜짐/꺼짐을 전부 저장했다: 새 기본값(두 알림 끄기)을 한 번 적용
if ((v.defaultsRev ?? 0) < 1) {
out.sfx = { ...out.sfx, play: false, chime: false };

View File

@@ -2737,6 +2737,33 @@ button.match:hover {
letter-spacing: 1px;
margin: 20px 0 8px;
}
.match-has {
margin: 4px 0 2px;
}
.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 +3963,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;
}
@@ -4070,6 +4112,143 @@ button.match:hover {
.r3d-foot {
font-size: 12px;
}
.r3d-cams {
display: inline-flex;
gap: 4px;
}
.r3d-pick {
display: block;
margin-top: 6px;
max-width: 260px;
background: rgba(8, 14, 20, 0.85);
color: inherit;
border: 1px solid rgba(255, 255, 255, 0.15);
border-radius: 6px;
padding: 3px 6px;
}
/* 1인칭 조준점 (lib/crosshair.ts 가 그린다): 화면 가운데 */
.r3d-stage canvas.r3d-xcanvas {
position: absolute;
left: 50%;
top: 50%;
width: 240px;
height: 240px;
margin: -120px 0 0 -120px;
pointer-events: none;
z-index: 3;
cursor: default;
}
/* 조준점 설정 창 */
.r3d-xpanel {
position: absolute;
z-index: 4;
right: 10px;
bottom: 10px;
width: min(320px, calc(100% - 20px));
max-height: calc(100% - 20px);
overflow-y: auto;
padding: 10px 12px;
border-radius: 10px;
background: rgba(8, 14, 20, 0.92);
border: 1px solid var(--line);
display: flex;
flex-direction: column;
gap: 6px;
font-size: 13px;
}
.r3d-xhead {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
}
.r3d-xcheck {
display: flex;
align-items: center;
gap: 6px;
cursor: pointer;
}
.r3d-xplayer {
display: flex;
align-items: center;
gap: 10px;
}
.r3d-xplayer > div {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 4px;
}
.r3d-stage canvas.r3d-xprev {
width: 72px;
height: 72px;
flex: none;
border-radius: 8px;
background: #3a4651;
cursor: default;
}
.r3d-xmine {
display: flex;
flex-direction: column;
gap: 6px;
border-top: 1px solid var(--line);
padding-top: 8px;
}
.r3d-xmine > .r3d-xprev {
align-self: center;
}
.r3d-xcode {
display: flex;
gap: 6px;
}
.r3d-xcode input {
flex: 1;
min-width: 0;
font-family: var(--font-mono);
font-size: 12px;
}
.r3d-xerr {
color: #ff9aa5;
}
.r3d-xrow {
display: grid;
grid-template-columns: 56px 1fr auto;
align-items: center;
gap: 6px;
}
.r3d-xrow input[type='range'] {
width: 100%;
accent-color: var(--accent);
}
.r3d-xrow .mono {
min-width: 30px;
text-align: right;
}
.r3d-xset {
border: 1px solid var(--line);
border-radius: 8px;
padding: 4px 8px 6px;
display: flex;
flex-direction: column;
gap: 4px;
}
.r3d-xset legend {
padding: 0 4px;
}
/* 저격총 줌: 둥근 조준경 밖은 검게, 가는 십자선 */
.r3d-scope {
position: absolute;
inset: 0;
pointer-events: none;
z-index: 2;
background:
linear-gradient(rgba(0, 0, 0, 0.85), rgba(0, 0, 0, 0.85)) center / 100% 1px no-repeat,
linear-gradient(rgba(0, 0, 0, 0.85), rgba(0, 0, 0, 0.85)) center / 1px 100% no-repeat,
radial-gradient(circle at center, transparent 0, transparent min(46vh, 46%), #000 calc(min(46vh, 46%) + 1px));
}
.r3d-stage canvas:focus {
outline: none;
}
.r3d-ceil {
display: inline-flex;
align-items: center;
@@ -4079,3 +4258,353 @@ button.match:hover {
width: 90px;
accent-color: var(--accent);
}
/* ── 내 정보 · 관리 페이지 (v1.6.0) ───────────────── */
.me-btn {
padding: 4px 8px 4px 4px;
border-radius: 20px;
border: 1px solid transparent;
transition: border-color 0.15s, background 0.15s;
}
.me-btn:hover,
.me-btn[aria-expanded='true'] {
border-color: var(--line);
background: #15222f;
}
.me-caret {
font-size: 10px;
color: var(--dim);
}
.popover.profile-pop {
right: 0;
width: 360px;
max-height: calc(100vh - var(--header-h) - 24px);
overflow: auto;
}
.pp-head {
display: flex;
align-items: center;
gap: 10px;
padding-bottom: 10px;
border-bottom: 1px solid var(--line);
margin-bottom: 4px;
}
.pp-head b {
font-size: 15px;
}
.pp-links {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin-top: 14px;
padding-top: 10px;
border-top: 1px solid var(--line);
}
.ue-block {
display: flex;
flex-direction: column;
gap: 6px;
}
.ue-row {
display: flex;
gap: 6px;
align-items: center;
}
.ue-input {
flex: 1;
min-width: 0;
background: #0b141c;
border: 1px solid var(--line);
border-radius: 7px;
padding: 6px 9px;
font-size: 13px;
color: var(--ink);
}
.ue-input:focus {
outline: none;
border-color: #3a5670;
}
.ue-label {
font-size: 11.5px;
color: var(--muted);
margin-top: 6px;
}
.ue-hint {
font-size: 11.5px;
color: var(--dim);
line-height: 1.5;
display: block;
}
.ue-msg {
font-size: 12px;
}
.ue-msg.ok {
color: var(--good);
}
.ue-msg.bad {
color: #ff8a8a;
}
.ue-colors {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.ue-sw {
width: 22px;
height: 22px;
border-radius: 50%;
border: 2px solid transparent;
box-shadow: 0 0 0 1px #2c3f52;
}
.ue-sw.on {
border-color: #fff;
}
.ue-sw.custom {
background: var(--panel2);
color: var(--muted);
font-size: 13px;
line-height: 1;
}
.ue-hidden {
position: absolute;
width: 0;
height: 0;
opacity: 0;
pointer-events: none;
}
.ue-check {
display: flex;
gap: 8px;
align-items: flex-start;
font-size: 13px;
margin-top: 6px;
cursor: pointer;
}
.ue-check input {
margin-top: 3px;
accent-color: var(--accent);
}
.ue-check > span {
display: flex;
flex-direction: column;
gap: 2px;
}
.admin-page .panel {
margin-bottom: 16px;
}
.adm-dev {
display: flex;
flex-direction: column;
gap: 6px;
font-size: 13.5px;
}
.dot-st {
display: inline-block;
width: 8px;
height: 8px;
border-radius: 50%;
background: #4a5866;
vertical-align: middle;
}
.dot-st.on {
background: var(--good);
}
.adm-update {
margin-left: 10px;
color: var(--gold);
font-weight: 700;
font-size: 12.5px;
}
.adm-search {
max-width: 240px;
}
.adm-note {
margin-bottom: 10px;
}
.adm-list {
display: flex;
flex-direction: column;
gap: 4px;
}
.adm-row {
border: 1px solid var(--line);
border-radius: 10px;
background: #0f1923;
}
.adm-row.open {
border-color: #34506a;
}
.adm-sum {
width: 100%;
display: flex;
align-items: center;
gap: 10px;
padding: 8px 12px;
text-align: left;
}
.adm-nm {
flex: 1;
min-width: 0;
display: flex;
align-items: center;
gap: 8px;
flex-wrap: wrap;
}
.adm-role {
width: 96px;
}
.adm-seen {
width: 200px;
text-align: right;
}
.adm-caret {
color: var(--dim);
font-size: 11px;
}
.adm-body {
padding: 4px 14px 14px 52px;
display: flex;
flex-direction: column;
gap: 6px;
align-items: flex-start;
}
.adm-body > .ue-block {
width: min(520px, 100%);
}
.adm-acts {
display: flex;
flex-wrap: wrap;
gap: 6px;
align-items: center;
}
.adm-acts .ue-label {
width: 100%;
}
.adm-add {
margin-top: 14px;
padding-top: 12px;
border-top: 1px solid var(--line);
max-width: 560px;
}
.adm-sel {
flex: none;
width: auto;
}
.b-name {
background: #13283a;
color: #8fc6ff;
border: 1px solid #23415c;
}
.b-role.superadmin {
background: #3a1820;
color: #ff8a95;
}
.b-role.admin {
background: #2b2412;
color: var(--gold);
}
.b-role.user {
background: #18303a;
color: var(--mint);
}
.btn.danger {
border-color: #5a2029;
color: #ff8a8a;
}
@media (max-width: 760px) {
.adm-seen,
.adm-role {
display: none;
}
.adm-body {
padding-left: 14px;
}
.popover.profile-pop {
position: fixed;
top: calc(var(--header-h) + 6px);
left: 8px;
right: 8px;
width: auto;
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);
}

View File

@@ -1,6 +1,7 @@
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { fileURLToPath } from 'node:url';
import { contentSecurityPolicy } from '../server/src/csp';
const sharedSrc = fileURLToPath(new URL('../../packages/shared/src/index.ts', import.meta.url));
// 목 서버(mock/server.mjs) 주소. 실제 배포에서는 사이트 서버가 같은 오리진으로 정적 파일을 서빙한다.
@@ -19,6 +20,7 @@ export default defineConfig({
plugins: [react()],
resolve: { alias: { '@gvr/shared': sharedSrc } },
server: { port: 5173, host: '127.0.0.1', proxy, fs: { allow: ['.', '../../packages/shared'] } },
preview: { port: 4173, host: '127.0.0.1', proxy },
// 미리보기(빌드 결과)는 실제 사이트와 같은 CSP 로 연다 (dev 는 vite 가 인라인 스크립트를 넣어 못 씀)
preview: { port: 4173, host: '127.0.0.1', proxy, headers: { 'content-security-policy': contentSecurityPolicy('ws://127.0.0.1:4173') } },
build: { outDir: 'dist', sourcemap: false, chunkSizeWarningLimit: 900 },
});

View File

@@ -2,3 +2,4 @@ vendor/
bin/
obj/
out/
__pycache__/

View File

@@ -16,5 +16,6 @@
<Compile Include="src/**/*.cs" />
<PackageReference Include="Serilog.Sinks.Console" Version="6.1.1" />
<ProjectReference Include="vendor/CUE4Parse/CUE4Parse/CUE4Parse.csproj" />
<ProjectReference Include="vendor/CUE4Parse/CUE4Parse-Conversion/CUE4Parse-Conversion.csproj" />
</ItemGroup>
</Project>

View File

@@ -12,4 +12,6 @@ if [ "$(git -C "$dst" rev-parse HEAD)" != "$CUE4PARSE_COMMIT" ]; then
git -C "$dst" fetch --quiet origin
git -C "$dst" checkout --quiet --force "$CUE4PARSE_COMMIT"
fi
# 애니메이션(ACL 압축) 풀기에 쓰는 네이티브 라이브러리 소스 (헤더만)
git -C "$dst" submodule update --quiet --init --recursive CUE4Parse-Natives/ACL/external/acl
echo "CUE4Parse @ $(git -C "$dst" rev-parse --short HEAD)"

View File

@@ -2,7 +2,7 @@
# 맵 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
# 코드를 고쳤으면 다시 실행하면 된다. 지금 바로 한 번 돌리기: systemctl --user start gvr-maps-update
# 코드를 고쳤으면 다시 실행하면 된다 (타이머를 꺼 뒀으면 꺼진 채로 둔다). 지금 바로 한 번 돌리기: systemctl --user start gvr-maps-update
set -euo pipefail
here="$(cd "$(dirname "$0")/.." && pwd)"
GVR_MAPS_HOME="${GVR_MAPS_HOME:-$HOME/gvr-maps}"
@@ -10,6 +10,10 @@ export PATH="$HOME/.dotnet:$PATH" DOTNET_ROOT="${DOTNET_ROOT:-$HOME/.dotnet}" DO
"$here/fetch-cue4parse.sh"
rm -rf "$GVR_MAPS_HOME/bin.new"
CUE4PARSE_SKIP_NATIVE=1 dotnet build "$here/MapExtract.csproj" -c Release -o "$GVR_MAPS_HOME/bin.new" -v quiet -nologo -clp:ErrorsOnly
# CUE4Parse-Natives (ACL 애니메이션 풀기만, cmake 없이 g++): 요원 애니메이션 추출에 필요
nat="$here/vendor/CUE4Parse/CUE4Parse-Natives"
g++ -shared -fPIC -O2 -std=c++17 -DWITH_ACL -I"$nat/ACL/external/acl/includes" -I"$nat/ACL/external/acl/external/rtm/includes" -I"$nat/common" -I"$nat/ACL/includes" \
"$nat/ACL/ACL.cpp" "$nat/Features.cpp" -o "$GVR_MAPS_HOME/bin.new/CUE4Parse-Natives.so"
rm -rf "$GVR_MAPS_HOME/bin.old"
[ -d "$GVR_MAPS_HOME/bin" ] && mv "$GVR_MAPS_HOME/bin" "$GVR_MAPS_HOME/bin.old"
mv "$GVR_MAPS_HOME/bin.new" "$GVR_MAPS_HOME/bin"
@@ -22,6 +26,12 @@ chmod +x "$GVR_MAPS_HOME/scripts/update.sh"
unit="$HOME/.config/systemd/user"
mkdir -p "$unit"
# 이미 설치돼 있는데 타이머를 꺼 뒀으면(사용자가 자동 갱신을 멈춤) 다시 켜지 않는다
timer_was="$( [ -f "$unit/gvr-maps-update.timer" ] && (systemctl --user is-enabled gvr-maps-update.timer 2>/dev/null || true) || echo new)"
# 알림 채널 · 토큰 파일: 환경변수로 주지 않았으면 이미 설치된 값을 그대로 쓴다 (다시 설치하면서 알림이 꺼지지 않게)
prev_env() { sed -n "s/^Environment=$1=//p" "$unit/gvr-maps-update.service" 2>/dev/null | tail -1; }
NOTIFY_CHANNEL="${NOTIFY_CHANNEL:-$(prev_env NOTIFY_CHANNEL)}"
NOTIFY_ENV="${NOTIFY_ENV:-$(prev_env NOTIFY_ENV)}"
node_dir="$(dirname "$(command -v node)")"
cat > "$unit/gvr-maps-update.service" <<EOF
[Unit]
@@ -58,5 +68,9 @@ Persistent=true
WantedBy=timers.target
EOF
systemctl --user daemon-reload
systemctl --user enable --now gvr-maps-update.timer
echo "설치 완료: $GVR_MAPS_HOME · $(systemctl --user list-timers gvr-maps-update.timer --no-legend | head -1)"
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)"
else
echo "설치 완료: $GVR_MAPS_HOME · 자동 갱신 타이머는 꺼진 채로 둠 (켜기: systemctl --user enable --now gvr-maps-update.timer, 한 번만: systemctl --user start gvr-maps-update)"
fi

View File

@@ -1,7 +1,13 @@
#!/usr/bin/env python3
"""gvr-map-extract 결과(<코드>.glb + <코드>.json)를 사이트용으로 압축한다.
pack.py <추출 폴더> <출력 폴더> <버전(예: VALORANT_13.08)>
(agents.json 이 있으면 요원 agent_*.glb · 무기 weapon_*.glb 도 같은 폴더에, index.json agents · weapons.
viewmodels.json 이 있으면 1인칭 팔 fparms_*.glb · 무기 fpweapon_*.glb · 팔 동작 fpanim_*.glb, index.json viewmodels.
anims.glb 가 있으면 공용 애니메이션 index.json anims, abilities/abilities.json 이 있으면 스킬 재료 index.json abilities)
출력: <출력>/<dir>/<코드>.glb.gz (gltfpack -cc 로 meshopt 압축 · 위치 양자화 → gzip) + <출력>/index.json
-ke: 재질 extras(두 층 섞기 B 층 · 구운 조명 K) 유지
-vtf: UV 를 실수 그대로. gltfpack 은 재질마다 TEXCOORD_0(반복 UV, 수십 단위) · TEXCOORD_1(라이트맵 아틀라스 0~1)을
한 범위로 묶어 양자화해서, 정수로 줄이면 라이트맵 UV 가 몇 텍셀씩 어긋난다 (meshopt 압축 뒤 크기는 비슷)
사이트 서버 data/maps3d 에 그대로 올리면 된다 (site/server/src/maps3d.ts)."""
import datetime, gzip, json, os, re, shutil, subprocess, sys
@@ -11,7 +17,7 @@ d = re.sub(r'[^\w.-]', '_', f'{version}-{stamp}')
os.makedirs(os.path.join(out, d), exist_ok=True)
maps = {}
for name in sorted(os.listdir(src)):
if not name.endswith('.json'):
if not name.endswith('.json') or name in ('agents.json', 'viewmodels.json'):
continue
info = json.load(open(os.path.join(src, name)))
code = info['code']
@@ -19,14 +25,76 @@ for name in sorted(os.listdir(src)):
if not os.path.exists(glb) or info.get('triangles', 0) == 0:
continue
packed = os.path.join(out, d, code + '.glb')
subprocess.run(['npx', '-y', 'gltfpack@1.3.0', '-i', glb, '-o', packed, '-cc'], check=True, stdout=subprocess.DEVNULL)
subprocess.run(['npx', '-y', 'gltfpack@1.3.0', '-i', glb, '-o', packed, '-cc', '-ke', '-vtf'], check=True, stdout=subprocess.DEVNULL)
with open(packed, 'rb') as f, gzip.open(packed + '.gz', 'wb', 9) as g:
shutil.copyfileobj(f, g)
os.remove(packed)
size = os.path.getsize(packed + '.gz')
maps[info['mapUrl']] = {'code': code, 'file': code + '.glb', 'bytes': size, 'triangles': info['triangles']}
print(f"{code}: {info['triangles']} 삼각형 → {size / 1e6:.1f}MB")
idx = {'version': version, 'dir': d, 'updatedAt': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'maps': maps}
# 요원 · 무기 (agents 명령 결과 agents.json 이 있으면): 뼈대 · 애니메이션 · 노드 이름을 지킨다 (-kn)
agents, weapons = {}, {}
def pack_one(file):
glb = os.path.join(src, file)
if not os.path.exists(glb):
return None
packed = os.path.join(out, d, file)
subprocess.run(['npx', '-y', 'gltfpack@1.3.0', '-i', glb, '-o', packed, '-cc', '-kn', '-ke'], check=True, stdout=subprocess.DEVNULL)
with open(packed, 'rb') as f, gzip.open(packed + '.gz', 'wb', 9) as g:
shutil.copyfileobj(f, g)
os.remove(packed)
return os.path.getsize(packed + '.gz')
aj = os.path.join(src, 'agents.json')
if os.path.exists(aj):
a = json.load(open(aj))
for cls, v in a.get('agents', {}).items():
size = pack_one(v['file'])
if size:
agents[cls] = {'code': v['code'], 'file': v['file'], 'bytes': size}
for name, v in a.get('weapons', {}).items():
size = pack_one(v['file'])
if size:
weapons[name] = {'file': v['file'], 'bytes': size, 'points': v.get('points') or {}}
print(f'요원 {len(agents)} · 무기 {len(weapons)}')
# 1인칭 팔 · 무기 · 팔 동작 (viewmodels 명령 결과 viewmodels.json): 뼈대 · 동작 · 노드 이름을 지킨다 (-kn)
viewmodels = None
vj = os.path.join(src, 'viewmodels.json')
if os.path.exists(vj):
v = json.load(open(vj))
vm_arms, vm_weapons, total = {}, {}, 0
for cls, a in v.get('arms', {}).items():
size = pack_one(a['file'])
if size:
vm_arms[cls] = {'code': a['code'], 'file': a['file'], 'bytes': size}
total += size
for name, w in v.get('weapons', {}).items():
s1, s2 = pack_one(w['file']), pack_one(w['anim'])
if s1 and s2:
vm_weapons[name] = {'file': w['file'], 'anim': w['anim'], 'clips': w.get('clips') or [], 'gunClips': w.get('gunClips') or [], 'points': w.get('points') or {}, 'bytes': s1 + s2}
total += s1 + s2
viewmodels = {'arms': vm_arms, 'weapons': vm_weapons}
print(f'1인칭 팔 {len(vm_arms)} · 무기 {len(vm_weapons)} · {total / 1e6:.1f}MB')
# 공용 애니메이션 (anims 명령 결과 anims.glb): 뼈 이름으로 요원 몸에 붙인다 (-kn)
anims = None
if os.path.exists(os.path.join(src, 'anims.glb')):
size = pack_one('anims.glb')
anims = {'file': 'anims.glb', 'bytes': size}
print(f'공용 애니메이션 {size / 1e6:.1f}MB')
# 스킬 재료 (abilities 명령 결과 abilities/ 폴더): abilities.json · m_*.glb · t_*.png 를 gzip 만 한다
# (메시는 작고 뼈대 · 텍스처가 든 것도 있어 gltfpack 을 거치지 않는다)
abilities = None
ad = os.path.join(src, 'abilities')
if os.path.exists(os.path.join(ad, 'abilities.json')):
total = 0
for f in sorted(os.listdir(ad)):
if not (f == 'abilities.json' or (f.startswith(('m_', 't_')) and f.endswith(('.glb', '.png')))):
continue
with open(os.path.join(ad, f), 'rb') as fi, gzip.open(os.path.join(out, d, f + '.gz'), 'wb', 9) as g:
shutil.copyfileobj(fi, g)
total += os.path.getsize(os.path.join(out, d, f + '.gz'))
abilities = {'file': 'abilities.json', 'bytes': os.path.getsize(os.path.join(out, d, 'abilities.json.gz'))}
print(f'스킬 재료 {total / 1e6:.1f}MB')
idx = {'version': version, 'dir': d, 'updatedAt': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'maps': maps, 'agents': agents, 'weapons': weapons, 'anims': anims, 'abilities': abilities, 'viewmodels': viewmodels}
tmp = os.path.join(out, 'index.json.tmp')
json.dump(idx, open(tmp, 'w'), ensure_ascii=False, indent=1)
os.replace(tmp, os.path.join(out, 'index.json'))

View File

@@ -1,6 +1,7 @@
#!/usr/bin/env bash
# update.sh 시험 (네트워크 · 사이트 서버 없이): 가짜 추출기 · 가짜 pack.py · ssh/scp 를 로컬 복사로 바꿔
# 성공 → 변경 없음 → 추출 실패(첫 실패만 알림, 대기) → 재시도 간격 2배 → 맵 누락이면 안 올림 → 압축 실패 → 복구 → uedb 장애
# 요원 · 무기: 전체 실패 · 일부 실패 · 빠진 결과는 안 올리고(사이트 목록 그대로) 다시 해 봄 → 복구
set -uo pipefail
UPD="$(cd "$(dirname "$0")" && pwd)/update.sh"
T="$(mktemp -d "${TMPDIR:-/tmp}/gvr-upd-test.XXXXXX")"
@@ -17,6 +18,20 @@ E
cat > "$T/fakebin" <<'E'
#!/bin/bash
[ "$1" = manifest ] && { echo "https://x/releases/${FAKE_MANIFEST:-AAA}.manifest"; exit 0; }
# 공용 애니메이션 · 1인칭 · 스킬 재료: 이 시험에서는 만들 것 없이 성공
[ "$1" = anims ] && exit 0
[ "$1" = viewmodels ] && exit 0
[ "$1" = abilities ] && { mkdir -p "$2"; exit 0; }
if [ "$1" = agents ]; then
# 요원 · 무기: FAKE_FAIL=agents 면 아무것도 못 뽑고 실패, agents-partial 이면 하나만 뽑고 실패 (실제 추출기처럼 종료 코드 1)
[ "${FAKE_FAIL:-}" = agents ] && exit 1
ag=${FAKE_AGENTS:-Wushu Hunter}; [ "${FAKE_FAIL:-}" = agents-partial ] && ag=Wushu
a=""; for c in $ag; do a="$a\"${c}_PC_C\":{\"code\":\"$c\",\"file\":\"agent_$c.glb\"},"; echo glb > "$2/agent_$c.glb"; done
echo glb > "$2/weapon_Vandal.glb"
echo "{\"agents\":{${a%,}},\"weapons\":{\"Vandal\":{\"file\":\"weapon_Vandal.glb\"}}}" > "$2/agents.json"
[ "${FAKE_FAIL:-}" = agents-partial ] && exit 1
exit 0
fi
[ "${FAKE_FAIL:-}" = extract ] && exit 1
for m in ${FAKE_MAPS:-Ascent Bind}; do echo "{\"code\":\"$m\",\"mapUrl\":\"/Game/Maps/$m/$m\",\"triangles\":10}" > "$2/$m.json"; echo glb > "$2/$m.glb"; done
E
@@ -24,9 +39,10 @@ cat > "$T/home/scripts/pack.py" <<'E'
import json, os, sys
src, out, ver = sys.argv[1:4]; d = ver + '-' + os.environ.get('FAKE_STAMP', '1'); os.makedirs(f'{out}/{d}', exist_ok=True); maps = {}
for n in os.listdir(src):
if n.endswith('.json'):
if n.endswith('.json') and n != 'agents.json':
i = json.load(open(f'{src}/{n}')); open(f"{out}/{d}/{i['code']}.glb.gz", 'w').write('x'); maps[i['mapUrl']] = {'code': i['code'], 'file': i['code'] + '.glb', 'bytes': 1, 'triangles': 10}
json.dump({'version': ver, 'dir': d, 'maps': maps}, open(f'{out}/index.json', 'w'))
a = json.load(open(f'{src}/agents.json')) if os.path.exists(f'{src}/agents.json') else {}
json.dump({'version': ver, 'dir': d, 'maps': maps, 'agents': a.get('agents', {}), 'weapons': a.get('weapons', {})}, open(f'{out}/index.json', 'w'))
E
chmod +x "$T/shim/"* "$T/fakebin"
echo usmap > "$T/m_br.usmap"
@@ -35,10 +51,11 @@ run() { PATH="$T/shim:$PATH" GVR_MAPS_HOME="$T/home" SITE_HOST=x SITE_DATA="$T/s
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"; }
agents() { jq -c '[(.agents // {} | keys | length), (.weapons // {} | keys | length)]' "$T/site/maps3d/index.json"; }
fail=0
ok() { if eval "$2"; then echo "ok - $1"; else echo "not ok - $1"; fail=1; fi; }
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 "처음: 올리고 알림" '[[ "$o" == *"사이트 반영 완료: 맵 2"* && "$o" == *"알림: 🗺️"* && "$(maps)" == *Bind* ]]'
o="$(run)"; ok "처음: 올리고 알림 (요원 2 · 무기 1 포함)" '[[ "$o" == *"사이트 반영 완료: 맵 2"* && "$o" == *"알림: 🗺️"* && "$(maps)" == *Bind* && "$(agents)" == "[2,1]" ]]'
o="$(run)"; ok "같으면 변경 없음" '[[ "$o" == *"변경 없음"* ]]'
o="$(FAKE_MANIFEST=BBB FAKE_FAIL=extract run)"; ok "추출 실패: 첫 실패 알림 · 30분 대기" '[[ "$o" == *"알림: ⚠️"* && "$o" == *"30분 뒤"* && "$(st failCount)" == 1 ]]'
o="$(FAKE_MANIFEST=BBB run)"; ok "대기 중에는 다시 안 함" '[[ "$o" == *"이후 다시"* ]]'
@@ -47,6 +64,13 @@ ready; o="$(FAKE_MANIFEST=BBB FAKE_MAPS=Ascent FAKE_STAMP=2 run)"; ok "맵이
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 ]]'
# 요원 · 무기 추출 실패: 맵이 다 있어도 안 올리고 사이트 목록 유지, 재시도
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]" ]]'
ready; o="$(FAKE_MANIFEST=EEE FAKE_MAPS="Ascent Bind Haven" FAKE_AGENTS=Wushu FAKE_STAMP=5 run)"; ok "추출은 성공했지만 요원이 빠진 결과: 안 올림 · 유지" '[[ "$o" == *"빠진 요원: Hunter_PC_C"* && "$(agents)" == "[2,1]" && "$(st failed)" == *EEE* ]]'
o="$(FAKE_MANIFEST=EEE run)"; ok "실패 기록이 남아 변경 없음으로 넘기지 않음 (대기 후 재시도)" '[[ "$o" == *"이후 다시"* && "$o" != *"변경 없음"* ]]'
ready; o="$(FAKE_MANIFEST=EEE FAKE_MAPS="Ascent Bind Haven" FAKE_AGENTS="Wushu Hunter Sarge" FAKE_STAMP=6 run)"; ok "요원 복구: 새 요원 포함해 올림" '[[ "$o" == *"사이트 반영 완료"* && "$(agents)" == "[3,1]" && "$(st failCount)" == 0 ]]'
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\"]" ]]'
exit $fail

View File

@@ -3,11 +3,11 @@
#
# 1. uedb.dev 발로란트 매핑(.usmap) 버전 · 라이브 패치 매니페스트를 본다. 지난번에 올린 것과 같으면 끝
# 2. 새 매핑이면 받아서 보관한다: $GVR_MAPS_HOME/mappings/ + nextcloud claude/game-voice-recorder/valorant/mappings/
# 3. 모든 맵을 Riot CDN 에서 바로 뽑고(gvr-map-extract, 필요한 조각만 받음 · 디스크 거의 안 씀) 압축한다 (pack.py)
# 3. 모든 맵 · 요원 · 무기를 Riot CDN 에서 바로 뽑고(gvr-map-extract, 필요한 조각만 받음 · 디스크 거의 안 씀) 압축한다 (pack.py)
# 4. 사이트 서버(.5) data/maps3d 에 올리고 index.json 을 바꿔 끼운다 → 사이트가 바로 새 맵을 쓴다
#
# 실패하면(어느 단계든) 사이트는 이전 맵을 그대로 쓰고, 같은 조합은 30분 · 1시간 · 2시간 … 최대 6시간 간격으로 다시 해 본다.
# 처음 실패 · 다시 성공했을 때 알린다. 지금 올라가 있는 맵 중 하나라도 새 결과에 없으면 올리지 않는다 (일부 누락 방지).
# 실패하면(어느 단계든, 요원 · 무기 추출 포함) 사이트는 이전 맵 · 요원 · 무기를 그대로 쓰고, 같은 조합은 30분 · 1시간 · 2시간 … 최대 6시간 간격으로 다시 해 본다.
# 처음 실패 · 다시 성공했을 때 알린다. 지금 올라가 있는 맵 · 요원 · 무기 중 하나라도 새 결과에 없으면 올리지 않는다 (일부 누락 방지).
# 강제로 다시(대기 · 누락 검사 무시): update.sh --force
set -Eeuo pipefail
GVR_MAPS_HOME="${GVR_MAPS_HOME:-$HOME/gvr-maps}"
@@ -122,20 +122,31 @@ out="$GVR_MAPS_HOME/work/out"
rm -rf "$raw" "$out"
mkdir -p "$raw" "$out"
GVR_USMAP="$usmap" GVR_MANIFEST="$manifest" "$BIN" extract "$raw"
# 요원 3D 몸 · 애니메이션 · 무기. 하나라도 실패하면 맵과 같이 올리지 않는다 (사이트의 이전 맵 · 요원 · 무기 유지, 재시도)
stage="요원 추출"
GVR_USMAP="$usmap" GVR_MANIFEST="$manifest" "$BIN" agents "$raw"
GVR_USMAP="$usmap" GVR_MANIFEST="$manifest" "$BIN" anims "$raw"
# 1인칭 팔 · 무기 · 동작 (사이트 1인칭 화면)
GVR_USMAP="$usmap" GVR_MANIFEST="$manifest" "$BIN" viewmodels "$raw"
# 스킬 재료 (메시 · 파티클 · 텍스처, 사이트가 스킬 효과를 그린다)
GVR_USMAP="$usmap" GVR_MANIFEST="$manifest" "$BIN" abilities "$raw/abilities"
stage="압축"
python3 "$GVR_MAPS_HOME/scripts/pack.py" "$raw" "$out" "$version"
dir="$(jq -r .dir "$out/index.json")"
count="$(jq '.maps | length' "$out/index.json")"
# 지금 사이트에 있는 맵이 새 결과에 다 있어야 올린다 (일부만 뽑힌 결과로 덮어쓰지 않게)
# 지금 사이트에 있는 맵 · 요원 · 무기가 새 결과에 다 있어야 올린다 (일부만 뽑힌 결과로 덮어쓰지 않게)
# 대소문자는 보지 않는다: 패치에서 폴더 이름 대소문자만 바뀌기도 하고(13.09 /Game/Maps/FoxTrot → Foxtrot) 사이트도 대소문자 무시로 찾는다
stage="맵 목록 대조"
cur="$(ssh -o BatchMode=yes "$SITE_HOST" "cat '$SITE_DATA/maps3d/index.json' 2>/dev/null || echo '{}'")"
prev="$(jq -r '.dir // empty' <<<"$cur")"
missing="$(jq -rn --argjson a "$cur" --slurpfile b "$out/index.json" '[($a.maps // {}) | keys[] as $k | select(($b[0].maps | has($k)) | not) | $k] | join(", ")')"
if [ -n "$missing" ] && [ "$FORCE" = 0 ]; then
log "새 결과에 빠진 맵: $missing → 올리지 않음 (게임에서 정말 빠진 맵이면 update.sh --force)"
false
fi
for kind in maps:맵 agents:요원 weapons:무기; do
missing="$(jq -rn --arg f "${kind%%:*}" --argjson a "$cur" --slurpfile b "$out/index.json" '(($b[0][$f] // {}) | keys | map(ascii_downcase)) as $nk | [($a[$f] // {}) | keys[] | select(ascii_downcase as $l | $nk | index([$l]) | not)] | join(", ")')"
if [ -n "$missing" ] && [ "$FORCE" = 0 ]; then
log "새 결과에 빠진 ${kind#*:}: $missing → 올리지 않음 (게임에서 정말 빠졌으면 update.sh --force)"
false
fi
done
[ "$count" -gt 0 ] || { log "맵 0개 → 올리지 않음"; false; }
# 4. 사이트 서버에 올리기 (폴더 먼저, index.json 은 마지막에 바꿔 끼움)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,354 @@
using System.Text.Json.Nodes;
using CUE4Parse.FileProvider;
using CUE4Parse.UE4.Assets.Exports.Animation;
using CUE4Parse.UE4.Assets.Exports.Component.SkeletalMesh;
using CUE4Parse.UE4.Assets.Exports.Material;
using CUE4Parse.UE4.Assets.Exports.SkeletalMesh;
using CUE4Parse.UE4.Objects.Core.Math;
using CUE4Parse_Conversion.Animations;
using CUE4Parse_Conversion.Dto;
using CUE4Parse_Conversion.Options;
namespace GvrMapExtract;
/// <summary>
/// 요원 3인칭 몸 (뼈대 · 피부 · 텍스처) + 공용 애니메이션을 요원마다 glb 하나로.
/// 좌표는 게임(UE) 그대로: cm, 메시 공간(발이 z=0 근처, 앞이 +Y). 사이트가 리플레이 좌표 · yaw 로 옮긴다.
/// 애니메이션은 위 · 아래 몸을 나눠 넣는다 (사이트가 위 = 총 든 자세, 아래 = 서기/걷기/달리기 방향을 따로 섞는다):
/// ub_rifle Spine1 아래 (총 든 서 있는 자세, Core_Rifle_Idle)
/// lb_idle Splitter · Pelvis 아래 (Core_Rifle_Idle 다리)
/// lb_run{N,S,E,W} TP_Core_Run*_LB, lb_walk{N,S,E,W} TP_Core_Walk*_LB
/// Skeleton · Root 뼈는 회전만 넣는다 (애니메이션 이동은 리플레이 위치가 대신한다).
/// </summary>
public static class Agents
{
private const string Anims = "/Game/Characters/_Core/3P/Anims/";
private static readonly (string Name, string Path, bool Upper)[] Clips =
[
("ub_rifle", Anims + "Rifle/Core_Rifle_Idle", true),
("lb_idle", Anims + "Rifle/Core_Rifle_Idle", false),
("lb_runN", Anims + "TP_Core_RunN_LB", false),
("lb_runS", Anims + "TP_Core_RunS_LB", false),
("lb_runE", Anims + "TP_Core_RunE_LB", false),
("lb_runW", Anims + "TP_Core_RunW_LB", false),
("lb_walkN", Anims + "TP_Core_WalkN_LB", false),
("lb_walkS", Anims + "TP_Core_WalkS_LB", false),
("lb_walkE", Anims + "TP_Core_WalkE_LB", false),
("lb_walkW", Anims + "TP_Core_WalkW_LB", false),
];
/// <summary>요원 = Characters/&lt;코드&gt;/&lt;코드&gt;_PC 블루프린트. 리플레이 선수 캐릭터 이름(Wushu_PC_C)과 같다</summary>
public static List<(string Code, string Blueprint)> Find(IFileProvider provider)
{
var res = new List<(string, string)>();
foreach (var k in provider.Files.Keys.Where(k => k.StartsWith("ShooterGame/Content/Characters/", StringComparison.OrdinalIgnoreCase) && k.EndsWith("_PC.uasset", StringComparison.OrdinalIgnoreCase)).OrderBy(k => k))
{
var parts = k.Split('/');
if (parts.Length != 5) continue; // Characters/<코드>/<코드>_PC.uasset 만
var code = parts[3];
if (!parts[4].Equals(code + "_PC.uasset", StringComparison.OrdinalIgnoreCase) || code.StartsWith('_')) continue;
res.Add((code, k));
}
return res;
}
/// <summary>블루프린트의 3인칭 몸 (SkeletalMeshComponent 중 /3P/ 의 요원 전용 메시)</summary>
public static USkeletalMesh? BodyMesh(IFileProvider provider, string blueprint)
{
var pkg = provider.LoadPackage(blueprint);
foreach (var e in pkg.GetExports().OfType<USkeletalMeshComponent>())
{
var idx = e.GetOrDefault<CUE4Parse.UE4.Objects.UObject.FPackageIndex?>("SkeletalMesh") ?? e.GetOrDefault<CUE4Parse.UE4.Objects.UObject.FPackageIndex?>("SkinnedAsset");
var path = idx?.ResolvedObject?.GetPathName() ?? "";
if (!path.Contains("/3P/") || path.Contains("/_Core/")) continue;
try { return idx!.Load<USkeletalMesh>(); } catch { }
}
return null;
}
public sealed record Result(int Triangles, int Bones, int Clips, int Textures, long TextureBytes);
public static Result Export(IFileProvider provider, USkeletalMesh mesh, string file, int maxTex, int lodWant)
{
var glb = new Glb();
var tex = new TexStore(provider, glb, maxTex);
var (boneNode, bones, skin, tris) = Skinned(provider, glb, tex, mesh, lodWant);
// 애니메이션
var nameToBone = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
for (var i = 0; i < bones.Length; i++) nameToBone.TryAdd(bones[i].Name, i);
var upperSet = Subtree(bones, "Spine1");
upperSet.UnionWith(Subtree(bones, "MasterWeaponAim")); // 총 붙는 뼈 (R_WeaponMaster) 도 위 몸 자세를 따른다
var lowerSet = Subtree(bones, "Pelvis");
if (nameToBone.TryGetValue("Splitter", out var spl)) lowerSet.Add(spl);
// Skeleton · Root 는 회전만 (애니메이션에 따라 몸 방향을 여기서 보정한다). 이동(루트 모션)은 뺀다
var rootOnlyRot = new HashSet<int>();
foreach (var n in new[] { "Skeleton", "Root" })
if (nameToBone.TryGetValue(n, out var ri)) { lowerSet.Add(ri); rootOnlyRot.Add(ri); }
var animations = new JsonArray();
foreach (var (name, path, upper) in Clips)
{
try
{
var a = provider.LoadPackageObject<UAnimSequence>(path + "." + path[(path.LastIndexOf('/') + 1)..]);
var set = a.ConvertAnims();
var seq = set.Sequences[0];
seq.RetargetTracks(mesh.ReferenceSkeleton);
var anim = Clip(glb, seq, set.Skeleton, nameToBone, upper ? upperSet : lowerSet, boneNode, bones, name, rootOnlyRot);
if (anim != null) animations.Add(anim);
}
catch (Exception e)
{
Console.Error.WriteLine($" 애니메이션 {name} 실패: {e.GetType().Name} {e.Message}");
}
}
glb.Write(file, new JsonObject { ["skins"] = new JsonArray(skin), ["animations"] = animations });
return new Result(tris, bones.Length, animations.Count, tex.Count, tex.Bytes);
}
/// <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)
{
var dto = new SkeletalMeshDto(mesh, EMeshQuality.All);
var lod = dto.LODs[Math.Min(lodWant, dto.LODs.Count - 1)];
var bones = dto.Bones;
// 뼈 노드 (참조 자세 TRS), 부모-자식
var boneNode = new int[bones.Length];
for (var i = 0; i < bones.Length; i++)
{
var t = bones[i].Transform;
glb.Nodes.Add(new JsonObject
{
["name"] = bones[i].Name,
["translation"] = Arr(t.Translation.X, t.Translation.Y, t.Translation.Z),
["rotation"] = Arr(t.Rotation.X, t.Rotation.Y, t.Rotation.Z, t.Rotation.W),
["scale"] = Arr(t.Scale3D.X, t.Scale3D.Y, t.Scale3D.Z),
});
boneNode[i] = glb.Nodes.Count - 1;
}
for (var i = 0; i < bones.Length; i++)
{
var p = bones[i].ParentIndex;
if (p < 0) { glb.Roots.Add(boneNode[i]); continue; }
var parent = glb.Nodes[boneNode[p]]!.AsObject();
if (parent["children"] is not JsonArray ch) parent["children"] = ch = new JsonArray();
ch.Add(boneNode[i]);
}
// 역바인드 행렬 = (참조 자세 전역 행렬)^-1
var global = new Mat4[bones.Length];
for (var i = 0; i < bones.Length; i++)
{
var local = Mat4.Trs(bones[i].Transform);
global[i] = bones[i].ParentIndex >= 0 ? global[bones[i].ParentIndex] * local : local;
}
var ibm = new float[bones.Length * 16];
for (var i = 0; i < bones.Length; i++) global[i].Inverse().CopyTo(ibm, i * 16);
var skin = new JsonObject
{
["joints"] = new JsonArray(boneNode.Select(x => (JsonNode)x).ToArray()),
["inverseBindMatrices"] = glb.Raw(ibm, "MAT4"),
["skeleton"] = boneNode[0],
};
// 정점 (모든 구간 공유) + 재질별 primitive
var vs = lod.Vertices;
var pos = new float[vs.Length * 3];
var nrm = new float[vs.Length * 3];
var uv = new float[vs.Length * 2];
var joints = new ushort[vs.Length * 4];
var weights = new float[vs.Length * 4];
for (var i = 0; i < vs.Length; i++)
{
var v = vs[i];
pos[i * 3] = v.Position.X; pos[i * 3 + 1] = v.Position.Y; pos[i * 3 + 2] = v.Position.Z;
var n = new FVector(v.Normal.X, v.Normal.Y, v.Normal.Z);
var len = n.Size();
if (len > 1e-6f) n /= len;
nrm[i * 3] = n.X; nrm[i * 3 + 1] = n.Y; nrm[i * 3 + 2] = n.Z;
uv[i * 2] = v.Uv.U; uv[i * 2 + 1] = v.Uv.V;
var inf = v.Influences.OrderByDescending(x => x.Weight).Take(4).ToArray();
var sum = inf.Sum(x => x.Weight);
for (var k = 0; k < inf.Length; k++)
{
joints[i * 4 + k] = inf[k].Bone;
weights[i * 4 + k] = sum > 0 ? inf[k].Weight / sum : (k == 0 ? 1 : 0);
}
if (inf.Length == 0) weights[i * 4] = 1;
}
var aPos = glb.Floats(pos, 3, bounds: true);
var aNrm = glb.Floats(nrm, 3);
var aUv = glb.Floats(uv, 2);
var aJ = glb.Ushorts(joints, 4);
var aW = glb.Floats(weights, 4);
var prims = new JsonArray();
var tris = 0;
foreach (var sec in lod.Sections)
{
if (!sec.IsValid || sec.NumFaces <= 0) continue;
UMaterialInterface? m = null;
try { m = 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))
{
if (Environment.GetEnvironmentVariable("GVR_DEBUG") != null) Console.Error.WriteLine($" 뺀 재질 {m?.Name} {mp.BlendMode} {mp.Base} 삼각형 {sec.NumFaces}");
continue;
}
var texPath = mp == null ? null : new[] { "Diffuse", "DF", "Albedo", "Base Color", "BaseColor", "Diffuse Map" }.Select(n => mp.Textures.GetValueOrDefault(n)).FirstOrDefault(x => !string.IsNullOrEmpty(x))
?? mp.Textures.FirstOrDefault(kv => kv.Value.EndsWith("_DF", StringComparison.OrdinalIgnoreCase) || kv.Value.Contains("_DF.", StringComparison.OrdinalIgnoreCase)).Value;
var t = tex.Get(texPath);
var pbr = new JsonObject { ["metallicFactor"] = 0, ["roughnessFactor"] = 0.8 };
if (t is { } tt) pbr["baseColorTexture"] = new JsonObject { ["index"] = tt.tex };
else pbr["baseColorFactor"] = Arr(0.55f, 0.55f, 0.6f, 1);
var mat = new JsonObject { ["name"] = m?.Name ?? "none", ["pbrMetallicRoughness"] = pbr };
if (mp?.BlendMode == "BLEND_Masked" && t is { alpha: true })
{
mat["alphaMode"] = "MASK";
mat["alphaCutoff"] = 0.333;
mat["doubleSided"] = true;
}
glb.Materials.Add(mat);
// UE 왼손 좌표 → glTF 앞면 방향으로 삼각형을 뒤집는다 (맵과 같음)
var idx = new uint[sec.NumFaces * 3];
for (var f = 0; f < sec.NumFaces; f++)
{
idx[f * 3] = lod.Indices[sec.FirstIndex + f * 3];
idx[f * 3 + 1] = lod.Indices[sec.FirstIndex + f * 3 + 2];
idx[f * 3 + 2] = lod.Indices[sec.FirstIndex + f * 3 + 1];
}
tris += sec.NumFaces;
prims.Add(new JsonObject
{
["attributes"] = new JsonObject { ["POSITION"] = aPos, ["NORMAL"] = aNrm, ["TEXCOORD_0"] = aUv, ["JOINTS_0"] = aJ, ["WEIGHTS_0"] = aW },
["indices"] = glb.Indices(idx),
["material"] = glb.Materials.Count - 1,
});
}
glb.Meshes.Add(new JsonObject { ["name"] = mesh.Name, ["primitives"] = prims });
glb.Nodes.Add(new JsonObject { ["name"] = mesh.Name, ["mesh"] = glb.Meshes.Count - 1, ["skin"] = skinIndex });
glb.Roots.Add(glb.Nodes.Count - 1);
return (boneNode, bones, skin, tris);
}
internal static HashSet<int> Subtree(MeshBoneDto[] bones, string rootName)
{
var set = new HashSet<int>();
var root = Array.FindIndex(bones, b => b.Name.Equals(rootName, StringComparison.OrdinalIgnoreCase));
if (root < 0) return set;
set.Add(root);
for (var i = root + 1; i < bones.Length; i++)
if (bones[i].ParentIndex >= 0 && set.Contains(bones[i].ParentIndex)) set.Add(i);
return set;
}
/// <summary>한 애니메이션을 glTF 애니메이션으로: 고른 뼈만, 프레임마다 회전(+움직이면 이동)</summary>
internal static JsonObject? Clip(Glb glb, CUE4Parse_Conversion.Writers.ActorX.Structs.Animations.CAnimSequence seq, USkeleton skel, Dictionary<string, int> nameToBone, HashSet<int> only, int[] boneNode, MeshBoneDto[] bones, string name, HashSet<int> noTranslate)
{
var frames = Math.Max(1, seq.NumFrames);
var fps = seq.FramesPerSecond > 0 ? seq.FramesPerSecond : 30;
var times = Enumerable.Range(0, frames).Select(f => f / fps).ToArray();
var tAcc = glb.Floats(times, 1, bounds: true);
var samplers = new JsonArray();
var channels = new JsonArray();
var info = skel.ReferenceSkeleton.FinalRefBoneInfo;
for (var si = 0; si < seq.Tracks.Count && si < info.Length; si++)
{
var track = seq.Tracks[si];
if (!track.HasKeys() || !nameToBone.TryGetValue(info[si].Name.Text, out var bi) || !only.Contains(bi)) continue;
var rot = new float[frames * 4];
var tr = new float[frames * 3];
var movesT = false;
var refT = bones[bi].Transform.Translation;
for (var f = 0; f < frames; f++)
{
FQuat q = bones[bi].Transform.Rotation;
FVector p = refT, s = FVector.OneVector;
track.GetBoneTransform(f, frames, ref q, ref p, ref s);
q.Normalize();
// 이웃 프레임과 같은 반구 (보간이 반대로 돌지 않게)
if (f > 0 && q.X * rot[(f - 1) * 4] + q.Y * rot[(f - 1) * 4 + 1] + q.Z * rot[(f - 1) * 4 + 2] + q.W * rot[(f - 1) * 4 + 3] < 0) q = new FQuat(-q.X, -q.Y, -q.Z, -q.W);
rot[f * 4] = q.X; rot[f * 4 + 1] = q.Y; rot[f * 4 + 2] = q.Z; rot[f * 4 + 3] = q.W;
tr[f * 3] = p.X; tr[f * 3 + 1] = p.Y; tr[f * 3 + 2] = p.Z;
if ((p - refT).Size() > 0.05f) movesT = true;
}
samplers.Add(new JsonObject { ["input"] = tAcc, ["output"] = glb.Floats(rot, 4), ["interpolation"] = "LINEAR" });
channels.Add(new JsonObject { ["sampler"] = samplers.Count - 1, ["target"] = new JsonObject { ["node"] = boneNode[bi], ["path"] = "rotation" } });
if (movesT && !noTranslate.Contains(bi))
{
samplers.Add(new JsonObject { ["input"] = tAcc, ["output"] = glb.Floats(tr, 3), ["interpolation"] = "LINEAR" });
channels.Add(new JsonObject { ["sampler"] = samplers.Count - 1, ["target"] = new JsonObject { ["node"] = boneNode[bi], ["path"] = "translation" } });
}
}
if (channels.Count == 0) return null;
return new JsonObject { ["name"] = name, ["samplers"] = samplers, ["channels"] = channels };
}
private static JsonArray Arr(params float[] v) => new(v.Select(x => (JsonNode)x).ToArray());
}
/// <summary>열 우선 4x4 행렬 (glTF 와 같은 배치)</summary>
public readonly struct Mat4
{
private readonly double[] _m; // column-major
private Mat4(double[] m) => _m = m;
public static Mat4 Trs(FTransform t)
{
double x = t.Rotation.X, y = t.Rotation.Y, z = t.Rotation.Z, w = t.Rotation.W;
double sx = t.Scale3D.X, sy = t.Scale3D.Y, sz = t.Scale3D.Z;
var m = new double[16];
m[0] = (1 - 2 * (y * y + z * z)) * sx; m[1] = 2 * (x * y + z * w) * sx; m[2] = 2 * (x * z - y * w) * sx;
m[4] = 2 * (x * y - z * w) * sy; m[5] = (1 - 2 * (x * x + z * z)) * sy; m[6] = 2 * (y * z + x * w) * sy;
m[8] = 2 * (x * z + y * w) * sz; m[9] = 2 * (y * z - x * w) * sz; m[10] = (1 - 2 * (x * x + y * y)) * sz;
m[12] = t.Translation.X; m[13] = t.Translation.Y; m[14] = t.Translation.Z; m[15] = 1;
return new Mat4(m);
}
public static Mat4 operator *(Mat4 a, Mat4 b)
{
var r = new double[16];
for (var c = 0; c < 4; c++)
for (var rr = 0; rr < 4; rr++)
{
double s = 0;
for (var k = 0; k < 4; k++) s += a._m[k * 4 + rr] * b._m[c * 4 + k];
r[c * 4 + rr] = s;
}
return new Mat4(r);
}
public Mat4 Inverse()
{
var m = _m;
var inv = new double[16];
inv[0] = m[5] * m[10] * m[15] - m[5] * m[11] * m[14] - m[9] * m[6] * m[15] + m[9] * m[7] * m[14] + m[13] * m[6] * m[11] - m[13] * m[7] * m[10];
inv[4] = -m[4] * m[10] * m[15] + m[4] * m[11] * m[14] + m[8] * m[6] * m[15] - m[8] * m[7] * m[14] - m[12] * m[6] * m[11] + m[12] * m[7] * m[10];
inv[8] = m[4] * m[9] * m[15] - m[4] * m[11] * m[13] - m[8] * m[5] * m[15] + m[8] * m[7] * m[13] + m[12] * m[5] * m[11] - m[12] * m[7] * m[9];
inv[12] = -m[4] * m[9] * m[14] + m[4] * m[10] * m[13] + m[8] * m[5] * m[14] - m[8] * m[6] * m[13] - m[12] * m[5] * m[10] + m[12] * m[6] * m[9];
inv[1] = -m[1] * m[10] * m[15] + m[1] * m[11] * m[14] + m[9] * m[2] * m[15] - m[9] * m[3] * m[14] - m[13] * m[2] * m[11] + m[13] * m[3] * m[10];
inv[5] = m[0] * m[10] * m[15] - m[0] * m[11] * m[14] - m[8] * m[2] * m[15] + m[8] * m[3] * m[14] + m[12] * m[2] * m[11] - m[12] * m[3] * m[10];
inv[9] = -m[0] * m[9] * m[15] + m[0] * m[11] * m[13] + m[8] * m[1] * m[15] - m[8] * m[3] * m[13] - m[12] * m[1] * m[11] + m[12] * m[3] * m[9];
inv[13] = m[0] * m[9] * m[14] - m[0] * m[10] * m[13] - m[8] * m[1] * m[14] + m[8] * m[2] * m[13] + m[12] * m[1] * m[10] - m[12] * m[2] * m[9];
inv[2] = m[1] * m[6] * m[15] - m[1] * m[7] * m[14] - m[5] * m[2] * m[15] + m[5] * m[3] * m[14] + m[13] * m[2] * m[7] - m[13] * m[3] * m[6];
inv[6] = -m[0] * m[6] * m[15] + m[0] * m[7] * m[14] + m[4] * m[2] * m[15] - m[4] * m[3] * m[14] - m[12] * m[2] * m[7] + m[12] * m[3] * m[6];
inv[10] = m[0] * m[5] * m[15] - m[0] * m[7] * m[13] - m[4] * m[1] * m[15] + m[4] * m[3] * m[13] + m[12] * m[1] * m[7] - m[12] * m[3] * m[5];
inv[14] = -m[0] * m[5] * m[14] + m[0] * m[6] * m[13] + m[4] * m[1] * m[14] - m[4] * m[2] * m[13] - m[12] * m[1] * m[6] + m[12] * m[2] * m[5];
inv[3] = -m[1] * m[6] * m[11] + m[1] * m[7] * m[10] + m[5] * m[2] * m[11] - m[5] * m[3] * m[10] - m[9] * m[2] * m[7] + m[9] * m[3] * m[6];
inv[7] = m[0] * m[6] * m[11] - m[0] * m[7] * m[10] - m[4] * m[2] * m[11] + m[4] * m[3] * m[10] + m[8] * m[2] * m[7] - m[8] * m[3] * m[6];
inv[11] = -m[0] * m[5] * m[11] + m[0] * m[7] * m[9] + m[4] * m[1] * m[11] - m[4] * m[3] * m[9] - m[8] * m[1] * m[7] + m[8] * m[3] * m[5];
inv[15] = m[0] * m[5] * m[10] - m[0] * m[6] * m[9] - m[4] * m[1] * m[10] + m[4] * m[2] * m[9] + m[8] * m[1] * m[6] - m[8] * m[2] * m[5];
var det = m[0] * inv[0] + m[1] * inv[4] + m[2] * inv[8] + m[3] * inv[12];
if (Math.Abs(det) < 1e-12) det = 1e-12;
for (var i = 0; i < 16; i++) inv[i] /= det;
return new Mat4(inv);
}
public void CopyTo(float[] dst, int offset)
{
for (var i = 0; i < 16; i++) dst[offset + i] = (float)_m[i];
}
}

View File

@@ -0,0 +1,160 @@
using System.Text.Json.Nodes;
using CUE4Parse.FileProvider;
using CUE4Parse.UE4.Assets.Exports.Animation;
using CUE4Parse_Conversion.Animations;
using CUE4Parse_Conversion.Dto;
namespace GvrMapExtract;
/// <summary>
/// 모든 요원이 같이 쓰는 3인칭 애니메이션 (Core_Skeleton, 뼈 이름이 모든 요원과 같다) → anims.glb 하나.
/// 메시 없이 뼈 노드(Core_Skeleton 참조 자세)와 애니메이션만 들어 있다. 사이트는 뼈 이름으로 요원 몸에 붙이고,
/// 이동 트랙은 (요원 참조 자세 − 이 파일 참조 자세)만큼 옮겨 쓴다.
/// 이름: lb_* 아래 몸(Pelvis 아래 + Splitter, Skeleton · Root 는 회전만), ub_* 위 몸(Spine1 · MasterWeaponAim 아래), fb_* 온몸.
/// 게임의 더하기(additive) 애니메이션(조준 각 · 사격 반동)은 CUE4Parse 가 기준 자세(RefPoseSeq)에 더해 온 자세로 풀어 준다.
/// 그래서 조준 위 · 아래(*Up · *Down)와 사격(*Fire)도 온 자세다: 사이트가 보는 각 · 사격 순간에 따라 비율로 섞는다.
/// </summary>
public static class CoreAnims
{
private const string A = "/Game/Characters/_Core/3P/Anims/";
private const string D = "/Game/Characters/_Core/Death/3P/Anims/";
private const string Ak = "/Game/Equippables/Guns/Rifles/AK/S0/3P/Anims/TP_Core_AK_S0_";
private const string Pistol = "/Game/Equippables/Guns/Sidearms/BasePistol/S0/3P/Anims/TP_Core_BasePistol_S0_";
private const string Sniper = "/Game/Equippables/Guns/SniperRifles/Boltsniper/S0/3P/Anims/TP_Core_Boltsniper_S0_";
private const string Knife = "/Game/Equippables/Melee/S0/3P/Anims/TP_Core_Melee_S0_";
private const string Core = "/Game/Characters/_Core/3P/Models/Core_Skeleton";
private static readonly (string Name, string Path, char Part)[] Clips =
[
// 아래 몸: 앉기 · 점프
("lb_crouch", A + "TP_Core_CrouchIdle_LB", 'L'),
("lb_crouchN", A + "TP_Core_CrouchWalkN_LB", 'L'),
("lb_crouchS", A + "TP_Core_CrouchWalkS_LB", 'L'),
("lb_crouchE", A + "TP_Core_CrouchWalkE_LB", 'L'),
("lb_crouchW", A + "TP_Core_CrouchWalkW_LB", 'L'),
("lb_jump", A + "TP_Core_Jump_LB", 'L'),
("lb_fall", A + "TP_Core_Falling_LB", 'L'),
("lb_land", A + "TP_Core_JumpLand_LB", 'L'),
// 위 몸: 무기 종류별 자세 (서기 / 앉기) + 조준 위(Up, AimN) · 아래(Down, AimS)
("ub_rifle", Ak + "IdlePose_UB", 'U'),
("ub_rifleUp", Ak + "AimN_UB", 'U'),
("ub_rifleDown", Ak + "AimS_UB", 'U'),
("ub_rifleCrouch", Ak + "CrouchPose_UB", 'U'),
("ub_rifleCrouchUp", Ak + "CrouchAimN_UB", 'U'),
("ub_rifleCrouchDown", Ak + "CrouchAimS_UB", 'U'),
("ub_rifleFire", Ak + "FireAdd", 'U'),
("ub_pistol", Pistol + "AimC", 'U'),
("ub_pistolUp", Pistol + "AimN_UB", 'U'),
("ub_pistolDown", Pistol + "AimS_UB", 'U'),
("ub_pistolCrouch", Pistol + "CrouchPose_UB", 'U'),
("ub_pistolCrouchUp", Pistol + "Crouch_AimN_UB", 'U'),
("ub_pistolCrouchDown", Pistol + "Crouch_AimS_UB", 'U'),
("ub_pistolFire", Pistol + "FireAdd_UB", 'U'),
("ub_sniper", Sniper + "IdlePose_UB", 'U'),
("ub_sniperUp", Sniper + "AimN_UB", 'U'),
("ub_sniperDown", Sniper + "AimS_UB", 'U'),
("ub_sniperCrouch", Sniper + "CrouchPose_UB", 'U'),
("ub_sniperCrouchUp", Sniper + "CrouchAimN_UB", 'U'),
("ub_sniperCrouchDown", Sniper + "CrouchAimS_UB", 'U'),
("ub_sniperFire", Sniper + "Fire_UB", 'U'),
("ub_knife", Knife + "Aggressive_Idle_UB", 'U'),
("ub_knifeCrouch", Knife + "Aggressive_CrouchIdle_UB", 'U'),
("ub_ability", A + "Grenade/TP_Core_Grenade_Idle_UB", 'U'),
("ub_abilityCrouch", A + "Grenade/TP_Core_Grenade_CrouchIdle_UB", 'U'),
// 위 몸: 동작
("ub_throw", A + "TP_Core_Grenade_ThrowPrimary_UB", 'U'),
("ub_equipAbility", A + "TP_Core_Grenade_Equip_UB", 'U'),
("ub_reloadRifle", Ak + "Reload_UB", 'U'),
("ub_reloadPistol", Pistol + "Reload_UB", 'U'),
("ub_reloadSniper", Sniper + "Reload_UB", 'U'),
("ub_equipRifle", Ak + "Equip_UB", 'U'),
("ub_equipPistol", Pistol + "Equip_UB", 'U'),
("ub_equipSniper", Sniper + "Equip_UB", 'U'),
("ub_equipKnife", Knife + "Aggressive_Equip_UB", 'U'),
("ub_knifeAttack", Knife + "Aggressive_Attack01_UB", 'U'),
("ub_knifeAttack2", Knife + "Aggressive_Attack02_UB", 'U'),
("ub_knifeAlt", Knife + "Aggressive_Attack_Alt_UB", 'U'),
("ub_defuse", A + "Bomb/Core_Bomb_Spike_Defuse", 'U'),
];
/// <summary>죽는 모션 (온몸): 경기 기록의 TP_Core_Death_X_Montage → fb_X</summary>
private static readonly string[] Deaths =
[
"Belly_Front_LG", "Belly_Front_SM", "BigN", "BodyN_Small",
"Body_Back_LG", "Body_Back_SM", "Body_Front_LG", "Body_Front_SM", "Body_Left_LG", "Body_Left_SM", "Body_Right_LG", "Body_Right_SM",
"Head_Back_LG", "Head_Back_SM", "Head_Front_LG", "Head_Front_SM", "Head_Left_LG", "Head_Left_SM", "Head_Right_LG", "Head_Right_SM", "Headshot01",
"Leg_Back_LG", "Leg_Front_LG", "Leg_Left_LG", "Leg_Right_LG",
"Lumbar_Back_LG", "Lumbar_Back_SM",
];
public sealed record Result(int Clips, int Failed, List<string> Missing);
public static Result Export(IFileProvider provider, string file)
{
var skel = provider.LoadPackageObject<USkeleton>(Core + "." + Core[(Core.LastIndexOf('/') + 1)..]);
var info = skel.ReferenceSkeleton.FinalRefBoneInfo;
var pose = skel.ReferenceSkeleton.FinalRefBonePose;
var bones = info.Select((b, i) => new MeshBoneDto(b, pose[i])).ToArray();
var glb = new Glb();
var boneNode = new int[bones.Length];
for (var i = 0; i < bones.Length; i++)
{
var t = bones[i].Transform;
glb.Nodes.Add(new JsonObject
{
["name"] = bones[i].Name,
["translation"] = Arr(t.Translation.X, t.Translation.Y, t.Translation.Z),
["rotation"] = Arr(t.Rotation.X, t.Rotation.Y, t.Rotation.Z, t.Rotation.W),
["scale"] = Arr(t.Scale3D.X, t.Scale3D.Y, t.Scale3D.Z),
});
boneNode[i] = glb.Nodes.Count - 1;
}
for (var i = 0; i < bones.Length; i++)
{
var p = bones[i].ParentIndex;
if (p < 0) { glb.Roots.Add(boneNode[i]); continue; }
var parent = glb.Nodes[boneNode[p]]!.AsObject();
if (parent["children"] is not JsonArray ch) parent["children"] = ch = new JsonArray();
ch.Add(boneNode[i]);
}
var nameToBone = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
for (var i = 0; i < bones.Length; i++) nameToBone.TryAdd(bones[i].Name, i);
var upper = Agents.Subtree(bones, "Spine1");
upper.UnionWith(Agents.Subtree(bones, "MasterWeaponAim"));
var lower = Agents.Subtree(bones, "Pelvis");
if (nameToBone.TryGetValue("Splitter", out var spl)) lower.Add(spl);
var rootOnlyRot = new HashSet<int>();
foreach (var n in new[] { "Skeleton", "Root" })
if (nameToBone.TryGetValue(n, out var ri)) { lower.Add(ri); rootOnlyRot.Add(ri); }
var all = Enumerable.Range(0, bones.Length).ToHashSet();
var list = Clips.Concat(Deaths.Select(d => ("fb_" + d, D + "TP_Core_Death_" + d, 'A'))).ToList();
var animations = new JsonArray();
var missing = new List<string>();
var failed = 0;
foreach (var (name, path, part) in list)
{
try
{
var a = provider.LoadPackageObject<UAnimSequence>(path + "." + path[(path.LastIndexOf('/') + 1)..]);
var set = a.ConvertAnims();
var seq = set.Sequences[0];
var only = part switch { 'U' => upper, 'L' => lower, _ => all };
var anim = Agents.Clip(glb, seq, set.Skeleton, nameToBone, only, boneNode, bones, name, rootOnlyRot);
if (anim != null) animations.Add(anim);
else missing.Add(name);
}
catch (Exception e)
{
failed++;
missing.Add(name);
Console.Error.WriteLine($" 애니메이션 {name} 실패: {e.GetType().Name} {e.Message}");
}
}
glb.Write(file, new JsonObject { ["animations"] = animations });
return new Result(animations.Count, failed, missing);
}
private static JsonArray Arr(params float[] v) => new(v.Select(x => (JsonNode)x).ToArray());
}

View File

@@ -0,0 +1,141 @@
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
namespace GvrMapExtract;
/// <summary>작은 glTF 2.0 바이너리(glb) 작성기: 버퍼 하나에 accessor · 이미지를 차례로 붙인다</summary>
public sealed class Glb
{
private readonly MemoryStream _bin = new();
public readonly JsonArray BufferViews = new(), Accessors = new(), Images = new(), Textures = new(), Materials = new(), Meshes = new(), Nodes = new(), Samplers = new();
public JsonObject? Extras;
/// <summary>장면의 최상위 노드 (비면 모든 노드)</summary>
public readonly List<int> Roots = new();
private int View(ReadOnlySpan<byte> data, int? target)
{
while (_bin.Length % 4 != 0) _bin.WriteByte(0);
var v = new JsonObject { ["buffer"] = 0, ["byteOffset"] = _bin.Length, ["byteLength"] = data.Length };
if (target is { } t) v["target"] = t;
_bin.Write(data);
BufferViews.Add(v);
return BufferViews.Count - 1;
}
private int Accessor(int view, int componentType, int count, string type, bool normalized = false, float[]? min = null, float[]? max = null)
{
var a = new JsonObject { ["bufferView"] = view, ["componentType"] = componentType, ["count"] = count, ["type"] = type };
if (normalized) a["normalized"] = true;
if (min != null) a["min"] = new JsonArray(min.Select(x => (JsonNode)x).ToArray());
if (max != null) a["max"] = new JsonArray(max.Select(x => (JsonNode)x).ToArray());
Accessors.Add(a);
return Accessors.Count - 1;
}
public int Floats(float[] data, int comps, bool bounds = false)
{
float[]? min = null, max = null;
if (bounds)
{
min = Enumerable.Repeat(float.MaxValue, comps).ToArray();
max = Enumerable.Repeat(float.MinValue, comps).ToArray();
for (var i = 0; i < data.Length; i++)
{
min[i % comps] = Math.Min(min[i % comps], data[i]);
max[i % comps] = Math.Max(max[i % comps], data[i]);
}
}
var v = View(System.Runtime.InteropServices.MemoryMarshal.AsBytes(data.AsSpan()), 34962);
return Accessor(v, 5126, data.Length / comps, comps switch { 1 => "SCALAR", 2 => "VEC2", 3 => "VEC3", _ => "VEC4" }, false, min, max);
}
/// <summary>정규화된 unsigned byte (색 · 가중치)</summary>
public int Bytes(byte[] data, int comps, bool normalized = true)
{
var v = View(data, 34962);
return Accessor(v, 5121, data.Length / comps, comps switch { 1 => "SCALAR", 2 => "VEC2", 3 => "VEC3", _ => "VEC4" }, normalized);
}
public int Ushorts(ushort[] data, int comps)
{
var v = View(System.Runtime.InteropServices.MemoryMarshal.AsBytes(data.AsSpan()), 34962);
return Accessor(v, 5123, data.Length / comps, comps switch { 1 => "SCALAR", 2 => "VEC2", 3 => "VEC3", _ => "VEC4" });
}
public int Indices(uint[] data)
{
var v = View(System.Runtime.InteropServices.MemoryMarshal.AsBytes(data.AsSpan()), 34963);
return Accessor(v, 5125, data.Length, "SCALAR");
}
/// <summary>행렬 같은 비정점 데이터 (target 없음)</summary>
public int Raw(float[] data, string type)
{
var v = View(System.Runtime.InteropServices.MemoryMarshal.AsBytes(data.AsSpan()), null);
var comps = type switch { "MAT4" => 16, "VEC4" => 4, "VEC3" => 3, _ => 1 };
return Accessor(v, 5126, data.Length / comps, type);
}
private int _clampSampler = -1;
/// <summary>텍스처 번호 (기본 반복 샘플러, clamp 면 가장자리 고정 샘플러)</summary>
public int Texture(byte[] image, string mime, bool clamp = false)
{
if (Samplers.Count == 0) Samplers.Add(new JsonObject { ["magFilter"] = 9729, ["minFilter"] = 9987, ["wrapS"] = 10497, ["wrapT"] = 10497 });
var sampler = 0;
if (clamp)
{
if (_clampSampler < 0)
{
Samplers.Add(new JsonObject { ["magFilter"] = 9729, ["minFilter"] = 9987, ["wrapS"] = 33071, ["wrapT"] = 33071 });
_clampSampler = Samplers.Count - 1;
}
sampler = _clampSampler;
}
Images.Add(new JsonObject { ["bufferView"] = View(image, null), ["mimeType"] = mime });
Textures.Add(new JsonObject { ["sampler"] = sampler, ["source"] = Images.Count - 1 });
return Textures.Count - 1;
}
public void Write(string file, JsonObject? extra = null)
{
var gltf = new JsonObject
{
["asset"] = new JsonObject { ["version"] = "2.0", ["generator"] = "gvr-map-extract" },
["scene"] = 0,
["scenes"] = new JsonArray(new JsonObject { ["nodes"] = new JsonArray((Roots.Count > 0 ? Roots : Enumerable.Range(0, Nodes.Count)).Select(i => (JsonNode)i).ToArray()) }),
["nodes"] = Nodes,
["meshes"] = Meshes,
["accessors"] = Accessors,
["bufferViews"] = BufferViews,
["buffers"] = new JsonArray(new JsonObject { ["byteLength"] = _bin.Length }),
};
if (Materials.Count > 0) gltf["materials"] = Materials;
if (Textures.Count > 0)
{
gltf["textures"] = Textures;
gltf["images"] = Images;
gltf["samplers"] = Samplers;
}
if (extra != null)
foreach (var (k, v) in extra) gltf[k] = v?.DeepClone();
if (Extras != null) gltf["extras"] = Extras;
var json = Encoding.UTF8.GetBytes(gltf.ToJsonString(new JsonSerializerOptions { WriteIndented = false }));
var jsonPad = (4 - json.Length % 4) % 4;
while (_bin.Length % 4 != 0) _bin.WriteByte(0);
using var fs = File.Create(file);
using var w = new BinaryWriter(fs);
w.Write(0x46546C67u); // glTF
w.Write(2u);
w.Write((uint)(12 + 8 + json.Length + jsonPad + 8 + _bin.Length));
w.Write((uint)(json.Length + jsonPad));
w.Write(0x4E4F534Au); // JSON
w.Write(json);
for (var i = 0; i < jsonPad; i++) w.Write((byte)' ');
w.Write((uint)_bin.Length);
w.Write(0x004E4942u); // BIN
_bin.Position = 0;
_bin.CopyTo(fs);
}
}

View File

@@ -0,0 +1,315 @@
using CUE4Parse.UE4.Assets.Exports.BuildData;
using CUE4Parse.UE4.Assets.Exports.Texture;
using CUE4Parse.UE4.Objects.Core.Math;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Jpeg;
using SixLabors.ImageSharp.PixelFormats;
namespace GvrMapExtract;
/// <summary>게임에 구워 둔 조명(HQ 라이트맵)을 맵 하나에 아틀라스 두 장으로 모은다.
///
/// 게임 라이트맵 텍스처(LightMapTexture2D, DXT5)는 위 절반이 계수 0(색 UVW² · 로그 밝기), 아래 절반이 계수 1(SH 방향 · 밝기 나머지)이다.
/// 메시마다(FLightMap2D) 범위(ScaleVectors · AddVectors)가 달라서, 메시가 차지한 칸(UV × CoordinateScale + Bias)마다 그 범위로 푼다
/// (UE LightmapCommon.ush GetLightMapColorHQ 와 같은 식).
///
/// 결과
/// irr: sRGB(밝기 / K) — 표면 방향을 빼고 본 조명 색 (L · UVW · L0)
/// sh : 방향 계수 / L0 를 ±2 → 0~1 로 — 사이트에서 조명 = irr · K · max(0, 1 + dot(sh, N.yzx)) (N 은 UE 월드 법선)
/// 칸 밖 텍셀은 이웃 값으로 채워(번짐 방지) 줄인 뒤 페이지째 아틀라스에 놓는다. 라이트맵이 없는 배치는 (0,0) 의 기본 칸(맵 평균 밝기, 방향 없음)을 쓴다.
///
/// 메모리: 배치를 모으는 동안은 텍스처 크기 · 칸 목록만 들고 있다가, Build 에서 페이지를 하나씩 풀어 바로 줄인다
/// (페이지가 200개 넘는 맵도 원래 크기 값은 한 장 분량만 메모리에 있다).</summary>
public sealed class Lightmaps
{
/// <summary>메시 하나가 차지한 칸: 범위(계수 0 · 1) · 페이지 안 위치</summary>
private readonly record struct Alloc(FVector4 S0, FVector4 A0, FVector4 S1, FVector4 A1, float Bx, float By, float Cx, float Cy);
private sealed class PageData
{
public required string Key;
public required UTexture2D Tex;
public required int W, H; // 계수 하나(텍스처 절반) 크기
public readonly List<Alloc> Allocs = new();
public int Ox, Oy, Sw, Sh2; // 아틀라스 위치 · 줄인 크기
public float[]? Irr, Sh; // 줄인 값 (Sw × Sh2 × 3)
public bool[]? Valid;
}
private readonly List<PageData> _pages = new();
private readonly Dictionary<string, int> _byKey = new(StringComparer.OrdinalIgnoreCase);
private readonly HashSet<(int, float, float)> _done = new();
public int Allocations, Failed;
private int _atlasW, _atlasH;
private const int Pad = 4; // 페이지 사이 여백 (밉맵 번짐 방지)
private const int DefaultCell = 8;
/// <summary>라이트맵 텍스처 → 페이지 번호 (못 읽으면 -1). 여기서는 크기만 본다</summary>
public int Page(FLightMap2D lm)
{
var idx = lm.Textures?[0];
if (idx == null || idx.IsNull) return -1;
var key = idx.ResolvedObject?.GetPathName() ?? idx.Name;
if (_byKey.TryGetValue(key, out var p)) return p;
try
{
var t = idx.Load<UTexture2D>();
var w = t?.PlatformData?.SizeX ?? 0;
var h = (t?.PlatformData?.SizeY ?? 0) / 2;
if (t == null || w < 1 || h < 1) { Failed++; return _byKey[key] = -1; }
_pages.Add(new PageData { Key = key, Tex = t, W = w, H = h });
return _byKey[key] = _pages.Count - 1;
}
catch (Exception e)
{
Failed++;
if (Failed <= 5) Console.Error.WriteLine($"라이트맵 실패 {key}: {e.GetType().Name} {e.Message}");
return _byKey[key] = -1;
}
}
/// <summary>메시 하나가 차지한 칸을 적어 둔다 (같은 칸은 한 번만, 푸는 건 Build 에서)</summary>
public void Allocate(int page, FLightMap2D lm, FVector2D bias)
{
if (page < 0 || !_done.Add((page, bias.X, bias.Y))) return;
Allocations++;
var cs = lm.CoordinateScale ?? new FVector2D(1, 1);
_pages[page].Allocs.Add(new Alloc(lm.ScaleVectors![0], lm.AddVectors![0], lm.ScaleVectors![1], lm.AddVectors![1], bias.X, bias.Y, cs.X, cs.Y));
}
/// <summary>페이지 공간 UV(0~1) → 아틀라스 UV. page &lt; 0 이면 기본 칸 가운데</summary>
public (float u, float v) ToAtlas(int page, float u, float v)
{
if (page < 0 || _atlasW == 0) return ((DefaultCell / 2f) / Math.Max(1, _atlasW), (DefaultCell / 2f) / Math.Max(1, _atlasH));
var p = _pages[page];
u = Math.Clamp(u, 0, 1);
v = Math.Clamp(v, 0, 1);
return ((p.Ox + u * p.Sw) / _atlasW, (p.Oy + v * p.Sh2) / _atlasH);
}
public bool Any => _pages.Count > 0;
public float K { get; private set; } = 1;
public int AtlasW => _atlasW;
public int AtlasH => _atlasH;
public int Factor { get; private set; } = 1;
public int Pages => _pages.Count;
/// <summary>아틀라스를 만든다 (너비 maxSide · 넓이 약 maxSide² 안에 들어가게 페이지를 1/2 씩 줄인다). 이 뒤에 ToAtlas 를 쓴다</summary>
public (byte[] irr, byte[] sh)? Build(int maxSide)
{
if (_pages.Count == 0) return null;
// 줄이는 배율: 너비 maxSide · 높이 2×maxSide · 넓이 1.25×maxSide² 안에 들어갈 때까지 1/2 씩
var f = 1;
while (!Pack(f, maxSide) && f < 64) f *= 2;
Factor = f;
// 페이지마다: 풀기 → 칸 밖 채우기 → 줄이기 (원래 크기 값은 한 장 분량만)
var lum = new List<float>();
double sr = 0, sg = 0, sb = 0;
long n = 0;
foreach (var p in _pages)
{
float[] irrF, shF;
bool[] valid;
try
{
(irrF, shF, valid) = Decode(p);
}
catch (Exception e)
{
Failed++;
if (Failed <= 5) Console.Error.WriteLine($"라이트맵 실패 {p.Key}: {e.GetType().Name} {e.Message}");
continue; // 이 페이지는 평균 밝기로 남는다
}
for (var i = 0; i < valid.Length; i++)
if (valid[i])
{
if ((i & 7) == 0) lum.Add(MathF.Max(irrF[i * 3], MathF.Max(irrF[i * 3 + 1], irrF[i * 3 + 2])));
sr += irrF[i * 3]; sg += irrF[i * 3 + 1]; sb += irrF[i * 3 + 2];
n++;
}
Dilate(p.W, p.H, irrF, shF, valid, 8);
Shrink(p, f, irrF, shF, valid);
}
if (n == 0) return null;
lum.Sort();
K = Math.Max(0.05f, lum[(int)(lum.Count * 0.998)]);
var avg = new[] { (float)(sr / n), (float)(sg / n), (float)(sb / n) };
using var irr = new Image<Rgb24>(_atlasW, _atlasH);
using var sh = new Image<Rgb24>(_atlasW, _atlasH, new Rgb24(128, 128, 128));
static byte Enc(float v) => (byte)Math.Clamp(MathF.Round(v * 255), 0, 255);
static float Srgb(float v) => v <= 0.0031308f ? v * 12.92f : 1.055f * MathF.Pow(v, 1 / 2.4f) - 0.055f;
Rgb24 IrrPx(float r, float g, float b) => new(Enc(Srgb(Math.Min(1, r / K))), Enc(Srgb(Math.Min(1, g / K))), Enc(Srgb(Math.Min(1, b / K))));
static Rgb24 ShPx(float x, float y, float z) => new(Enc(x / 4 + 0.5f), Enc(y / 4 + 0.5f), Enc(z / 4 + 0.5f));
// 기본 칸
for (var y = 0; y < DefaultCell; y++)
for (var x = 0; x < DefaultCell; x++) irr[x, y] = IrrPx(avg[0], avg[1], avg[2]);
foreach (var p in _pages)
{
// 여백은 가장자리 값으로
for (var y = -Pad; y < p.Sh2 + Pad; y++)
for (var x = -Pad; x < p.Sw + Pad; x++)
{
var k = Math.Clamp(y, 0, p.Sh2 - 1) * p.Sw + Math.Clamp(x, 0, p.Sw - 1);
var ax = p.Ox + x;
var ay = p.Oy + y;
if (p.Valid == null || !p.Valid[k])
{
irr[ax, ay] = IrrPx(avg[0], avg[1], avg[2]);
continue;
}
irr[ax, ay] = IrrPx(p.Irr![k * 3], p.Irr[k * 3 + 1], p.Irr[k * 3 + 2]);
sh[ax, ay] = ShPx(p.Sh![k * 3], p.Sh[k * 3 + 1], p.Sh[k * 3 + 2]);
}
p.Irr = p.Sh = null;
p.Valid = null;
}
var enc = new JpegEncoder { Quality = 90, ColorType = JpegEncodingColor.YCbCrRatio444 };
using var mi = new MemoryStream();
irr.SaveAsJpeg(mi, enc);
using var ms = new MemoryStream();
sh.SaveAsJpeg(ms, enc);
return (mi.ToArray(), ms.ToArray());
}
/// <summary>페이지 텍스처를 풀어 칸마다 그 범위로 irr · sh 를 계산한다 (원래 크기)</summary>
private static (float[] irr, float[] sh, bool[] valid) Decode(PageData p)
{
var c = CUE4Parse_Conversion.Textures.TextureDecoder.Decode(p.Tex) ?? throw new InvalidDataException("텍스처를 못 풂");
var bgra = c.PixelFormat == EPixelFormat.PF_B8G8R8A8;
if (!bgra && c.PixelFormat != EPixelFormat.PF_R8G8B8A8) throw new InvalidDataException("형식 " + c.PixelFormat);
if (c.Width != p.W || c.Height < p.H * 2 || c.Data.Length < c.Width * c.Height * 4) throw new InvalidDataException($"크기 {c.Width}x{c.Height}");
var src = c.Data;
int R = bgra ? 2 : 0, B = bgra ? 0 : 2;
var irr = new float[p.W * p.H * 3];
var sh = new float[p.W * p.H * 3];
var valid = new bool[p.W * p.H];
const float LogBlackPoint = 0.01858136f;
float C(int i) => src[i] / 255f;
foreach (var a in p.Allocs)
{
// 칸 + 1 텍셀 (UE 는 칸 둘레에 여백을 두고 구운 값을 채운다)
var x0 = Math.Max(0, (int)Math.Floor(a.Bx * p.W) - 1);
var y0 = Math.Max(0, (int)Math.Floor(a.By * p.H) - 1);
var x1 = Math.Min(p.W, (int)Math.Ceiling((a.Bx + a.Cx) * p.W) + 1);
var y1 = Math.Min(p.H, (int)Math.Ceiling((a.By + a.Cy) * p.H) + 1);
for (var y = y0; y < y1; y++)
for (var x = x0; x < x1; x++)
{
var i0 = (y * p.W + x) * 4;
var i1 = ((y + p.H) * p.W + x) * 4;
var logL = C(i0 + 3) + C(i1 + 3) / 255f - 0.5f / 255f;
logL = logL * a.S0.W + a.A0.W;
var l = MathF.Max(0, MathF.Pow(2, logL) - LogBlackPoint);
var r = C(i0 + R) * C(i0 + R) * a.S0.X + a.A0.X;
var g = C(i0 + 1) * C(i0 + 1) * a.S0.Y + a.A0.Y;
var b = C(i0 + B) * C(i0 + B) * a.S0.Z + a.A0.Z;
var l0 = C(i1 + 3) * a.S1.W + a.A1.W;
if (l0 < 1e-4f) l0 = 0.282095f;
var o = (y * p.W + x) * 3;
irr[o] = MathF.Max(0, l * r * l0);
irr[o + 1] = MathF.Max(0, l * g * l0);
irr[o + 2] = MathF.Max(0, l * b * l0);
sh[o] = (C(i1 + R) * a.S1.X + a.A1.X) / l0;
sh[o + 1] = (C(i1 + 1) * a.S1.Y + a.A1.Y) / l0;
sh[o + 2] = (C(i1 + B) * a.S1.Z + a.A1.Z) / l0;
valid[y * p.W + x] = true;
}
}
return (irr, sh, valid);
}
/// <summary>f×f 평균으로 줄여 페이지에 둔다 (칸 밖 · 채우지 못한 텍셀은 빼고)</summary>
private static void Shrink(PageData p, int f, float[] irrF, float[] shF, bool[] validF)
{
p.Irr = new float[p.Sw * p.Sh2 * 3];
p.Sh = new float[p.Sw * p.Sh2 * 3];
p.Valid = new bool[p.Sw * p.Sh2];
for (var y = 0; y < p.Sh2; y++)
for (var x = 0; x < p.Sw; x++)
{
float r = 0, g = 0, b = 0, hx = 0, hy = 0, hz = 0;
var cnt = 0;
for (var dy = 0; dy < f; dy++)
for (var dx = 0; dx < f; dx++)
{
var px = Math.Min(p.W - 1, x * f + dx);
var py = Math.Min(p.H - 1, y * f + dy);
var k = py * p.W + px;
if (!validF[k]) continue;
r += irrF[k * 3]; g += irrF[k * 3 + 1]; b += irrF[k * 3 + 2];
hx += shF[k * 3]; hy += shF[k * 3 + 1]; hz += shF[k * 3 + 2];
cnt++;
}
if (cnt == 0) continue;
var o = (y * p.Sw + x) * 3;
p.Irr[o] = r / cnt; p.Irr[o + 1] = g / cnt; p.Irr[o + 2] = b / cnt;
p.Sh[o] = hx / cnt; p.Sh[o + 1] = hy / cnt; p.Sh[o + 2] = hz / cnt;
p.Valid[y * p.Sw + x] = true;
}
}
/// <summary>1/f 로 줄인 페이지를 너비 maxSide 선반에 쌓는다 (높은 것부터). 한도 안이면 true</summary>
private bool Pack(int f, int maxSide)
{
foreach (var p in _pages)
{
p.Sw = Math.Max(1, p.W / f);
p.Sh2 = Math.Max(1, p.H / f);
}
var order = Enumerable.Range(0, _pages.Count).OrderByDescending(i => _pages[i].Sh2).ThenByDescending(i => _pages[i].Sw).ToList();
int cx = DefaultCell + Pad, cy = 0, shelf = DefaultCell, wMax = 0;
foreach (var i in order)
{
var p = _pages[i];
if (p.Sw + Pad * 2 > maxSide) return false;
if (cx + p.Sw + Pad * 2 > maxSide) { cx = 0; cy += shelf; shelf = 0; }
p.Ox = cx + Pad;
p.Oy = cy + Pad;
cx += p.Sw + Pad * 2;
shelf = Math.Max(shelf, p.Sh2 + Pad * 2);
wMax = Math.Max(wMax, cx);
}
// WebGL2 는 2 의 거듭제곱이 아니어도 밉맵을 쓴다 → 8 의 배수로만 (JPEG 블록)
_atlasW = (wMax + 7) / 8 * 8;
_atlasH = (cy + shelf + 7) / 8 * 8;
return _atlasH <= maxSide * 2 && (long)_atlasW * _atlasH <= (long)maxSide * maxSide * 5 / 4;
}
/// <summary>칸 밖 텍셀을 이웃 칸 값으로 채운다 (줄이기 · 선형 보간에서 검은 테두리가 번지지 않게)</summary>
private static void Dilate(int w, int h, float[] irr, float[] sh, bool[] valid, int passes)
{
var add = new List<int>();
for (var pass = 0; pass < passes; pass++)
{
add.Clear();
for (var y = 0; y < h; y++)
for (var x = 0; x < w; x++)
{
var k = y * w + x;
if (valid[k]) continue;
float r = 0, g = 0, b = 0, hx = 0, hy = 0, hz = 0;
var cnt = 0;
for (var dy = -1; dy <= 1; dy++)
for (var dx = -1; dx <= 1; dx++)
{
var nx = x + dx;
var ny = y + dy;
if (nx < 0 || ny < 0 || nx >= w || ny >= h) continue;
var j = ny * w + nx;
if (!valid[j]) continue;
r += irr[j * 3]; g += irr[j * 3 + 1]; b += irr[j * 3 + 2];
hx += sh[j * 3]; hy += sh[j * 3 + 1]; hz += sh[j * 3 + 2];
cnt++;
}
if (cnt == 0) continue;
irr[k * 3] = r / cnt; irr[k * 3 + 1] = g / cnt; irr[k * 3 + 2] = b / cnt;
sh[k * 3] = hx / cnt; sh[k * 3 + 1] = hy / cnt; sh[k * 3 + 2] = hz / cnt;
add.Add(k);
}
if (add.Count == 0) break;
foreach (var k in add) valid[k] = true;
}
}
}

View File

@@ -1,9 +1,12 @@
using System.Text;
using CUE4Parse.FileProvider;
using CUE4Parse.UE4.Assets.Exports;
using CUE4Parse.UE4.Assets.Exports.BuildData;
using CUE4Parse.UE4.Assets.Exports.Component.StaticMesh;
using CUE4Parse.UE4.Assets.Exports.StaticMesh;
using CUE4Parse.UE4.Assets.Exports.Material;
using CUE4Parse.UE4.Objects.Core.Math;
using CUE4Parse.UE4.Objects.UObject;
namespace GvrMapExtract;
@@ -12,13 +15,10 @@ namespace GvrMapExtract;
public sealed record MapInfo(string Code, string MapUrl, List<string> Levels);
/// <summary>맵 레벨들의 StaticMesh 배치를 모아 월드 좌표(UE cm) 삼각형 하나로 굽는다.
/// 재질 · 텍스처는 없다 (사이트는 높이 · 면 방향으로 색을 칠한다).</summary>
/// 재질마다 텍스처(디퓨즈, 작게 줄임) · 색을 붙인다.</summary>
public sealed class MapScene
{
public int Placements, Meshes, Failed, Skipped;
public long Triangles => _idx.Count / 3;
private readonly List<float> _pos = new();
private readonly List<uint> _idx = new();
private readonly List<string> _levels = new();
private string _code = "";
private string _mapUrl = "";
@@ -80,14 +80,69 @@ public sealed class MapScene
// 부피 · 하늘 · 먼 배경 · 블록아웃 메시는 뺀다
private static readonly string[] SkipMesh = ["Box_For_Volumes", "BasicShapes/Plane", "Blockout", "/Sky", "Vista", "EditorMeshes", "Cubemap"];
private sealed record Sec(int First, int Tris, int Mat);
/// <summary>메시 한 LOD: 위치 · 법선 · UV · 라이트맵 UV(LOD0 만) · 정점 색 · 삼각형 · 재질 구간</summary>
private sealed record Geo(FVector[] V, FVector[] N, float[] Uv, float[]? Lm, FColor[]? Col, uint[] Ib, Sec[] Secs, int Lod);
/// <summary>배치 하나의 라이트맵 자리: 페이지 · 페이지 안 UV = 라이트맵 UV × Scale + Bias</summary>
private readonly record struct LmPlace(int Page, float Sx, float Sy, float Bx, float By);
private readonly Lightmaps _lm = new();
public int LitPlacements;
/// <summary>재질 하나 = glb primitive 하나. 같은 재질의 배치를 모두 모은다</summary>
private sealed class Bucket
{
public readonly List<float> Pos = new(), Nrm = new(), Uv = new(), Lm = new();
public readonly List<int> LmPage = new();
public readonly List<byte> Col = new();
public readonly List<uint> Idx = new();
}
/// <summary>사이트에 쓸 재질 요약. Blend = 정점 색(R)으로 두 층(A · B) 섞기</summary>
private sealed record Mat(string Key, string Name, string? TexA, string? TexB, float[] TintA, float[] TintB, bool Masked, bool Translucent, bool Blend);
private readonly Dictionary<string, Mat?> _mats = new();
private readonly Dictionary<string, Bucket> _buckets = new();
private long _verts, _tris;
private Mat? MaterialOf(UMaterialInterface? m)
{
var key = m?.GetPathName() ?? "";
if (_mats.TryGetValue(key, out var r)) return r;
if (m == null) return _mats[key] = new Mat("", "(없음)", null, null, [0.6f, 0.6f, 0.6f], [1, 1, 1], false, false, false);
var p = MatParams.Resolve(m);
if (p.BlendMode is "BLEND_Additive" or "BLEND_Modulate" || p.Base.Contains("/VFX/Materials/")) return _mats[key] = null;
string? Tex(params string[] names) => names.Select(n => p.Textures.GetValueOrDefault(n)).FirstOrDefault(x => !string.IsNullOrEmpty(x))
?? (names.Length > 0 && names[0] == "Diffuse" ? p.Textures.FirstOrDefault(kv => kv.Key.Contains("Diffuse", StringComparison.OrdinalIgnoreCase) && !kv.Key.Contains("Low") && !kv.Key.EndsWith(" B")).Value : null);
float[] Tint(params string[] names)
{
foreach (var n in names)
if (p.Vectors.TryGetValue(n, out var c)) return [c.R, c.G, c.B];
return [1, 1, 1];
}
var blend = p.Base.Contains("Blend", StringComparison.OrdinalIgnoreCase) && p.Textures.ContainsKey("Diffuse B");
var texA = blend ? Tex("Diffuse A", "Diffuse") : Tex("Diffuse", "Diffuse A", "Albedo", "Base Color", "Texture");
var tintA = blend ? Tint("Layer A Tint") : Tint("DiffuseColor", "Diffuse Tint", "Layer A Tint", "Tree Base Color");
// 텍스처가 없으면 색만 (없으면 회색)
if (texA == null && !p.Vectors.Keys.Any(k => k is "DiffuseColor" or "Diffuse Tint" or "Layer A Tint" or "Tree Base Color")) tintA = [0.6f, 0.6f, 0.6f];
return _mats[key] = new Mat(key, m.Name, texA, blend ? p.Textures["Diffuse B"] : null, tintA, Tint("Layer B Tint"),
p.BlendMode == "BLEND_Masked", p.BlendMode == "BLEND_Translucent", blend);
}
public static MapScene Build(IFileProvider provider, MapInfo map)
{
var s = new MapScene { _code = map.Code, _mapUrl = map.MapUrl };
var meshCache = new Dictionary<string, (FVector[] v, uint[] i)?>();
var meshCache = new Dictionary<string, Geo?>();
foreach (var level in map.Levels)
{
s._levels.Add(Path.GetFileNameWithoutExtension(level));
var pkg = provider.LoadPackage(level);
// 이 레벨에 구워 둔 조명 (<레벨>_BuiltData)
UMapBuildDataRegistry? reg = null;
var bd = level[..^".umap".Length] + "_BuiltData.uasset";
if (provider.Files.ContainsKey(bd))
try { reg = provider.LoadPackage(bd).GetExports().OfType<UMapBuildDataRegistry>().FirstOrDefault(); }
catch (Exception e) { Console.Error.WriteLine($"{bd}: 조명 읽기 실패 {e.GetType().Name} {e.Message}"); }
foreach (var lazy in pkg.ExportsLazy)
{
UObject o;
@@ -99,111 +154,247 @@ public sealed class MapScene
if (mesh == null) continue;
var path = mesh.GetPathName();
if (SkipMesh.Any(x => path.Contains(x, StringComparison.OrdinalIgnoreCase))) { s.Skipped++; continue; }
if (!meshCache.TryGetValue(path, out var geo))
// 구운 조명이 있으면 LOD0 (라이트맵 UV 는 LOD0 에만 있다), 없으면 가장 낮은 LOD
FLightMap2D? lm = null;
FMeshMapBuildData? bdata = null;
if (reg?.MeshBuildData != null && c.LODData is { Length: > 0 } ld0 && reg.MeshBuildData.TryGetValue(ld0[0].MapBuildDataId, out bdata)
&& bdata.LightMap is FLightMap2D l2 && l2.Textures?[0] is { IsNull: false } && l2.ScaleVectors != null && l2.AddVectors != null) lm = l2;
var lmIdx = lm != null ? mesh.GetOrDefault("LightMapCoordinateIndex", 0) : -1;
var key = lm != null ? $"{path}#lm{lmIdx}" : path;
if (!meshCache.TryGetValue(key, out var geo))
{
geo = Geometry(mesh);
meshCache[path] = geo;
try { geo = Geometry(mesh, lmIdx); } catch { geo = null; s.Failed++; }
meshCache[key] = geo;
if (geo != null) s.Meshes++;
}
if (geo == null) continue;
var page = lm != null && geo.Lm != null ? s._lm.Page(lm) : -1;
FTransform w;
try { w = c.GetAbsoluteTransform(); } catch { s.Failed++; continue; }
// 재질: 컴포넌트가 바꾼 것 먼저, 없으면 메시 기본
var over = c.GetOrDefault<FPackageIndex[]>("OverrideMaterials", []);
var mats = new Mat?[geo.Secs.Length];
for (var k = 0; k < geo.Secs.Length; k++)
{
var mi = geo.Secs[k].Mat;
var idx = mi < over.Length && over[mi] is { IsNull: false } ov ? ov : mi < mesh.StaticMaterials.Length ? mesh.StaticMaterials[mi].MaterialInterface : null;
UMaterialInterface? mat = null;
try { mat = idx?.Load<UMaterialInterface>(); } catch { }
mats[k] = s.MaterialOf(mat);
}
// 칠한 정점 색 (두 층 섞기에 쓴다): 컴포넌트 값이 정점 수와 맞을 때만
var col = geo.Col;
if (c is { LODData: { } lodData } && geo.Lod < lodData.Length && lodData[geo.Lod].OverrideVertexColors is { Data: { } oc } && oc.Length == geo.V.Length) col = oc;
var cs = lm?.CoordinateScale ?? new FVector2D(1, 1);
LmPlace? Place(FVector2D bias)
{
if (page < 0) return null;
s._lm.Allocate(page, lm!, bias);
return new LmPlace(page, cs.X, cs.Y, bias.X, bias.Y);
}
if (c is UInstancedStaticMeshComponent ism && ism.PerInstanceSMData is { Length: > 0 } data)
foreach (var d in data) s.Add(geo.Value, d.TransformData * w);
else s.Add(geo.Value, w);
{
// 인스턴스마다 라이트맵 칸이 따로 (FPerInstanceLightmapData). HISM 은 순서가 바뀌어 있을 수 있다 (InstanceReorderTable)
var per = bdata?.PerInstanceLightmapData ?? [];
var reorder = c.GetOrDefault<int[]>("InstanceReorderTable", []);
for (var i = 0; i < data.Length; i++)
{
var ri = reorder.Length == data.Length ? reorder[i] : i;
var lp = ri >= 0 && ri < per.Length ? Place(per[ri].LightmapUVBias) : null;
s.Add(geo, mats, col, data[i].TransformData * w, lp);
}
}
else s.Add(geo, mats, col, w, lm != null ? Place(lm.CoordinateBias ?? new FVector2D(0, 0)) : null);
}
}
return s;
}
/// <summary>가장 낮은 LOD 의 위치 · 삼각형 (사이트에서 내려다보는 용도라 충분하다)</summary>
private static (FVector[] v, uint[] i)? Geometry(UStaticMesh mesh)
/// <summary>가장 낮은 LOD (사이트에서 쓰기에 충분하고 가볍다). lmIdx ≥ 0 이면 LOD0 + 그 UV 채널(라이트맵)</summary>
private static Geo? Geometry(UStaticMesh mesh, int lmIdx = -1)
{
var lods = mesh.RenderData?.LODs;
if (lods == null) return null;
for (var l = lods.Length - 1; l >= 0; l--)
for (var l = lmIdx >= 0 ? 0 : lods.Length - 1; l >= 0 && l < lods.Length; l += lmIdx >= 0 ? 1 : -1)
{
var lod = lods[l];
if (lod.SkipLod || lod.PositionVertexBuffer?.Verts is not { Length: > 0 } v || lod.IndexBuffer?.Buffer is not { Length: > 0 } ib) continue;
var idx = new List<uint>();
foreach (var sec in lod.Sections)
for (var k = 0; k < sec.NumTriangles * 3; k++) idx.Add(ib[sec.FirstIndex + k]);
return (v, idx.ToArray());
var uvItems = lod.VertexBuffer?.UV;
var n = new FVector[v.Length];
var uv = new float[v.Length * 2];
var lmUv = lmIdx >= 0 && uvItems != null && uvItems.Length == v.Length && uvItems.All(x => x.UV != null && x.UV.Length > lmIdx) ? new float[v.Length * 2] : null;
if (uvItems != null && uvItems.Length == v.Length)
for (var i = 0; i < v.Length; i++)
{
var it = uvItems[i];
if (it.Normal is { Length: >= 3 }) n[i] = (FVector)it.Normal[2];
if (it.UV is { Length: > 0 })
{
uv[i * 2] = it.UV[0].U;
uv[i * 2 + 1] = it.UV[0].V;
}
if (lmUv != null)
{
lmUv[i * 2] = it.UV[lmIdx].U;
lmUv[i * 2 + 1] = it.UV[lmIdx].V;
}
}
var col = lod.ColorVertexBuffer?.Data is { } cd && cd.Length == v.Length ? cd : null;
var secs = lod.Sections.Select(x => new Sec(x.FirstIndex, x.NumTriangles, x.MaterialIndex)).ToArray();
return new Geo(v, n, uv, lmUv, col, ib.Select(x => (uint)x).ToArray(), secs, l);
}
return null;
}
private void Add((FVector[] v, uint[] i) g, FTransform t)
private void Add(Geo g, Mat?[] mats, FColor[]? col, FTransform t, LmPlace? lp)
{
Placements++;
var b = (uint)(_pos.Count / 3);
foreach (var p in g.v)
if (lp != null) LitPlacements++;
// UE 는 왼손 좌표계라 glTF(오른손, 반시계 앞면) 로 그대로 옮기면 앞뒤가 바뀐다 → 기본으로 뒤집는다.
// 크기가 음수(거울)면 한 번 더 뒤집힌다
var flip = t.Scale3D.X * t.Scale3D.Y * t.Scale3D.Z >= 0;
var inv = new FVector(1 / NonZero(t.Scale3D.X), 1 / NonZero(t.Scale3D.Y), 1 / NonZero(t.Scale3D.Z));
for (var k = 0; k < g.Secs.Length; k++)
{
var w = t.TransformPosition(p);
_pos.Add(w.X);
_pos.Add(w.Y);
_pos.Add(w.Z);
}
// 크기가 음수(거울)면 삼각형 방향이 뒤집힌다
var flip = t.Scale3D.X * t.Scale3D.Y * t.Scale3D.Z < 0;
for (var k = 0; k + 2 < g.i.Length; k += 3)
{
_idx.Add(b + g.i[k]);
_idx.Add(b + g.i[flip ? k + 2 : k + 1]);
_idx.Add(b + g.i[flip ? k + 1 : k + 2]);
var m = mats[k];
if (m == null) continue;
var sec = g.Secs[k];
if (!_buckets.TryGetValue(m.Key, out var b)) _buckets[m.Key] = b = new Bucket();
// 이 구간이 쓰는 정점만 옮긴다
var map = new Dictionary<uint, uint>();
uint Vert(uint i)
{
if (map.TryGetValue(i, out var o)) return o;
o = (uint)(b.Pos.Count / 3);
var p = t.TransformPosition(g.V[i]);
b.Pos.Add(p.X); b.Pos.Add(p.Y); b.Pos.Add(p.Z);
var nn = t.Rotation.RotateVector(g.N[i] * inv);
var len = nn.Size();
if (len > 1e-6f) nn /= len;
b.Nrm.Add(nn.X); b.Nrm.Add(nn.Y); b.Nrm.Add(nn.Z);
b.Uv.Add(g.Uv[i * 2]); b.Uv.Add(g.Uv[i * 2 + 1]);
if (lp is { } q && g.Lm != null)
{
b.Lm.Add(g.Lm[i * 2] * q.Sx + q.Bx); b.Lm.Add(g.Lm[i * 2 + 1] * q.Sy + q.By);
b.LmPage.Add(q.Page);
}
else
{
b.Lm.Add(0); b.Lm.Add(0);
b.LmPage.Add(-1);
}
if (m.Blend)
{
var c = col != null ? col[i] : new FColor(255, 255, 255, 255);
b.Col.Add(c.R); b.Col.Add(c.G); b.Col.Add(c.B); b.Col.Add(c.A);
}
map[i] = o;
_verts++;
return o;
}
for (var j = 0; j < sec.Tris; j++)
{
var i0 = g.Ib[sec.First + j * 3];
var i1 = g.Ib[sec.First + j * 3 + 1];
var i2 = g.Ib[sec.First + j * 3 + 2];
b.Idx.Add(Vert(i0));
b.Idx.Add(Vert(flip ? i2 : i1));
b.Idx.Add(Vert(flip ? i1 : i2));
_tris++;
}
}
}
/// <summary>glb: 메시 하나, 위치(float32, UE 월드 cm 그대로) + 삼각형(uint32). 사이트가 미니맵 좌표로 옮긴다</summary>
public void WriteGlb(string file)
private static float NonZero(float v) => Math.Abs(v) < 1e-6f ? 1e-6f : v;
public long Triangles => _tris;
public int Materials => _buckets.Count;
public int TextureCount, TextureFailed;
public long TextureBytes, LightmapBytes;
public string LightmapSummary => _lm.Any ? $"조명 {LitPlacements}/{Placements} 배치 · 페이지 {_lm.Pages}(실패 {_lm.Failed}) · 칸 {_lm.Allocations} · 아틀라스 {_lm.AtlasW}x{_lm.AtlasH} (1/{_lm.Factor}) {LightmapBytes >> 10}KB · K {_lm.K:F2}" : "조명 없음";
/// <summary>glb: 재질마다 primitive 하나 (위치는 UE 월드 cm 그대로, 법선 · UV · (두 층 재질만) 정점 색).
/// 재질은 baseColor 텍스처 + 색(tint). 두 층 재질은 extras.blend = {texture, tint} 로 B 층을 넘긴다 (사이트가 정점 색 R 로 섞는다)</summary>
public void WriteGlb(IFileProvider provider, string file, int maxTex)
{
var pos = _pos.ToArray();
var idx = _idx.ToArray();
float[] min = [float.MaxValue, float.MaxValue, float.MaxValue], max = [float.MinValue, float.MinValue, float.MinValue];
for (var i = 0; i < pos.Length; i++)
var glb = new Glb();
var tex = new TexStore(provider, glb, maxTex);
var prims = new System.Text.Json.Nodes.JsonArray();
// 구운 조명 아틀라스: 모든 재질에 occlusionTexture(irr) · emissiveTexture(sh, 세기 0) 로 TEXCOORD_1 에 붙인다.
// (gltfpack 이 쓰지 않는 UV 채널을 버리지 않게 텍스처가 그 채널을 가리켜야 한다. 사이트는 둘을 떼어 조명으로 쓴다)
int? irrTex = null, shTex = null;
var lmMax = int.Parse(Environment.GetEnvironmentVariable("GVR_LIGHTMAP") ?? "2048");
if (lmMax > 0 && _lm.Build(lmMax) is var (irrJpg, shJpg))
{
min[i % 3] = Math.Min(min[i % 3], pos[i]);
max[i % 3] = Math.Max(max[i % 3], pos[i]);
irrTex = glb.Texture(irrJpg, "image/jpeg", clamp: true);
shTex = glb.Texture(shJpg, "image/jpeg", clamp: true);
LightmapBytes = irrJpg.Length + shJpg.Length;
}
var posBytes = pos.Length * 4;
var idxBytes = idx.Length * 4;
var gltf = new
var byKey = _mats.Values.Where(x => x != null).ToDictionary(x => x!.Key, x => x!);
foreach (var (key, b) in _buckets.OrderBy(x => x.Key, StringComparer.Ordinal))
{
asset = new { version = "2.0", generator = "gvr-map-extract" },
scene = 0,
scenes = new[] { new { nodes = new[] { 0 } } },
nodes = new[] { new { mesh = 0, name = _code } },
meshes = new[] { new { name = _code, primitives = new[] { new { attributes = new { POSITION = 0 }, indices = 1, mode = 4 } } } },
accessors = new object[]
if (b.Idx.Count == 0) continue;
var m = byKey[key];
var a = tex.Get(m.TexA);
var bt = m.Blend ? tex.Get(m.TexB) : null;
var pbr = new System.Text.Json.Nodes.JsonObject
{
new { bufferView = 0, componentType = 5126, count = pos.Length / 3, type = "VEC3", min, max },
new { bufferView = 1, componentType = 5125, count = idx.Length, type = "SCALAR" },
},
bufferViews = new[]
["baseColorFactor"] = new System.Text.Json.Nodes.JsonArray(Clamp(m.TintA[0]), Clamp(m.TintA[1]), Clamp(m.TintA[2]), m.Translucent ? 0.45f : 1f),
["metallicFactor"] = 0,
["roughnessFactor"] = 0.9,
};
if (a is { } at) pbr["baseColorTexture"] = new System.Text.Json.Nodes.JsonObject { ["index"] = at.tex };
var mat = new System.Text.Json.Nodes.JsonObject { ["name"] = m.Name, ["pbrMetallicRoughness"] = pbr };
if (irrTex is { } it && shTex is { } st)
{
new { buffer = 0, byteOffset = 0, byteLength = posBytes, target = 34962 },
new { buffer = 0, byteOffset = posBytes, byteLength = idxBytes, target = 34963 },
},
buffers = new[] { new { byteLength = posBytes + idxBytes } },
};
var json = Encoding.UTF8.GetBytes(System.Text.Json.JsonSerializer.Serialize(gltf));
var jsonPad = (4 - json.Length % 4) % 4;
using var fs = File.Create(file);
using var w = new BinaryWriter(fs);
var total = 12 + 8 + json.Length + jsonPad + 8 + posBytes + idxBytes;
w.Write(0x46546C67u); // glTF
w.Write(2u);
w.Write((uint)total);
w.Write((uint)(json.Length + jsonPad));
w.Write(0x4E4F534Au); // JSON
w.Write(json);
for (var i = 0; i < jsonPad; i++) w.Write((byte)' ');
w.Write((uint)(posBytes + idxBytes));
w.Write(0x004E4942u); // BIN
foreach (var f in pos) w.Write(f);
foreach (var i in idx) w.Write(i);
mat["occlusionTexture"] = new System.Text.Json.Nodes.JsonObject { ["index"] = it, ["texCoord"] = 1, ["strength"] = 1 };
mat["emissiveTexture"] = new System.Text.Json.Nodes.JsonObject { ["index"] = st, ["texCoord"] = 1 };
mat["emissiveFactor"] = new System.Text.Json.Nodes.JsonArray(0, 0, 0);
}
if (m.Translucent) mat["alphaMode"] = "BLEND";
else if (m.Masked && a is { alpha: true })
{
mat["alphaMode"] = "MASK";
mat["alphaCutoff"] = 0.333;
mat["doubleSided"] = true;
}
var extras = new System.Text.Json.Nodes.JsonObject();
if (m.Blend)
{
var ex = new System.Text.Json.Nodes.JsonObject { ["tint"] = new System.Text.Json.Nodes.JsonArray(Clamp(m.TintB[0]), Clamp(m.TintB[1]), Clamp(m.TintB[2])) };
if (bt is { } btt) ex["texture"] = btt.tex;
extras["blend"] = ex;
}
// 구운 조명: irr 텍스처 값(sRGB) 1 = 밝기 K
if (irrTex != null) extras["lightmap"] = new System.Text.Json.Nodes.JsonObject { ["k"] = _lm.K, ["v"] = 1 };
if (extras.Count > 0) mat["extras"] = extras;
glb.Materials.Add(mat);
var attrs = new System.Text.Json.Nodes.JsonObject
{
["POSITION"] = glb.Floats(b.Pos.ToArray(), 3, bounds: true),
["NORMAL"] = glb.Floats(b.Nrm.ToArray(), 3),
["TEXCOORD_0"] = glb.Floats(b.Uv.ToArray(), 2),
};
if (m.Blend) attrs["COLOR_0"] = glb.Bytes(b.Col.ToArray(), 4);
if (irrTex != null)
{
var lmuv = new float[b.Lm.Count];
for (var i = 0; i < b.LmPage.Count; i++)
(lmuv[i * 2], lmuv[i * 2 + 1]) = _lm.ToAtlas(b.LmPage[i], b.Lm[i * 2], b.Lm[i * 2 + 1]);
attrs["TEXCOORD_1"] = glb.Floats(lmuv, 2);
}
prims.Add(new System.Text.Json.Nodes.JsonObject { ["attributes"] = attrs, ["indices"] = glb.Indices(b.Idx.ToArray()), ["material"] = glb.Materials.Count - 1, ["mode"] = 4 });
}
glb.Meshes.Add(new System.Text.Json.Nodes.JsonObject { ["name"] = _code, ["primitives"] = prims });
glb.Nodes.Add(new System.Text.Json.Nodes.JsonObject { ["mesh"] = 0, ["name"] = _code });
glb.Write(file);
TextureCount = tex.Count;
TextureFailed = tex.Failed;
TextureBytes = tex.Bytes;
}
private static float Clamp(float v) => Math.Clamp(v, 0f, 1f);
public void WriteInfo(string file, string manifest, string? usmap)
{
var info = new
@@ -214,6 +405,12 @@ public sealed class MapScene
placements = Placements,
meshes = Meshes,
triangles = Triangles,
vertices = _verts,
materials = Materials,
textures = TextureCount,
texturesFailed = TextureFailed,
textureBytes = TextureBytes,
lightmap = _lm.Any ? new { placements = LitPlacements, pages = _lm.Pages, failed = _lm.Failed, allocations = _lm.Allocations, atlas = new[] { _lm.AtlasW, _lm.AtlasH }, factor = _lm.Factor, bytes = LightmapBytes, k = _lm.K } : null,
skipped = Skipped,
failed = Failed,
manifest,

View File

@@ -0,0 +1,65 @@
using CUE4Parse.UE4.Assets.Exports.Material;
using CUE4Parse.UE4.Objects.Core.Math;
namespace GvrMapExtract;
/// <summary>재질 인스턴스 사슬을 따라 올라가며 텍스처 · 색 매개변수를 모은다 (자식 값이 먼저)</summary>
public sealed class MatParams
{
public string Path = "";
public string Base = "";
public readonly Dictionary<string, string> Textures = new(StringComparer.OrdinalIgnoreCase);
public readonly Dictionary<string, FLinearColor> Vectors = new(StringComparer.OrdinalIgnoreCase);
public readonly Dictionary<string, float> Scalars = new(StringComparer.OrdinalIgnoreCase);
public readonly Dictionary<string, bool> Switches = new(StringComparer.OrdinalIgnoreCase);
public string? BlendMode;
public bool TwoSided;
public string? ShadingModel;
public static MatParams Resolve(UMaterialInterface mat)
{
var r = new MatParams { Path = mat.GetPathName() };
bool? twoSided = null;
UMaterialInterface? cur = mat;
for (var d = 0; d < 12 && cur != null; d++)
{
if (cur is UMaterialInstanceConstant mi)
{
foreach (var t in mi.TextureParameterValues)
if (t.ParameterValue is { IsNull: false } tv && !r.Textures.ContainsKey(t.Name))
r.Textures[t.Name] = tv.ResolvedObject?.GetPathName() ?? "";
foreach (var v in mi.VectorParameterValues)
if (v.ParameterValue is { } c && !r.Vectors.ContainsKey(v.Name)) r.Vectors[v.Name] = c;
foreach (var s in mi.ScalarParameterValues)
if (!r.Scalars.ContainsKey(s.Name)) r.Scalars[s.Name] = s.ParameterValue;
if (mi.TryGetValue(out CUE4Parse.UE4.Assets.Objects.FStructFallback bpo, "BasePropertyOverrides"))
{
if (r.BlendMode == null && bpo.TryGetValue(out bool ov, "bOverride_BlendMode") && ov)
r.BlendMode = bpo.GetOrDefault<EBlendMode>("BlendMode").ToString();
if (twoSided == null && bpo.TryGetValue(out bool ots, "bOverride_TwoSided") && ots)
twoSided = bpo.GetOrDefault<bool>("TwoSided");
}
// 정적 스위치 (StaticParameters): 덮어쓴 것만, 자식 값이 먼저
if (mi.StaticParameters?.StaticSwitchParameters is { } sws)
foreach (var sp in sws)
if (sp.bOverride && !r.Switches.ContainsKey(sp.Name)) r.Switches[sp.Name] = sp.Value;
UMaterialInterface? parent = null;
try { parent = mi.Parent?.Load<UMaterialInterface>(); } catch { }
cur = parent;
}
else
{
r.Base = cur.GetPathName();
if (cur is UMaterial m)
{
r.BlendMode ??= m.BlendMode.ToString();
twoSided ??= m.TwoSided;
r.ShadingModel = m.ShadingModel.ToString();
}
break;
}
}
r.TwoSided = twoSided ?? false;
return r;
}
}

View File

@@ -0,0 +1,84 @@
using CUE4Parse.FileProvider;
using CUE4Parse.UE4.Assets.Exports;
using CUE4Parse.UE4.Assets.Exports.Component.StaticMesh;
using CUE4Parse.UE4.Assets.Exports.Material;
using CUE4Parse.UE4.Assets.Exports.StaticMesh;
using CUE4Parse.UE4.Objects.UObject;
namespace GvrMapExtract;
/// <summary>조사용: 맵이 쓰는 재질 매개변수 통계</summary>
public static class Probe
{
public static void Mats(IFileProvider provider, MapInfo map)
{
var tris = new Dictionary<string, long>();
var mats = new Dictionary<string, UMaterialInterface>();
foreach (var level in map.Levels)
{
var pkg = provider.LoadPackage(level);
foreach (var lazy in pkg.ExportsLazy)
{
UObject o;
try { o = lazy.Value; } catch { continue; }
if (o is not UStaticMeshComponent c) continue;
UStaticMesh? mesh;
try { mesh = c.GetStaticMesh()?.Load<UStaticMesh>(); } catch { continue; }
var lod = mesh?.RenderData?.LODs?.LastOrDefault(l => !l.SkipLod);
if (mesh == null || lod == null) continue;
var over = c.GetOrDefault<FPackageIndex[]>("OverrideMaterials", []);
var inst = c is UInstancedStaticMeshComponent ism ? Math.Max(1, ism.PerInstanceSMData?.Length ?? 1) : 1;
foreach (var sec in lod.Sections)
{
var mi = sec.MaterialIndex;
var idx = mi < over.Length && !over[mi].IsNull ? over[mi] : mi < mesh.StaticMaterials.Length ? mesh.StaticMaterials[mi].MaterialInterface : null;
UMaterialInterface? m = null;
try { m = idx?.Load<UMaterialInterface>(); } catch { }
var key = m?.GetPathName() ?? "(none)";
if (m != null) mats[key] = m;
tris[key] = tris.GetValueOrDefault(key) + sec.NumTriangles * (long)inst;
}
}
}
var texNames = new Dictionary<string, (int n, long t)>();
var vecNames = new Dictionary<string, (int n, long t)>();
var bases = new Dictionary<string, (int n, long t)>();
long noDiffuse = 0, total = tris.Values.Sum();
void Add(Dictionary<string, (int n, long t)> d, string k, long t) { var v = d.GetValueOrDefault(k); d[k] = (v.n + 1, v.t + t); }
foreach (var (k, m) in mats)
{
var p = MatParams.Resolve(m);
var t = tris[k];
foreach (var n in p.Textures.Keys) Add(texNames, n, t);
foreach (var n in p.Vectors.Keys) Add(vecNames, n, t);
Add(bases, p.Base + " " + p.BlendMode, t);
if (!p.Textures.Keys.Any(x => x.Contains("Diffuse", StringComparison.OrdinalIgnoreCase) || x.Contains("Albedo", StringComparison.OrdinalIgnoreCase) || x.Contains("Base Color", StringComparison.OrdinalIgnoreCase)))
noDiffuse += t;
}
Console.WriteLine($"재질 {mats.Count} · 삼각형 {total} · 디퓨즈 없음 {noDiffuse * 100.0 / total:F1}% · 없음 {tris.GetValueOrDefault("(none)")}");
Console.WriteLine("== 기본 재질"); foreach (var (k, v) in bases.OrderByDescending(x => x.Value.t).Take(40)) Console.WriteLine($"{v.n,5} {v.t * 100.0 / total,6:F1}% {k}");
Console.WriteLine("== 텍스처"); foreach (var (k, v) in texNames.OrderByDescending(x => x.Value.t).Take(50)) Console.WriteLine($"{v.n,5} {v.t * 100.0 / total,6:F1}% {k}");
Console.WriteLine("== 색"); foreach (var (k, v) in vecNames.OrderByDescending(x => x.Value.t).Take(50)) Console.WriteLine($"{v.n,5} {v.t * 100.0 / total,6:F1}% {k}");
}
}
public static class ProbeAnim
{
public static void Anim(CUE4Parse.FileProvider.IFileProvider provider, string path)
{
var a = provider.LoadPackageObject<CUE4Parse.UE4.Assets.Exports.Animation.UAnimSequence>(path);
var set = CUE4Parse_Conversion.Animations.AnimConverter.ConvertAnims(a);
var seq = set.Sequences[0];
var bones = set.Skeleton.ReferenceSkeleton.FinalRefBoneInfo;
var keyed = seq.Tracks.Select((t, i) => (t, i)).Where(x => x.t.HasKeys() && (x.t.KeyQuat.Length > 1 || x.t.KeyPos.Length > 1)).Select(x => bones[x.i].Name.Text).ToList();
Console.WriteLine($"{a.Name}: skeleton {set.Skeleton.Name} bones {bones.Length} frames {seq.NumFrames} fps {seq.FramesPerSecond:F1} len {a.SequenceLength:F2}s additive {seq.IsAdditive} animated {keyed.Count}: {string.Join(',', keyed.Take(80))}");
}
public static void Skel(CUE4Parse.FileProvider.IFileProvider provider, string path)
{
var m = provider.LoadPackageObject<CUE4Parse.UE4.Assets.Exports.SkeletalMesh.USkeletalMesh>(path);
var rs = m.ReferenceSkeleton;
Console.WriteLine($"{m.Name}: bones {rs.FinalRefBoneInfo.Length} lods {m.LODModels?.Length} tris {string.Join('/', m.LODModels?.Select(l => l.Sections.Sum(s => s.NumTriangles)) ?? [])} mats {string.Join(',', m.SkeletalMaterials.Select(x => x.MaterialInterface?.Name))}");
Console.WriteLine(string.Join(' ', rs.FinalRefBoneInfo.Select((b, i) => $"{i}:{b.Name.Text}<{b.ParentIndex}")));
}
}

View File

@@ -0,0 +1,76 @@
using SixLabors.ImageSharp;
using CUE4Parse.FileProvider;
using CUE4Parse.UE4.Assets.Exports;
using CUE4Parse.UE4.Assets.Exports.BuildData;
using CUE4Parse.UE4.Assets.Exports.Component.StaticMesh;
using CUE4Parse.UE4.Assets.Exports.StaticMesh;
using CUE4Parse.UE4.Assets.Exports.Texture;
namespace GvrMapExtract;
/// <summary>조사용: 레벨 BuiltData 의 라이트맵</summary>
public static class ProbeLight
{
public static void Run(IFileProvider provider, string umap)
{
var bd = umap[..^".umap".Length] + "_BuiltData.uasset";
var pkg = provider.LoadPackage(bd);
var reg = pkg.GetExports().OfType<UMapBuildDataRegistry>().FirstOrDefault();
Console.WriteLine($"{bd}: exports {string.Join(',', pkg.GetExports().GroupBy(e => e.ExportType).Select(g => g.Key + "x" + g.Count()))}");
if (reg == null) return;
Console.WriteLine($"mesh build data {reg.MeshBuildData?.Count} light {reg.LightBuildData?.Count} vlm {reg.LevelPrecomputedVolumetricLightmapBuildData?.Count}");
var dump = Environment.GetEnvironmentVariable("GVR_LM_DUMP");
foreach (var t in pkg.GetExports().OfType<UTexture2D>().Where(t => !t.Name.StartsWith("AOMaterial")))
{
Console.WriteLine($" tex {t.Name} {t.ExportType} {t.PlatformData?.SizeX}x{t.PlatformData?.SizeY} {t.Format} mips {t.PlatformData?.Mips?.Length} srgb {t.SRGB}");
if (dump == null) continue;
var c = CUE4Parse_Conversion.Textures.TextureDecoder.Decode(t);
if (c == null) { Console.WriteLine(" decode null"); continue; }
Console.WriteLine($" decoded {c.Width}x{c.Height} {c.PixelFormat} {c.Data.Length}");
Directory.CreateDirectory(dump);
var px = c.Data;
using var rgb = new SixLabors.ImageSharp.Image<SixLabors.ImageSharp.PixelFormats.Rgba32>(c.Width, c.Height);
using var a = new SixLabors.ImageSharp.Image<SixLabors.ImageSharp.PixelFormats.L8>(c.Width, c.Height);
var bgra = c.PixelFormat == CUE4Parse.UE4.Assets.Exports.Texture.EPixelFormat.PF_B8G8R8A8;
for (var y = 0; y < c.Height; y++) for (var x = 0; x < c.Width; x++)
{
var i = (y * c.Width + x) * 4;
rgb[x, y] = bgra ? new(px[i + 2], px[i + 1], px[i], 255) : new(px[i], px[i + 1], px[i + 2], 255);
a[x, y] = new(px[i + 3]);
}
rgb.SaveAsPng(Path.Combine(dump, t.Name + ".rgb.png"));
a.SaveAsPng(Path.Combine(dump, t.Name + ".a.png"));
}
var n = 0;
foreach (var (g, d) in reg.MeshBuildData ?? new())
{
if (n++ >= 4) break;
if (d.LightMap is FLightMap2D lm)
Console.WriteLine($" {g}: tex {lm.Textures?[0]?.Name}/{lm.Textures?[1]?.Name} vt {lm.VirtualTextures?[0]?.Name} sky {lm.SkyOcclusionTexture?.Name} scale {string.Join(' ', lm.ScaleVectors!.Select(v => $"({v.X:F3},{v.Y:F3},{v.Z:F3},{v.W:F3})"))} add {string.Join(' ', lm.AddVectors!.Select(v => $"({v.X:F3},{v.Y:F3},{v.Z:F3},{v.W:F3})"))} cs {lm.CoordinateScale} cb {lm.CoordinateBias} inst {d.PerInstanceLightmapData.Length} shadow {d.ShadowMap?.GetType().Name}");
else Console.WriteLine($" {g}: lightmap {d.LightMap?.GetType().Name ?? "none"} inst {d.PerInstanceLightmapData.Length}");
}
// 레벨 컴포넌트 → 빌드 데이터 연결
var lvl = provider.LoadPackage(umap);
int comps = 0, hit = 0, ism = 0, ismHit = 0, lodMulti = 0;
foreach (var lazy in lvl.ExportsLazy)
{
UObject o;
try { o = lazy.Value; } catch { continue; }
if (o is not UStaticMeshComponent c) continue;
comps++;
var ids = c.LODData?.Select(l => l.MapBuildDataId).ToArray() ?? [];
if (ids.Length > 1) lodMulti++;
var ok = ids.Length > 0 && reg.MeshBuildData!.ContainsKey(ids[0]);
if (ok) hit++;
if (c is UInstancedStaticMeshComponent im) { ism++; if (ok) ismHit++; }
if (comps <= 5)
{
UStaticMesh? mesh = null;
try { mesh = c.GetStaticMesh()?.Load<UStaticMesh>(); } catch { }
var lods = mesh?.RenderData?.LODs;
Console.WriteLine($" comp {c.Name} {c.ExportType} lods {ids.Length} [{string.Join(',', ids.Select(i => reg.MeshBuildData!.ContainsKey(i) ? "Y" : "n"))}] mesh {mesh?.Name} lmIdx {mesh?.GetOrDefault<int>("LightMapCoordinateIndex")} lmRes {mesh?.GetOrDefault<int>("LightMapResolution")} meshLods {lods?.Length} uvs {string.Join('/', lods?.Select(l => l.VertexBuffer?.NumTexCoords ?? 0) ?? [])} compLmRes {c.GetOrDefault<int>("OverriddenLightMapRes")}");
}
}
Console.WriteLine($"comps {comps} with build data {hit}; ism {ism} hit {ismHit}; multi-lod {lodMulti}");
}
}

View File

@@ -15,11 +15,17 @@ using GvrMapExtract;
// gvr-map-extract ls <정규식> [개수] 파일 목록
// gvr-map-extract maps 맵 목록 (코드 이름 · 레벨 수)
// gvr-map-extract extract <출력 폴더> [맵...] 맵마다 <코드>.glb (UE 월드 좌표 cm, 위치 + 삼각형) + <코드>.json
// gvr-map-extract agents <출력 폴더> [요원...] 요원 몸 agent_<코드>.glb · 무기 weapon_<이름>.glb + agents.json
// 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_USMAP 매핑 파일 (.usmap, 필수: 13.08 부터 패키지에 형 정보가 없다). uedb.dev 에서 받는다
// GVR_MANIFEST 매니페스트 URL (없으면 지금 라이브 패치를 Riot 설정에서 찾는다)
// GVR_CACHE_MB 받은 조각을 메모리에 둘 크기 (기본 1500)
// GVR_TEX 텍스처 최대 크기 (기본 256)
// GVR_LIGHTMAP 구운 조명 아틀라스 너비 (기본 2048, 넓이도 약 이것의 제곱 안. 0 이면 조명을 넣지 않는다)
// GVR_OODLE Oodle 라이브러리 경로 (없으면 실행 파일 옆, 없으면 받는다)
Serilog.Log.Logger = new Serilog.LoggerConfiguration().MinimumLevel.Error().WriteTo.Console().CreateLogger();
@@ -96,9 +102,9 @@ switch (args[0])
try
{
var r = MapScene.Build(provider, m);
r.WriteGlb(Path.Combine(outDir, m.Code + ".glb"));
r.WriteGlb(provider, Path.Combine(outDir, m.Code + ".glb"), int.Parse(Environment.GetEnvironmentVariable("GVR_TEX") ?? "256"));
r.WriteInfo(Path.Combine(outDir, m.Code + ".json"), manifestUrl, usmap);
Console.WriteLine($"{m.Code}: 배치 {r.Placements} · 메시 {r.Meshes} · 삼각형 {r.Triangles} · 빠짐 {r.Skipped} · 실패 {r.Failed} · 받은 양 {(store.DownloadedBytes - d0) >> 20}MB · {(sw.Elapsed - t0).TotalSeconds:F0}초");
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}초");
}
catch (Exception e)
{
@@ -111,6 +117,90 @@ switch (args[0])
Console.WriteLine($"끝: 맵 {maps.Count - (failed - findErrors)}/{maps.Count} · 받은 양 {store.DownloadedBytes >> 20}MB ({store.Requests}번) · {sw.Elapsed.TotalMinutes:F1}분");
return failed == 0 ? 0 : 1;
}
case "mats":
foreach (var m in MapScene.FindMaps(provider).Where(m => args.Skip(1).Contains(m.Code, StringComparer.OrdinalIgnoreCase))) Probe.Mats(provider, m);
break;
case "agents":
{
// 요원마다 agent_<코드>.glb + agents.json {캐릭터 클래스(Wushu_PC_C): {code, file, triangles}}
var outDir = args[1];
Directory.CreateDirectory(outDir);
var want = args.Skip(2).ToHashSet(StringComparer.OrdinalIgnoreCase);
var maxTex = int.Parse(Environment.GetEnvironmentVariable("GVR_AGENT_TEX") ?? "512");
var lodWant = int.Parse(Environment.GetEnvironmentVariable("GVR_AGENT_LOD") ?? "1");
var list = new SortedDictionary<string, object>();
var failedAgents = 0;
foreach (var (code, bp) in Agents.Find(provider).Where(a => want.Count == 0 || want.Contains(a.Code)))
{
var t0 = sw.Elapsed;
try
{
var mesh = Agents.BodyMesh(provider, bp);
if (mesh == null) { Console.WriteLine($"{code}: 3인칭 몸 없음 (건너뜀)"); continue; }
var file = $"agent_{code}.glb";
var r = Agents.Export(provider, mesh, Path.Combine(outDir, file), maxTex, lodWant);
list[code + "_PC_C"] = new { code, file, mesh = mesh.Name, triangles = r.Triangles };
Console.WriteLine($"{code}: {mesh.Name} 삼각형 {r.Triangles} · 뼈 {r.Bones} · 애니메이션 {r.Clips} · 텍스처 {r.Textures}({r.TextureBytes >> 10}KB) · {(sw.Elapsed - t0).TotalSeconds:F0}초");
}
catch (Exception e)
{
failedAgents++;
Console.WriteLine($"{code}: 실패 {e.GetType().Name} {e.Message}");
}
GC.Collect();
}
// 무기 (기본 스킨): weapon_<이름>.glb
var weapons = new SortedDictionary<string, object>();
if (want.Count == 0 || want.Contains("weapons"))
foreach (var (name, bp) in Weapons.List)
{
try
{
var (wm, mag) = Weapons.Find(provider, bp);
if (wm == null) { Console.WriteLine($"무기 {name}: 메시 없음"); continue; }
var file = Weapons.FileName(name);
var tris = Weapons.Export(provider, wm, mag, Path.Combine(outDir, file), maxTex);
weapons[name] = new { file, mesh = wm.Name, triangles = tris, points = Weapons.Points };
Console.WriteLine($"무기 {name}: {wm.Name}{(mag != null ? " + " + mag.Name : "")} 삼각형 {tris} {Weapons.Points?.ToJsonString()}");
}
catch (Exception e)
{
failedAgents++;
Console.WriteLine($"무기 {name}: 실패 {e.GetType().Name} {e.Message}");
}
}
File.WriteAllText(Path.Combine(outDir, "agents.json"), System.Text.Json.JsonSerializer.Serialize(new { agents = list, weapons }, new System.Text.Json.JsonSerializerOptions { WriteIndented = true }));
Console.WriteLine($"끝: 요원 {list.Count} · 무기 {weapons.Count} · 실패 {failedAgents} · 받은 양 {store.DownloadedBytes >> 20}MB · {sw.Elapsed.TotalMinutes:F1}분");
return failedAgents == 0 ? 0 : 1;
}
case "anims":
{
// 모든 요원 공용 애니메이션 anims.glb (앉기 · 점프 · 무기별 자세 · 재장전 · 던지기 · 죽음)
Directory.CreateDirectory(args[1]);
var r = CoreAnims.Export(provider, Path.Combine(args[1], "anims.glb"));
Console.WriteLine($"끝: 공용 애니메이션 {r.Clips} · 실패 {r.Failed}{(r.Missing.Count > 0 ? " · 빠짐 " + string.Join(',', r.Missing) : "")} · 받은 양 {store.DownloadedBytes >> 20}MB · {sw.Elapsed.TotalMinutes:F1}분");
return r.Failed == 0 ? 0 : 1;
}
case "viewmodels":
// 1인칭 팔 · 무기 · 동작: fparms_*.glb · fpweapon_*.glb · fpanim_*.glb + viewmodels.json (Viewmodels.cs)
return Viewmodels.Run(provider, args[1], args.Skip(2).ToHashSet(StringComparer.OrdinalIgnoreCase), int.Parse(Environment.GetEnvironmentVariable("GVR_AGENT_TEX") ?? "512"));
case "abilities":
// 요원 스킬 3D 재료: abilities.json + m_*.glb + t_*.png (Abilities.cs)
return Abilities.Run(provider, args[1], args.Skip(2).ToList(), store);
case "lmprobe":
foreach (var a in args.Skip(1)) ProbeLight.Run(provider, a);
break;
case "anim":
foreach (var a in args.Skip(1)) ProbeAnim.Anim(provider, a);
break;
case "skel":
foreach (var a in args.Skip(1)) ProbeAnim.Skel(provider, a);
break;
case "json":
// 패키지 내용 (조사용)
foreach (var path in args.Skip(1))
Console.WriteLine(Newtonsoft.Json.JsonConvert.SerializeObject(provider.LoadPackage(path).GetExports(), Newtonsoft.Json.Formatting.Indented));
break;
default:
Console.Error.WriteLine("모르는 명령 " + args[0]);
return 2;

View File

@@ -0,0 +1,80 @@
using CUE4Parse.FileProvider;
using CUE4Parse.UE4.Assets.Exports.Texture;
using CUE4Parse_Conversion.Textures;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Jpeg;
using SixLabors.ImageSharp.Formats.Png;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
namespace GvrMapExtract;
/// <summary>게임 텍스처 → 작게 줄여 glb 이미지로 (같은 텍스처는 한 번만). 알파가 있으면 PNG, 없으면 JPEG</summary>
public sealed class TexStore(IFileProvider provider, Glb glb, int maxSize)
{
private readonly Dictionary<string, (int tex, bool alpha)?> _done = new(StringComparer.OrdinalIgnoreCase);
public int Count, Failed;
public long Bytes;
public (int tex, bool alpha)? Get(string? path)
{
if (string.IsNullOrEmpty(path)) return null;
if (_done.TryGetValue(path, out var r)) return r;
r = null;
try
{
var t = provider.LoadPackageObject<UTexture>(path);
var c = t.Decode(maxSize);
using var img = c == null ? null : ToImage(c);
if (img != null)
{
if (img.Width > maxSize || img.Height > maxSize)
img.Mutate(x => x.Resize(new ResizeOptions { Size = new Size(maxSize, maxSize), Mode = ResizeMode.Max }));
var alpha = HasAlpha(img);
using var ms = new MemoryStream();
if (alpha) img.SaveAsPng(ms, new PngEncoder { CompressionLevel = PngCompressionLevel.BestCompression });
else img.SaveAsJpeg(ms, new JpegEncoder { Quality = 82 });
r = (glb.Texture(ms.ToArray(), alpha ? "image/png" : "image/jpeg"), alpha);
Count++;
Bytes += ms.Length;
}
else Failed++;
}
catch (Exception e)
{
Failed++;
if (Failed <= 5) Console.Error.WriteLine($"텍스처 실패 {path}: {e.GetType().Name} {e.Message}");
}
_done[path] = r;
return r;
}
private static Image<Rgba32>? ToImage(CTexture c)
{
var d = c.Data;
var n = c.Width * c.Height;
switch (c.PixelFormat)
{
case CUE4Parse.UE4.Assets.Exports.Texture.EPixelFormat.PF_R8G8B8A8:
return d.Length >= n * 4 ? Image.LoadPixelData<Rgba32>(d.AsSpan(0, n * 4), c.Width, c.Height) : null;
case CUE4Parse.UE4.Assets.Exports.Texture.EPixelFormat.PF_B8G8R8A8:
return d.Length >= n * 4 ? Image.LoadPixelData<Bgra32>(d.AsSpan(0, n * 4), c.Width, c.Height).CloneAs<Rgba32>() : null;
case CUE4Parse.UE4.Assets.Exports.Texture.EPixelFormat.PF_G8:
return d.Length >= n ? Image.LoadPixelData<L8>(d.AsSpan(0, n), c.Width, c.Height).CloneAs<Rgba32>() : null;
default:
return null;
}
}
private static bool HasAlpha(Image<Rgba32> img)
{
var any = false;
img.ProcessPixelRows(a =>
{
for (var y = 0; y < a.Height && !any; y++)
foreach (var p in a.GetRowSpan(y))
if (p.A < 250) { any = true; break; }
});
return any;
}
}

View File

@@ -0,0 +1,203 @@
using System.Text.Json.Nodes;
using CUE4Parse.FileProvider;
using CUE4Parse.UE4.Assets.Exports.Animation;
using CUE4Parse.UE4.Assets.Exports.SkeletalMesh;
using CUE4Parse.UE4.Assets.Exports.StaticMesh;
using CUE4Parse.UE4.Objects.UObject;
using CUE4Parse_Conversion.Animations;
using CUE4Parse_Conversion.Dto;
using CUE4Parse_Conversion.Options;
namespace GvrMapExtract;
/// <summary>
/// 1인칭 화면(뷰모델): 요원 1인칭 팔 · 무기 1인칭 모델 · 동작. 좌표는 게임(UE) 그대로 cm.
/// fparms_&lt;코드&gt;.glb 요원 1인칭 팔 (Characters/&lt;코드&gt;/S0/1P/Models/FP_&lt;코드&gt;_S0_Skelmesh). 뼈대는 모든 요원 공용 (Camera 뼈 = 눈)
/// fpweapon_&lt;이름&gt;.glb 무기 1인칭 모델 (&lt;무기 폴더&gt;/S0/1P/Models/GN|EQ_*_S0_Skelmesh) + 탄창 + 총 동작(gun_fire · gun_reload · gun_equip)
/// fpanim_&lt;이름&gt;.glb 그 무기를 든 팔 동작 (뼈 노드만): idle · fire · reload · equip · ads · walk · activate
/// 사이트는 팔 뼈 MasterWeapon 에 무기 뿌리를 붙이고, 팔 Camera 뼈가 화면 카메라에 오게 놓는다.
/// 덧셈 동작(FireAdd · WalkAdd)은 CUE4Parse 가 기준 자세에 더해 온전한 자세로 바꿔 준다.
/// </summary>
public static class Viewmodels
{
private static readonly (string Role, string[] Names)[] ArmClips =
[
("idle", ["IdlePose", "Idle"]),
("fire", ["Fire", "FireAdd"]),
("reload", ["Reload"]),
("equip", ["Equip"]),
("ads", ["AltIdlePose"]),
("walk", ["WalkAdd"]),
("activate", ["Activate"]),
];
private static readonly (string Role, string[] Names)[] GunClips =
[
("gun_fire", ["Fire", "FireAdd"]),
("gun_reload", ["Reload"]),
("gun_equip", ["Equip"]),
];
private static readonly System.Text.RegularExpressions.Regex SpareMaterial = new(@"^(AB|ABTP|CS|TP)_", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
public static string ArmsFile(string code) => $"fparms_{code}.glb";
public static string WeaponFile(string name) => "fpweapon_" + name.Replace(' ', '_') + ".glb";
public static string AnimFile(string name) => "fpanim_" + name.Replace(' ', '_') + ".glb";
public static int Run(IFileProvider provider, string outDir, IReadOnlyCollection<string> want, int maxTex)
{
Directory.CreateDirectory(outDir);
var failed = 0;
var arms = new SortedDictionary<string, object>();
USkeletalMesh? refArms = null;
foreach (var (code, _) in Agents.Find(provider).Where(a => want.Count == 0 || want.Contains(a.Code)))
{
// 보통 FP_<코드>_S0_Skelmesh, 바뀐 요원은 FP_<코드>_New_S0_Skelmesh (브리치)
var mdir = $"ShooterGame/Content/Characters/{code}/S0/1P/Models/";
var mre = new System.Text.RegularExpressions.Regex($@"/FP_{code}(_[A-Za-z0-9]+)?_S0_Skelmesh\.uasset$", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
var mf = provider.Files.Keys.Where(k => k.StartsWith(mdir, StringComparison.OrdinalIgnoreCase) && mre.IsMatch(k)).OrderBy(k => k.Length).FirstOrDefault();
if (mf == null) { Console.WriteLine($"{code}: 1인칭 팔 없음 (건너뜀)"); continue; }
try
{
var mesh = provider.LoadPackageObject<USkeletalMesh>(ObjPath(mf));
refArms ??= mesh;
var glb = new Glb();
var tex = new TexStore(provider, glb, maxTex);
// 1인칭 팔 메시에 같이 든 스킬 · 3인칭 조각(AB_ · ABTP_ · CS_ · TP_ 재질)은 평소에 안 보이므로 뺀다 (모든 구간이 그런 요원은 그대로)
var names = mesh.SkeletalMaterials.Select(x => x.MaterialInterface?.Name ?? "").ToList();
var spare = SpareMaterial;
var (_, bones, skin, tris) = Agents.Skinned(provider, glb, tex, mesh, 0, 0, names.All(n => spare.IsMatch(n)) ? null : n => spare.IsMatch(n));
glb.Write(Path.Combine(outDir, ArmsFile(code)), new JsonObject { ["skins"] = new JsonArray(skin) });
arms[code + "_PC_C"] = new { code, file = ArmsFile(code), triangles = tris };
Console.WriteLine($"{code}: 1인칭 팔 삼각형 {tris} · 뼈 {bones.Length} · 텍스처 {tex.Count}");
}
catch (Exception e)
{
failed++;
Console.WriteLine($"{code}: 1인칭 팔 실패 {e.GetType().Name} {e.Message}");
}
GC.Collect();
}
// 팔 동작의 뼈 노드는 공용 뼈대 메시(없으면 처음 뽑은 요원 팔)로
try { refArms = provider.LoadPackageObject<USkeletalMesh>("/Game/Characters/_Core/1P/Models/FP_Core_Retarget_Skelmesh.FP_Core_Retarget_Skelmesh"); } catch { }
var weapons = new SortedDictionary<string, object>();
if (want.Count == 0 || want.Contains("weapons"))
foreach (var (name, bp) in Weapons.List)
{
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 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 armRoles = new List<string>();
if (refArms != null)
{
var ag = new Glb();
var adto = new SkeletalMeshDto(refArms, EMeshQuality.All);
var aNodes = BoneNodes(ag, adto.Bones);
var ac = Clips(provider, ag, refArms, aNodes, adto.Bones, ArmClips.Select(c => (c.Role, Find("FP_Core_", c.Names))));
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)}");
}
catch (Exception e)
{
failed++;
Console.WriteLine($"무기 {name}: 1인칭 실패 {e.GetType().Name} {e.Message}");
}
GC.Collect();
}
File.WriteAllText(Path.Combine(outDir, "viewmodels.json"), System.Text.Json.JsonSerializer.Serialize(new { arms, weapons }, new System.Text.Json.JsonSerializerOptions { WriteIndented = true }));
Console.WriteLine($"끝: 1인칭 팔 {arms.Count} · 무기 {weapons.Count} · 실패 {failed}");
return failed == 0 ? 0 : 1;
}
private static string ObjPath(string file)
{
var p = "/Game" + file["ShooterGame/Content".Length..^".uasset".Length];
return p + "." + p[(p.LastIndexOf('/') + 1)..];
}
/// <summary>뼈 노드만 (참조 자세 TRS, 부모-자식). 최상위는 Roots 에</summary>
private static int[] BoneNodes(Glb glb, MeshBoneDto[] bones)
{
var node = new int[bones.Length];
for (var i = 0; i < bones.Length; i++)
{
var t = bones[i].Transform;
glb.Nodes.Add(new JsonObject
{
["name"] = bones[i].Name,
["translation"] = new JsonArray(t.Translation.X, t.Translation.Y, t.Translation.Z),
["rotation"] = new JsonArray(t.Rotation.X, t.Rotation.Y, t.Rotation.Z, t.Rotation.W),
});
node[i] = glb.Nodes.Count - 1;
}
for (var i = 0; i < bones.Length; i++)
{
var p = bones[i].ParentIndex;
if (p < 0) { glb.Roots.Add(node[i]); continue; }
var parent = glb.Nodes[node[p]]!.AsObject();
if (parent["children"] is not JsonArray ch) parent["children"] = ch = new JsonArray();
ch.Add(node[i]);
}
return node;
}
/// <summary>역할마다 동작 하나 (모든 뼈, 움직이면 이동도). 못 찾거나 못 읽은 역할은 뺀다</summary>
private static (JsonArray json, List<string> roles) Clips(IFileProvider provider, Glb glb, USkeletalMesh mesh, int[] boneNode, MeshBoneDto[] bones, IEnumerable<(string Role, string? File)> list)
{
var json = new JsonArray();
var roles = new List<string>();
var nameToBone = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
for (var i = 0; i < bones.Length; i++) nameToBone.TryAdd(bones[i].Name, i);
var all = Enumerable.Range(0, bones.Length).ToHashSet();
foreach (var (role, file) in list)
{
if (file == null) continue;
try
{
var a = provider.LoadPackageObject<UAnimSequence>(ObjPath(file));
var set = a.ConvertAnims();
var seq = set.Sequences[0];
seq.RetargetTracks(mesh.ReferenceSkeleton);
var clip = Agents.Clip(glb, seq, set.Skeleton, nameToBone, all, boneNode, bones, role, []);
if (clip == null) continue;
json.Add(clip);
roles.Add(role);
}
catch (Exception e)
{
Console.Error.WriteLine($" 동작 {role} ({Path.GetFileNameWithoutExtension(file)}) 실패: {e.GetType().Name} {e.Message}");
}
}
return (json, roles);
}
}

View File

@@ -0,0 +1,205 @@
using System.Text.Json.Nodes;
using CUE4Parse.FileProvider;
using CUE4Parse.UE4.Assets.Exports.Component.SkeletalMesh;
using CUE4Parse.UE4.Assets.Exports.Component.StaticMesh;
using CUE4Parse.UE4.Assets.Exports.Material;
using CUE4Parse.UE4.Assets.Exports.SkeletalMesh;
using CUE4Parse.UE4.Assets.Exports.StaticMesh;
using CUE4Parse.UE4.Objects.Core.Math;
using CUE4Parse.UE4.Objects.UObject;
using CUE4Parse_Conversion.Dto;
using CUE4Parse_Conversion.Options;
namespace GvrMapExtract;
/// <summary>
/// 무기(기본 스킨) 3D: 총 몸(참조 자세) + 탄창을 정적 메시 glb 하나로. 원점 = 총 뿌리(요원 R_WeaponPoint 뼈에 붙인다).
/// 이름은 리플레이 변환기 equipKinds 와 같다 (ValorantEquippableResolver 이름).
/// </summary>
public static class Weapons
{
public static readonly (string Name, string Blueprint)[] List =
[
("Classic", "/Game/Equippables/Guns/Sidearms/BasePistol/BasePistol"),
("Shorty", "/Game/Equippables/Guns/Sidearms/Slim/SawedOffShotgun"),
("Frenzy", "/Game/Equippables/Guns/Sidearms/AutoPistol/AutomaticPistol"),
("Ghost", "/Game/Equippables/Guns/Sidearms/Luger/LugerPistol"),
("Compact Pistol", "/Game/Equippables/Guns/Sidearms/Compact/CompactPistol"),
("Sheriff", "/Game/Equippables/Guns/Sidearms/Revolver/RevolverPistol"),
("Stinger", "/Game/Equippables/Guns/SubMachineGuns/Vector/Vector"),
("Spectre", "/Game/Equippables/Guns/SubMachineGuns/MP5/SubMachineGun_MP5"),
("Bucky", "/Game/Equippables/Guns/Shotguns/PumpShotgun/PumpShotgun"),
("Judge", "/Game/Equippables/Guns/Shotguns/AutoShotgun/AutomaticShotgun"),
("Bulldog", "/Game/Equippables/Guns/Rifles/Burst/AssaultRifle_Burst"),
("Warden", "/Game/Equippables/Guns/Rifles/BattleRifle/BattleRifle"),
("Guardian", "/Game/Equippables/Guns/SniperRifles/Dmr/DMR"),
("Phantom", "/Game/Equippables/Guns/Rifles/Carbine/AssaultRifle_ACR"),
("Vandal", "/Game/Equippables/Guns/Rifles/AK/AssaultRifle_AK"),
("Marshal", "/Game/Equippables/Guns/SniperRifles/Leversniper/LeverSniperRifle"),
("Operator", "/Game/Equippables/Guns/SniperRifles/Boltsniper/BoltSniper"),
("Outlaw", "/Game/Equippables/Guns/SniperRifles/Doublesniper/DS_Gun"),
("Ares", "/Game/Equippables/Guns/HvyMachineGuns/LMG/LightMachineGun"),
("Odin", "/Game/Equippables/Guns/HvyMachineGuns/HMG/HeavyMachineGun"),
("Melee", "/Game/Equippables/Melee/Ability_Melee_Base"),
("Spike", "/Game/Equippables/Bomb/BombEquippable"),
];
/// <summary>마지막으로 내보낸 무기의 맞출 점 (weapons 목록에 같이 쓴다)</summary>
public static JsonObject? Points;
public static string FileName(string name) => "weapon_" + name.Replace(' ', '_') + ".glb";
/// <summary>블루프린트의 3인칭(없으면 아무) 스켈레탈 메시와 탄창(이름에 Magazine, 보조 탄창 제외)</summary>
public static (USkeletalMesh? Mesh, UStaticMesh? Magazine) Find(IFileProvider provider, string blueprint)
{
var pkg = provider.LoadPackage(blueprint);
USkeletalMesh? mesh = null;
UStaticMesh? mag = null;
foreach (var c in pkg.GetExports().OfType<USkeletalMeshComponent>().OrderByDescending(c => c.Name.Contains("3P")))
{
var idx = c.GetOrDefault<FPackageIndex?>("SkeletalMesh") ?? c.GetOrDefault<FPackageIndex?>("SkinnedAsset");
if (idx is null || idx.IsNull) continue;
try { mesh = idx.Load<USkeletalMesh>(); } catch { }
if (mesh != null) break;
}
// 블루프린트에 메시가 없으면(스킨 데이터로 정하는 총) 기본 스킨 폴더의 GN_<이름>_S0_Skelmesh
if (mesh == null)
{
var dir = "ShooterGame/Content" + blueprint["/Game".Length..blueprint.LastIndexOf('/')] + "/S0/1P/Models/";
var re = new System.Text.RegularExpressions.Regex(@"/GN_[A-Za-z0-9]+_S0_Skelmesh\.uasset$", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
var f = provider.Files.Keys.FirstOrDefault(k => k.StartsWith(dir, StringComparison.OrdinalIgnoreCase) && re.IsMatch(k));
if (f != null)
try { mesh = provider.LoadPackageObject<USkeletalMesh>("/Game" + f["ShooterGame/Content".Length..^".uasset".Length] + "." + Path.GetFileNameWithoutExtension(f)); } catch { }
}
foreach (var c in pkg.GetExports().OfType<UStaticMeshComponent>())
{
if (!c.Name.Contains("Magazine", StringComparison.OrdinalIgnoreCase) || c.Name.Contains("Secondary", StringComparison.OrdinalIgnoreCase)) continue;
try { mag = c.GetStaticMesh()?.Load<UStaticMesh>(); } catch { }
if (mag != null) break;
}
return (mesh, mag);
}
public static int Export(IFileProvider provider, USkeletalMesh mesh, UStaticMesh? magazine, string file, int maxTex)
{
var glb = new Glb();
var tex = new TexStore(provider, glb, maxTex);
var prims = new JsonArray();
var tris = 0;
var dto = new SkeletalMeshDto(mesh, EMeshQuality.All);
var lod = dto.LODs[0];
var pos = new List<float>();
var nrm = new List<float>();
var uv = new List<float>();
foreach (var v in lod.Vertices)
{
pos.AddRange([v.Position.X, v.Position.Y, v.Position.Z]);
var n = new FVector(v.Normal.X, v.Normal.Y, v.Normal.Z);
if (n.Size() > 1e-6f) n /= n.Size();
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);
// 탄창: 총 뼈 Magazine_Main 위치에
if (magazine?.RenderData?.LODs?.FirstOrDefault(l => !l.SkipLod) is { } ml && ml.PositionVertexBuffer?.Verts is { Length: > 0 } mv && ml.IndexBuffer?.Buffer is { } mib)
{
var bi = Array.FindIndex(dto.Bones, b => b.Name.Equals("Magazine_Main", StringComparison.OrdinalIgnoreCase));
var g = FTransform.Identity;
for (var i = bi; i >= 0; i = dto.Bones[i].ParentIndex) g = g * dto.Bones[i].Transform;
pos = []; nrm = []; uv = [];
for (var i = 0; i < mv.Length; i++)
{
var p = g.TransformPosition(mv[i]);
pos.AddRange([p.X, p.Y, p.Z]);
var it = ml.VertexBuffer?.UV is { } u && i < u.Length ? u[i] : null;
var n = it?.Normal is { Length: >= 3 } nn ? g.Rotation.RotateVector((FVector)nn[2]) : new FVector(0, 0, 1);
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);
}
glb.Meshes.Add(new JsonObject { ["name"] = mesh.Name, ["primitives"] = prims });
// 손에 쥘 때 맞출 점 (총 공간 cm): 총구 · 왼손 자리 (사이트가 오른손 = 원점, 왼손 = Left_Hand_Target 이 되게 놓는다)
var extras = new JsonObject();
foreach (var (key, bone) in new[] { ("muzzle", "Muzzle"), ("leftHand", "Left_Hand_Target"), ("root", "Root") })
{
var bi = Array.FindIndex(dto.Bones, b => b.Name.Equals(bone, StringComparison.OrdinalIgnoreCase));
if (bi < 0) continue;
var g = FTransform.Identity;
for (var i = bi; i >= 0; i = dto.Bones[i].ParentIndex) g = g * dto.Bones[i].Transform;
extras[key] = new JsonArray(g.Translation.X, g.Translation.Y, g.Translation.Z);
}
glb.Nodes.Add(new JsonObject { ["name"] = mesh.Name, ["mesh"] = 0, ["extras"] = extras });
Points = extras;
glb.Write(file);
return tris;
}
/// <summary>정적 메시(탄창)를 뼈 노드의 자식 메시로 붙인다 (뼈 공간 그대로). 붙인 삼각형 수</summary>
public static int AttachStatic(IFileProvider provider, Glb glb, TexStore tex, UStaticMesh sm, int[] boneNode, MeshBoneDto[] bones, string bone)
{
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;
var pos = new List<float>();
var nrm = new List<float>();
var uv = new List<float>();
for (var i = 0; i < mv.Length; i++)
{
pos.AddRange([mv[i].X, mv[i].Y, mv[i].Z]);
var it = ml.VertexBuffer?.UV is { } u && i < u.Length ? u[i] : null;
var n = it?.Normal is { Length: >= 3 } nn ? (FVector)nn[2] : new FVector(0, 0, 1);
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 prims = new JsonArray();
var tris = AddPrims(provider, glb, tex, prims, pos, nrm, uv, mib.Select(x => (uint)x).ToArray(), secs);
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 });
var parent = glb.Nodes[boneNode[bi]]!.AsObject();
if (parent["children"] is not JsonArray ch) parent["children"] = ch = new JsonArray();
ch.Add(glb.Nodes.Count - 1);
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)
{
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)
{
UMaterialInterface? m = null;
try { m = 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))
?? mp.Textures.FirstOrDefault(kv => kv.Value.Contains("_DF", StringComparison.OrdinalIgnoreCase)).Value;
var t = tex.Get(texPath);
var pbr = new JsonObject { ["metallicFactor"] = 0.2, ["roughnessFactor"] = 0.6 };
if (t is { } tt) pbr["baseColorTexture"] = new JsonObject { ["index"] = tt.tex };
else pbr["baseColorFactor"] = new JsonArray(0.3, 0.3, 0.32, 1);
glb.Materials.Add(new JsonObject { ["name"] = m?.Name ?? "none", ["pbrMetallicRoughness"] = pbr });
var idx = new uint[faces * 3];
for (var f = 0; f < faces; f++)
{
idx[f * 3] = indices[first + f * 3];
idx[f * 3 + 1] = indices[first + f * 3 + 2];
idx[f * 3 + 2] = indices[first + f * 3 + 1];
}
tris += faces;
prims.Add(new JsonObject
{
["attributes"] = new JsonObject { ["POSITION"] = aPos, ["NORMAL"] = aNrm, ["TEXCOORD_0"] = aUv },
["indices"] = glb.Indices(idx),
["material"] = glb.Materials.Count - 1,
});
}
return tris;
}
}

View File

@@ -1,4 +1,5 @@
using System.Text.RegularExpressions;
using Replay.Models.Descriptors;
using Replay.Models.Events;
using Replay.Models.Unreal;
using Replay.Valorant.Combat;
@@ -6,6 +7,7 @@ using Replay.Valorant.Descriptors;
using Replay.Valorant.Descriptors.Agents;
using Replay.Valorant.Events.Combat;
using Replay.Valorant.Events.Movement;
using Replay.Valorant.Flashes.Descriptors;
using Replay.Valorant.GameState;
namespace GvrReplay;
@@ -26,10 +28,28 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink
private readonly List<(int T, int NewRoundIndex)> _roundEnds = [];
private readonly List<(int T, uint Killer, uint Victim)> _kills = [];
private readonly List<(int T, uint State, int X, int Y, int Z, int Yaw, int Pitch)> _shots = [];
private readonly List<(int T0, uint Actor, string Kind, int X, int Y, int Z)> _objects = [];
private readonly List<(int T0, uint Actor, string Kind, int X, int Y, int Z, int Yaw, int Pitch)> _objects = [];
private readonly Dictionary<uint, int> _closedAt = [];
private readonly Dictionary<uint, uint> _objectOwner = [];
// 액터의 Instigator / Owner (진단 필드). 스킬 → 요원 몸 (또는 장비 · 드론 → 요원 몸)
private readonly Dictionary<uint, uint> _instigator = [];
private readonly Dictionary<uint, uint> _ownerRef = [];
private readonly Dictionary<uint, string> _pathByGuid = [];
// 투사체 비행: ReplicatedMovement [t, x, y, z] · 부딪힌 시각 (MulticastStopProjectile) · 피닉스 섬광 미리 계산된 경로
private readonly Dictionary<uint, List<int[]>> _flight = [];
private readonly Dictionary<uint, (double X, double Y, double Z)> _spawnLoc = [];
private readonly Dictionary<uint, int> _stopAt = [];
private readonly Dictionary<uint, List<int[]>> _presetPath = [];
// 무기 · 스킬 상태 머신 (장비 액터, 상태 이름)
private readonly List<(int T, uint Equip, string State)> _esm = [];
private readonly List<(int T, uint Victim, uint Attacker, int[] Origin, int[] Impact, int Region, bool Killed, string? Montage)> _hits = [];
private readonly List<(int T, uint Planter, int X, int Y, int Z)> _plants = [];
private readonly Dictionary<ulong, (int T, uint Actor, string Kind)> _fxOpen = [];
private readonly List<(int T0, int T1, uint Actor, string Kind)> _actions = [];
private readonly Dictionary<string, int> _stats = [];
// 들고 있는 것: 장비 액터 → 이름 (총은 파서 목록 이름, 나머지는 클래스 이름), 캐릭터별 바뀐 시각
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 static int Ms(float seconds) => (int)Math.Round(seconds * 1000.0);
private static int R(double v) => (int)Math.Round(v);
@@ -42,20 +62,30 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink
[GeneratedRegex(@"^Default__(GameObject_|Patch_|Pawn_|Projectile_|TimedBomb_C$)")]
private static partial Regex ObjectClass();
/// PlayerState 액터 → 선수 puuid
public string? SubjectOfState(uint state) => _subjectByState.GetValueOrDefault(state);
public void Emit(ReplayEvent e)
{
switch (e)
{
case NetGuidExported g:
if (_map is null && MapPath().IsMatch(g.Path)) _map = g.Path;
_pathByGuid[g.NetGuid] = g.Path;
break;
case ActorSpawned s:
if (s.ArchetypePath is { } arch)
{
_archetypeByActor[s.ActorNetGuid] = arch;
if (ValorantEquippableResolver.TryResolve(s.ActorNetGuid, [s.ReplicationClassPath, s.ArchetypePath, s.ActorPath], out var eq) && eq.Name is { } en)
_equipName[s.ActorNetGuid] = en;
Count("spawn " + Simplify(arch));
if (s.Location is { } loc && ObjectClass().IsMatch(arch) && !arch.EndsWith("_PC_C"))
_objects.Add((Ms(s.TimeSeconds), s.ActorNetGuid, Simplify(arch), R(loc.X), R(loc.Y), R(loc.Z)));
{
var rot = s.Rotation;
_objects.Add((Ms(s.TimeSeconds), s.ActorNetGuid, Simplify(arch), R(loc.X), R(loc.Y), R(loc.Z), R(rot?.Yaw ?? 0), R(rot?.Pitch ?? 0)));
_spawnLoc[s.ActorNetGuid] = (loc.X, loc.Y, loc.Z);
}
}
break;
case ActorClosed c:
@@ -78,11 +108,21 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink
private void OnExport(ExportGroupReceived x)
{
OnFields(x);
switch (x.Payload)
{
case BombGameStateDescriptor gs when gs.HasDecoded(nameof(BombGameStateDescriptor.MatchID)) && !string.IsNullOrEmpty(gs.MatchID):
_matchId ??= gs.MatchID;
break;
case AresInventoryDescriptor inv:
{
var ch = inv.HasDecoded(nameof(AresInventoryDescriptor.Character)) && inv.Character.NetGuid != 0 ? inv.Character.NetGuid : x.ActorNetGuid;
uint eq = 0;
if (inv.HasDecoded(nameof(AresInventoryDescriptor.CurrentEquippable))) eq = inv.CurrentEquippable.NetGuid;
else if (inv.HasDecoded(nameof(AresInventoryDescriptor.NewCurrentEquippable))) eq = inv.NewCurrentEquippable.NetGuid;
if (eq != 0) _equips.Add((Ms(x.TimeSeconds), ch, eq));
break;
}
case BombPlayerStateDescriptor ps:
if (ps.HasDecoded(nameof(BombPlayerStateDescriptor.Subject)) && !string.IsNullOrEmpty(ps.Subject))
_subjectByState[x.ActorNetGuid] = ps.Subject!;
@@ -94,19 +134,89 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink
case GenericAgentDescriptor agent:
if (agent.HasDecoded(nameof(GenericAgentDescriptor.PlayerState)) && agent.PlayerState.NetGuid != 0)
_stateByCharacter.TryAdd(x.ActorNetGuid, agent.PlayerState.NetGuid);
if (agent.HasDecoded(nameof(GenericAgentDescriptor.Owner)) && agent.Owner.NetGuid != 0)
_objectOwner.TryAdd(x.ActorNetGuid, agent.Owner.NetGuid);
if (agent.HasDecoded(nameof(GenericAgentDescriptor.Instigator)) && agent.Instigator.NetGuid != 0)
_objectOwner[x.ActorNetGuid] = agent.Instigator.NetGuid;
break;
}
}
// 진단 필드 (모든 페이로드 공통): Instigator · Owner · ReplicatedMovement · 상태 머신 CurrentState
private void OnFields(ExportGroupReceived x)
{
var a = x.ActorNetGuid;
foreach (var f in x.DiagnosticFields)
{
var v = f.Value;
switch (v.Kind)
{
case DecodedFieldValueKind.ObjectReference when v.ObjectReferenceValue.NetGuid != 0:
if (f.Name == "Instigator" && x.IsActor) _instigator.TryAdd(a, v.ObjectReferenceValue.NetGuid);
else if (f.Name == "Owner" && x.IsActor) _ownerRef.TryAdd(a, v.ObjectReferenceValue.NetGuid);
else if (f.Name == "CurrentState" && x.ExportGroupPath is { } gp && gp.EndsWith("EquippableStateMachineComponent"))
{
var st = Leaf(v.ObjectReferenceValue.Path ?? _pathByGuid.GetValueOrDefault(v.ObjectReferenceValue.NetGuid));
if (st != null) _esm.Add((Ms(x.TimeSeconds), a, st));
}
break;
case DecodedFieldValueKind.RepMovement when x.IsActor && v.RepMovementValue.Location is { } l && _spawnLoc.TryGetValue(a, out var sp)
&& _archetypeByActor.TryGetValue(a, out var arch) && arch.StartsWith("Default__Projectile_"):
{
// 파서가 위치를 1/100 로 읽는다 (VectorNetQuantize100 로 보지만 발로란트는 정수 cm). 생긴 위치에 더 가까운 쪽을 쓴다
double D(double k) => Math.Abs(l.X * k - sp.X) + Math.Abs(l.Y * k - sp.Y) + Math.Abs(l.Z * k - sp.Z);
if (!_flight.TryGetValue(a, out var list)) _flight[a] = list = [];
var k = list.Count > 0 ? list[0][4] : D(100) < D(1) ? 100 : 1;
list.Add([Ms(x.TimeSeconds), R(l.X * k), R(l.Y * k), R(l.Z * k), k]);
break;
}
}
}
}
private static string? Leaf(string? path)
{
if (string.IsNullOrEmpty(path)) return null;
var i = path.LastIndexOfAny(['.', '/']);
return i >= 0 ? path[(i + 1)..] : path;
}
private void OnRpc(RpcReceived r)
{
var t = Ms(r.TimeSeconds);
if (ValorantEquippableResolver.TryResolveClassNetCachePath(r.ClassPath, r.ActorNetGuid, out var eq) && eq.Name is { } en)
_equipName.TryAdd(r.ActorNetGuid, en);
if (r.FunctionName == "MulticastStopProjectile") _stopAt.TryAdd(r.ActorNetGuid, t);
switch (r.Payload)
{
case PrecalculatedProjectileSetPathParameters sp when sp.NetworkedProjectilePath is { } pts:
_presetPath[r.ActorNetGuid] = pts.Where(q => q?.Location is not null)
.Select(q => new[] { t + Ms(q!.ElapsedSeconds ?? 0), R(q.Location!.Value.X), R(q.Location.Value.Y), R(q.Location.Value.Z) }).ToList();
break;
case MulticastNotifyDamagePointParameters d:
{
int[] V(Replay.Models.Unreal.FVector? q) => q is { } w ? [R(w.X), R(w.Y), R(w.Z)] : [0, 0, 0];
var bone = d.DamagedBone ?? "";
var region = bone.Length == 0 ? 0 : bone.Contains("Head", StringComparison.OrdinalIgnoreCase) || bone.Contains("Neck", StringComparison.OrdinalIgnoreCase) ? 1
: bone.Contains("Leg", StringComparison.OrdinalIgnoreCase) || bone.Contains("Foot", StringComparison.OrdinalIgnoreCase) || bone.Contains("Thigh", StringComparison.OrdinalIgnoreCase) || bone.Contains("Calf", StringComparison.OrdinalIgnoreCase) ? 3 : 2;
var montage = d.DamageKilledTarget && d.DeathAnimMontage.NetGuid != 0 ? Leaf(d.DeathAnimMontage.Path ?? _pathByGuid.GetValueOrDefault(d.DeathAnimMontage.NetGuid)) : null;
_hits.Add((t, r.ActorNetGuid, d.EventInstigatorPawn.NetGuid, V(d.DamageOrigin), V(d.DamageImpactLocation), region, d.DamageKilledTarget, montage));
break;
}
case BombPlantedRpcParameters bp:
_plants.Add((t, bp.BombPlanter.NetGuid, R(bp.PlantLocation.X), R(bp.PlantLocation.Y), R(bp.PlantLocation.Z)));
break;
case EffectManagerPlayContinuousParameters fx when fx.EffectId is { } id:
{
var kind = Leaf(fx.EffectContainerPath ?? (fx.EffectContainer is { } ec ? ec.Path ?? _pathByGuid.GetValueOrDefault(ec.NetGuid) : null)) switch
{
"FXC_Bomb_Plant_C" => "Plant",
"FXC_DefuseBomb_Defuser_C" => "Defuse",
"FXC_Ascender_OnRope_C" => "Rope",
_ => null,
};
if (kind != null) _fxOpen[id] = (t, r.ActorNetGuid, kind);
break;
}
case EffectManagerStopContinuousParameters fs when fs.EffectId is { } id && _fxOpen.Remove(id, out var open):
_actions.Add((open.T, t, open.Actor, open.Kind));
break;
case ClientGamePhaseBeginParameters p:
// 같은 시각에 같은 단계가 여러 컨트롤러로 올 수 있다
if (_phases.Count == 0 || _phases[^1][1] != p.NewPhase || _phases[^1][0] != t)
@@ -131,7 +241,10 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink
_lastMoveT[ch] = t;
var p = m.Move.Position;
if (!_moves.TryGetValue(ch, out var list)) _moves[ch] = list = [];
list.Add([t, R(p.X), R(p.Y), R(p.Z), R(m.Move.Yaw), R(m.Move.Pitch)]);
// RotationYawMultiplier 는 실제로 움직임 비트 (0x02 앉음 · 0x10 걷기), UnusedByte 는 이동 모드 (1 땅 · 3 공중 · 5 날기)
var bits = (byte)m.Move.RotationYawMultiplier;
var flags = ((bits & 0x02) != 0 ? 1 : 0) | ((bits & 0x10) != 0 ? 2 : 0) | (m.Move.UnusedByte == 3 ? 4 : 0) | (m.Move.UnusedByte == 5 ? 8 : 0);
list.Add([t, R(p.X), R(p.Y), R(p.Z), R(m.Move.Yaw), R(m.Move.Pitch), flags]);
}
private void OnShot(ValorantShotReceived s)
@@ -152,6 +265,11 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink
pitch = Math.Atan2(v.Z, Math.Sqrt(v.X * v.X + v.Y * v.Y)) * 180 / Math.PI;
}
_shots.Add((Ms(s.TimeSeconds), state, R(loc.X), R(loc.Y), R(loc.Z), R(yaw), R(pitch)));
if (shot.Equippable is { Name: { } en })
{
_shotEquips.Add((Ms(s.TimeSeconds), state, en));
if (shot.Equippable.NetGuid != 0) _equipName.TryAdd(shot.Equippable.NetGuid, en);
}
}
private static string Simplify(string archetype) => archetype.StartsWith("Default__") ? archetype[9..] : archetype;
@@ -206,7 +324,7 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink
{
if (mv[0] - lastT < sampleMs) continue;
lastT = mv[0];
tr.T.Add(mv[0]); tr.X.Add(mv[1]); tr.Y.Add(mv[2]); tr.Z.Add(mv[3]); tr.Yaw.Add(mv[4]); tr.Pitch.Add(mv[5]);
tr.T.Add(mv[0]); tr.X.Add(mv[1]); tr.Y.Add(mv[2]); tr.Z.Add(mv[3]); tr.Yaw.Add(mv[4]); tr.Pitch.Add(mv[5]); tr.F.Add(mv[6]);
}
}
@@ -223,30 +341,159 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink
rounds.Add(new ReplayRound { Num = starts[r].Num, Buy = buy >= 0 ? buy : from, Combat = Phase(4), End = Phase(5) });
}
// 액터 → 선수: Instigator(없으면 Owner)를 따라 올라가 요원 몸 · 선수 상태를 만날 때까지 (스킬 → 장비/드론 → 요원)
int OwnerOf(uint actor)
{
var cur = actor;
for (var d = 0; d < 6; d++)
{
if (indexByCharacter.TryGetValue(cur, out var pi)) return pi;
if (_subjectByState.ContainsKey(cur)) return PlayerOfState(cur);
if (!_instigator.TryGetValue(cur, out var up) && !_ownerRef.TryGetValue(cur, out up)) return -1;
if (up == cur) return -1;
cur = up;
}
return -1;
}
var kinds = new List<string>();
var kindIndex = new Dictionary<string, int>();
var objects = new List<int[]>();
var paths = new List<ObjectPath>();
// 맵 자체 연출(예: GameObject_Infinity_Rain_*)은 뺀다
var mapName = _map?.Split('/')[^1];
foreach (var o in _objects)
{
if (mapName is not null && o.Kind.Contains("_" + mapName + "_")) continue;
if (!kindIndex.TryGetValue(o.Kind, out var k)) { k = kinds.Count; kinds.Add(o.Kind); kindIndex[o.Kind] = k; }
var owner = -1;
var cur = o.Actor;
for (var d = 0; d < 6 && _objectOwner.TryGetValue(cur, out var up); d++)
var owner = OwnerOf(o.Actor);
// 스파이크는 심은 사람 (같은 자리 설치 기록)
if (owner < 0 && o.Kind == "TimedBomb_C")
{
if (indexByCharacter.TryGetValue(up, out owner)) break;
owner = -1;
if (_stateByCharacter.ContainsKey(up)) break;
if (_subjectByState.ContainsKey(up)) { owner = PlayerOfState(up); break; }
cur = up;
var pl = _plants.Where(q => Math.Abs(q.T - o.T0) < 3000).OrderBy(q => Math.Abs(q.T - o.T0)).FirstOrDefault();
if (pl.Planter != 0) owner = OwnerOf(pl.Planter);
}
objects.Add([o.T0, _closedAt.TryGetValue(o.Actor, out var t1) && t1 >= o.T0 ? t1 : -1, k, o.X, o.Y, o.Z, owner]);
// 요루 분신 생성기는 참조가 없다: 생성기가 사라질 때 같은 자리에 나온 분신의 주인
if (owner < 0 && o.Kind.StartsWith("GameObject_Stealth_DecoySpawner") && _closedAt.TryGetValue(o.Actor, out var sc))
{
var dec = _objects.Where(q => q.Kind.StartsWith("Pawn_Stealth_4_Decoy") && Math.Abs(q.T0 - sc) < 1000 && Math.Abs(q.X - o.X) + Math.Abs(q.Y - o.Y) < 600).Select(q => q.Actor).FirstOrDefault();
if (dec != 0) owner = OwnerOf(dec);
}
var t1 = _closedAt.TryGetValue(o.Actor, out var tc) && tc >= o.T0 ? tc : -1;
// 날아가는 것은 부딪힌 시각에 끝 (닫힘은 1~2초 늦을 수 있다)
if (_stopAt.TryGetValue(o.Actor, out var ts) && ts >= o.T0 && (t1 < 0 || ts < t1)) t1 = ts;
var oi = objects.Count;
objects.Add([o.T0, t1, k, o.X, o.Y, o.Z, owner, o.Yaw, o.Pitch]);
// 경로: 미리 계산된 경로(피닉스 섬광) > ReplicatedMovement (투사체) > 캐릭터 이동 (드론 · 분신 · 가짜 순간이동)
var path = new ObjectPath { O = oi };
if (_presetPath.TryGetValue(o.Actor, out var pre) && pre.Count > 1)
{
foreach (var q in pre) { path.T.Add(q[0]); path.X.Add(q[1]); path.Y.Add(q[2]); path.Z.Add(q[3]); }
}
else if (_flight.TryGetValue(o.Actor, out var fl) && fl.Count > 0)
{
path.T.Add(o.T0); path.X.Add(o.X); path.Y.Add(o.Y); path.Z.Add(o.Z);
foreach (var q in fl)
{
if (q[0] <= path.T[^1] || (t1 >= 0 && q[0] > t1)) continue;
path.T.Add(q[0]); path.X.Add(q[1]); path.Y.Add(q[2]); path.Z.Add(q[3]);
}
}
else if (o.Kind.StartsWith("Pawn_") && _moves.TryGetValue(o.Actor, out var mv) && mv.Count > 1)
{
foreach (var q in mv.OrderBy(q => q[0]))
{
if (path.T.Count > 0 && q[0] - path.T[^1] < sampleMs) continue;
path.T.Add(q[0]); path.X.Add(q[1]); path.Y.Add(q[2]); path.Z.Add(q[3]); path.Yaw.Add(q[4]);
}
}
if (path.T.Count > 1) paths.Add(path);
}
var hits = _hits.Select(h => new[] { h.T, OwnerOf(h.Attacker), OwnerOf(h.Victim), h.Origin[0], h.Origin[1], h.Origin[2], h.Impact[0], h.Impact[1], h.Impact[2], h.Region, h.Killed ? 1 : 0 }).ToList();
var deathAnims = new List<string>();
int DeathAnim(int t, uint victim)
{
var h = _hits.Where(q => q.Killed && q.Montage != null && q.Victim == victim && Math.Abs(q.T - t) < 500).OrderBy(q => Math.Abs(q.T - t)).FirstOrDefault();
if (h.Montage is null) return -1;
var i = deathAnims.IndexOf(h.Montage);
if (i < 0) { i = deathAnims.Count; deathAnims.Add(h.Montage); }
return i;
}
var actionKinds = new List<string>();
var actions = new List<int[]>();
foreach (var a in _actions.Concat(_fxOpen.Values.Select(o => (T0: o.T, T1: -1, o.Actor, o.Kind))).OrderBy(a => a.T0))
{
var pi = OwnerOf(a.Actor);
if (pi < 0) continue;
var ak = actionKinds.IndexOf(a.Kind);
if (ak < 0) { ak = actionKinds.Count; actionKinds.Add(a.Kind); }
actions.Add([a.T0, a.T1, pi, ak]);
}
// 들고 있는 것: [t, 선수, 종류]. 같은 선수가 같은 것을 다시 들면 뺀다
var equipKinds = new List<string>();
var equipKindIndex = new Dictionary<string, int>();
int EquipKind(string name)
{
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)>();
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));
}
// 인벤토리 기록이 없는 선수는 사격 무기로 채운다
var hasInv = equipRows.Select(e => e.P).ToHashSet();
foreach (var (t, st, name) 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)]);
}
// 무기 · 스킬 상태: 장비 액터 → 그 시각의 선수 (인벤토리 기록, 없으면 Instigator).
// 무기는 떨어뜨리고 주울 수 있어서 마지막 주인이 아니라 상태가 생긴 때의 주인을 쓴다
var equipOwners = EquipOwners.Build(_equips.Select(e => (e.T, e.Equip, indexByCharacter.TryGetValue(e.Character, out var p) ? p : -1)));
var fallbackOwner = new Dictionary<uint, int>();
var stateKinds = new List<string>();
var stateKindIndex = new Dictionary<string, int>();
var states = new List<int[]>();
var lastState = new Dictionary<uint, string>();
// 들고 있지 않은 장비의 상태(Inactive · 줌 꺼짐)는 쓸모가 없다
foreach (var (t, eq, st) in _esm)
{
if (st is "InactiveState" or "ZoomStateDisabled") continue;
if (lastState.TryGetValue(eq, out var ls) && ls == st) continue;
lastState[eq] = st;
var pi = EquipOwners.At(equipOwners, eq, t);
if (pi < 0)
{
if (!fallbackOwner.TryGetValue(eq, out pi)) fallbackOwner[eq] = pi = OwnerOf(eq);
if (pi < 0) continue;
}
var name = _equipName.TryGetValue(eq, out var en) ? en : _archetypeByActor.TryGetValue(eq, out var ea) ? Simplify(ea) : null;
if (name is null) continue;
if (!stateKindIndex.TryGetValue(st, out var sk)) { sk = stateKinds.Count; stateKinds.Add(st); stateKindIndex[st] = sk; }
states.Add([t, pi, EquipKind(name), sk]);
}
return new ReplayFile
{
Equips = equips,
EquipKinds = equipKinds,
MatchId = _matchId,
Map = _map,
Build = branch?.Replace("++Ares-Core+", ""),
@@ -256,10 +503,47 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink
Players = players,
Rounds = rounds,
Phases = _phases,
Kills = _kills.Select(k => new[] { k.T, indexByCharacter.GetValueOrDefault(k.Killer, -1), indexByCharacter.GetValueOrDefault(k.Victim, -1) }).ToList(),
Kills = _kills.Select(k => new[] { k.T, indexByCharacter.GetValueOrDefault(k.Killer, -1), indexByCharacter.GetValueOrDefault(k.Victim, -1), DeathAnim(k.T, k.Victim) }).ToList(),
DeathAnims = deathAnims,
ObjectPaths = paths,
States = states,
StateKinds = stateKinds,
Hits = hits,
Plants = _plants.Select(p => new[] { p.T, OwnerOf(p.Planter), p.X, p.Y, p.Z }).ToList(),
Actions = actions,
ActionKinds = actionKinds,
Shots = _shots.Select(s => new[] { s.T, PlayerOfState(s.State), s.X, s.Y, s.Z, s.Yaw, s.Pitch }).ToList(),
Objects = objects,
ObjectKinds = kinds,
};
}
}
/// <summary>장비 액터의 주인 시간표: 인벤토리 기록 (t, 장비, 선수) → 시각별 주인</summary>
public static class EquipOwners
{
public static Dictionary<uint, List<(int T, int Player)>> Build(IEnumerable<(int T, uint Equip, int Player)> rows)
{
var d = new Dictionary<uint, List<(int, int)>>();
foreach (var (t, eq, p) in rows.OrderBy(r => r.T))
{
if (p < 0) continue;
if (!d.TryGetValue(eq, out var l)) d[eq] = l = [];
l.Add((t, p));
}
return d;
}
/// <summary>t 시각 주인: t 이하 마지막 기록, 첫 기록보다 앞이면 첫 주인. 기록이 없으면 -1</summary>
public static int At(Dictionary<uint, List<(int T, int Player)>> owners, uint eq, int t)
{
if (!owners.TryGetValue(eq, out var l) || l.Count == 0) return -1;
var who = l[0].Player;
foreach (var (rt, p) in l)
{
if (rt > t) break;
who = p;
}
return who;
}
}

View File

@@ -0,0 +1,195 @@
using System.Text.Json;
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>
/// 선수 조준점 설정. BombPlayerState 에 선수마다 조준점 프로필(주 조준점 · 정조준 · 저격 조준경 · 프로필 이름)이 복제된다
/// (관전자에게 보이는 조준점). 파서의 BombPlayerState 형식에는 이 필드가 없어서, 첫 번째 읽기에서 받은 필드 목록으로
/// 번호(handle)를 찾고 이 필드만 읽는 두 번째 읽기를 한다.
/// 필드는 기본값(색 흰색 255 · 숫자 0 · 끔)과 다를 때만 오고, 바뀐 필드만 다시 온다.
/// </summary>
public static class Crosshair
{
public const string StatePath = "/Game/GameModes/Bomb/BombPlayerState.BombPlayerState_C";
// 13.08 · 13.09 에서 주 조준점 색(B)의 번호. 패치로 앞에 필드가 늘면 이름이 맞는 곳으로 옮겨 찾는다
private const int KnownBase = 39;
private static readonly string[] Lines =
[
"LineThickness", "LineLength", "LineLengthVertical", "LineOffset", "bAllowVertScaling", "bShowMovementError",
"bShowShootingError", "bShowMinError", "Opacity", "bShowLines", "FiringErrorScale", "MovementErrorScale",
];
private static readonly string?[] Cross =
[
"B", "G", "R", "A", "B", "G", "R", "A", "bUseCustomColor", "bHasOutline", "OutlineThickness", "B", "G", "R", "A",
"OutlineOpacity", "CenterDotSize", "CenterDotOpacity", "bDisplayCenterDot", "bFadeCrosshairWithFiringError",
"bShowSpectatedPlayerCrosshair", null, "bFixMinErrorAcrossWeapons", .. Lines, .. Lines,
];
private static readonly string?[] Sniper =
[
"B", "G", "R", "A", "B", "G", "R", "A", "CenterDotSize", "CenterDotOpacity", "bDisplayCenterDot", null,
"bUsePrimaryCrosshairForADS", null, null, "bUseAdvancedOptions", null, "ProfileName",
];
/// 기준 번호부터의 (이름, 열쇠). 세 번째 조준점 묶음(번호 94~140)은 값이 오는 것을 본 적이 없어 읽지 않는다
private static readonly (string? Name, string? Key)[] Layout = BuildLayout();
private static (string?, string?)[] BuildLayout()
{
var o = new List<(string?, string?)>();
string?[] lineKeys = ["thickness", "length", "vLength", "offset", "allowVert", "moveError", "fireError", "minError", "opacity", "on", "fireScale", "moveScale"];
string?[] crossKeys =
[
"cb", "cg", "cr", null, "ub", "ug", "ur", null, "useCustom", "outline", "outlineThickness", null, null, null, null,
"outlineOpacity", "dotSize", "dotOpacity", "dot", null, null, null, null,
.. lineKeys.Select(k => "i." + k), .. lineKeys.Select(k => "o." + k),
];
foreach (var prefix in new[] { "p.", "a.", null })
for (var i = 0; i < Cross.Length; i++)
o.Add(prefix is null ? (null, null) : (Cross[i], crossKeys[i] is { } k ? prefix + k : null));
string?[] sniperKeys = ["s.cb", "s.cg", "s.cr", null, null, null, null, null, "s.dotSize", "s.dotOpacity", "s.dot", null, "adsFromPrimary", null, null, "advanced", null, "name"];
for (var i = 0; i < Sniper.Length; i++) o.Add((Sniper[i], sniperKeys[i]));
return [.. o];
}
/// <summary>필드 목록(번호 → 이름)에서 조준점 기준 번호. 이름이 하나라도 어긋나면 그 자리는 아니다. 못 찾으면 null</summary>
public static int? FindBase(IReadOnlyDictionary<int, string> names)
{
int? best = null;
var bestHits = 0;
for (var d = 0; d <= 80; d++)
foreach (var b in d == 0 ? new[] { KnownBase } : new[] { KnownBase + d, KnownBase - d })
{
if (b < 0) continue;
var hits = 0;
var bad = false;
foreach (var (h, name) in names)
{
var i = h - b;
if (i < 0 || i >= Layout.Length || Layout[i].Name is not { } want) continue;
if (want != name) { bad = true; break; }
hits++;
}
// 프로필 이름 + 몇 개 이상 맞아야 한다 (조준점을 하나도 안 바꾼 경기면 필드가 거의 안 온다)
if (!bad && hits > bestHits && names.GetValueOrDefault(b + Layout.Length - 1) == "ProfileName")
{
best = b;
bestHits = hits;
}
}
return bestHits >= 3 ? best : null;
}
/// <summary>두 번째 읽기: PlayerState 액터 → 조준점이 바뀐 시각마다 전체 설정</summary>
public static Dictionary<uint, List<CrosshairAt>> Read(string path, ValorantReplayReadResult first)
{
var group = first.ExportGroups.FirstOrDefault(g => g.PathName == StatePath);
if (group is null) return [];
var names = new Dictionary<int, string>();
foreach (var f in group.Fields)
if (f.Name is { } n) names[(int)f.Handle] = n;
if (FindBase(names) is not { } b) return [];
var keyByHandle = new Dictionary<int, string>();
var fields = new List<FieldDescriptor>();
for (var i = 0; i < Layout.Length; i++)
{
if (Layout[i] is not { Name: { } name, Key: { } key }) continue;
var h = b + i;
keyByHandle[h] = key;
fields.Add(new FieldDescriptor
{
Handle = (uint)h,
ExportName = name,
PropertyName = key,
Categories = ExportCategory.GameState,
Decoder = name == "ProfileName" ? PrimitiveDecoders.FString
: name.Length == 1 ? PrimitiveDecoders.Byte
: name.StartsWith('b') ? PrimitiveDecoders.Bool
: PrimitiveDecoders.Float,
});
}
// 기본 목록(경로 별칭 · 하위 객체 등 읽기에 필요)에서 BombPlayerState 만 조준점 필드로 바꾼다 (같은 경로는 나중 것이 쓰인다)
var catalog = ValorantDescriptors.CreateCatalog();
catalog.Add(new ExportGroupDescriptor(StatePath, ExportCategory.GameState, ExportGroupKind.Actor, fields: fields));
var sink = new Sink(keyByHandle);
var profile = new ParseProfile
{
EnabledCategories = ExportCategory.All,
CaptureDiagnosticFields = true,
IncludedPaths = [StatePath],
};
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(Dictionary<int, string> keyByHandle) : IReplayEventSink
{
private readonly Dictionary<uint, Dictionary<string, object>> _now = [];
public Dictionary<uint, List<CrosshairAt>> Result { get; } = [];
public void Emit(ReplayEvent e)
{
if (e is not ExportGroupReceived x || x.ExportGroupPath != StatePath || x.DiagnosticFields.Count == 0) return;
if (!_now.TryGetValue(x.ActorNetGuid, out var v)) _now[x.ActorNetGuid] = v = [];
var changed = false;
foreach (var f in x.DiagnosticFields)
{
if (!keyByHandle.TryGetValue(f.Handle, out var key)) continue;
object val = f.Value.Kind switch
{
DecodedFieldValueKind.Bool => f.Value.BoolValue,
DecodedFieldValueKind.Byte => (int)f.Value.ByteValue,
DecodedFieldValueKind.Float => Math.Round(f.Value.FloatValue, 3),
DecodedFieldValueKind.String => (f.Value.StringValue ?? "").TrimEnd('\0'),
_ => null!,
};
if (val is null) continue;
v[key] = val;
changed = true;
}
if (!changed) return;
var t = (int)Math.Round(x.TimeSeconds * 1000.0);
var at = Snapshot(t, v);
if (!Result.TryGetValue(x.ActorNetGuid, out var list)) Result[x.ActorNetGuid] = list = [];
// 같은 시각에 나눠 온 것은 하나로, 바뀐 것이 없으면 넣지 않는다
if (list.Count > 0 && list[^1].T == t) list.RemoveAt(list.Count - 1);
if (list.Count > 0 && Same(list[^1], at)) return;
list.Add(at);
}
}
private static bool Same(CrosshairAt a, CrosshairAt b) =>
JsonSerializer.Serialize(a with { T = 0 }, ReplayJson.Options) == JsonSerializer.Serialize(b with { T = 0 }, ReplayJson.Options);
public static CrosshairAt Snapshot(int t, IReadOnlyDictionary<string, object> v)
{
// 오지 않은 필드는 기본값: 색 255 · 숫자 0 · 끔
int C(string k) => v.TryGetValue(k, out var o) ? (int)o : 255;
double F(string k) => v.TryGetValue(k, out var o) ? (double)o : 0;
bool B(string k) => v.TryGetValue(k, out var o) && (bool)o;
string Hex(string p) => $"#{C(p + "r"):x2}{C(p + "g"):x2}{C(p + "b"):x2}";
CrossLines L(string p) => new(B(p + "on"), F(p + "length"), B(p + "allowVert") ? F(p + "vLength") : F(p + "length"),
F(p + "thickness"), F(p + "offset"), F(p + "opacity"), B(p + "moveError"), B(p + "fireError"), F(p + "moveScale"), F(p + "fireScale"));
CrossSet S(string p) => new(Hex(p + (B(p + "useCustom") ? "u" : "c")), B(p + "outline"), F(p + "outlineThickness"), F(p + "outlineOpacity"),
B(p + "dot"), F(p + "dotSize"), F(p + "dotOpacity"), L(p + "i."), L(p + "o."));
return new CrosshairAt(t, v.TryGetValue("name", out var n) ? (string)n : "", S("p."), S("a."),
new SniperDot(Hex("s.c"), B("s.dot"), F("s.dotSize"), F("s.dotOpacity")), B("adsFromPrimary"), B("advanced"));
}
}
/// 조준점 설정 (t 부터). ads 는 adsFromPrimary 가 꺼져 있을 때 정조준에 쓴다. 크기는 발로란트 설정 값 그대로 (화면 픽셀)
public sealed record CrosshairAt(int T, string Name, CrossSet Primary, CrossSet Ads, SniperDot Sniper, bool AdsFromPrimary, bool Advanced);
/// color 는 실제로 보이는 색 (사용자 지정 색을 쓰면 그 색)
public sealed record CrossSet(string Color, bool Outline, double OutlineThickness, double OutlineOpacity, bool Dot, double DotSize, double DotOpacity, CrossLines Inner, CrossLines Outer);
/// vLength 는 세로 길이를 따로 쓰지 않으면 length 와 같다
public sealed record CrossLines(bool On, double Length, double VLength, double Thickness, double Offset, double Opacity, bool MoveError, bool FireError, double MoveScale, double FireScale);
public sealed record SniperDot(string Color, bool Dot, double DotSize, double DotOpacity);

View File

@@ -7,7 +7,8 @@ namespace GvrReplay;
public sealed class ReplayFile
{
public string Format { get; set; } = "gvr-replay";
public int V { get; set; } = 1;
/// 2: objects 에 yaw · pitch, objectPaths · track.f · states · hits · plants · actions · kills 4번째 열 추가 (v1 열은 그대로)
public int V { get; set; } = 2;
public string? MatchId { get; set; }
public string? Map { get; set; }
public string? Build { get; set; }
@@ -19,13 +20,30 @@ public sealed class ReplayFile
public List<ReplayRound> Rounds { get; set; } = [];
/// [t, phase] 게임 단계 바뀜 (원본 값)
public List<int[]> Phases { get; set; } = [];
/// [t, killer, victim] (선수 번호, 모르면 -1)
/// [t, killer, victim, deathAnim] (선수 번호, 모르면 -1. deathAnim = deathAnims 번호, 모르면 -1)
public List<int[]> Kills { get; set; } = [];
/// 죽는 모션 이름 (예: TP_Core_Death_Head_Front_SM_Montage)
public List<string> DeathAnims { get; set; } = [];
/// [t, player, x, y, z, yaw, pitch] 사격 위치와 방향
public List<int[]> Shots { get; set; } = [];
/// 스킬 · 설치물 [t0, t1, kind 번호, x, y, z, player] (t1 = 사라진 시각, 모르면 -1)
/// 스킬 · 설치물 [t0, t1, kind 번호, x, y, z, player, yaw, pitch] (t1 = 사라진 시각, 날아가는 것은 부딪힌 시각, 모르면 -1. yaw · pitch 는 생길 때 방향(도))
public List<int[]> Objects { get; set; } = [];
public List<string> ObjectKinds { get; set; } = [];
/// 움직이는 스킬의 경로 (투사체 비행 · 드론 · 분신). o = objects 번호
public List<ObjectPath> ObjectPaths { get; set; } = [];
/// 무기 · 스킬 상태 바뀜 [t, player, equipKind, stateKind] (FiringState · ReloadState · ZoomStateLevel1 · EquipState …)
public List<int[]> States { get; set; } = [];
public List<string> StateKinds { get; set; } = [];
/// 맞은 것 [t, attacker, victim, 쏜 x, y, z, 맞은 x, y, z, 부위(1 머리 · 2 몸 · 3 다리 · 0 모름), 죽였으면 1]
public List<int[]> Hits { get; set; } = [];
/// 스파이크 설치 [t, player, x, y, z]
public List<int[]> Plants { get; set; } = [];
/// 이어지는 동작 [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, 스킬은 클래스 이름
public List<int[]> Equips { get; set; } = [];
public List<string> EquipKinds { get; set; } = [];
}
public sealed class ReplayPlayer
@@ -35,6 +53,8 @@ public sealed class ReplayPlayer
public string? Character { get; set; }
/// 이동 기록. 열 별 배열 (같은 길이): t, x, y, z, yaw(도), pitch(도)
public PlayerTrack Track { get; set; } = new();
/// 조준점 설정이 바뀐 시각마다 전체 설정 (시간 순). 리플레이에 없으면 null
public List<CrosshairAt>? Crosshair { get; set; }
}
public sealed class PlayerTrack
@@ -45,6 +65,19 @@ public sealed class PlayerTrack
public List<int> Z { get; set; } = [];
public List<int> Yaw { get; set; } = [];
public List<int> Pitch { get; set; } = [];
/// 움직임 상태 비트: 1 앉음 · 2 걷기(Shift) · 4 공중(점프 · 떨어짐) · 8 날기(제트 대시 등)
public List<int> F { get; set; } = [];
}
public sealed class ObjectPath
{
public int O { get; set; }
public List<int> T { get; set; } = [];
public List<int> X { get; set; } = [];
public List<int> Y { get; set; } = [];
public List<int> Z { get; set; } = [];
/// 드론 · 분신만 (보는 방향, 도). 투사체는 빈 배열
public List<int> Yaw { get; set; } = [];
}
public sealed class ReplayRound

View File

@@ -1,6 +1,8 @@
// gvr-replay: 발로란트 리플레이(.vrf) → 사이트 재생기용 JSON (형식 gvr-replay v1)
// gvr-replay: 발로란트 리플레이(.vrf) → 사이트 재생기용 JSON (형식 gvr-replay v2)
// gvr-replay <file.vrf> <out.json> [--hz 10]
// gvr-replay <file.vrf> --stats (디버그: 액터 종류별 개수)
// gvr-replay <file.vrf> --fields (디버그: 복제 필드 목록 <경로\t이름>, 번호 순)
// gvr-replay --self-test (회귀 검사: 무기 주인 시간표 · 조준점 필드 자리)
// 성공하면 종료 코드 0 과 함께 stdout 마지막 줄에 {"ok":true,...} 요약을 쓴다. 실패는 1 과 {"ok":false,"error":...}
using System.Diagnostics;
using System.Text.Json;
@@ -13,8 +15,51 @@ namespace GvrReplay;
public static class Program
{
/// <summary>회귀 검사 (리플레이 파일 없이): 무기를 넘겨받아도 넘기기 전 상태는 이전 주인 것</summary>
private static int SelfTest()
{
var fails = new List<string>();
void Eq(string name, int got, int want)
{
if (got != want) fails.Add($"{name}: {got} (기대 {want})");
}
// 선수 0 이 1초에 들고 2초에 재장전, 10초에 선수 1 이 주움
var o = EquipOwners.Build([(1000, 7u, 0), (10000, 7u, 1)]);
Eq("주기 전 재장전(2초)", EquipOwners.At(o, 7, 2000), 0);
Eq("주운 순간(10초)", EquipOwners.At(o, 7, 10000), 1);
Eq("주운 뒤(12초)", EquipOwners.At(o, 7, 12000), 1);
Eq("첫 기록 전(0.5초)", EquipOwners.At(o, 7, 500), 0);
Eq("기록 없는 장비", EquipOwners.At(o, 8, 2000), -1);
// 같은 시각 순서가 뒤섞여 들어와도 시간 순으로
var o2 = EquipOwners.Build([(5000, 9u, 2), (1000, 9u, 3)]);
Eq("순서 섞임(3초)", EquipOwners.At(o2, 9, 3000), 3);
Eq("순서 섞임(6초)", EquipOwners.At(o2, 9, 6000), 2);
// 선수를 모르는 기록(-1)은 건너뛴다
var o3 = EquipOwners.Build([(1000, 4u, 5), (2000, 4u, -1)]);
Eq("모르는 선수 건너뜀", EquipOwners.At(o3, 4, 3000), 5);
// 조준점 필드 자리: 13.08 번호 그대로 · 앞에 필드가 2개 늘어난 패치 · 이름이 어긋나면 못 찾음
Dictionary<int, string> Names(int b) => new()
{
[b] = "B", [b + 8] = "bUseCustomColor", [b + 23] = "LineThickness", [b + 35] = "LineThickness",
[b + 70] = "LineThickness", [b + 153] = "bUsePrimaryCrosshairForADS", [b + 158] = "ProfileName", [b - 13] = "AssignedTeamState",
};
Eq("조준점 자리 13.08", Crosshair.FindBase(Names(39)) ?? -1, 39);
Eq("조준점 자리 +2", Crosshair.FindBase(Names(41)) ?? -1, 41);
var wrong = Names(39);
wrong[39 + 23] = "LineOffset";
Eq("조준점 이름 어긋남", Crosshair.FindBase(wrong) ?? -1, -1);
// 기본값: 오지 않은 색은 흰색, 사용자 지정 색을 쓰면 그 색
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)");
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;
}
public static int Main(string[] args)
{
if (args.Length == 1 && args[0] == "--self-test") return SelfTest();
if (args.Length < 2)
{
Console.Error.WriteLine("사용법: gvr-replay <file.vrf> <out.json> [--hz 10] | gvr-replay <file.vrf> --stats");
@@ -32,9 +77,18 @@ public static class Program
using var file = File.OpenRead(input);
using var archive = new FBinaryArchive(file);
var enricher = new ValorantEventEnricher(collector);
var result = ValorantReplayReader.CreateDefault(null, enricher, ParseProfile.Default).Read(archive);
// 진단 필드: 스킬 주인(Instigator) · 투사체 비행(ReplicatedMovement) · 무기 상태(CurrentState)를 페이로드 종류와 상관없이 읽는다
var profile = new ParseProfile { EnabledCategories = ExportCategory.All, CaptureDiagnosticFields = true };
var result = ValorantReplayReader.CreateDefault(null, enricher, profile).Read(archive);
enricher.Complete();
var info = result.Metadata.ReplayInfo;
if (args[1] == "--fields")
{
foreach (var g in result.ExportGroups)
foreach (var f in g.Fields)
Console.WriteLine(g.PathName + "\t" + f.Name);
return 0;
}
if (stats)
{
collector.PrintStats();
@@ -45,6 +99,21 @@ public static class Program
FDateTimeToUnixMs(info.Timestamp),
info.LengthInMs,
hz);
// 선수 조준점 (두 번째 읽기). 못 읽어도 나머지 변환은 그대로 쓴다
var crosshairs = 0;
try
{
foreach (var (state, list) in Crosshair.Read(input, result))
if (collector.SubjectOfState(state) is { } subject && replay.Players.FirstOrDefault(p => p.Puuid == subject) is { } pl)
{
pl.Crosshair = list;
crosshairs++;
}
}
catch (Exception e)
{
Console.Error.WriteLine("조준점 읽기 실패: " + e.Message);
}
var tmp = args[1] + ".tmp";
using (var fs = File.Create(tmp))
JsonSerializer.Serialize(fs, replay, ReplayJson.Options);
@@ -58,6 +127,7 @@ public static class Program
players = replay.Players.Count,
rounds = replay.Rounds.Count,
kills = replay.Kills.Count,
crosshairs,
elapsedMs = sw.ElapsedMilliseconds,
status = result.Status.ToString(),
warnings = result.TotalDiagnosticCount,

View File

@@ -151,6 +151,9 @@ try {
$exe = Join-Path $tx 'out\win\gvr-replay.exe'
if (-not (Test-Path $exe)) { throw 'gvr-replay.exe 없음' }
"gvr-replay.exe $([math]::Round((Get-Item $exe).Length / 1MB, 1)) MB"
# 회귀 검사 (리플레이 파일 없이: 무기 주인 시간표 등)
& $exe --self-test
if ($LASTEXITCODE -ne 0) { throw "gvr-replay --self-test exit $LASTEXITCODE" }
# 실제 13.08 리플레이 변환 (호스트가 serve/ 에 둔 시험 파일, 없으면 건너뜀)
$vrf = Join-Path $OutDir '4145f041-7d83-4785-ac4b-b532154f14a4.vrf'
try { Invoke-WebRequest -Uri 'http://10.0.2.2:8099/gvr-test.vrf' -OutFile $vrf -UseBasicParsing -TimeoutSec 600 } catch { Remove-Item $vrf -Force -ErrorAction SilentlyContinue; "시험 리플레이 없음: $($_.Exception.Message)" }

View File

@@ -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},