3D 리플레이 1단계: .vrf 변환기(tools/replay-extract) · 사이트 3D 재생기 · 대화 동기화

- tools/replay-extract: ValorantReplayParser(MIT, 고정 커밋) → gvr-replay JSON v1
  (선수 이동 10Hz · 라운드 · 킬 · 사격 · 스킬/설치물 · 녹화 시작 시각)
- 사이트: 경기 화면 '3D 리플레이' 칸 (three.js 지연 로드). 미니맵 바닥 + 실제 높이,
  회전 · 확대 · 선수 선택 · 따라가기 · 킬피드 · 자막 · 말하는 사람 표시
- 동기화: 같은 킬의 경기 기록 시각과 리플레이 시각 차이 중앙값 (못 맞추면 라운드 시작)
  현장 모드 시계에 묶어 재생 · 멈춤 · 이동 · 배속이 대화와 같이 움직임
- 목 서버 데모(GVR_MOCK_REPLAY), 동기화 테스트 4개

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-17 03:56:43 +09:00
parent 50fc90070b
commit 9592efeff6
18 changed files with 1539 additions and 1 deletions

View File

@@ -0,0 +1,265 @@
using System.Text.RegularExpressions;
using Replay.Models.Events;
using Replay.Models.Unreal;
using Replay.Valorant.Combat;
using Replay.Valorant.Descriptors;
using Replay.Valorant.Descriptors.Agents;
using Replay.Valorant.Events.Combat;
using Replay.Valorant.Events.Movement;
using Replay.Valorant.GameState;
namespace GvrReplay;
/// 파서 이벤트 → 필요한 것만 모은다 (선수 이동은 sampleMs 간격으로 줄임)
public sealed partial class Collector(int sampleMs) : IReplayEventSink
{
private string? _matchId;
private string? _map;
private readonly Dictionary<uint, string> _archetypeByActor = [];
private readonly Dictionary<uint, string> _subjectByState = [];
private readonly Dictionary<uint, uint> _stateByCharacter = [];
// 조종 중인 폰 (드론 · 카메라 · 클로브 사후 몸 등). 요원 몸(*_PC_C)만 선수 이동으로 쓴다
private readonly Dictionary<uint, uint> _possessedByState = [];
private readonly Dictionary<uint, List<int[]>> _moves = [];
private readonly Dictionary<uint, int> _lastMoveT = [];
private readonly List<int[]> _phases = [];
private readonly List<(int T, int NewRoundIndex)> _roundEnds = [];
private readonly List<(int T, uint Killer, uint Victim)> _kills = [];
private readonly List<(int T, uint State, int X, int Y, int Z, int Yaw, int Pitch)> _shots = [];
private readonly List<(int T0, uint Actor, string Kind, int X, int Y, int Z)> _objects = [];
private readonly Dictionary<uint, int> _closedAt = [];
private readonly Dictionary<uint, uint> _objectOwner = [];
private readonly Dictionary<string, int> _stats = [];
private static int Ms(float seconds) => (int)Math.Round(seconds * 1000.0);
private static int R(double v) => (int)Math.Round(v);
[GeneratedRegex(@"^/Game/Maps/([^/.]+)/\1$")]
private static partial Regex MapPath();
// 스킬 · 설치물로 보는 액터 클래스 (요원 본체 *_PC_C 와 무기 · 상태는 뺀다)
// GameObject_* (연막 · 함정 · 정찰 등), Patch_* (장판), Pawn_* (드론 · 분신), Projectile_* (날아가는 스킬), TimedBomb_C (설치된 스파이크)
[GeneratedRegex(@"^Default__(GameObject_|Patch_|Pawn_|Projectile_|TimedBomb_C$)")]
private static partial Regex ObjectClass();
public void Emit(ReplayEvent e)
{
switch (e)
{
case NetGuidExported g:
if (_map is null && MapPath().IsMatch(g.Path)) _map = g.Path;
break;
case ActorSpawned s:
if (s.ArchetypePath is { } arch)
{
_archetypeByActor[s.ActorNetGuid] = arch;
Count("spawn " + Simplify(arch));
if (s.Location is { } loc && ObjectClass().IsMatch(arch) && !arch.EndsWith("_PC_C"))
_objects.Add((Ms(s.TimeSeconds), s.ActorNetGuid, Simplify(arch), R(loc.X), R(loc.Y), R(loc.Z)));
}
break;
case ActorClosed c:
_closedAt[c.ActorNetGuid] = Ms(c.TimeSeconds);
break;
case ExportGroupReceived x:
OnExport(x);
break;
case RpcReceived r:
OnRpc(r);
break;
case RemoteCharacterMovementReceived m:
OnMove(m);
break;
case ValorantShotReceived shot:
OnShot(shot);
break;
}
}
private void OnExport(ExportGroupReceived x)
{
switch (x.Payload)
{
case BombGameStateDescriptor gs when gs.HasDecoded(nameof(BombGameStateDescriptor.MatchID)) && !string.IsNullOrEmpty(gs.MatchID):
_matchId ??= gs.MatchID;
break;
case BombPlayerStateDescriptor ps:
if (ps.HasDecoded(nameof(BombPlayerStateDescriptor.Subject)) && !string.IsNullOrEmpty(ps.Subject))
_subjectByState[x.ActorNetGuid] = ps.Subject!;
if (ps.HasDecoded(nameof(BombPlayerStateDescriptor.SpawnedCharacter)) && ps.SpawnedCharacter.NetGuid != 0)
_stateByCharacter[ps.SpawnedCharacter.NetGuid] = x.ActorNetGuid;
if (ps.HasDecoded(nameof(BombPlayerStateDescriptor.PossessedCharacter)) && ps.PossessedCharacter.NetGuid != 0)
_possessedByState[ps.PossessedCharacter.NetGuid] = x.ActorNetGuid;
break;
case GenericAgentDescriptor agent:
if (agent.HasDecoded(nameof(GenericAgentDescriptor.PlayerState)) && agent.PlayerState.NetGuid != 0)
_stateByCharacter.TryAdd(x.ActorNetGuid, agent.PlayerState.NetGuid);
if (agent.HasDecoded(nameof(GenericAgentDescriptor.Owner)) && agent.Owner.NetGuid != 0)
_objectOwner.TryAdd(x.ActorNetGuid, agent.Owner.NetGuid);
if (agent.HasDecoded(nameof(GenericAgentDescriptor.Instigator)) && agent.Instigator.NetGuid != 0)
_objectOwner[x.ActorNetGuid] = agent.Instigator.NetGuid;
break;
}
}
private void OnRpc(RpcReceived r)
{
var t = Ms(r.TimeSeconds);
switch (r.Payload)
{
case ClientGamePhaseBeginParameters p:
// 같은 시각에 같은 단계가 여러 컨트롤러로 올 수 있다
if (_phases.Count == 0 || _phases[^1][1] != p.NewPhase || _phases[^1][0] != t)
_phases.Add([t, p.NewPhase]);
break;
case MulticastEndRoundParameters er:
if (_roundEnds.Count == 0 || _roundEnds[^1].NewRoundIndex != er.NewRoundNumber)
_roundEnds.Add((t, er.NewRoundNumber));
break;
case MulticastNotifyKilledEnemyParameters k:
if (!_kills.Any(q => Math.Abs(q.T - t) < 50 && q.Victim == k.KilledCharacter.NetGuid))
_kills.Add((t, k.KillerCharacter.NetGuid, k.KilledCharacter.NetGuid));
break;
}
}
private void OnMove(RemoteCharacterMovementReceived m)
{
var t = Ms(m.TimeSeconds);
var ch = m.ShooterCharacterNetGuidValue;
if (_lastMoveT.TryGetValue(ch, out var last) && t - last < sampleMs) return;
_lastMoveT[ch] = t;
var p = m.Move.Position;
if (!_moves.TryGetValue(ch, out var list)) _moves[ch] = list = [];
list.Add([t, R(p.X), R(p.Y), R(p.Z), R(m.Move.Yaw), R(m.Move.Pitch)]);
}
private void OnShot(ValorantShotReceived s)
{
var shot = s.Shot;
if (shot.Location is not { } loc) return;
var state = shot.FiringPlayerState?.NetGuid ?? 0;
double yaw = 0, pitch = 0;
if (shot.Rotation is { } rot)
{
yaw = rot.Yaw;
pitch = rot.Pitch;
}
else if (shot.AttackVectors.Count > 0)
{
var v = shot.AttackVectors[0];
yaw = Math.Atan2(v.Y, v.X) * 180 / Math.PI;
pitch = Math.Atan2(v.Z, Math.Sqrt(v.X * v.X + v.Y * v.Y)) * 180 / Math.PI;
}
_shots.Add((Ms(s.TimeSeconds), state, R(loc.X), R(loc.Y), R(loc.Z), R(yaw), R(pitch)));
}
private static string Simplify(string archetype) => archetype.StartsWith("Default__") ? archetype[9..] : archetype;
private void Count(string key) => _stats[key] = _stats.GetValueOrDefault(key) + 1;
public void PrintStats()
{
Console.WriteLine($"match {_matchId} map {_map} states {_subjectByState.Count} chars {_stateByCharacter.Count} moves {_moves.Count} kills {_kills.Count} shots {_shots.Count} objects {_objects.Count} phases {_phases.Count} roundEnds {_roundEnds.Count}");
Console.WriteLine("stateByChar: " + string.Join(",", _stateByCharacter.Select(kv => $"{kv.Key}->{kv.Value}({(_archetypeByActor.TryGetValue(kv.Key, out var a) ? a : "?")})")));
Console.WriteLine("moves: " + string.Join(",", _moves.OrderByDescending(kv => kv.Value.Count).Take(14).Select(kv => $"{kv.Key}:{kv.Value.Count}({(_archetypeByActor.TryGetValue(kv.Key, out var a) ? a : "?")})")));
Console.WriteLine("states: " + string.Join(",", _subjectByState.Keys));
foreach (var (k, v) in _stats.OrderByDescending(kv => kv.Value).Take(150)) Console.WriteLine($"{v,6} {k}");
}
public ReplayFile Build(string? branch, long recordedAt, int durationMs, int hz)
{
// 선수 = 계정(subject) 하나. 캐릭터가 여러 번 바뀌어도(부활 등) 같은 선수로 묶는다
var players = new List<ReplayPlayer>();
var indexBySubject = new Dictionary<string, int>();
var indexByCharacter = new Dictionary<uint, int>();
int PlayerOfState(uint state)
{
if (!_subjectByState.TryGetValue(state, out var subject)) return -1;
if (!indexBySubject.TryGetValue(subject, out var i))
{
i = players.Count;
indexBySubject[subject] = i;
players.Add(new ReplayPlayer { Puuid = subject });
}
return i;
}
foreach (var state in _subjectByState.Keys.OrderBy(k => k)) PlayerOfState(state);
foreach (var (ch, state) in _possessedByState)
if (_archetypeByActor.TryGetValue(ch, out var a) && a.EndsWith("_PC_C")) _stateByCharacter.TryAdd(ch, state);
foreach (var (ch, state) in _stateByCharacter)
{
var i = PlayerOfState(state);
if (i < 0) continue;
indexByCharacter[ch] = i;
if (_archetypeByActor.TryGetValue(ch, out var arch) && arch.EndsWith("_PC_C"))
players[i].Character ??= Simplify(arch);
}
var merged = players.Select(_ => new List<int[]>()).ToList();
foreach (var (ch, moves) in _moves)
if (indexByCharacter.TryGetValue(ch, out var i)) merged[i].AddRange(moves);
for (var i = 0; i < players.Count; i++)
{
var tr = players[i].Track;
var lastT = int.MinValue / 2;
foreach (var mv in merged[i].OrderBy(m => m[0]))
{
if (mv[0] - lastT < sampleMs) continue;
lastT = mv[0];
tr.T.Add(mv[0]); tr.X.Add(mv[1]); tr.Y.Add(mv[2]); tr.Z.Add(mv[3]); tr.Yaw.Add(mv[4]); tr.Pitch.Add(mv[5]);
}
}
// 라운드: MulticastEndRound(NewRoundNumber=k) 는 라운드 k+1(1부터) 의 시작. 단계 3=구매, 4=교전, 5=라운드 끝
var rounds = new List<ReplayRound>();
var starts = new List<(int T, int Num)> { (0, 1) };
foreach (var (t, idx) in _roundEnds) starts.Add((t, idx + 1));
for (var r = 0; r < starts.Count; r++)
{
var from = starts[r].T;
var to = r + 1 < starts.Count ? starts[r + 1].T : int.MaxValue;
int Phase(int ph) => _phases.FirstOrDefault(p => p[1] == ph && p[0] >= from && p[0] < to)?[0] ?? -1;
var buy = Phase(3);
rounds.Add(new ReplayRound { Num = starts[r].Num, Buy = buy >= 0 ? buy : from, Combat = Phase(4), End = Phase(5) });
}
var kinds = new List<string>();
var kindIndex = new Dictionary<string, int>();
var objects = new List<int[]>();
// 맵 자체 연출(예: GameObject_Infinity_Rain_*)은 뺀다
var mapName = _map?.Split('/')[^1];
foreach (var o in _objects)
{
if (mapName is not null && o.Kind.Contains("_" + mapName + "_")) continue;
if (!kindIndex.TryGetValue(o.Kind, out var k)) { k = kinds.Count; kinds.Add(o.Kind); kindIndex[o.Kind] = k; }
var owner = -1;
var cur = o.Actor;
for (var d = 0; d < 6 && _objectOwner.TryGetValue(cur, out var up); d++)
{
if (indexByCharacter.TryGetValue(up, out owner)) break;
owner = -1;
if (_stateByCharacter.ContainsKey(up)) break;
if (_subjectByState.ContainsKey(up)) { owner = PlayerOfState(up); break; }
cur = up;
}
objects.Add([o.T0, _closedAt.TryGetValue(o.Actor, out var t1) && t1 >= o.T0 ? t1 : -1, k, o.X, o.Y, o.Z, owner]);
}
return new ReplayFile
{
MatchId = _matchId,
Map = _map,
Build = branch?.Replace("++Ares-Core+", ""),
RecordedAt = recordedAt,
DurationMs = durationMs,
SampleMs = sampleMs,
Players = players,
Rounds = rounds,
Phases = _phases,
Kills = _kills.Select(k => new[] { k.T, indexByCharacter.GetValueOrDefault(k.Killer, -1), indexByCharacter.GetValueOrDefault(k.Victim, -1) }).ToList(),
Shots = _shots.Select(s => new[] { s.T, PlayerOfState(s.State), s.X, s.Y, s.Z, s.Yaw, s.Pitch }).ToList(),
Objects = objects,
ObjectKinds = kinds,
};
}
}

