diff --git a/site/web/src/components/ReplayViewer.tsx b/site/web/src/components/ReplayViewer.tsx index 6bcb817..3f0f814 100644 --- a/site/web/src/components/ReplayViewer.tsx +++ b/site/web/src/components/ReplayViewer.tsx @@ -159,8 +159,9 @@ export default function ReplayViewer({ m, replay, sync }: Props) { controls.update(); }; resetCam.current(); - scene.add(new THREE.HemisphereLight(0xffffff, 0x223344, 1.6)); - const sun = new THREE.DirectionalLight(0xffffff, 1.2); + // 게임처럼 밝게: 하늘빛 + 해 (맵 텍스처가 어둡게 묻히지 않게) + scene.add(new THREE.HemisphereLight(0xffffff, 0x8a8f99, 2.6)); + const sun = new THREE.DirectionalLight(0xfff4e0, 1.8); sun.position.set(30, 80, 20); scene.add(sun); @@ -200,8 +201,8 @@ export default function ReplayViewer({ m, replay, sync }: Props) { .then((info) => { if (disposed) return; if (!info) return setMap3d({ state: 'none' }); - const mat = mapMaterial(clip, { lo: 0, hi: Math.max(8, (zTop - zBase + 600) * hPerCm) }); - return loadMap3d(info.url, mat, (p) => !disposed && setMap3d({ state: 'loading', progress: p })).then((obj) => { + const fallback = () => mapMaterial(clip, { lo: 0, hi: Math.max(8, (zTop - zBase + 600) * hPerCm) }); + return loadMap3d(info.url, clip, fallback, (p) => !disposed && setMap3d({ state: 'loading', progress: p })).then((obj) => { if (disposed) return; mapGroup.add(obj); mapGroup.updateMatrixWorld(true); diff --git a/site/web/src/lib/map3d.ts b/site/web/src/lib/map3d.ts index 7e43d48..35a4d95 100644 --- a/site/web/src/lib/map3d.ts +++ b/site/web/src/lib/map3d.ts @@ -40,22 +40,57 @@ export async function findMap3d(mapUrl: string): Promise { 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 { +/** + * glb 를 받아 장면 하나로. onProgress: 0~1 + * 재질이 든 glb(텍스처 · 색)는 그 재질에 천장 자르기만 붙이고, 재질이 없는 옛 glb 는 fallback(높이 색) 재질을 쓴다. + * 두 층 재질(extras.blend = {texture, tint})은 정점 색 R 로 A 층(기본 텍스처) · B 층을 섞는다. + */ +export function loadMap3d(url: string, clip: THREE.Plane, fallback: () => THREE.Material, onProgress?: (p: number) => void): Promise { 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[] = []; + const done = new Map(); 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 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; + if (blend) pending.push(blendLayer(gltf.parser, m, blend)); + 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 +98,39 @@ export function loadMap3d(url: string, material: THREE.Material, onProgress?: (p }); } +/** B 층 텍스처 · 색을 붙이고 셰이더에서 정점 색 R 로 섞는다 */ +async function blendLayer(parser: { getDependency: (type: string, i: number) => Promise }, m: THREE.MeshStandardMaterial, b: { texture?: number; tint?: number[] }) { + let texB: THREE.Texture | null = null; + if (b.texture != null) { + texB = (await parser.getDependency('texture', b.texture)) as THREE.Texture; + 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); + const md = m as unknown as { defines?: Record }; + md.defines = { ...(md.defines ?? {}), GVR_BLEND: '', ...(texB ? { GVR_BLEND_MAP: '' } : {}) }; + m.onBeforeCompile = (sh) => { + sh.uniforms.mapB = { value: texB }; + sh.uniforms.tintB = { value: tintB }; + sh.vertexShader = sh.vertexShader + .replace('#include ', '#include \nattribute vec4 blendCol;\nvarying float vBlend;\nvarying vec2 vUvB;') + .replace('#include ', '#include \nvBlend = blendCol.r;\nvUvB = uv;'); + sh.fragmentShader = sh.fragmentShader + .replace('#include ', '#include \nuniform sampler2D mapB;\nuniform vec3 tintB;\nvarying float vBlend;\nvarying vec2 vUvB;') + .replace( + '#include ', + `#include +#ifdef GVR_BLEND_MAP +vec3 layerB = texture2D(mapB, vUvB).rgb * tintB; +#else +vec3 layerB = tintB; +#endif +diffuseColor.rgb = mix(layerB, diffuseColor.rgb, vBlend);`, + ); + }; + 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; diff --git a/tools/map-extract/MapExtract.csproj b/tools/map-extract/MapExtract.csproj index e3b2878..2f25446 100644 --- a/tools/map-extract/MapExtract.csproj +++ b/tools/map-extract/MapExtract.csproj @@ -16,5 +16,6 @@ + diff --git a/tools/map-extract/scripts/pack.py b/tools/map-extract/scripts/pack.py index 9e268e9..6217fca 100755 --- a/tools/map-extract/scripts/pack.py +++ b/tools/map-extract/scripts/pack.py @@ -2,6 +2,7 @@ """gvr-map-extract 결과(<코드>.glb + <코드>.json)를 사이트용으로 압축한다. pack.py <추출 폴더> <출력 폴더> <버전(예: VALORANT_13.08)> 출력: <출력>//<코드>.glb.gz (gltfpack -cc 로 meshopt 압축 · 위치 양자화 → gzip) + <출력>/index.json + -ke: 재질 extras(두 층 섞기 B 층) 유지, -vt 14: 반복 UV 가 뭉개지지 않게 사이트 서버 data/maps3d 에 그대로 올리면 된다 (site/server/src/maps3d.ts).""" import datetime, gzip, json, os, re, shutil, subprocess, sys @@ -19,7 +20,7 @@ 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', '-vt', '14'], 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) diff --git a/tools/map-extract/src/Glb.cs b/tools/map-extract/src/Glb.cs new file mode 100644 index 0000000..9574c6d --- /dev/null +++ b/tools/map-extract/src/Glb.cs @@ -0,0 +1,129 @@ +using System.Text; +using System.Text.Json; +using System.Text.Json.Nodes; + +namespace GvrMapExtract; + +/// 작은 glTF 2.0 바이너리(glb) 작성기: 버퍼 하나에 accessor · 이미지를 차례로 붙인다 +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; + /// 장면의 최상위 노드 (비면 모든 노드) + public readonly List Roots = new(); + + private int View(ReadOnlySpan 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); + } + + /// 정규화된 unsigned byte (색 · 가중치) + 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"); + } + + /// 행렬 같은 비정점 데이터 (target 없음) + 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); + } + + /// 텍스처 (반복 샘플러) 번호 + public int Texture(byte[] image, string mime) + { + if (Samplers.Count == 0) Samplers.Add(new JsonObject { ["magFilter"] = 9729, ["minFilter"] = 9987, ["wrapS"] = 10497, ["wrapT"] = 10497 }); + Images.Add(new JsonObject { ["bufferView"] = View(image, null), ["mimeType"] = mime }); + Textures.Add(new JsonObject { ["sampler"] = 0, ["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); + } +} diff --git a/tools/map-extract/src/MapScene.cs b/tools/map-extract/src/MapScene.cs index 2a88aed..ec03026 100644 --- a/tools/map-extract/src/MapScene.cs +++ b/tools/map-extract/src/MapScene.cs @@ -3,7 +3,9 @@ using CUE4Parse.FileProvider; using CUE4Parse.UE4.Assets.Exports; 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 +14,10 @@ namespace GvrMapExtract; public sealed record MapInfo(string Code, string MapUrl, List Levels); /// 맵 레벨들의 StaticMesh 배치를 모아 월드 좌표(UE cm) 삼각형 하나로 굽는다. -/// 재질 · 텍스처는 없다 (사이트는 높이 · 면 방향으로 색을 칠한다). +/// 재질마다 텍스처(디퓨즈, 작게 줄임) · 색을 붙인다. public sealed class MapScene { public int Placements, Meshes, Failed, Skipped; - public long Triangles => _idx.Count / 3; - private readonly List _pos = new(); - private readonly List _idx = new(); private readonly List _levels = new(); private string _code = ""; private string _mapUrl = ""; @@ -80,10 +79,53 @@ 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); + /// 메시 한 LOD: 위치 · 법선 · UV · 정점 색 · 삼각형 · 재질 구간 + private sealed record Geo(FVector[] V, FVector[] N, float[] Uv, FColor[]? Col, uint[] Ib, Sec[] Secs, int Lod); + + /// 재질 하나 = glb primitive 하나. 같은 재질의 배치를 모두 모은다 + private sealed class Bucket + { + public readonly List Pos = new(), Nrm = new(), Uv = new(); + public readonly List Col = new(); + public readonly List Idx = new(); + } + + /// 사이트에 쓸 재질 요약. Blend = 정점 색(R)으로 두 층(A · B) 섞기 + 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 _mats = new(); + private readonly Dictionary _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(); + var meshCache = new Dictionary(); foreach (var level in map.Levels) { s._levels.Add(Path.GetFileNameWithoutExtension(level)); @@ -101,23 +143,37 @@ public sealed class MapScene if (SkipMesh.Any(x => path.Contains(x, StringComparison.OrdinalIgnoreCase))) { s.Skipped++; continue; } if (!meshCache.TryGetValue(path, out var geo)) { - geo = Geometry(mesh); + try { geo = Geometry(mesh); } catch { geo = null; s.Failed++; } meshCache[path] = geo; if (geo != null) s.Meshes++; } if (geo == null) continue; FTransform w; try { w = c.GetAbsoluteTransform(); } catch { s.Failed++; continue; } + // 재질: 컴포넌트가 바꾼 것 먼저, 없으면 메시 기본 + var over = c.GetOrDefault("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(); } 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; 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); + foreach (var d in data) s.Add(geo, mats, col, d.TransformData * w); + else s.Add(geo, mats, col, w); } } return s; } - /// 가장 낮은 LOD 의 위치 · 삼각형 (사이트에서 내려다보는 용도라 충분하다) - private static (FVector[] v, uint[] i)? Geometry(UStaticMesh mesh) + /// 가장 낮은 LOD (사이트에서 쓰기에 충분하고 가볍다) + private static Geo? Geometry(UStaticMesh mesh) { var lods = mesh.RenderData?.LODs; if (lods == null) return null; @@ -125,85 +181,137 @@ public sealed class MapScene { 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(); - 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]; + 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; + } + } + 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, 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) { Placements++; - var b = (uint)(_pos.Count / 3); - foreach (var p in g.v) + // 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 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 (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++; + } } } - /// glb: 메시 하나, 위치(float32, UE 월드 cm 그대로) + 삼각형(uint32). 사이트가 미니맵 좌표로 옮긴다 - 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; + + /// glb: 재질마다 primitive 하나 (위치는 UE 월드 cm 그대로, 법선 · UV · (두 층 재질만) 정점 색). + /// 재질은 baseColor 텍스처 + 색(tint). 두 층 재질은 extras.blend = {texture, tint} 로 B 층을 넘긴다 (사이트가 정점 색 R 로 섞는다) + 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(); + 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)) { - min[i % 3] = Math.Min(min[i % 3], pos[i]); - max[i % 3] = Math.Max(max[i % 3], pos[i]); + 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 + { + ["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 (m.Translucent) mat["alphaMode"] = "BLEND"; + else if (m.Masked && a is { alpha: true }) + { + mat["alphaMode"] = "MASK"; + mat["alphaCutoff"] = 0.333; + mat["doubleSided"] = true; + } + 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; + mat["extras"] = new System.Text.Json.Nodes.JsonObject { ["blend"] = ex }; + } + 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); + prims.Add(new System.Text.Json.Nodes.JsonObject { ["attributes"] = attrs, ["indices"] = glb.Indices(b.Idx.ToArray()), ["material"] = glb.Materials.Count - 1, ["mode"] = 4 }); } - 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); + 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 +322,11 @@ public sealed class MapScene placements = Placements, meshes = Meshes, triangles = Triangles, + vertices = _verts, + materials = Materials, + textures = TextureCount, + texturesFailed = TextureFailed, + textureBytes = TextureBytes, skipped = Skipped, failed = Failed, manifest, diff --git a/tools/map-extract/src/Materials.cs b/tools/map-extract/src/Materials.cs new file mode 100644 index 0000000..79d17db --- /dev/null +++ b/tools/map-extract/src/Materials.cs @@ -0,0 +1,46 @@ +using CUE4Parse.UE4.Assets.Exports.Material; +using CUE4Parse.UE4.Objects.Core.Math; + +namespace GvrMapExtract; + +/// 재질 인스턴스 사슬을 따라 올라가며 텍스처 · 색 매개변수를 모은다 (자식 값이 먼저) +public sealed class MatParams +{ + public string Path = ""; + public string Base = ""; + public readonly Dictionary Textures = new(StringComparer.OrdinalIgnoreCase); + public readonly Dictionary Vectors = new(StringComparer.OrdinalIgnoreCase); + public readonly Dictionary Scalars = new(StringComparer.OrdinalIgnoreCase); + public string? BlendMode; + + public static MatParams Resolve(UMaterialInterface mat) + { + var r = new MatParams { Path = mat.GetPathName() }; + 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 (r.BlendMode == null && mi.TryGetValue(out CUE4Parse.UE4.Assets.Objects.FStructFallback bpo, "BasePropertyOverrides") && bpo.TryGetValue(out bool ov, "bOverride_BlendMode") && ov) + r.BlendMode = bpo.GetOrDefault("BlendMode").ToString(); + UMaterialInterface? parent = null; + try { parent = mi.Parent?.Load(); } catch { } + cur = parent; + } + else + { + r.Base = cur.GetPathName(); + if (r.BlendMode == null && cur is UMaterial m) r.BlendMode = m.BlendMode.ToString(); + break; + } + } + return r; + } +} diff --git a/tools/map-extract/src/Probe.cs b/tools/map-extract/src/Probe.cs new file mode 100644 index 0000000..045dda2 --- /dev/null +++ b/tools/map-extract/src/Probe.cs @@ -0,0 +1,63 @@ +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; + +/// 조사용: 맵이 쓰는 재질 매개변수 통계 +public static class Probe +{ + public static void Mats(IFileProvider provider, MapInfo map) + { + var tris = new Dictionary(); + var mats = new Dictionary(); + 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(); } catch { continue; } + var lod = mesh?.RenderData?.LODs?.LastOrDefault(l => !l.SkipLod); + if (mesh == null || lod == null) continue; + var over = c.GetOrDefault("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(); } 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(); + var vecNames = new Dictionary(); + var bases = new Dictionary(); + long noDiffuse = 0, total = tris.Values.Sum(); + void Add(Dictionary 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}"); + } +} diff --git a/tools/map-extract/src/Program.cs b/tools/map-extract/src/Program.cs index fa1b83d..7f58b41 100644 --- a/tools/map-extract/src/Program.cs +++ b/tools/map-extract/src/Program.cs @@ -20,6 +20,7 @@ using GvrMapExtract; // GVR_USMAP 매핑 파일 (.usmap, 필수: 13.08 부터 패키지에 형 정보가 없다). uedb.dev 에서 받는다 // GVR_MANIFEST 매니페스트 URL (없으면 지금 라이브 패치를 Riot 설정에서 찾는다) // GVR_CACHE_MB 받은 조각을 메모리에 둘 크기 (기본 1500) +// GVR_TEX 텍스처 최대 크기 (기본 256) // GVR_OODLE Oodle 라이브러리 경로 (없으면 실행 파일 옆, 없으면 받는다) Serilog.Log.Logger = new Serilog.LoggerConfiguration().MinimumLevel.Error().WriteTo.Console().CreateLogger(); @@ -96,9 +97,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.Skipped} · 실패 {r.Failed} · 받은 양 {(store.DownloadedBytes - d0) >> 20}MB · {(sw.Elapsed - t0).TotalSeconds:F0}초"); } catch (Exception e) { @@ -111,6 +112,14 @@ 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 "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; diff --git a/tools/map-extract/src/TexStore.cs b/tools/map-extract/src/TexStore.cs new file mode 100644 index 0000000..05ff821 --- /dev/null +++ b/tools/map-extract/src/TexStore.cs @@ -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; + +/// 게임 텍스처 → 작게 줄여 glb 이미지로 (같은 텍스처는 한 번만). 알파가 있으면 PNG, 없으면 JPEG +public sealed class TexStore(IFileProvider provider, Glb glb, int maxSize) +{ + private readonly Dictionary _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(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? 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(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(d.AsSpan(0, n * 4), c.Width, c.Height).CloneAs() : null; + case CUE4Parse.UE4.Assets.Exports.Texture.EPixelFormat.PF_G8: + return d.Length >= n ? Image.LoadPixelData(d.AsSpan(0, n), c.Width, c.Height).CloneAs() : null; + default: + return null; + } + } + + private static bool HasAlpha(Image 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; + } +}