발로란트 맵 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:
EJClaw
2026-10-17 14:01:22 +09:00
parent 86f422e8f0
commit 0c1e726168
23 changed files with 1350 additions and 9 deletions

View 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 }));
}
}