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; /// /// 선수 조준점 설정. BombPlayerState 에 선수마다 조준점 프로필(주 조준점 · 정조준 · 저격 조준경 · 프로필 이름)이 복제된다 /// (관전자에게 보이는 조준점). 파서의 BombPlayerState 형식에는 이 필드가 없어서, 첫 번째 읽기에서 받은 필드 목록으로 /// 번호(handle)를 찾고 이 필드만 읽는 두 번째 읽기를 한다. /// 필드는 기본값(색 흰색 255 · 숫자 0 · 끔)과 다를 때만 오고, 바뀐 필드만 다시 온다. /// 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]; } /// 필드 목록(번호 → 이름)에서 조준점 기준 번호. 이름이 하나라도 어긋나면 그 자리는 아니다. 못 찾으면 null public static int? FindBase(IReadOnlyDictionary 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; } /// 두 번째 읽기: PlayerState 액터 → 조준점이 바뀐 시각마다 전체 설정 public static Dictionary> Read(string path, ValorantReplayReadResult first) { var group = first.ExportGroups.FirstOrDefault(g => g.PathName == StatePath); if (group is null) return []; var names = new Dictionary(); 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(); var fields = new List(); 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 keyByHandle) : IReplayEventSink { private readonly Dictionary> _now = []; public Dictionary> 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 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);