3D 리플레이 실감 3단계: 게임에 구워 둔 조명(라이트맵)으로 맵을 칠한다

- 추출기: 레벨 BuiltData 의 HQ 라이트맵을 메시 칸마다 풀어 irr · sh 아틀라스 두 장으로 (src/Lightmaps.cs), 조명 있는 배치는 LOD0 + 라이트맵 UV(TEXCOORD_1), ISM 은 인스턴스마다 칸
- glb: 재질 occlusionTexture(irr) · emissiveTexture(sh, 세기 0) · extras.lightmap.k. pack.py 는 맵 UV 를 실수로(-vtf, gltfpack 이 두 UV 채널을 한 범위로 양자화해서 라이트맵이 어긋나던 것)
- 사이트 map3d.ts: 색 = 텍스처 × irr × K × max(0, 1 + dot(sh, N.yzx)). 옛 glb 는 그대로
- install.sh: 꺼 둔 자동 갱신 타이머는 다시 켜지 않는다
- 조사 명령 lmprobe · 작업 노트 docs/dev/replay-3d.md

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-29 15:45:43 +09:00
parent 37c898cd73
commit 185e8c17bd
9 changed files with 566 additions and 39 deletions

View File

@@ -51,6 +51,18 @@
- 개발 확인: 효과 하나만 따로 그리는 판(`~/.tmp/gvr/vfxHarness.ts` 를 `site/web/src/dev/` 에 잠시 두고 vite dev 에서 `import('/src/dev/vfxHarness.ts')`). 저장소에는 넣지 않았다.
- 한계: 재질 그래프 근사라 색 · 무늬가 게임과 조금 다르다. 리본 · beam 일부, 화면 효과(섬광 눈부심 등)는 없다. 오멘 연막처럼 추출기가 클래스를 못 찾은 것은 예전 모양.
## 구운 조명 (2026-10-29, 실감 3단계)
- 계기: aim.sheepu.dev(브라우저 발로란트 에임 연습장)의 맵이 게임처럼 보이는 이유를 보니 게임이 구워 둔 라이트맵(밝기 + SH 방향)을 그대로 쓴다. 우리 맵은 텍스처 × 장면 조명(하늘빛 + 해)이라 평평했다. 그 사이트 파일은 쓰지 않고 우리 추출기로 게임 파일에서 직접 뽑는다.
- 게임 쪽: 레벨마다 `<레벨>_BuiltData` (UMapBuildDataRegistry). 컴포넌트 `LODData[0].MapBuildDataId` → FMeshMapBuildData → FLightMap2D (텍스처 · ScaleVectors/AddVectors · CoordinateScale/Bias), ISM 은 인스턴스마다 `PerInstanceLightmapData[i].LightmapUVBias` (HISM 은 `InstanceReorderTable`). 라이트맵 UV 채널은 메시 `LightMapCoordinateIndex`, LOD0 에만 있다 (구운 조명이 있는 배치는 LOD0, 삼각형은 거의 같다: 어센트 233만 → 235만).
- HQ_Lightmap 텍스처(DXT5 1024²)는 위 절반 = 계수 0(UVW² · 로그 밝기), 아래 절반 = 계수 1(SH 방향 xyz · 밝기 나머지). 푸는 식은 UE `LightmapCommon.ush` GetLightMapColorHQ 와 같다. 햇빛 그림자까지 다 구워져 있다 (정적 조명).
- 추출기 `src/Lightmaps.cs`: 메시가 차지한 칸마다 그 메시 범위로 풀어 irr(L·UVW·L0, sRGB/K) · sh(방향/L0, ±2) 두 장으로 → 칸 밖은 이웃 값으로 채움 → 1/2 씩 줄여 선반 쌓기 아틀라스(너비 `GVR_LIGHTMAP` 기본 2048, 넓이 약 그 제곱 안). 조명 없는 배치는 (0,0) 기본 칸(맵 평균 밝기).
- glb: 모든 재질에 `occlusionTexture`(irr) · `emissiveTexture`(sh, 세기 0) 를 TEXCOORD_1 로, `extras.lightmap.k`. gltfpack 이 쓰지 않는 UV 채널을 버리지 않게 텍스처가 그 채널을 가리켜야 한다. 옛 사이트는 aoMap 으로만 써서(어두워지기만) 깨지지 않는다.
- pack.py 는 맵을 `-vtf`(UV 실수) 로: gltfpack 은 재질마다 TEXCOORD_0(반복, 수십 단위) · TEXCOORD_1 을 한 범위로 양자화해서 정수로 줄이면 라이트맵이 몇 텍셀씩 어긋난다.
- 13.09 실측: 어센트 페이지 72 → 1864×1360(1/4) 2.5MB, 어비스 116 → 1864×2176(1/4) 3.4MB. 맵 압축 크기 어센트 14.7 → 18.8MB, 어비스 12.1 → 17.4MB. 최대 메모리 3.4~3.6GB (페이지 값은 반 정밀도).
- 사이트 `lib/map3d.ts` `installShader`: 색 = 텍스처 × irr × K × max(0, 1 + dot(sh, N.yzx)) (N 은 glb 법선 = UE 월드 법선 그대로), 0.8 위는 살짝 눌러 하얗게 날지 않게. 장면 조명은 맵에 쓰지 않는다 (요원 · 효과는 그대로 장면 조명).
- 조사 명령: `gvr-map-extract lmprobe <레벨.umap>` (빌드 데이터 · 텍스처 · 연결 통계, `GVR_LM_DUMP=<폴더>` 면 라이트맵 png).
- 한계: 1/4 로 줄여 그림자 가장자리가 흐리다. 움직이는 것(요원)은 구운 조명을 받지 않는다 (볼륨 라이트맵은 아직 안 씀). 어비스 낭떠러지처럼 게임에서 어두운 곳은 그대로 어둡다.
## 남은 일
- 실제 경기로 동기화 오차 확인 (사이트 아래 줄 "킬 N개로 맞춤 (최대 오차 X초)")

View File

