발로란트 맵 3D: 모든 맵을 Riot CDN 에서 바로 추출해 3D 리플레이에 붙임 · 매핑 업데이트 자동 적용
- tools/map-extract (C#, CUE4Parse 고정 커밋): 게임 파일을 받지 않고 매니페스트 조각만 HTTP Range 로 읽어 맵 22개(일반 13 · 팀 데스매치 5 · 스커미시 3 · 어빌리티 드래프트)를 월드 좌표 glb 로. 3.1분 · 587MB 받음 - scripts/pack.py (gltfpack -cc + gzip, 맵당 0.5~4.6MB) · update.sh (uedb 매핑 · 라이브 패치 확인 → 매핑 보관 → 추출 → .5 data/maps3d 반영) · install.sh (systemd 사용자 타이머 30분, 메모리 6GB 상한) - 사이트 서버: GET /site/maps3d* (로그인 필요, gzip 그대로). CSP 에 'wasm-unsafe-eval' (meshopt 압축 풀기만) - 3D 재생기: 맵 3D 위에 선수 표시, 천장 자르기(자동 · 없음 · 직접), 높이 색칠. 맵이 없거나 실패하면 미니맵 - 리플레이 칸: 리플레이를 아직 안 보내는 앱 버전이면 그렇게 안내 - 테스트: maps3d.test.ts 2개, CSP 테스트 갱신 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
220
tools/map-extract/src/Cdn.cs
Normal file
220
tools/map-extract/src/Cdn.cs
Normal file
@@ -0,0 +1,220 @@
|
||||
using System.Net;
|
||||
using System.Net.Http.Headers;
|
||||
using CUE4Parse.UE4.Readers;
|
||||
using CUE4Parse.UE4.Versions;
|
||||
|
||||
namespace GvrMapExtract;
|
||||
|
||||
/// <summary>Riot CDN 번들에서 매니페스트 조각을 필요할 때만 받는다 (HTTP Range).
|
||||
/// 받은 조각은 압축을 풀어 메모리에 둔다 (오래 안 쓴 것부터 버림). 디스크는 쓰지 않는다.</summary>
|
||||
public sealed class CdnStore(string bundleBase, long cacheBytes)
|
||||
{
|
||||
private readonly HttpClient _http = new(new SocketsHttpHandler { MaxConnectionsPerServer = 8, AutomaticDecompression = DecompressionMethods.None })
|
||||
{
|
||||
Timeout = TimeSpan.FromSeconds(90),
|
||||
};
|
||||
private readonly object _lock = new();
|
||||
private readonly Dictionary<(ulong, uint), LinkedListNode<((ulong, uint) key, byte[] data)>> _map = new();
|
||||
private readonly LinkedList<((ulong, uint) key, byte[] data)> _lru = new();
|
||||
private readonly Dictionary<(ulong, uint), Task> _inflight = new();
|
||||
private long _cached;
|
||||
public long DownloadedBytes;
|
||||
public long Requests;
|
||||
|
||||
private bool TryGet((ulong, uint) key, out byte[] data)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_map.TryGetValue(key, out var node))
|
||||
{
|
||||
_lru.Remove(node);
|
||||
_lru.AddFirst(node);
|
||||
data = node.Value.data;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
data = [];
|
||||
return false;
|
||||
}
|
||||
|
||||
private void Put((ulong, uint) key, byte[] data)
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
if (_map.ContainsKey(key)) return;
|
||||
_map[key] = _lru.AddFirst((key, data));
|
||||
_cached += data.Length;
|
||||
while (_cached > cacheBytes && _lru.Last is { } last)
|
||||
{
|
||||
_lru.RemoveLast();
|
||||
_map.Remove(last.Value.key);
|
||||
_cached -= last.Value.data.Length;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>파일의 i 번째 조각. 없으면 뒤로 이어진 조각(같은 번들 · 연속 위치)까지 한 번에 받는다</summary>
|
||||
public byte[] Get(Rman.RFile f, int i)
|
||||
{
|
||||
var c = f.Chunks[i];
|
||||
var key = (c.BundleId, c.BundleOffset);
|
||||
for (var attempt = 0; ; attempt++)
|
||||
{
|
||||
if (TryGet(key, out var hit)) return hit;
|
||||
Task? wait;
|
||||
TaskCompletionSource? mine = null;
|
||||
lock (_lock)
|
||||
{
|
||||
if (!_inflight.TryGetValue(key, out wait))
|
||||
{
|
||||
mine = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
|
||||
_inflight[key] = mine.Task;
|
||||
}
|
||||
}
|
||||
if (mine == null)
|
||||
{
|
||||
try { wait!.Wait(); } catch { /* 받던 쪽이 실패하면 다시 시도 */ }
|
||||
if (attempt > 4) throw new IOException("조각 받기 실패 (반복)");
|
||||
continue;
|
||||
}
|
||||
// 이어 받을 조각 범위
|
||||
var run = new List<int> { i };
|
||||
long total = c.CompressedSize;
|
||||
for (var j = i + 1; j < f.Chunks.Length && run.Count < 64 && total < 8 << 20; j++)
|
||||
{
|
||||
var n = f.Chunks[j];
|
||||
var prev = f.Chunks[j - 1];
|
||||
if (n.BundleId != c.BundleId || n.BundleOffset != prev.BundleOffset + prev.CompressedSize) break;
|
||||
lock (_lock) if (_map.ContainsKey((n.BundleId, n.BundleOffset)) || _inflight.ContainsKey((n.BundleId, n.BundleOffset))) break;
|
||||
run.Add(j);
|
||||
total += n.CompressedSize;
|
||||
}
|
||||
lock (_lock) foreach (var j in run.Skip(1)) _inflight.TryAdd((f.Chunks[j].BundleId, f.Chunks[j].BundleOffset), mine.Task);
|
||||
try
|
||||
{
|
||||
var raw = Fetch(c.BundleId, c.BundleOffset, total);
|
||||
var pos = 0;
|
||||
using var z = new ZstdSharp.Decompressor();
|
||||
foreach (var j in run)
|
||||
{
|
||||
var cj = f.Chunks[j];
|
||||
var outBuf = new byte[cj.UncompressedSize];
|
||||
var n = z.Unwrap(raw.AsSpan(pos, (int)cj.CompressedSize), outBuf);
|
||||
if (n != cj.UncompressedSize) throw new IOException("조각 크기가 다름");
|
||||
pos += (int)cj.CompressedSize;
|
||||
Put((cj.BundleId, cj.BundleOffset), outBuf);
|
||||
}
|
||||
mine.SetResult();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
mine.SetException(e);
|
||||
if (attempt > 4) throw;
|
||||
}
|
||||
finally
|
||||
{
|
||||
lock (_lock) foreach (var j in run) if (_inflight.TryGetValue((f.Chunks[j].BundleId, f.Chunks[j].BundleOffset), out var t) && t == mine.Task) _inflight.Remove((f.Chunks[j].BundleId, f.Chunks[j].BundleOffset));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private byte[] Fetch(ulong bundle, uint offset, long length)
|
||||
{
|
||||
var url = $"{bundleBase}/{bundle:X16}.bundle";
|
||||
for (var attempt = 0; ; attempt++)
|
||||
{
|
||||
try
|
||||
{
|
||||
using var req = new HttpRequestMessage(HttpMethod.Get, url);
|
||||
req.Headers.Range = new RangeHeaderValue(offset, offset + length - 1);
|
||||
using var res = _http.Send(req, HttpCompletionOption.ResponseHeadersRead);
|
||||
if (res.StatusCode != HttpStatusCode.PartialContent) throw new IOException($"{url} {(int)res.StatusCode}");
|
||||
using var s = res.Content.ReadAsStream();
|
||||
var buf = new byte[length];
|
||||
s.ReadExactly(buf);
|
||||
Interlocked.Add(ref DownloadedBytes, length);
|
||||
Interlocked.Increment(ref Requests);
|
||||
return buf;
|
||||
}
|
||||
catch (Exception) when (attempt < 4)
|
||||
{
|
||||
Thread.Sleep(1000 * (attempt + 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<byte[]> GetBytes(string url) => await _http.GetByteArrayAsync(url);
|
||||
}
|
||||
|
||||
/// <summary>매니페스트 파일 하나를 CUE4Parse 가 읽는 파일처럼 보이게 한다 (임의 위치 읽기)</summary>
|
||||
public sealed class CdnArchive : FArchive
|
||||
{
|
||||
private readonly CdnStore _store;
|
||||
private readonly Rman.RFile _file;
|
||||
private readonly long[] _starts;
|
||||
|
||||
public CdnArchive(CdnStore store, Rman.RFile file, VersionContainer? versions) : base(versions)
|
||||
{
|
||||
_store = store;
|
||||
_file = file;
|
||||
_starts = file.Chunks.Select(c => c.FileOffset).ToArray();
|
||||
Name = file.Path;
|
||||
}
|
||||
|
||||
public override string Name { get; }
|
||||
public override bool CanSeek => true;
|
||||
public override long Length => _file.Size;
|
||||
public override long Position { get; set; }
|
||||
|
||||
public override int Read(byte[] buffer, int offset, int count)
|
||||
{
|
||||
var n = ReadAt(Position, buffer, offset, count);
|
||||
Position += n;
|
||||
return n;
|
||||
}
|
||||
|
||||
public override int ReadAt(long position, byte[] buffer, int offset, int count)
|
||||
{
|
||||
if (position >= Length) return 0;
|
||||
count = (int)Math.Min(count, Length - position);
|
||||
var done = 0;
|
||||
var i = Array.BinarySearch(_starts, position);
|
||||
if (i < 0) i = ~i - 1;
|
||||
while (done < count)
|
||||
{
|
||||
var c = _file.Chunks[i];
|
||||
var data = _store.Get(_file, i);
|
||||
var inChunk = (int)(position + done - c.FileOffset);
|
||||
var n = Math.Min(count - done, data.Length - inChunk);
|
||||
Buffer.BlockCopy(data, inChunk, buffer, offset + done, n);
|
||||
done += n;
|
||||
i++;
|
||||
}
|
||||
return done;
|
||||
}
|
||||
|
||||
public override Task<int> ReadAtAsync(long position, byte[] buffer, int offset, int count, CancellationToken cancellationToken = default)
|
||||
=> Task.FromResult(ReadAt(position, buffer, offset, count));
|
||||
|
||||
public override ValueTask<int> ReadAtAsync(long position, Memory<byte> memory, CancellationToken cancellationToken = default)
|
||||
{
|
||||
var tmp = new byte[memory.Length];
|
||||
var n = ReadAt(position, tmp, 0, tmp.Length);
|
||||
tmp.AsSpan(0, n).CopyTo(memory.Span);
|
||||
return ValueTask.FromResult(n);
|
||||
}
|
||||
|
||||
public override long Seek(long offset, SeekOrigin origin)
|
||||
{
|
||||
Position = origin switch
|
||||
{
|
||||
SeekOrigin.Begin => offset,
|
||||
SeekOrigin.Current => Position + offset,
|
||||
SeekOrigin.End => Length + offset,
|
||||
_ => throw new ArgumentOutOfRangeException(nameof(origin)),
|
||||
};
|
||||
return Position;
|
||||
}
|
||||
|
||||
public override object Clone() => new CdnArchive(_store, _file, Versions) { Position = Position };
|
||||
}
|
||||
225
tools/map-extract/src/MapScene.cs
Normal file
225
tools/map-extract/src/MapScene.cs
Normal file
@@ -0,0 +1,225 @@
|
||||
using System.Text;
|
||||
using CUE4Parse.FileProvider;
|
||||
using CUE4Parse.UE4.Assets.Exports;
|
||||
using CUE4Parse.UE4.Assets.Exports.Component.StaticMesh;
|
||||
using CUE4Parse.UE4.Assets.Exports.StaticMesh;
|
||||
using CUE4Parse.UE4.Objects.Core.Math;
|
||||
|
||||
namespace GvrMapExtract;
|
||||
|
||||
/// <param name="Code">영구 레벨 이름 (Ascent, HURM_Alley …)</param>
|
||||
/// <param name="MapUrl">경기 기록의 맵 경로 (/Game/Maps/Ascent/Ascent)</param>
|
||||
public sealed record MapInfo(string Code, string MapUrl, List<string> Levels);
|
||||
|
||||
/// <summary>맵 레벨들의 StaticMesh 배치를 모아 월드 좌표(UE cm) 삼각형 하나로 굽는다.
|
||||
/// 재질 · 텍스처는 없다 (사이트는 높이 · 면 방향으로 색을 칠한다).</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 = "";
|
||||
|
||||
/// <summary>맵 = 하위 레벨을 불러오는 영구 레벨 (경기 기록의 맵 경로 "/Game/Maps/Ascent/Ascent" 와 같다).
|
||||
/// 연습장 · 튜토리얼 · 메뉴처럼 경기가 없는 곳은 뺀다</summary>
|
||||
public static List<MapInfo> FindMaps(IFileProvider provider, Action<string>? log = null)
|
||||
{
|
||||
var umaps = provider.Files.Keys.Where(k => k.StartsWith("ShooterGame/Content/Maps/", StringComparison.OrdinalIgnoreCase) && k.EndsWith(".umap", StringComparison.OrdinalIgnoreCase)).ToList();
|
||||
var byDir = umaps.GroupBy(k => k[..k.LastIndexOf('/')]).ToDictionary(g => g.Key, g => g.Select(x => Path.GetFileNameWithoutExtension(x)).ToList());
|
||||
var res = new List<MapInfo>();
|
||||
foreach (var k in umaps.OrderBy(x => x))
|
||||
{
|
||||
var dir = k[..k.LastIndexOf('/')];
|
||||
var name = Path.GetFileNameWithoutExtension(k);
|
||||
if (NotPlayable.Any(x => k.Contains(x, StringComparison.OrdinalIgnoreCase))) continue;
|
||||
if (!byDir[dir].Any(o => o.StartsWith(name + "_", StringComparison.OrdinalIgnoreCase))) continue;
|
||||
List<(string level, string cls, string props)> subs;
|
||||
try { subs = StreamingLevels(provider, k); } catch (Exception e) { log?.Invoke($"{k}: 레벨 목록 실패 {e.Message}"); continue; }
|
||||
var levels = subs.Where(x => x.cls == "LevelStreamingAlwaysLoaded" && IsVisualLevel(x.level))
|
||||
.Select(x => "ShooterGame/Content" + x.level["/Game".Length..] + ".umap")
|
||||
.Where(provider.Files.ContainsKey).ToList();
|
||||
if (levels.Count == 0) continue;
|
||||
levels.Insert(0, k);
|
||||
res.Add(new MapInfo(name, "/Game" + k["ShooterGame/Content".Length..^".umap".Length], levels));
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
private static readonly string[] NotPlayable = ["/Poveglia", "/NPE", "/Menu/", "/Init/", "/Pregame", "_Copy/", "/SharedSubLevels/"];
|
||||
// 보이는 모양이 아닌 하위 레벨 (게임 규칙 · 빛 · 소리 · 부피 · 길찾기 · 카메라 · 효과 · 먼 배경 · 이벤트 장식)
|
||||
private static readonly string[] NotVisual = ["Gameplay", "Lighting", "Volume", "NavMesh", "Audio", "Sound", "_BV", "Callout", "VFX", "_FX", "Vista", "Background", "Decal",
|
||||
"Activation", "Birthday", "Snow", "LiveStory", "Sequence", "Camera", "Probe", "Profiling", "Greybox", "Blockout", "Design", "Layout", "Lanes", "Mode_", "Spawns_Proto", "SpawnPoints", "Skybox", "AuxiliaryZones", "KillVol", "Barrier", "Collider"];
|
||||
|
||||
/// <summary>영구 레벨이 불러오는 하위 레벨들 (패키지 경로 · 형 · b 로 시작하는 속성)</summary>
|
||||
public static List<(string level, string cls, string props)> StreamingLevels(IFileProvider provider, string umap)
|
||||
{
|
||||
var res = new List<(string, string, string)>();
|
||||
var pkg = provider.LoadPackage(umap);
|
||||
var world = pkg.GetExports().OfType<CUE4Parse.UE4.Objects.Engine.UWorld>().FirstOrDefault();
|
||||
if (world?.StreamingLevels == null) return res;
|
||||
foreach (var r in world.StreamingLevels)
|
||||
{
|
||||
var ls = r.Load<CUE4Parse.UE4.Objects.Engine.ULevelStreaming>();
|
||||
if (ls?.WorldAsset == null) continue;
|
||||
var pkgName = ls.WorldAsset.Value.AssetPathName.Text.Split('.')[0];
|
||||
var props = string.Join(' ', ls.Properties.Where(p => p.Name.Text.StartsWith('b')).Select(p => $"{p.Name.Text}={p.Tag?.GenericValue}"));
|
||||
res.Add((pkgName, ls.ExportType, props));
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
public static bool IsVisualLevel(string level)
|
||||
{
|
||||
var name = level[(level.LastIndexOf('/') + 1)..];
|
||||
return !NotVisual.Any(x => name.Contains(x, StringComparison.OrdinalIgnoreCase));
|
||||
}
|
||||
|
||||
// 부피 · 하늘 · 먼 배경 · 블록아웃 메시는 뺀다
|
||||
private static readonly string[] SkipMesh = ["Box_For_Volumes", "BasicShapes/Plane", "Blockout", "/Sky", "Vista", "EditorMeshes", "Cubemap"];
|
||||
|
||||
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)?>();
|
||||
foreach (var level in map.Levels)
|
||||
{
|
||||
s._levels.Add(Path.GetFileNameWithoutExtension(level));
|
||||
var pkg = provider.LoadPackage(level);
|
||||
foreach (var lazy in pkg.ExportsLazy)
|
||||
{
|
||||
UObject o;
|
||||
try { o = lazy.Value; } catch { s.Failed++; continue; }
|
||||
if (o is not UStaticMeshComponent c) continue;
|
||||
if (c.GetOrDefault<bool>("bHiddenInGame") || !c.GetOrDefault("bVisible", true)) { s.Skipped++; continue; }
|
||||
UStaticMesh? mesh;
|
||||
try { mesh = c.GetStaticMesh()?.Load<UStaticMesh>(); } catch { s.Failed++; continue; }
|
||||
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))
|
||||
{
|
||||
geo = Geometry(mesh);
|
||||
meshCache[path] = geo;
|
||||
if (geo != null) s.Meshes++;
|
||||
}
|
||||
if (geo == null) continue;
|
||||
FTransform w;
|
||||
try { w = c.GetAbsoluteTransform(); } catch { s.Failed++; continue; }
|
||||
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);
|
||||
}
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/// <summary>가장 낮은 LOD 의 위치 · 삼각형 (사이트에서 내려다보는 용도라 충분하다)</summary>
|
||||
private static (FVector[] v, uint[] i)? Geometry(UStaticMesh mesh)
|
||||
{
|
||||
var lods = mesh.RenderData?.LODs;
|
||||
if (lods == null) return null;
|
||||
for (var l = lods.Length - 1; l >= 0; l--)
|
||||
{
|
||||
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());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void Add((FVector[] v, uint[] i) g, FTransform t)
|
||||
{
|
||||
Placements++;
|
||||
var b = (uint)(_pos.Count / 3);
|
||||
foreach (var p in g.v)
|
||||
{
|
||||
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]);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>glb: 메시 하나, 위치(float32, UE 월드 cm 그대로) + 삼각형(uint32). 사이트가 미니맵 좌표로 옮긴다</summary>
|
||||
public void WriteGlb(string file)
|
||||
{
|
||||
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++)
|
||||
{
|
||||
min[i % 3] = Math.Min(min[i % 3], pos[i]);
|
||||
max[i % 3] = Math.Max(max[i % 3], pos[i]);
|
||||
}
|
||||
var posBytes = pos.Length * 4;
|
||||
var idxBytes = idx.Length * 4;
|
||||
var gltf = new
|
||||
{
|
||||
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[]
|
||||
{
|
||||
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[]
|
||||
{
|
||||
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);
|
||||
}
|
||||
|
||||
public void WriteInfo(string file, string manifest, string? usmap)
|
||||
{
|
||||
var info = new
|
||||
{
|
||||
code = _code,
|
||||
mapUrl = _mapUrl,
|
||||
levels = _levels,
|
||||
placements = Placements,
|
||||
meshes = Meshes,
|
||||
triangles = Triangles,
|
||||
skipped = Skipped,
|
||||
failed = Failed,
|
||||
manifest,
|
||||
usmap = usmap == null ? null : Path.GetFileName(usmap),
|
||||
extractedAt = DateTimeOffset.UtcNow.ToString("o"),
|
||||
};
|
||||
File.WriteAllText(file, System.Text.Json.JsonSerializer.Serialize(info, new System.Text.Json.JsonSerializerOptions { WriteIndented = true }));
|
||||
}
|
||||
}
|
||||
124
tools/map-extract/src/Program.cs
Normal file
124
tools/map-extract/src/Program.cs
Normal file
@@ -0,0 +1,124 @@
|
||||
using Serilog;
|
||||
using System.Diagnostics;
|
||||
using System.Text.RegularExpressions;
|
||||
using CUE4Parse;
|
||||
using CUE4Parse.Compression;
|
||||
using CUE4Parse.Encryption.Aes;
|
||||
using CUE4Parse.FileProvider;
|
||||
using CUE4Parse.MappingsProvider.Usmap;
|
||||
using CUE4Parse.UE4.Objects.Core.Misc;
|
||||
using CUE4Parse.UE4.Versions;
|
||||
using GvrMapExtract;
|
||||
|
||||
// gvr-map-extract: 발로란트 맵 3D 모양을 Riot CDN 에서 바로 뽑는다 (게임 설치 · 전체 다운로드 없음)
|
||||
//
|
||||
// gvr-map-extract ls <정규식> [개수] 파일 목록
|
||||
// gvr-map-extract maps 맵 목록 (코드 이름 · 레벨 수)
|
||||
// gvr-map-extract extract <출력 폴더> [맵...] 맵마다 <코드>.glb (UE 월드 좌표 cm, 위치 + 삼각형) + <코드>.json
|
||||
//
|
||||
// 환경변수
|
||||
// GVR_USMAP 매핑 파일 (.usmap, 필수: 13.08 부터 패키지에 형 정보가 없다). uedb.dev 에서 받는다
|
||||
// GVR_MANIFEST 매니페스트 URL (없으면 지금 라이브 패치를 Riot 설정에서 찾는다)
|
||||
// GVR_CACHE_MB 받은 조각을 메모리에 둘 크기 (기본 1500)
|
||||
// GVR_OODLE Oodle 라이브러리 경로 (없으면 실행 파일 옆, 없으면 받는다)
|
||||
|
||||
Serilog.Log.Logger = new Serilog.LoggerConfiguration().MinimumLevel.Error().WriteTo.Console().CreateLogger();
|
||||
CUE4ParseLog.UseLogger(Serilog.Log.Logger);
|
||||
|
||||
const string AesKey = "0x4BE71AF2459CF83899EC9DC2CB60E22AC4B3047E0211034BBABE9D174C069DD6"; // 발로란트 공개 키 (모든 패치 같음)
|
||||
const string BundleBase = "https://valorant.secure.dyn.riotcdn.net/channels/public/bundles";
|
||||
const string Patchlines = "https://clientconfig.rpg.riotgames.com/api/v1/config/public?namespace=keystone.products.valorant.patchlines";
|
||||
|
||||
if (args.Length == 0)
|
||||
{
|
||||
Console.Error.WriteLine("사용법: gvr-map-extract ls <정규식> | maps | extract <출력 폴더> [맵...] | manifest");
|
||||
return 2;
|
||||
}
|
||||
var sw = Stopwatch.StartNew();
|
||||
var store = new CdnStore(BundleBase, long.Parse(Environment.GetEnvironmentVariable("GVR_CACHE_MB") ?? "1500") << 20);
|
||||
var manifestUrl = Environment.GetEnvironmentVariable("GVR_MANIFEST") ?? await LiveManifest(store);
|
||||
if (args[0] == "manifest")
|
||||
{
|
||||
Console.WriteLine(manifestUrl);
|
||||
return 0;
|
||||
}
|
||||
var rman = Rman.Parse(await store.GetBytes(manifestUrl));
|
||||
Console.Error.WriteLine($"매니페스트 {manifestUrl} 파일 {rman.Files.Count}");
|
||||
|
||||
var oodle = Environment.GetEnvironmentVariable("GVR_OODLE") ?? Path.Combine(AppContext.BaseDirectory, OodleHelper.OodleFileName);
|
||||
await OodleHelper.InitializeAsync(oodle);
|
||||
var versions = new VersionContainer(EGame.GAME_Valorant);
|
||||
var provider = new StreamedFileProvider("VALORANT", versions, StringComparer.OrdinalIgnoreCase);
|
||||
provider.Initialize();
|
||||
foreach (var f in rman.Files.Values.Where(f => f.Path.StartsWith("ShooterGame/Content/Paks/", StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
var ext = Path.GetExtension(f.Path).ToLowerInvariant();
|
||||
if (ext == ".utoc")
|
||||
provider.RegisterRandomAccessVfs(new CdnArchive(store, f, versions), null, open =>
|
||||
rman.Files.TryGetValue(open, out var c) ? new CdnArchive(store, c, versions) : throw new FileNotFoundException(open));
|
||||
else if (ext == ".pak")
|
||||
provider.RegisterRandomAccessVfs(new CdnArchive(store, f, versions), null, null);
|
||||
}
|
||||
provider.SubmitKey(new FGuid(), new FAesKey(AesKey));
|
||||
provider.PostMount();
|
||||
var usmap = Environment.GetEnvironmentVariable("GVR_USMAP");
|
||||
if (usmap != null) provider.MappingsContainer = new FileUsmapTypeMappingsProvider(usmap);
|
||||
Console.Error.WriteLine($"파일 {provider.Files.Count} · 묶음 {provider.MountedVfs.Count} (못 연 것 {provider.UnloadedVfs.Count}) · 받은 양 {store.DownloadedBytes >> 20}MB · {sw.Elapsed.TotalSeconds:F0}초");
|
||||
|
||||
switch (args[0])
|
||||
{
|
||||
case "ls":
|
||||
{
|
||||
var re = new Regex(args[1], RegexOptions.IgnoreCase);
|
||||
foreach (var k in provider.Files.Keys.Where(k => re.IsMatch(k)).OrderBy(k => k).Take(args.Length > 2 ? int.Parse(args[2]) : 200)) Console.WriteLine(k);
|
||||
break;
|
||||
}
|
||||
case "levels":
|
||||
foreach (var (lvl, cls, props) in MapScene.StreamingLevels(provider, args[1]))
|
||||
Console.WriteLine($"{lvl}\t{cls}\t{props}");
|
||||
break;
|
||||
case "maps":
|
||||
foreach (var m in MapScene.FindMaps(provider, Console.Error.WriteLine)) Console.WriteLine($"{m.Code}\t{m.MapUrl}\t{m.Levels.Count}\t{string.Join(',', m.Levels.Select(Path.GetFileNameWithoutExtension))}");
|
||||
break;
|
||||
case "extract":
|
||||
{
|
||||
var outDir = args[1];
|
||||
Directory.CreateDirectory(outDir);
|
||||
var want = args.Skip(2).ToHashSet(StringComparer.OrdinalIgnoreCase);
|
||||
var maps = MapScene.FindMaps(provider, Console.Error.WriteLine).Where(m => want.Count == 0 || want.Contains(m.Code)).ToList();
|
||||
var failed = 0;
|
||||
foreach (var m in maps)
|
||||
{
|
||||
var t0 = sw.Elapsed;
|
||||
var d0 = store.DownloadedBytes;
|
||||
try
|
||||
{
|
||||
var r = MapScene.Build(provider, m);
|
||||
r.WriteGlb(Path.Combine(outDir, m.Code + ".glb"));
|
||||
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}초");
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
failed++;
|
||||
Console.WriteLine($"{m.Code}: 실패 {e.GetType().Name} {e.Message}");
|
||||
}
|
||||
GC.Collect();
|
||||
}
|
||||
Console.WriteLine($"끝: 맵 {maps.Count - failed}/{maps.Count} · 받은 양 {store.DownloadedBytes >> 20}MB ({store.Requests}번) · {sw.Elapsed.TotalMinutes:F1}분");
|
||||
return failed == 0 ? 0 : 1;
|
||||
}
|
||||
default:
|
||||
Console.Error.WriteLine("모르는 명령 " + args[0]);
|
||||
return 2;
|
||||
}
|
||||
return 0;
|
||||
|
||||
static async Task<string> LiveManifest(CdnStore store)
|
||||
{
|
||||
var json = System.Text.Json.JsonDocument.Parse(await store.GetBytes(Patchlines));
|
||||
var live = json.RootElement.GetProperty("keystone.products.valorant.patchlines.live");
|
||||
foreach (var c in live.GetProperty("platforms").GetProperty("win").GetProperty("configurations").EnumerateArray())
|
||||
if (c.TryGetProperty("patch_url", out var u)) return u.GetString()!;
|
||||
throw new InvalidOperationException("라이브 매니페스트를 못 찾음");
|
||||
}
|
||||
119
tools/map-extract/src/Rman.cs
Normal file
119
tools/map-extract/src/Rman.cs
Normal file
@@ -0,0 +1,119 @@
|
||||
using System.Buffers.Binary;
|
||||
using System.Text;
|
||||
|
||||
namespace GvrMapExtract;
|
||||
|
||||
/// <summary>Riot 매니페스트(.manifest, RMAN 2.x) 읽기. 본문은 zstd 로 압축된 FlatBuffers.
|
||||
/// 구조는 Morilli/ManifestDownloader rman.c 를 따랐다.</summary>
|
||||
public sealed class Rman
|
||||
{
|
||||
public sealed record Chunk(ulong BundleId, uint BundleOffset, uint CompressedSize, uint UncompressedSize, long FileOffset);
|
||||
public sealed record RFile(string Path, long Size, Chunk[] Chunks);
|
||||
|
||||
public ulong ManifestId { get; private set; }
|
||||
public Dictionary<string, RFile> Files { get; } = new(StringComparer.OrdinalIgnoreCase);
|
||||
|
||||
public static Rman Parse(byte[] data)
|
||||
{
|
||||
if (data.Length < 28 || Encoding.ASCII.GetString(data, 0, 4) != "RMAN") throw new InvalidDataException("RMAN 아님");
|
||||
if (data[4] != 2) throw new InvalidDataException($"모르는 매니페스트 버전 {data[4]}.{data[5]}");
|
||||
var contentOffset = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(8));
|
||||
var compressedSize = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(12));
|
||||
var r = new Rman { ManifestId = BinaryPrimitives.ReadUInt64LittleEndian(data.AsSpan(16)) };
|
||||
var uncompressedSize = BinaryPrimitives.ReadUInt32LittleEndian(data.AsSpan(24));
|
||||
var body = new byte[uncompressedSize];
|
||||
using (var z = new ZstdSharp.Decompressor())
|
||||
{
|
||||
var n = z.Unwrap(data.AsSpan((int)contentOffset, (int)compressedSize), body);
|
||||
if (n != uncompressedSize) throw new InvalidDataException("매니페스트 압축 풀기 실패");
|
||||
}
|
||||
r.ParseBody(new Fb(body));
|
||||
return r;
|
||||
}
|
||||
|
||||
private void ParseBody(Fb b)
|
||||
{
|
||||
var root = b.Root();
|
||||
// 번들 → 조각 (번들 안 위치는 앞 조각 크기의 누적)
|
||||
var chunks = new Dictionary<ulong, (ulong bundle, uint off, uint comp, uint raw)>();
|
||||
foreach (var bt in b.Tables(root, 0))
|
||||
{
|
||||
var bundleId = b.U64(bt, 0);
|
||||
uint off = 0;
|
||||
foreach (var ct in b.Tables(bt, 1))
|
||||
{
|
||||
var comp = b.U32(ct, 1);
|
||||
chunks[b.U64(ct, 0)] = (bundleId, off, comp, b.U32(ct, 2));
|
||||
off += comp;
|
||||
}
|
||||
}
|
||||
// 폴더
|
||||
var dirs = new Dictionary<ulong, (ulong parent, string name)>();
|
||||
foreach (var dt in b.Tables(root, 3)) dirs[b.U64(dt, 0)] = (b.U64(dt, 1), b.Str(dt, 2));
|
||||
// 파일
|
||||
foreach (var ft in b.Tables(root, 2))
|
||||
{
|
||||
var name = b.Str(ft, 3);
|
||||
var dir = b.U64(ft, 1);
|
||||
while (dir != 0 && dirs.TryGetValue(dir, out var d))
|
||||
{
|
||||
if (d.name.Length > 0) name = d.name + "/" + name;
|
||||
dir = d.parent;
|
||||
}
|
||||
var ids = b.U64Vector(ft, 7);
|
||||
var list = new Chunk[ids.Length];
|
||||
long fo = 0;
|
||||
for (var i = 0; i < ids.Length; i++)
|
||||
{
|
||||
var c = chunks[ids[i]];
|
||||
list[i] = new Chunk(c.bundle, c.off, c.comp, c.raw, fo);
|
||||
fo += c.raw;
|
||||
}
|
||||
Files[name] = new RFile(name, (long)b.U64(ft, 2), list);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>아주 작은 FlatBuffers 읽기 (필요한 형만)</summary>
|
||||
private sealed class Fb(byte[] d)
|
||||
{
|
||||
private uint U32At(int p) => BinaryPrimitives.ReadUInt32LittleEndian(d.AsSpan(p));
|
||||
public int Root() => (int)U32At(0);
|
||||
/// <summary>테이블 필드 위치. 없으면 -1</summary>
|
||||
private int Field(int table, int idx)
|
||||
{
|
||||
var vt = table - BinaryPrimitives.ReadInt32LittleEndian(d.AsSpan(table));
|
||||
var vsize = BinaryPrimitives.ReadUInt16LittleEndian(d.AsSpan(vt));
|
||||
if (4 + idx * 2 >= vsize) return -1;
|
||||
var off = BinaryPrimitives.ReadUInt16LittleEndian(d.AsSpan(vt + 4 + idx * 2));
|
||||
return off == 0 ? -1 : table + off;
|
||||
}
|
||||
private int Ref(int p) => p + (int)U32At(p);
|
||||
public ulong U64(int t, int i) { var p = Field(t, i); return p < 0 ? 0 : BinaryPrimitives.ReadUInt64LittleEndian(d.AsSpan(p)); }
|
||||
public uint U32(int t, int i) { var p = Field(t, i); return p < 0 ? 0 : U32At(p); }
|
||||
public string Str(int t, int i)
|
||||
{
|
||||
var p = Field(t, i);
|
||||
if (p < 0) return "";
|
||||
var v = Ref(p);
|
||||
return Encoding.UTF8.GetString(d, v + 4, (int)U32At(v));
|
||||
}
|
||||
public ulong[] U64Vector(int t, int i)
|
||||
{
|
||||
var p = Field(t, i);
|
||||
if (p < 0) return [];
|
||||
var v = Ref(p);
|
||||
var n = (int)U32At(v);
|
||||
var a = new ulong[n];
|
||||
for (var k = 0; k < n; k++) a[k] = BinaryPrimitives.ReadUInt64LittleEndian(d.AsSpan(v + 4 + k * 8));
|
||||
return a;
|
||||
}
|
||||
public IEnumerable<int> Tables(int t, int i)
|
||||
{
|
||||
var p = Field(t, i);
|
||||
if (p < 0) yield break;
|
||||
var v = Ref(p);
|
||||
var n = (int)U32At(v);
|
||||
for (var k = 0; k < n; k++) yield return Ref(v + 4 + k * 4);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user