View File

@@ -0,0 +1,69 @@
using System.Text.Json;
using System.Text.Json.Serialization;
namespace GvrReplay;
// 사이트로 가는 형식. 시간은 모두 리플레이 시작부터 ms (t), 좌표는 게임 월드 단위(cm) 정수
public sealed class ReplayFile
{
public string Format { get; set; } = "gvr-replay";
public int V { get; set; } = 1;
public string? MatchId { get; set; }
public string? Map { get; set; }
public string? Build { get; set; }
/// 리플레이 녹화 시작 시각 (서버 기준 유닉스 ms). t 를 실제 시각으로 바꿀 때 recordedAt + t
public long RecordedAt { get; set; }
public int DurationMs { get; set; }
public int SampleMs { get; set; }
public List<ReplayPlayer> Players { get; set; } = [];
public List<ReplayRound> Rounds { get; set; } = [];
/// [t, phase] 게임 단계 바뀜 (원본 값)
public List<int[]> Phases { get; set; } = [];
/// [t, killer, victim] (선수 번호, 모르면 -1)
public List<int[]> Kills { get; set; } = [];
/// [t, player, x, y, z, yaw, pitch] 사격 위치와 방향
public List<int[]> Shots { get; set; } = [];
/// 스킬 · 설치물 [t0, t1, kind 번호, x, y, z, player] (t1 = 사라진 시각, 모르면 -1)
public List<int[]> Objects { get; set; } = [];
public List<string> ObjectKinds { get; set; } = [];
}
public sealed class ReplayPlayer
{
public string? Puuid { get; set; }
/// 캐릭터 클래스 (예: Wushu_PC_C). 요원 이름은 사이트가 경기 상세(match-details)로 붙인다
public string? Character { get; set; }
/// 이동 기록. 열 별 배열 (같은 길이): t, x, y, z, yaw(도), pitch(도)
public PlayerTrack Track { get; set; } = new();
}
public sealed class PlayerTrack
{
public List<int> T { get; set; } = [];
public List<int> X { get; set; } = [];
public List<int> Y { get; set; } = [];
public List<int> Z { get; set; } = [];
public List<int> Yaw { get; set; } = [];
public List<int> Pitch { get; set; } = [];
}
public sealed class ReplayRound
{
/// 1부터
public int Num { get; set; }
/// 구매 단계 시작
public int Buy { get; set; }
/// 교전 시작 (구매 단계 끝), 모르면 -1
public int Combat { get; set; }
/// 라운드 끝 (승패 확정), 모르면 -1
public int End { get; set; }
}
public static class ReplayJson
{
public static readonly JsonSerializerOptions Options = new()
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.Never,
};
}