@@ -51,6 +51,8 @@ export async function findMap3d(mapUrl: string): Promise<Map3dInfo | null> {
* glb 를 받아 장면 하나로. onProgress: 0~1
* 재질이 든 glb(텍스처 · 색)는 그 재질에 천장 자르기만 붙이고, 재질이 없는 옛 glb 는 fallback(높이 색) 재질을 쓴다.
* 두 층 재질(extras.blend = {texture, tint})은 정점 색 R 로 A 층(기본 텍스처) · B 층을 섞는다.
* 구운 조명(extras.lightmap = {k}): 추출기가 aoMap(irr) · emissiveMap(sh) 자리에 TEXCOORD_1 로 넣어 둔 아틀라스로
* 색 = 텍스처 × irr × K × max(0, 1 + dot(sh, N.yzx)) (N 은 UE 월드 법선, tools/map-extract/src/Lightmaps.cs). 장면 조명은 쓰지 않는다.
*/
export function loadMap3d(url: string, clip: THREE.Plane, fallback: () => THREE.Material, onProgress?: (p: number) => void): Promise<THREE.Object3D> {
const loader = new GLTFLoader();
@@ -73,6 +75,7 @@ export function loadMap3d(url: string, clip: THREE.Plane, fallback: () => THREE.
}
const src = mesh.material as THREE.MeshStandardMaterial;
const blend = src.userData?.blend as { texture?: number; tint?: number[] } | undefined;
const lm = src.userData?.lightmap as { k?: number } | undefined;
// 정점 색은 색칠이 아니라 두 층 섞는 비율이다
const col = mesh.geometry.getAttribute('color');
if (col) {
@@ -91,7 +94,20 @@ export function loadMap3d(url: string, clip: THREE.Plane, fallback: () => THREE.
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));
const shader: ShaderParts = {};
if (lm?.k && m.aoMap && m.emissiveMap) {
shader.lightmap = { k: lm.k };
for (const t of [m.aoMap, m.emissiveMap]) {
t.colorSpace = THREE.NoColorSpace; // 셰이더에서 직접 푼다
t.anisotropy = 4;
}
} else {
// 조명 없는 재질에 붙은 조명 텍스처는 쓰지 않는다
m.aoMap = null;
m.emissiveMap = null;
}
const ready = blend ? blendLayer(gltf.parser, blend).then((b) => void (shader.blend = b)) : Promise.resolve();
pending.push(ready.then(() => installShader(m, shader)));
done.set(src, m);
mat = m;
}
@@ -105,8 +121,13 @@ export function loadMap3d(url: string, clip: THREE.Plane, fallback: () => THREE.
});
}
/** B 층 텍스처 · 색을 붙이고 셰이더에서 정점 색 R 로 섞는다 */
async function blendLayer(parser: { getDependency: (type: string, i: number) => Promise<unknown> }, m: THREE.MeshStandardMaterial, b: { texture?: number; tint?: number[] }) {
interface ShaderParts {
blend?: { texB: THREE.Texture | null; tintB: THREE.Color };
lightmap?: { k: number };
}
/** B 층 텍스처 · 색 (셰이더에서 정점 색 R 로 섞는다) */
async function blendLayer(parser: { getDependency: (type: string, i: number) => Promise<unknown> }, b: { texture?: number; tint?: number[] }) {
let texB: THREE.Texture | null = null;
if (b.texture != null) {
// 텍스처 하나를 못 읽어도 맵 전체를 버리지 않고 B 층 색만 쓴다
@@ -117,26 +138,65 @@ async function blendLayer(parser: { getDependency: (type: string, i: number) =>
}
}
const tintB = new THREE.Color().setRGB(b.tint?.[0] ?? 1, b.tint?.[1] ?? 1, b.tint?.[2] ?? 1, THREE.SRGBColorSpace);
return { texB, tintB };
}
/** 두 층 섞기 · 구운 조명을 셰이더에 넣는다 */
function installShader(m: THREE.MeshStandardMaterial, parts: ShaderParts) {
const { blend, lightmap } = parts;
if (!blend && !lightmap) return;
const md = m as unknown as { defines?: Record<string, string> };
md.defines = { ...(md.defines ?? {}), GVR_BLEND: '', ...(texB ? { GVR_BLEND_MAP: '' } : {}) };
md.defines = { ...(md.defines ?? {}) };
if (blend) {
md.defines.GVR_BLEND = '';
if (blend.texB) md.defines.GVR_BLEND_MAP = '';
}
if (lightmap) md.defines.GVR_LIGHTMAP = '';
// 같은 프로그램을 나눠 쓰도록 (uniform 값만 재질마다 다름)
m.customProgramCacheKey = () => `gvr:${blend ? (blend.texB ? 'bm' : 'b') : ''}:${lightmap ? 'l' : ''}`;
m.onBeforeCompile = (sh) => {
sh.uniforms.mapB = { value: texB };
sh.uniforms.tintB = { value: tintB };
sh.vertexShader = sh.vertexShader
.replace('#include <common>', '#include <common>\nattribute vec4 blendCol;\nvarying float vBlend;\nvarying vec2 vUvB;')
.replace('#include <uv_vertex>', '#include <uv_vertex>\nvBlend = blendCol.r;\nvUvB = uv;');
sh.fragmentShader = sh.fragmentShader
.replace('#include <common>', '#include <common>\nuniform sampler2D mapB;\nuniform vec3 tintB;\nvarying float vBlend;\nvarying vec2 vUvB;')
.replace(
'#include <map_fragment>',
`#include <map_fragment>
if (blend) {
sh.uniforms.mapB = { value: blend.texB };
sh.uniforms.tintB = { value: blend.tintB };
sh.vertexShader = sh.vertexShader
.replace('#include <common>', '#include <common>\nattribute vec4 blendCol;\nvarying float vBlend;\nvarying vec2 vUvB;')
.replace('#include <uv_vertex>', '#include <uv_vertex>\nvBlend = blendCol.r;\nvUvB = uv;');
sh.fragmentShader = sh.fragmentShader
.replace('#include <common>', '#include <common>\nuniform sampler2D mapB;\nuniform vec3 tintB;\nvarying float vBlend;\nvarying vec2 vUvB;')
.replace(
'#include <map_fragment>',
`#include <map_fragment>
#ifdef GVR_BLEND_MAP
vec3 layerB = texture2D(mapB, vUvB).rgb * tintB;
#else
vec3 layerB = tintB;
#endif
diffuseColor.rgb = mix(layerB, diffuseColor.rgb, vBlend);`,
);
);
}
if (lightmap) {
sh.uniforms.lmK = { value: lightmap.k };
sh.vertexShader = sh.vertexShader
.replace('#include <common>', '#include <common>\nvarying vec3 vUeN;')
.replace('#include <beginnormal_vertex>', '#include <beginnormal_vertex>\nvUeN = objectNormal;');
sh.fragmentShader = sh.fragmentShader
.replace('#include <common>', '#include <common>\nuniform float lmK;\nvarying vec3 vUeN;')
.replace(
'#include <opaque_fragment>',
`{
// 구운 조명 (UE HQ 라이트맵을 추출기가 풀어 둔 값): irr 는 sRGB, sh 는 ±2 → 0~1
vec3 lmIrr = texture2D(aoMap, vAoMapUv).rgb;
lmIrr = mix(lmIrr / 12.92, pow((lmIrr + 0.055) / 1.055, vec3(2.4)), step(vec3(0.04045), lmIrr));
vec3 lmSh = texture2D(emissiveMap, vEmissiveMapUv).rgb * 4.0 - 2.0;
vec3 n = normalize(vUeN);
float lmDir = max(0.0, 1.0 + dot(lmSh, n.yzx));
vec3 lit = diffuseColor.rgb * lmIrr * (lmK * lmDir);
// 밝은 곳이 하얗게 날아가지 않게 살짝 누른다
outgoingLight = lit / (1.0 + max(lit - 0.8, 0.0));
}
#include <opaque_fragment>`,
);
}
};
m.needsUpdate = true;
}

View File

@@ -2,7 +2,7 @@
# 맵 3D 자동 갱신을 이 리눅스 서버(.9)에 설치한다. 저장소에서: tools/map-extract/scripts/install.sh
# - gvr-map-extract 를 빌드해 $GVR_MAPS_HOME/bin 에 둔다 (저장소 작업 폴더가 바뀌어도 타이머는 그대로 돈다)
# - systemd 사용자 타이머 gvr-maps-update.timer (30분마다 update.sh). 메모리 6GB · CPU 3코어 상한, 봇과 다른 cgroup
# 코드를 고쳤으면 다시 실행하면 된다. 지금 바로 한 번 돌리기: systemctl --user start gvr-maps-update
# 코드를 고쳤으면 다시 실행하면 된다 (타이머를 꺼 뒀으면 꺼진 채로 둔다). 지금 바로 한 번 돌리기: systemctl --user start gvr-maps-update
set -euo pipefail
here="$(cd "$(dirname "$0")/.." && pwd)"
GVR_MAPS_HOME="${GVR_MAPS_HOME:-$HOME/gvr-maps}"
@@ -26,6 +26,8 @@ chmod +x "$GVR_MAPS_HOME/scripts/update.sh"
unit="$HOME/.config/systemd/user"
mkdir -p "$unit"
# 이미 설치돼 있는데 타이머를 꺼 뒀으면(사용자가 자동 갱신을 멈춤) 다시 켜지 않는다
timer_was="$( [ -f "$unit/gvr-maps-update.timer" ] && (systemctl --user is-enabled gvr-maps-update.timer 2>/dev/null || true) || echo new)"
node_dir="$(dirname "$(command -v node)")"
cat > "$unit/gvr-maps-update.service" <<EOF
[Unit]
@@ -62,5 +64,9 @@ Persistent=true
WantedBy=timers.target
EOF
systemctl --user daemon-reload
systemctl --user enable --now gvr-maps-update.timer
echo "설치 완료: $GVR_MAPS_HOME · $(systemctl --user list-timers gvr-maps-update.timer --no-legend | head -1)"
if [ "$timer_was" = new ] || [ "$timer_was" = enabled ]; then
systemctl --user enable --now gvr-maps-update.timer
echo "설치 완료: $GVR_MAPS_HOME · $(systemctl --user list-timers gvr-maps-update.timer --no-legend | head -1)"
else
echo "설치 완료: $GVR_MAPS_HOME · 자동 갱신 타이머는 꺼진 채로 둠 (켜기: systemctl --user enable --now gvr-maps-update.timer, 한 번만: systemctl --user start gvr-maps-update)"
fi

View File

@@ -4,7 +4,9 @@
(agents.json 이 있으면 요원 agent_*.glb · 무기 weapon_*.glb 도 같은 폴더에, index.json agents · weapons.
anims.glb 가 있으면 공용 애니메이션 index.json anims, abilities/abilities.json 이 있으면 스킬 재료 index.json abilities)
출력: <출력>/<dir>/<코드>.glb.gz (gltfpack -cc 로 meshopt 압축 · 위치 양자화 → gzip) + <출력>/index.json
-ke: 재질 extras(두 층 섞기 B 층) 유지, -vt 14: 반복 UV 가 뭉개지지 않게
-ke: 재질 extras(두 층 섞기 B 층 · 구운 조명 K) 유지
-vtf: UV 를 실수 그대로. gltfpack 은 재질마다 TEXCOORD_0(반복 UV, 수십 단위) · TEXCOORD_1(라이트맵 아틀라스 0~1)을
한 범위로 묶어 양자화해서, 정수로 줄이면 라이트맵 UV 가 몇 텍셀씩 어긋난다 (meshopt 압축 뒤 크기는 비슷)
사이트 서버 data/maps3d 에 그대로 올리면 된다 (site/server/src/maps3d.ts)."""
import datetime, gzip, json, os, re, shutil, subprocess, sys
@@ -22,7 +24,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', '-ke', '-vt', '14'], check=True, stdout=subprocess.DEVNULL)
subprocess.run(['npx', '-y', 'gltfpack@1.3.0', '-i', glb, '-o', packed, '-cc', '-ke', '-vtf'], 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)

View File

@@ -77,12 +77,24 @@ public sealed class Glb
return Accessor(v, 5126, data.Length / comps, type);
}
/// <summary>텍스처 (반복 샘플러) 번호</summary>
public int Texture(byte[] image, string mime)
private int _clampSampler = -1;
/// <summary>텍스처 번호 (기본 반복 샘플러, clamp 면 가장자리 고정 샘플러)</summary>
public int Texture(byte[] image, string mime, bool clamp = false)
{
if (Samplers.Count == 0) Samplers.Add(new JsonObject { ["magFilter"] = 9729, ["minFilter"] = 9987, ["wrapS"] = 10497, ["wrapT"] = 10497 });
var sampler = 0;
if (clamp)
{
if (_clampSampler < 0)
{
Samplers.Add(new JsonObject { ["magFilter"] = 9729, ["minFilter"] = 9987, ["wrapS"] = 33071, ["wrapT"] = 33071 });
_clampSampler = Samplers.Count - 1;
}
sampler = _clampSampler;
}
Images.Add(new JsonObject { ["bufferView"] = View(image, null), ["mimeType"] = mime });
Textures.Add(new JsonObject { ["sampler"] = 0, ["source"] = Images.Count - 1 });
Textures.Add(new JsonObject { ["sampler"] = sampler, ["source"] = Images.Count - 1 });
return Textures.Count - 1;
}

View File

@@ -0,0 +1,271 @@
using CUE4Parse.UE4.Assets.Exports.BuildData;
using CUE4Parse.UE4.Assets.Exports.Texture;
using CUE4Parse.UE4.Objects.Core.Math;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Jpeg;
using SixLabors.ImageSharp.PixelFormats;
namespace GvrMapExtract;
/// <summary>게임에 구워 둔 조명(HQ 라이트맵)을 맵 하나에 아틀라스 두 장으로 모은다.
///
/// 게임 라이트맵 텍스처(LightMapTexture2D, DXT5)는 위 절반이 계수 0(색 UVW² · 로그 밝기), 아래 절반이 계수 1(SH 방향 · 밝기 나머지)이다.
/// 메시마다(FLightMap2D) 범위(ScaleVectors · AddVectors)가 달라서, 메시가 차지한 칸(UV × CoordinateScale + Bias)마다 그 범위로 풀어 둔다
/// (UE LightmapCommon.ush GetLightMapColorHQ 와 같은 식).
///
/// 결과
/// irr: sRGB(밝기 / K) — 표면 방향을 빼고 본 조명 색 (L · UVW · L0)
/// sh : 방향 계수 / L0 를 ±2 → 0~1 로 — 사이트에서 조명 = irr · K · max(0, 1 + dot(sh, N.yzx)) (N 은 UE 월드 법선)
/// 칸 밖 텍셀은 이웃 값으로 채워(번짐 방지) 줄인 뒤 페이지째 아틀라스에 놓는다. 라이트맵이 없는 배치는 (0,0) 의 기본 칸(맵 평균 밝기, 방향 없음)을 쓴다.</summary>
public sealed class Lightmaps
{
private sealed class PageData
{
public required string Key;
public required int W, H; // 계수 하나(텍스처 절반) 크기
public required byte[] Src; // RGBA, W × 2H
public Half[] Irr = null!, Sh = null!; // 메모리를 줄이려고 반 정밀도 (맵 하나에 페이지 100개 넘게)
public bool[] Valid = null!;
public int Ox, Oy, Sw, Sh2; // 아틀라스 위치 · 줄인 크기
}
private readonly List<PageData> _pages = new();
private readonly Dictionary<string, int> _byKey = new(StringComparer.OrdinalIgnoreCase);
private readonly HashSet<(int, float, float)> _done = new();
public int Allocations, Failed;
private int _atlasW, _atlasH;
private const int Pad = 4; // 페이지 사이 여백 (밉맵 번짐 방지)
private const int DefaultCell = 8;
/// <summary>라이트맵 텍스처 → 페이지 번호 (못 읽으면 -1)</summary>
public int Page(FLightMap2D lm)
{
var idx = lm.Textures?[0];
if (idx == null || idx.IsNull) return -1;
var key = idx.ResolvedObject?.GetPathName() ?? idx.Name;
if (_byKey.TryGetValue(key, out var p)) return p;
try
{
var t = idx.Load<UTexture2D>();
var c = t == null ? null : CUE4Parse_Conversion.Textures.TextureDecoder.Decode(t);
if (c == null || c.Height < 2 || c.Data.Length < c.Width * c.Height * 4) { Failed++; return _byKey[key] = -1; }
var bgra = c.PixelFormat == EPixelFormat.PF_B8G8R8A8;
if (!bgra && c.PixelFormat != EPixelFormat.PF_R8G8B8A8) { Failed++; return _byKey[key] = -1; }
var src = c.Data;
if (bgra)
{
src = (byte[])src.Clone();
for (var i = 0; i < src.Length; i += 4) (src[i], src[i + 2]) = (src[i + 2], src[i]);
}
var w = c.Width;
var h = c.Height / 2;
_pages.Add(new PageData { Key = key, W = w, H = h, Src = src, Irr = new Half[w * h * 3], Sh = new Half[w * h * 3], Valid = new bool[w * h] });
return _byKey[key] = _pages.Count - 1;
}
catch (Exception e)
{
Failed++;
if (Failed <= 5) Console.Error.WriteLine($"라이트맵 실패 {key}: {e.GetType().Name} {e.Message}");
return _byKey[key] = -1;
}
}
/// <summary>메시 하나가 차지한 칸을 풀어 둔다 (같은 칸은 한 번만)</summary>
public void Allocate(int page, FLightMap2D lm, FVector2D bias)
{
if (page < 0 || !_done.Add((page, bias.X, bias.Y))) return;
Allocations++;
var p = _pages[page];
var cs = lm.CoordinateScale ?? new FVector2D(1, 1);
var s0 = lm.ScaleVectors![0];
var a0 = lm.AddVectors![0];
var s1 = lm.ScaleVectors![1];
var a1 = lm.AddVectors![1];
// 칸 + 1 텍셀 (UE 는 칸 둘레에 여백을 두고 구운 값을 채운다)
var x0 = Math.Max(0, (int)Math.Floor(bias.X * p.W) - 1);
var y0 = Math.Max(0, (int)Math.Floor(bias.Y * p.H) - 1);
var x1 = Math.Min(p.W, (int)Math.Ceiling((bias.X + cs.X) * p.W) + 1);
var y1 = Math.Min(p.H, (int)Math.Ceiling((bias.Y + cs.Y) * p.H) + 1);
const float LogBlackPoint = 0.01858136f;
for (var y = y0; y < y1; y++)
for (var x = x0; x < x1; x++)
{
var i0 = (y * p.W + x) * 4;
var i1 = ((y + p.H) * p.W + x) * 4;
float C(int i) => p.Src[i] / 255f;
var logL = C(i0 + 3) + C(i1 + 3) / 255f - 0.5f / 255f;
logL = logL * s0.W + a0.W;
var l = MathF.Max(0, MathF.Pow(2, logL) - LogBlackPoint);
var r = C(i0) * C(i0) * s0.X + a0.X;
var g = C(i0 + 1) * C(i0 + 1) * s0.Y + a0.Y;
var b = C(i0 + 2) * C(i0 + 2) * s0.Z + a0.Z;
var l0 = C(i1 + 3) * s1.W + a1.W;
if (l0 < 1e-4f) l0 = 0.282095f;
var o = (y * p.W + x) * 3;
p.Irr[o] = (Half)(MathF.Max(0, l * r * l0));
p.Irr[o + 1] = (Half)(MathF.Max(0, l * g * l0));
p.Irr[o + 2] = (Half)(MathF.Max(0, l * b * l0));
p.Sh[o] = (Half)((C(i1) * s1.X + a1.X) / l0);
p.Sh[o + 1] = (Half)((C(i1 + 1) * s1.Y + a1.Y) / l0);
p.Sh[o + 2] = (Half)((C(i1 + 2) * s1.Z + a1.Z) / l0);
p.Valid[y * p.W + x] = true;
}
}
/// <summary>페이지 공간 UV(0~1) → 아틀라스 UV. page &lt; 0 이면 기본 칸 가운데</summary>
public (float u, float v) ToAtlas(int page, float u, float v)
{
if (page < 0 || _atlasW == 0) return ((DefaultCell / 2f) / Math.Max(1, _atlasW), (DefaultCell / 2f) / Math.Max(1, _atlasH));
var p = _pages[page];
u = Math.Clamp(u, 0, 1);
v = Math.Clamp(v, 0, 1);
return ((p.Ox + u * p.Sw) / _atlasW, (p.Oy + v * p.Sh2) / _atlasH);
}
public bool Any => _pages.Count > 0;
public float K { get; private set; } = 1;
public int AtlasW => _atlasW;
public int AtlasH => _atlasH;
/// <summary>아틀라스를 만든다 (너비 maxSide · 넓이 약 maxSide² 안에 들어가게 페이지를 1/2 씩 줄인다). 이 뒤에 ToAtlas 를 쓴다</summary>
public (byte[] irr, byte[] sh)? Build(int maxSide)
{
if (_pages.Count == 0) return null;
// 맵 평균 · 최대 밝기
var lum = new List<float>();
double sr = 0, sg = 0, sb = 0;
long n = 0;
foreach (var p in _pages)
for (var i = 0; i < p.Valid.Length; i++)
if (p.Valid[i])
{
var m = MathF.Max((float)p.Irr[i * 3], MathF.Max((float)p.Irr[i * 3 + 1], (float)p.Irr[i * 3 + 2]));
if ((i & 7) == 0) lum.Add(m);
sr += (float)p.Irr[i * 3]; sg += (float)p.Irr[i * 3 + 1]; sb += (float)p.Irr[i * 3 + 2];
n++;
}
if (n == 0) return null;
lum.Sort();
K = Math.Max(0.05f, lum[(int)(lum.Count * 0.998)]);
var avg = new[] { (float)(sr / n), (float)(sg / n), (float)(sb / n) };
foreach (var p in _pages) Dilate(p, 8);
// 줄이는 배율: 너비 maxSide · 높이 2×maxSide · 넓이 1.25×maxSide² 안에 들어갈 때까지 1/2 씩
var f = 1;
while (!Pack(f, maxSide) && f < 64) f *= 2;
using var irr = new Image<Rgb24>(_atlasW, _atlasH);
using var sh = new Image<Rgb24>(_atlasW, _atlasH, new Rgb24(128, 128, 128));
static byte Enc(float v) => (byte)Math.Clamp(MathF.Round(v * 255), 0, 255);
static float Srgb(float v) => v <= 0.0031308f ? v * 12.92f : 1.055f * MathF.Pow(v, 1 / 2.4f) - 0.055f;
Rgb24 IrrPx(float r, float g, float b) => new(Enc(Srgb(Math.Min(1, r / K))), Enc(Srgb(Math.Min(1, g / K))), Enc(Srgb(Math.Min(1, b / K))));
static Rgb24 ShPx(float x, float y, float z) => new(Enc(x / 4 + 0.5f), Enc(y / 4 + 0.5f), Enc(z / 4 + 0.5f));
// 기본 칸
for (var y = 0; y < DefaultCell; y++)
for (var x = 0; x < DefaultCell; x++) irr[x, y] = IrrPx(avg[0], avg[1], avg[2]);
foreach (var p in _pages)
{
// 줄이기 (f×f 평균) + 여백은 가장자리 값으로
for (var y = -Pad; y < p.Sh2 + Pad; y++)
for (var x = -Pad; x < p.Sw + Pad; x++)
{
var sx = Math.Clamp(x, 0, p.Sw - 1);
var sy = Math.Clamp(y, 0, p.Sh2 - 1);
float r = 0, g = 0, b = 0, hx = 0, hy = 0, hz = 0;
var cnt = 0;
for (var dy = 0; dy < f; dy++)
for (var dx = 0; dx < f; dx++)
{
var px = Math.Min(p.W - 1, sx * f + dx);
var py = Math.Min(p.H - 1, sy * f + dy);
var k = py * p.W + px;
if (!p.Valid[k]) continue;
r += (float)p.Irr[k * 3]; g += (float)p.Irr[k * 3 + 1]; b += (float)p.Irr[k * 3 + 2];
hx += (float)p.Sh[k * 3]; hy += (float)p.Sh[k * 3 + 1]; hz += (float)p.Sh[k * 3 + 2];
cnt++;
}
var ax = p.Ox + x;
var ay = p.Oy + y;
if (cnt == 0)
{
irr[ax, ay] = IrrPx(avg[0], avg[1], avg[2]);
continue;
}
irr[ax, ay] = IrrPx(r / cnt, g / cnt, b / cnt);
sh[ax, ay] = ShPx(hx / cnt, hy / cnt, hz / cnt);
}
}
var enc = new JpegEncoder { Quality = 90, ColorType = JpegEncodingColor.YCbCrRatio444 };
using var mi = new MemoryStream();
irr.SaveAsJpeg(mi, enc);
using var ms = new MemoryStream();
sh.SaveAsJpeg(ms, enc);
Factor = f;
foreach (var p in _pages) { p.Src = []; p.Irr = []; p.Sh = []; }
return (mi.ToArray(), ms.ToArray());
}
public int Factor { get; private set; } = 1;
/// <summary>1/f 로 줄인 페이지를 너비 maxSide 선반에 쌓는다 (높은 것부터). 한도 안이면 true</summary>
private bool Pack(int f, int maxSide)
{
foreach (var p in _pages)
{
p.Sw = Math.Max(1, p.W / f);
p.Sh2 = Math.Max(1, p.H / f);
}
var order = Enumerable.Range(0, _pages.Count).OrderByDescending(i => _pages[i].Sh2).ThenByDescending(i => _pages[i].Sw).ToList();
int cx = DefaultCell + Pad, cy = 0, shelf = DefaultCell, wMax = 0;
foreach (var i in order)
{
var p = _pages[i];
if (p.Sw + Pad * 2 > maxSide) return false;
if (cx + p.Sw + Pad * 2 > maxSide) { cx = 0; cy += shelf; shelf = 0; }
p.Ox = cx + Pad;
p.Oy = cy + Pad;
cx += p.Sw + Pad * 2;
shelf = Math.Max(shelf, p.Sh2 + Pad * 2);
wMax = Math.Max(wMax, cx);
}
// WebGL2 는 2 의 거듭제곱이 아니어도 밉맵을 쓴다 → 8 의 배수로만 (JPEG 블록)
_atlasW = (wMax + 7) / 8 * 8;
_atlasH = (cy + shelf + 7) / 8 * 8;
return _atlasH <= maxSide * 2 && (long)_atlasW * _atlasH <= (long)maxSide * maxSide * 5 / 4;
}
public int Pages => _pages.Count;
/// <summary>칸 밖 텍셀을 이웃 칸 값으로 채운다 (줄이기 · 선형 보간에서 검은 테두리가 번지지 않게)</summary>
private static void Dilate(PageData p, int passes)
{
for (var pass = 0; pass < passes; pass++)
{
var add = new List<int>();
for (var y = 0; y < p.H; y++)
for (var x = 0; x < p.W; x++)
{
var k = y * p.W + x;
if (p.Valid[k]) continue;
float r = 0, g = 0, b = 0, hx = 0, hy = 0, hz = 0;
var cnt = 0;
for (var dy = -1; dy <= 1; dy++)
for (var dx = -1; dx <= 1; dx++)
{
var nx = x + dx;
var ny = y + dy;
if (nx < 0 || ny < 0 || nx >= p.W || ny >= p.H) continue;
var j = ny * p.W + nx;
if (!p.Valid[j]) continue;
r += (float)p.Irr[j * 3]; g += (float)p.Irr[j * 3 + 1]; b += (float)p.Irr[j * 3 + 2];
hx += (float)p.Sh[j * 3]; hy += (float)p.Sh[j * 3 + 1]; hz += (float)p.Sh[j * 3 + 2];
cnt++;
}
if (cnt == 0) continue;
p.Irr[k * 3] = (Half)(r / cnt); p.Irr[k * 3 + 1] = (Half)(g / cnt); p.Irr[k * 3 + 2] = (Half)(b / cnt);
p.Sh[k * 3] = (Half)(hx / cnt); p.Sh[k * 3 + 1] = (Half)(hy / cnt); p.Sh[k * 3 + 2] = (Half)(hz / cnt);
add.Add(k);
}
if (add.Count == 0) break;
foreach (var k in add) p.Valid[k] = true;
}
}
}

View File

@@ -1,6 +1,7 @@
using System.Text;
using CUE4Parse.FileProvider;
using CUE4Parse.UE4.Assets.Exports;
using CUE4Parse.UE4.Assets.Exports.BuildData;
using CUE4Parse.UE4.Assets.Exports.Component.StaticMesh;
using CUE4Parse.UE4.Assets.Exports.StaticMesh;
using CUE4Parse.UE4.Assets.Exports.Material;
@@ -80,13 +81,19 @@ 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);
/// <summary>메시 한 LOD: 위치 · 법선 · UV · 정점 색 · 삼각형 · 재질 구간</summary>
private sealed record Geo(FVector[] V, FVector[] N, float[] Uv, FColor[]? Col, uint[] Ib, Sec[] Secs, int Lod);
/// <summary>메시 한 LOD: 위치 · 법선 · UV · 라이트맵 UV(LOD0 만) · 정점 색 · 삼각형 · 재질 구간</summary>
private sealed record Geo(FVector[] V, FVector[] N, float[] Uv, float[]? Lm, FColor[]? Col, uint[] Ib, Sec[] Secs, int Lod);
/// <summary>배치 하나의 라이트맵 자리: 페이지 · 페이지 안 UV = 라이트맵 UV × Scale + Bias</summary>
private readonly record struct LmPlace(int Page, float Sx, float Sy, float Bx, float By);
private readonly Lightmaps _lm = new();
public int LitPlacements;
/// <summary>재질 하나 = glb primitive 하나. 같은 재질의 배치를 모두 모은다</summary>
private sealed class Bucket
{
public readonly List<float> Pos = new(), Nrm = new(), Uv = new();
public readonly List<float> Pos = new(), Nrm = new(), Uv = new(), Lm = new();
public readonly List<int> LmPage = new();
public readonly List<byte> Col = new();
public readonly List<uint> Idx = new();
}
@@ -130,6 +137,12 @@ public sealed class MapScene
{
s._levels.Add(Path.GetFileNameWithoutExtension(level));
var pkg = provider.LoadPackage(level);
// 이 레벨에 구워 둔 조명 (<레벨>_BuiltData)
UMapBuildDataRegistry? reg = null;
var bd = level[..^".umap".Length] + "_BuiltData.uasset";
if (provider.Files.ContainsKey(bd))
try { reg = provider.LoadPackage(bd).GetExports().OfType<UMapBuildDataRegistry>().FirstOrDefault(); }
catch (Exception e) { Console.Error.WriteLine($"{bd}: 조명 읽기 실패 {e.GetType().Name} {e.Message}"); }
foreach (var lazy in pkg.ExportsLazy)
{
UObject o;
@@ -141,13 +154,21 @@ public sealed class MapScene
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))
// 구운 조명이 있으면 LOD0 (라이트맵 UV 는 LOD0 에만 있다), 없으면 가장 낮은 LOD
FLightMap2D? lm = null;
FMeshMapBuildData? bdata = null;
if (reg?.MeshBuildData != null && c.LODData is { Length: > 0 } ld0 && reg.MeshBuildData.TryGetValue(ld0[0].MapBuildDataId, out bdata)
&& bdata.LightMap is FLightMap2D l2 && l2.Textures?[0] is { IsNull: false } && l2.ScaleVectors != null && l2.AddVectors != null) lm = l2;
var lmIdx = lm != null ? mesh.GetOrDefault("LightMapCoordinateIndex", 0) : -1;
var key = lm != null ? $"{path}#lm{lmIdx}" : path;
if (!meshCache.TryGetValue(key, out var geo))
{
try { geo = Geometry(mesh); } catch { geo = null; s.Failed++; }
meshCache[path] = geo;
try { geo = Geometry(mesh, lmIdx); } catch { geo = null; s.Failed++; }
meshCache[key] = geo;
if (geo != null) s.Meshes++;
}
if (geo == null) continue;
var page = lm != null && geo.Lm != null ? s._lm.Page(lm) : -1;
FTransform w;
try { w = c.GetAbsoluteTransform(); } catch { s.Failed++; continue; }
// 재질: 컴포넌트가 바꾼 것 먼저, 없으면 메시 기본
@@ -164,26 +185,44 @@ public sealed class MapScene
// 칠한 정점 색 (두 층 섞기에 쓴다): 컴포넌트 값이 정점 수와 맞을 때만
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;
var cs = lm?.CoordinateScale ?? new FVector2D(1, 1);
LmPlace? Place(FVector2D bias)
{
if (page < 0) return null;
s._lm.Allocate(page, lm!, bias);
return new LmPlace(page, cs.X, cs.Y, bias.X, bias.Y);
}
if (c is UInstancedStaticMeshComponent ism && ism.PerInstanceSMData is { Length: > 0 } data)
foreach (var d in data) s.Add(geo, mats, col, d.TransformData * w);
else s.Add(geo, mats, col, w);
{
// 인스턴스마다 라이트맵 칸이 따로 (FPerInstanceLightmapData). HISM 은 순서가 바뀌어 있을 수 있다 (InstanceReorderTable)
var per = bdata?.PerInstanceLightmapData ?? [];
var reorder = c.GetOrDefault<int[]>("InstanceReorderTable", []);
for (var i = 0; i < data.Length; i++)
{
var ri = reorder.Length == data.Length ? reorder[i] : i;
var lp = ri >= 0 && ri < per.Length ? Place(per[ri].LightmapUVBias) : null;
s.Add(geo, mats, col, data[i].TransformData * w, lp);
}
}
else s.Add(geo, mats, col, w, lm != null ? Place(lm.CoordinateBias ?? new FVector2D(0, 0)) : null);
}
}
return s;
}
/// <summary>가장 낮은 LOD (사이트에서 쓰기에 충분하고 가볍다)</summary>
private static Geo? Geometry(UStaticMesh mesh)
/// <summary>가장 낮은 LOD (사이트에서 쓰기에 충분하고 가볍다). lmIdx ≥ 0 이면 LOD0 + 그 UV 채널(라이트맵)</summary>
private static Geo? Geometry(UStaticMesh mesh, int lmIdx = -1)
{
var lods = mesh.RenderData?.LODs;
if (lods == null) return null;
for (var l = lods.Length - 1; l >= 0; l--)
for (var l = lmIdx >= 0 ? 0 : lods.Length - 1; l >= 0 && l < lods.Length; l += lmIdx >= 0 ? 1 : -1)
{
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 uvItems = lod.VertexBuffer?.UV;
var n = new FVector[v.Length];
var uv = new float[v.Length * 2];
var lmUv = lmIdx >= 0 && uvItems != null && uvItems.Length == v.Length && uvItems.All(x => x.UV != null && x.UV.Length > lmIdx) ? new float[v.Length * 2] : null;
if (uvItems != null && uvItems.Length == v.Length)
for (var i = 0; i < v.Length; i++)
{
@@ -194,17 +233,23 @@ public sealed class MapScene
uv[i * 2] = it.UV[0].U;
uv[i * 2 + 1] = it.UV[0].V;
}
if (lmUv != null)
{
lmUv[i * 2] = it.UV[lmIdx].U;
lmUv[i * 2 + 1] = it.UV[lmIdx].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 new Geo(v, n, uv, lmUv, col, ib.Select(x => (uint)x).ToArray(), secs, l);
}
return null;
}
private void Add(Geo g, Mat?[] mats, FColor[]? col, FTransform t)
private void Add(Geo g, Mat?[] mats, FColor[]? col, FTransform t, LmPlace? lp)
{
Placements++;
if (lp != null) LitPlacements++;
// UE 는 왼손 좌표계라 glTF(오른손, 반시계 앞면) 로 그대로 옮기면 앞뒤가 바뀐다 → 기본으로 뒤집는다.
// 크기가 음수(거울)면 한 번 더 뒤집힌다
var flip = t.Scale3D.X * t.Scale3D.Y * t.Scale3D.Z >= 0;
@@ -228,6 +273,16 @@ public sealed class MapScene
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 (lp is { } q && g.Lm != null)
{
b.Lm.Add(g.Lm[i * 2] * q.Sx + q.Bx); b.Lm.Add(g.Lm[i * 2 + 1] * q.Sy + q.By);
b.LmPage.Add(q.Page);
}
else
{
b.Lm.Add(0); b.Lm.Add(0);
b.LmPage.Add(-1);
}
if (m.Blend)
{
var c = col != null ? col[i] : new FColor(255, 255, 255, 255);
@@ -255,7 +310,8 @@ public sealed class MapScene
public long Triangles => _tris;
public int Materials => _buckets.Count;
public int TextureCount, TextureFailed;
public long TextureBytes;
public long TextureBytes, LightmapBytes;
public string LightmapSummary => _lm.Any ? $"조명 {LitPlacements}/{Placements} 배치 · 페이지 {_lm.Pages}(실패 {_lm.Failed}) · 칸 {_lm.Allocations} · 아틀라스 {_lm.AtlasW}x{_lm.AtlasH} (1/{_lm.Factor}) {LightmapBytes >> 10}KB · K {_lm.K:F2}" : "조명 없음";
/// <summary>glb: 재질마다 primitive 하나 (위치는 UE 월드 cm 그대로, 법선 · UV · (두 층 재질만) 정점 색).
/// 재질은 baseColor 텍스처 + 색(tint). 두 층 재질은 extras.blend = {texture, tint} 로 B 층을 넘긴다 (사이트가 정점 색 R 로 섞는다)</summary>
@@ -264,6 +320,16 @@ public sealed class MapScene
var glb = new Glb();
var tex = new TexStore(provider, glb, maxTex);
var prims = new System.Text.Json.Nodes.JsonArray();
// 구운 조명 아틀라스: 모든 재질에 occlusionTexture(irr) · emissiveTexture(sh, 세기 0) 로 TEXCOORD_1 에 붙인다.
// (gltfpack 이 쓰지 않는 UV 채널을 버리지 않게 텍스처가 그 채널을 가리켜야 한다. 사이트는 둘을 떼어 조명으로 쓴다)
int? irrTex = null, shTex = null;
var lmMax = int.Parse(Environment.GetEnvironmentVariable("GVR_LIGHTMAP") ?? "2048");
if (lmMax > 0 && _lm.Build(lmMax) is var (irrJpg, shJpg))
{
irrTex = glb.Texture(irrJpg, "image/jpeg", clamp: true);
shTex = glb.Texture(shJpg, "image/jpeg", clamp: true);
LightmapBytes = irrJpg.Length + shJpg.Length;
}
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))
{
@@ -279,6 +345,12 @@ public sealed class MapScene
};
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 (irrTex is { } it && shTex is { } st)
{
mat["occlusionTexture"] = new System.Text.Json.Nodes.JsonObject { ["index"] = it, ["texCoord"] = 1, ["strength"] = 1 };
mat["emissiveTexture"] = new System.Text.Json.Nodes.JsonObject { ["index"] = st, ["texCoord"] = 1 };
mat["emissiveFactor"] = new System.Text.Json.Nodes.JsonArray(0, 0, 0);
}
if (m.Translucent) mat["alphaMode"] = "BLEND";
else if (m.Masked && a is { alpha: true })
{
@@ -286,12 +358,16 @@ public sealed class MapScene
mat["alphaCutoff"] = 0.333;
mat["doubleSided"] = true;
}
var extras = new System.Text.Json.Nodes.JsonObject();
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 };
extras["blend"] = ex;
}
// 구운 조명: irr 텍스처 값(sRGB) 1 = 밝기 K
if (irrTex != null) extras["lightmap"] = new System.Text.Json.Nodes.JsonObject { ["k"] = _lm.K, ["v"] = 1 };
if (extras.Count > 0) mat["extras"] = extras;
glb.Materials.Add(mat);
var attrs = new System.Text.Json.Nodes.JsonObject
{
@@ -300,6 +376,13 @@ public sealed class MapScene
["TEXCOORD_0"] = glb.Floats(b.Uv.ToArray(), 2),
};
if (m.Blend) attrs["COLOR_0"] = glb.Bytes(b.Col.ToArray(), 4);
if (irrTex != null)
{
var lmuv = new float[b.Lm.Count];
for (var i = 0; i < b.LmPage.Count; i++)
(lmuv[i * 2], lmuv[i * 2 + 1]) = _lm.ToAtlas(b.LmPage[i], b.Lm[i * 2], b.Lm[i * 2 + 1]);
attrs["TEXCOORD_1"] = glb.Floats(lmuv, 2);
}
prims.Add(new System.Text.Json.Nodes.JsonObject { ["attributes"] = attrs, ["indices"] = glb.Indices(b.Idx.ToArray()), ["material"] = glb.Materials.Count - 1, ["mode"] = 4 });
}
glb.Meshes.Add(new System.Text.Json.Nodes.JsonObject { ["name"] = _code, ["primitives"] = prims });
@@ -327,6 +410,7 @@ public sealed class MapScene
textures = TextureCount,
texturesFailed = TextureFailed,
textureBytes = TextureBytes,
lightmap = _lm.Any ? new { placements = LitPlacements, pages = _lm.Pages, failed = _lm.Failed, allocations = _lm.Allocations, atlas = new[] { _lm.AtlasW, _lm.AtlasH }, factor = _lm.Factor, bytes = LightmapBytes, k = _lm.K } : null,
skipped = Skipped,
failed = Failed,
manifest,

View File

@@ -0,0 +1,76 @@
using SixLabors.ImageSharp;
using CUE4Parse.FileProvider;
using CUE4Parse.UE4.Assets.Exports;
using CUE4Parse.UE4.Assets.Exports.BuildData;
using CUE4Parse.UE4.Assets.Exports.Component.StaticMesh;
using CUE4Parse.UE4.Assets.Exports.StaticMesh;
using CUE4Parse.UE4.Assets.Exports.Texture;
namespace GvrMapExtract;
/// <summary>조사용: 레벨 BuiltData 의 라이트맵</summary>
public static class ProbeLight
{
public static void Run(IFileProvider provider, string umap)
{
var bd = umap[..^".umap".Length] + "_BuiltData.uasset";
var pkg = provider.LoadPackage(bd);
var reg = pkg.GetExports().OfType<UMapBuildDataRegistry>().FirstOrDefault();
Console.WriteLine($"{bd}: exports {string.Join(',', pkg.GetExports().GroupBy(e => e.ExportType).Select(g => g.Key + "x" + g.Count()))}");
if (reg == null) return;
Console.WriteLine($"mesh build data {reg.MeshBuildData?.Count} light {reg.LightBuildData?.Count} vlm {reg.LevelPrecomputedVolumetricLightmapBuildData?.Count}");
var dump = Environment.GetEnvironmentVariable("GVR_LM_DUMP");
foreach (var t in pkg.GetExports().OfType<UTexture2D>().Where(t => !t.Name.StartsWith("AOMaterial")))
{
Console.WriteLine($" tex {t.Name} {t.ExportType} {t.PlatformData?.SizeX}x{t.PlatformData?.SizeY} {t.Format} mips {t.PlatformData?.Mips?.Length} srgb {t.SRGB}");
if (dump == null) continue;
var c = CUE4Parse_Conversion.Textures.TextureDecoder.Decode(t);
if (c == null) { Console.WriteLine(" decode null"); continue; }
Console.WriteLine($" decoded {c.Width}x{c.Height} {c.PixelFormat} {c.Data.Length}");
Directory.CreateDirectory(dump);
var px = c.Data;
using var rgb = new SixLabors.ImageSharp.Image<SixLabors.ImageSharp.PixelFormats.Rgba32>(c.Width, c.Height);
using var a = new SixLabors.ImageSharp.Image<SixLabors.ImageSharp.PixelFormats.L8>(c.Width, c.Height);
var bgra = c.PixelFormat == CUE4Parse.UE4.Assets.Exports.Texture.EPixelFormat.PF_B8G8R8A8;
for (var y = 0; y < c.Height; y++) for (var x = 0; x < c.Width; x++)
{
var i = (y * c.Width + x) * 4;
rgb[x, y] = bgra ? new(px[i + 2], px[i + 1], px[i], 255) : new(px[i], px[i + 1], px[i + 2], 255);
a[x, y] = new(px[i + 3]);
}
rgb.SaveAsPng(Path.Combine(dump, t.Name + ".rgb.png"));
a.SaveAsPng(Path.Combine(dump, t.Name + ".a.png"));
}
var n = 0;
foreach (var (g, d) in reg.MeshBuildData ?? new())
{
if (n++ >= 4) break;
if (d.LightMap is FLightMap2D lm)
Console.WriteLine($" {g}: tex {lm.Textures?[0]?.Name}/{lm.Textures?[1]?.Name} vt {lm.VirtualTextures?[0]?.Name} sky {lm.SkyOcclusionTexture?.Name} scale {string.Join(' ', lm.ScaleVectors!.Select(v => $"({v.X:F3},{v.Y:F3},{v.Z:F3},{v.W:F3})"))} add {string.Join(' ', lm.AddVectors!.Select(v => $"({v.X:F3},{v.Y:F3},{v.Z:F3},{v.W:F3})"))} cs {lm.CoordinateScale} cb {lm.CoordinateBias} inst {d.PerInstanceLightmapData.Length} shadow {d.ShadowMap?.GetType().Name}");
else Console.WriteLine($" {g}: lightmap {d.LightMap?.GetType().Name ?? "none"} inst {d.PerInstanceLightmapData.Length}");
}
// 레벨 컴포넌트 → 빌드 데이터 연결
var lvl = provider.LoadPackage(umap);
int comps = 0, hit = 0, ism = 0, ismHit = 0, lodMulti = 0;
foreach (var lazy in lvl.ExportsLazy)
{
UObject o;
try { o = lazy.Value; } catch { continue; }
if (o is not UStaticMeshComponent c) continue;
comps++;
var ids = c.LODData?.Select(l => l.MapBuildDataId).ToArray() ?? [];
if (ids.Length > 1) lodMulti++;
var ok = ids.Length > 0 && reg.MeshBuildData!.ContainsKey(ids[0]);
if (ok) hit++;
if (c is UInstancedStaticMeshComponent im) { ism++; if (ok) ismHit++; }
if (comps <= 5)
{
UStaticMesh? mesh = null;
try { mesh = c.GetStaticMesh()?.Load<UStaticMesh>(); } catch { }
var lods = mesh?.RenderData?.LODs;
Console.WriteLine($" comp {c.Name} {c.ExportType} lods {ids.Length} [{string.Join(',', ids.Select(i => reg.MeshBuildData!.ContainsKey(i) ? "Y" : "n"))}] mesh {mesh?.Name} lmIdx {mesh?.GetOrDefault<int>("LightMapCoordinateIndex")} lmRes {mesh?.GetOrDefault<int>("LightMapResolution")} meshLods {lods?.Length} uvs {string.Join('/', lods?.Select(l => l.VertexBuffer?.NumTexCoords ?? 0) ?? [])} compLmRes {c.GetOrDefault<int>("OverriddenLightMapRes")}");
}
}
Console.WriteLine($"comps {comps} with build data {hit}; ism {ism} hit {ismHit}; multi-lod {lodMulti}");
}
}

View File

@@ -24,6 +24,7 @@ using GvrMapExtract;
// GVR_MANIFEST 매니페스트 URL (없으면 지금 라이브 패치를 Riot 설정에서 찾는다)
// GVR_CACHE_MB 받은 조각을 메모리에 둘 크기 (기본 1500)
// GVR_TEX 텍스처 최대 크기 (기본 256)
// GVR_LIGHTMAP 구운 조명 아틀라스 너비 (기본 2048, 넓이도 약 이것의 제곱 안. 0 이면 조명을 넣지 않는다)
// GVR_OODLE Oodle 라이브러리 경로 (없으면 실행 파일 옆, 없으면 받는다)
Serilog.Log.Logger = new Serilog.LoggerConfiguration().MinimumLevel.Error().WriteTo.Console().CreateLogger();
@@ -102,7 +103,7 @@ switch (args[0])
var r = MapScene.Build(provider, m);
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.Materials} · 텍스처 {r.TextureCount}({r.TextureBytes >> 20}MB, 실패 {r.TextureFailed}) · 빠짐 {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.LightmapSummary} · 빠짐 {r.Skipped} · 실패 {r.Failed} · 받은 양 {(store.DownloadedBytes - d0) >> 20}MB · {(sw.Elapsed - t0).TotalSeconds:F0}초");
}
catch (Exception e)
{
@@ -182,6 +183,9 @@ switch (args[0])
case "abilities":
// 요원 스킬 3D 재료: abilities.json + m_*.glb + t_*.png (Abilities.cs)
return Abilities.Run(provider, args[1], args.Skip(2).ToList(), store);
case "lmprobe":
foreach (var a in args.Skip(1)) ProbeLight.Run(provider, a);
break;
case "anim":
foreach (var a in args.Skip(1)) ProbeAnim.Anim(provider, a);
break;