View File

@@ -0,0 +1,76 @@
// gvr-replay: 발로란트 리플레이(.vrf) → 사이트 재생기용 JSON (형식 gvr-replay v1)
// gvr-replay <file.vrf> <out.json> [--hz 10]
// gvr-replay <file.vrf> --stats (디버그: 액터 종류별 개수)
// 성공하면 종료 코드 0 과 함께 stdout 마지막 줄에 {"ok":true,...} 요약을 쓴다. 실패는 1 과 {"ok":false,"error":...}
using System.Diagnostics;
using System.Text.Json;
using Replay.Encoding.Archives;
using Replay.Models.Descriptors;
using Replay.Valorant;
using Replay.Valorant.Events;
namespace GvrReplay;
public static class Program
{
public static int Main(string[] args)
{
if (args.Length < 2)
{
Console.Error.WriteLine("사용법: gvr-replay <file.vrf> <out.json> [--hz 10] | gvr-replay <file.vrf> --stats");
return 2;
}
var input = args[0];
var stats = args[1] == "--stats";
var hz = 10;
for (var i = 2; i < args.Length - 1; i++)
if (args[i] == "--hz") hz = Math.Clamp(int.Parse(args[i + 1]), 1, 60);
try
{
var sw = Stopwatch.StartNew();
var collector = new Collector(1000 / hz);
using var file = File.OpenRead(input);
using var archive = new FBinaryArchive(file);
var enricher = new ValorantEventEnricher(collector);
var result = ValorantReplayReader.CreateDefault(null, enricher, ParseProfile.Default).Read(archive);
enricher.Complete();
var info = result.Metadata.ReplayInfo;
if (stats)
{
collector.PrintStats();
return 0;
}
var replay = collector.Build(
result.Metadata.ReplayVersion.Branch,
FDateTimeToUnixMs(info.Timestamp),
info.LengthInMs,
hz);
var tmp = args[1] + ".tmp";
using (var fs = File.Create(tmp))
JsonSerializer.Serialize(fs, replay, ReplayJson.Options);
File.Move(tmp, args[1], true);
Console.WriteLine(JsonSerializer.Serialize(new
{
ok = true,
matchId = replay.MatchId,
map = replay.Map,
build = replay.Build,
players = replay.Players.Count,
rounds = replay.Rounds.Count,
kills = replay.Kills.Count,
elapsedMs = sw.ElapsedMilliseconds,
status = result.Status.ToString(),
warnings = result.TotalDiagnosticCount,
}));
return 0;
}
catch (Exception e)
{
Console.WriteLine(JsonSerializer.Serialize(new { ok = false, error = e.GetType().Name + ": " + e.Message }));
return 1;
}
}
/// UE FDateTime ticks (100ns, 0001-01-01 기준, UTC) → 유닉스 ms
public static long FDateTimeToUnixMs(long ticks) => ticks <= 0 ? 0 : (ticks - 621355968000000000L) / 10000L;
}