using System.Globalization;
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
using CUE4Parse.FileProvider;
using CUE4Parse.UE4.Assets.Exports;
using CUE4Parse.UE4.Assets.Exports.Animation;
using CUE4Parse.UE4.Assets.Exports.Material;
using CUE4Parse.UE4.Assets.Exports.SkeletalMesh;
using CUE4Parse.UE4.Assets.Exports.StaticMesh;
using CUE4Parse.UE4.Assets.Exports.Texture;
using CUE4Parse.UE4.Objects.Core.Math;
using CUE4Parse.UE4.Objects.UObject;
using CUE4Parse_Conversion.Options;
using CUE4Parse_Conversion.Textures;
using CUE4Parse_Conversion.Dto;
using Newtonsoft.Json.Linq;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.Formats.Png;
using SixLabors.ImageSharp.PixelFormats;
using SixLabors.ImageSharp.Processing;
namespace GvrMapExtract;
///
/// 요원 스킬 3D 재료: gvr-map-extract abilities <출력 폴더> [요원 코드 · 클래스 이름...]
///
/// 출력: abilities.json + m_<메시>.glb + t_<텍스처>.png (형식 설명: abilities-schema.md)
/// classes 리플레이 클래스(블루프린트 이름 + "_C") → 메시(액터 공간 위치 · 회전 · 크기) · 효과(파티클 시스템 키) · 숫자 매개변수
/// systems Cascade 파티클 시스템 → 켜진 이미터(LOD 0, 높음 품질)마다 모양 · 재질 · 분포 표
/// materials 재질 인스턴스 → 기반 재질 · 섞기 · 텍스처 · 색 · 숫자 · 스위치 (인스턴스 사슬에서 덮어쓴 것)
/// masters 기반 재질의 매개변수 기본값 (재질 그래프 자체는 쿡된 파일에 없다)
///
/// 분포 표 TABLE = { op, n, tb, ts, v[, lock] } (UE FRawDistribution 의 구운 표 그대로):
/// x = max(0, (t - tb) * ts), i = floor(x), a = x - i, 항목 i, i+1 (EntryCount-1 에서 멈춤) 을 a 로 섞는다.
/// 항목 하나 = op 1(없음): n 개 값 / op 2(무작위): 최소 n 개 + 최대 n 개 (입자마다 0~1 난수로 섞음) / op 3(극값): 최소나 최대 하나.
/// lock (벡터, op 2·3): 1=XY 2=XZ 3=YZ 4=XYZ 축이 같은 난수를 쓴다 (op 1 은 값에 이미 반영).
/// 상수(op 1, 항목 1개) 는 숫자 또는 [x,y,z] 로만 쓴다.
/// t: *Life / subUVIndex / sizeScale 등 "over life" 는 입자 나이 0~1, 시작 값(size · color · vel · life · rot ...) 과 spawnRate 는 이미터 시간(초).
///
public static class Abilities
{
public static int Run(IFileProvider provider, string outDir, IReadOnlyCollection filter, CdnStore? store = null)
{
Directory.CreateDirectory(outDir);
var x = new AbilityExtractor(provider, outDir, store);
return x.Run(filter);
}
}
internal sealed class AbilityExtractor(IFileProvider provider, string outDir, CdnStore? store)
{
private readonly int _texMax = int.Parse(Environment.GetEnvironmentVariable("GVR_ABILITY_TEX") ?? "256");
private const int BigTex = 512;
private const int TriBudget = 5000;
// ---------- 결과 ----------
private readonly JsonObject _classes = new(), _systems = new(), _materials = new(), _masters = new();
private readonly Dictionary _psKey = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary _matKey = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary> _matTex = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary _meshFile = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary _tex = new(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary> _usedNames = new();
private int _texOk, _texFail, _meshFail, _psFail, _emittersSkippedDetail, _emittersDisabled;
public int Run(IReadOnlyCollection filter)
{
var sw = System.Diagnostics.Stopwatch.StartNew();
var list = FindClasses().Where(c => filter.Count == 0 || filter.Any(f =>
f.Equals(c.Agent, StringComparison.OrdinalIgnoreCase) || f.Equals(c.Class, StringComparison.OrdinalIgnoreCase) || (f + "_C").Equals(c.Class, StringComparison.OrdinalIgnoreCase))).ToList();
Console.Error.WriteLine($"스킬 클래스 {list.Count}개");
var failed = 0;
foreach (var g in list.GroupBy(c => c.Agent))
{
var t0 = sw.Elapsed;
var d0 = store?.DownloadedBytes ?? 0;
int n = 0, bad = 0, ps0 = _systems.Count, m0 = _meshFile.Count;
foreach (var c in g)
{
try
{
var e = BuildClassEntry(c);
if (e == null) continue;
_classes[c.Class] = e;
n++;
}
catch (Exception ex)
{
bad++;
Console.WriteLine($" {c.Class}: 실패 {ex.GetType().Name} {ex.Message}");
}
}
failed += bad;
Console.WriteLine($"{g.Key}: 클래스 {n} · 실패 {bad} · 새 파티클 시스템 {_systems.Count - ps0} · 새 메시 {_meshFile.Count - m0} · 받은 양 {((store?.DownloadedBytes ?? 0) - d0) >> 20}MB · {(sw.Elapsed - t0).TotalSeconds:F0}초");
TrimCache();
GC.Collect();
}
ExportTextures();
int nClasses = _classes.Count, nSystems = _systems.Count;
var root = new JsonObject
{
["version"] = 1,
["units"] = "UE: cm, degrees (rot = [pitch, yaw, roll]), Z up, left-handed; glb vertices in UE mesh space",
["extractedAt"] = DateTimeOffset.UtcNow.ToString("o"),
["classes"] = Sorted(_classes),
["systems"] = Sorted(_systems),
["materials"] = Sorted(_materials),
["masters"] = Sorted(_masters),
};
File.WriteAllText(Path.Combine(outDir, "abilities.json"), root.ToJsonString());
Console.WriteLine($"텍스처 {_texOk} (실패 {_texFail}) · 메시 실패 {_meshFail} · 파티클 시스템 실패 {_psFail} · 꺼진 이미터 {_emittersDisabled} · 품질로 뺀 이미터 {_emittersSkippedDetail}");
Console.WriteLine($"끝: 클래스 {nClasses} · 파티클 시스템 {nSystems} · 메시 {_meshFile.Values.Count(v => v != null)} · 텍스처 {_texOk} · 받은 양 {(store?.DownloadedBytes ?? 0) >> 20}MB · {sw.Elapsed.TotalMinutes:F1}분");
return failed == 0 ? 0 : 1;
}
private static JsonObject Sorted(JsonObject o)
{
var r = new JsonObject();
foreach (var k in o.Select(kv => kv.Key).OrderBy(k => k, StringComparer.Ordinal).ToList())
{
var v = o[k];
o.Remove(k);
r[k] = v;
}
return r;
}
// ---------- 클래스 찾기 ----------
private sealed record ClassInfo(string Agent, string Class, string Package);
private static readonly Regex ClassName = new(@"^(GameObject_|Projectile_|Patch_|Pawn_|Zone_)", RegexOptions.IgnoreCase);
private static readonly Regex SkipDir = new(@"/(Console|NPE|AI|_Test|Test)/", RegexOptions.IgnoreCase);
private List FindClasses()
{
const string root = "ShooterGame/Content/Characters/";
var res = new List();
foreach (var k in provider.Files.Keys)
{
if (!k.StartsWith(root, StringComparison.OrdinalIgnoreCase) || !k.EndsWith(".uasset", StringComparison.OrdinalIgnoreCase)) continue;
var rest = k[root.Length..];
var slash = rest.IndexOf('/');
if (slash <= 0) continue;
var agent = rest[..slash];
if (agent.StartsWith('_') || agent is "Global" or "Components" or "AI") continue;
if (SkipDir.IsMatch(rest)) continue;
var name = Path.GetFileNameWithoutExtension(k);
if (!ClassName.IsMatch(name) || name.EndsWith("_PC", StringComparison.OrdinalIgnoreCase) || name.Contains("Parent", StringComparison.OrdinalIgnoreCase)) continue;
res.Add(new ClassInfo(agent, name + "_C", "/Game/" + k["ShooterGame/Content/".Length..^".uasset".Length]));
}
res.Add(new ClassInfo("Bomb", "TimedBomb_C", "/Game/GameModes/Bomb/TimedBomb"));
return res.OrderBy(c => c.Agent, StringComparer.Ordinal).ThenBy(c => c.Class, StringComparer.Ordinal).ToList();
}
// ---------- 패키지 JSON (CUE4Parse 내보내기 → JObject) ----------
private sealed class Pkg
{
public required string Path;
public required JObject?[] Ex;
public readonly Dictionary ByName = new(StringComparer.OrdinalIgnoreCase);
public JObject? Get(int idx, string? name)
{
if (idx >= 0 && idx < Ex.Length && Ex[idx] is { } e && (name == null || string.Equals((string?)e["Name"], name, StringComparison.OrdinalIgnoreCase))) return e;
if (name != null && ByName.TryGetValue(name, out var i)) return Ex[i];
return idx >= 0 && idx < Ex.Length ? Ex[idx] : null;
}
}
private static readonly HashSet SkipExportTypes = new(StringComparer.Ordinal) { "Function", "EdGraph", "MetaData", "UserDefinedStruct", "DelegateFunction", "SparseDelegateFunction" };
private readonly Dictionary _pkgs = new(StringComparer.OrdinalIgnoreCase);
private readonly Newtonsoft.Json.JsonSerializer _ser = Newtonsoft.Json.JsonSerializer.CreateDefault();
private Pkg? LoadPkg(string path, bool cache = true)
{
if (cache && _pkgs.TryGetValue(path, out var p)) return p;
p = null;
try
{
var pkg = provider.LoadPackage(path);
var lazy = pkg.ExportsLazy;
var ex = new JObject?[lazy.Length];
p = new Pkg { Path = path, Ex = ex };
for (var i = 0; i < lazy.Length; i++)
{
UObject o;
try { o = lazy[i].Value; } catch { continue; }
if (SkipExportTypes.Contains(o.ExportType)) { p.ByName.TryAdd(o.Name, i); continue; }
try { ex[i] = JObject.FromObject(o, _ser); } catch { continue; }
p.ByName.TryAdd(o.Name, i);
}
}
catch (Exception e)
{
if (e is not KeyNotFoundException and not FileNotFoundException) Console.Error.WriteLine($" 패키지 실패 {path}: {e.GetType().Name} {e.Message}");
}
if (cache) _pkgs[path] = p;
return p;
}
private void TrimCache()
{
// 요원 사이: 블루프린트 JSON 은 부모(여러 요원이 같이 씀)만 남긴다
if (_pkgs.Count < 400) return;
var keep = new HashSet(_models.Values.Where(m => m != null && m.UsedBy > 1).Select(m => m!.Pkg), StringComparer.OrdinalIgnoreCase);
foreach (var k in _pkgs.Keys.Where(k => !keep.Contains(k)).ToList()) _pkgs.Remove(k);
_tmplProps.Clear();
}
// ---------- 참조 ----------
private readonly record struct Ref(string Pkg, int Index, string Type, string Name, bool Native)
{
public string ObjectPath => Pkg + "." + Name;
}
private static Ref? ParseRef(JToken? t)
{
if (t is not JObject o) return null;
var path = (string?)o["ObjectPath"];
var oname = (string?)o["ObjectName"] ?? "";
string type = "", name = "";
var q = oname.IndexOf('\'');
if (q > 0)
{
type = oname[..q];
name = oname[(q + 1)..].TrimEnd('\'');
var cut = name.LastIndexOfAny([':', '.']);
if (cut >= 0) name = name[(cut + 1)..];
}
if (path != null)
{
if (path.StartsWith("/Script/")) return new Ref(path, -1, type, name, true);
var dot = path.LastIndexOf('.');
if (dot > path.LastIndexOf('/') && int.TryParse(path[(dot + 1)..], out var idx)) return new Ref(path[..dot], idx, type, name, false);
return new Ref(dot > path.LastIndexOf('/') ? path[..dot] : path, -1, type, name, false);
}
var ap = (string?)o["AssetPathName"];
if (!string.IsNullOrEmpty(ap) && ap != "None")
{
var dot = ap.LastIndexOf('.');
var pkg = dot > 0 ? ap[..dot] : ap;
var nm = dot > 0 ? ap[(dot + 1)..] : ap[(ap.LastIndexOf('/') + 1)..];
if (pkg.StartsWith("/Script/")) return new Ref(pkg, -1, "", nm, true);
return new Ref(pkg, -1, nm.EndsWith("_C") ? "BlueprintGeneratedClass" : "", nm, false);
}
return null;
}
private JObject? Resolve(Ref? r) => r is { Native: false } x ? LoadPkg(x.Pkg)?.Get(x.Index, x.Name) : null;
private static Dictionary Props(JObject? e)
{
var d = new Dictionary(StringComparer.Ordinal);
if (e?["Properties"] is JObject p)
foreach (var (k, v) in p)
if (v != null) d[k] = v;
return d;
}
private static Dictionary Merge(Dictionary? a, Dictionary b)
{
var d = a == null ? new Dictionary(StringComparer.Ordinal) : new Dictionary(a, StringComparer.Ordinal);
foreach (var (k, v) in b) d[k] = v;
return d;
}
private readonly Dictionary> _tmplProps = new(StringComparer.OrdinalIgnoreCase);
/// 원형(Template) 사슬을 따라 합친 속성 (원형 값 위에 자기 값)
private Dictionary TemplateProps(JToken? tmplRef, int depth = 0)
{
var r = ParseRef(tmplRef);
if (r is not { Native: false } x || depth > 12) return new(StringComparer.Ordinal);
var key = x.Pkg + "." + x.Index + "." + x.Name;
if (_tmplProps.TryGetValue(key, out var hit)) return hit;
var e = Resolve(x);
var res = e == null ? new(StringComparer.Ordinal) : Merge(TemplateProps(e["Template"], depth + 1), Props(e));
_tmplProps[key] = res;
return res;
}
// ---------- 클래스 모형 (부모 사슬 + 컴포넌트 계층) ----------
private sealed record Comp(string Name, string Type, Dictionary Props, string? Parent, string? Socket);
private sealed class Model
{
public string Pkg = "", Class = "";
public string? NativeBase, Root;
public List Chain = new();
public Dictionary Cdo = new(StringComparer.Ordinal);
public Dictionary Comps = new(StringComparer.OrdinalIgnoreCase);
public int UsedBy;
public Model Clone() => new()
{
Pkg = Pkg, Class = Class, NativeBase = NativeBase, Root = Root, Chain = new List(Chain),
Cdo = new Dictionary(Cdo, StringComparer.Ordinal), Comps = new Dictionary(Comps, StringComparer.OrdinalIgnoreCase),
};
}
private readonly Dictionary _models = new(StringComparer.OrdinalIgnoreCase);
private static string VarName(string n) => n.EndsWith("_GEN_VARIABLE") ? n[..^"_GEN_VARIABLE".Length] : n;
private Model? BuildModel(string pkgPath, string className, int depth = 0)
{
var key = pkgPath + ":" + className;
if (_models.TryGetValue(key, out var memo))
{
if (memo != null) memo.UsedBy++;
return memo;
}
_models[key] = null; // 순환 방지
var pkg = LoadPkg(pkgPath);
if (pkg == null) return null;
var bpIdx = pkg.ByName.TryGetValue(className, out var bi) ? bi : -1;
var bp = bpIdx >= 0 ? pkg.Ex[bpIdx] : null;
if (bp == null || !((string?)bp["Type"] ?? "").Contains("BlueprintGeneratedClass")) return null;
Model m;
var sup = ParseRef(bp["Super"] ?? bp["SuperStruct"]);
if (sup is { Native: false } s && depth < 20 && BuildModel(s.Pkg, s.Name, depth + 1) is { } pm) m = pm.Clone();
else m = new Model { NativeBase = sup?.Name };
m.Pkg = pkgPath;
m.Class = className;
m.Chain.Add(className);
// CDO 와 그 하위 객체 (C++ 컴포넌트)
if (pkg.ByName.TryGetValue("Default__" + className, out var ci) && pkg.Ex[ci] is { } cdo)
{
m.Cdo = Merge(m.Cdo, Props(cdo));
var outer = pkgPath + "." + ci;
for (var i = 0; i < pkg.Ex.Length; i++)
{
var e = pkg.Ex[i];
if (e == null || (string?)e["Outer"]?["ObjectPath"] != outer) continue;
var name = (string)e["Name"]!;
m.Comps.TryGetValue(name, out var old);
var props = Merge(old?.Props ?? TemplateProps(e["Template"]), Props(e));
var parent = ParseRef(props.GetValueOrDefault("AttachParent")) is { } ap ? VarName(ap.Name) : old?.Parent;
var socket = (string?)props.GetValueOrDefault("AttachSocketName");
m.Comps[name] = new Comp(name, (string?)e["Type"] ?? "", props, parent, string.IsNullOrEmpty(socket) || socket == "None" ? null : socket);
}
if (ParseRef(m.Cdo.GetValueOrDefault("RootComponent")) is { } rc) m.Root = VarName(rc.Name);
}
// SimpleConstructionScript (블루프린트에서 더한 컴포넌트)
var bpProps = Props(bp);
if (Resolve(ParseRef(bpProps.GetValueOrDefault("SimpleConstructionScript"))) is { } scs)
{
var visited = new HashSet();
void Visit(JToken? nodeRef, string? parentVar)
{
var node = Resolve(ParseRef(nodeRef));
if (node == null || !visited.Add((string?)node["Name"] ?? "")) return;
var np = Props(node);
var tmpl = Resolve(ParseRef(np.GetValueOrDefault("ComponentTemplate")));
var var = (string?)np.GetValueOrDefault("InternalVariableName") ?? (tmpl != null ? VarName((string)tmpl["Name"]!) : null);
if (var == null) return;
var props = tmpl == null ? new Dictionary() : Merge(TemplateProps(tmpl["Template"]), Props(tmpl));
var parent = parentVar;
if (parent == null)
{
var pn = (string?)np.GetValueOrDefault("ParentComponentOrVariableName");
if (!string.IsNullOrEmpty(pn) && pn != "None") parent = VarName(pn);
else if (m.Root == null) m.Root = var;
else parent = m.Root;
}
var socket = (string?)np.GetValueOrDefault("AttachToName");
m.Comps[var] = new Comp(var, (string?)tmpl?["Type"] ?? "", props, parent == var ? null : parent, string.IsNullOrEmpty(socket) || socket == "None" ? null : socket);
if (np.GetValueOrDefault("ChildNodes") is JArray ch)
foreach (var c in ch) Visit(c, var);
}
if (Props(scs).GetValueOrDefault("RootNodes") is JArray roots)
foreach (var r in roots) Visit(r, null);
}
// InheritableComponentHandler (부모 블루프린트 컴포넌트를 덮어쓴 값)
if (Resolve(ParseRef(bpProps.GetValueOrDefault("InheritableComponentHandler"))) is { } ich && Props(ich).GetValueOrDefault("Records") is JArray recs)
foreach (var rec in recs)
{
var var = (string?)rec["ComponentKey"]?["SCSVariableName"];
var tmpl = Resolve(ParseRef(rec["ComponentTemplate"]));
if (var == null || tmpl == null) continue;
if (m.Comps.TryGetValue(var, out var old)) m.Comps[var] = old with { Props = Merge(old.Props, Props(tmpl)) };
else m.Comps[var] = new Comp(var, (string?)tmpl["Type"] ?? "", Merge(TemplateProps(tmpl["Template"]), Props(tmpl)), m.Root, null);
}
_models[key] = m;
m.UsedBy = 1;
return m;
}
// ---------- 변환 ----------
private static float F(JToken? t, float def = 0) => t is { Type: JTokenType.Float or JTokenType.Integer } ? (float)t : def;
private static FVector Vec(JToken? t, float def = 0) => t is JObject o ? new FVector(F(o["X"], def), F(o["Y"], def), F(o["Z"], def)) : new FVector(def, def, def);
private static FTransform Rel(Dictionary p)
{
var loc = Vec(p.GetValueOrDefault("RelativeLocation"));
var r = p.GetValueOrDefault("RelativeRotation") as JObject;
var rot = r == null ? new FRotator(0, 0, 0) : new FRotator(F(r["Pitch"]), F(r["Yaw"]), F(r["Roll"]));
var scale = Vec(p.GetValueOrDefault("RelativeScale3D"), 1);
return new FTransform(rot, loc, scale);
}
/// 액터 공간(루트 컴포넌트 = 원점) 변환
private FTransform World(Model m, string name, int guard = 0)
{
if (guard > 32 || name == m.Root || !m.Comps.TryGetValue(name, out var c)) return FTransform.Identity;
var t = Rel(c.Props);
var parent = c.Parent ?? m.Root;
if (parent == null || parent == name || !m.Comps.TryGetValue(parent, out var pc)) return t;
if (c.Socket != null && SocketTransform(pc) is { } st) t = t * st(c.Socket);
return t * World(m, parent, guard + 1);
}
private Func? SocketTransform(Comp parent)
{
if (ParseRef(parent.Props.GetValueOrDefault("SkeletalMesh") ?? parent.Props.GetValueOrDefault("SkinnedAsset")) is not { Native: false } r) return null;
USkeletalMesh? mesh;
try { mesh = provider.LoadPackageObject(r.ObjectPath); } catch { return null; }
return socket =>
{
try
{
var bones = mesh.ReferenceSkeleton.FinalRefBoneInfo;
var pose = mesh.ReferenceSkeleton.FinalRefBonePose;
FTransform Bone(int bi)
{
var g = FTransform.Identity;
for (var i = bi; i >= 0; i = bones[i].ParentIndex) g = g * pose[i];
return g;
}
var sockets = mesh.Sockets.Select(s => { try { return s.Load(); } catch { return null; } }).ToList();
if (mesh.Skeleton?.Load() is { } sk)
sockets.AddRange(sk.Sockets.Select(s => { try { return s.Load(); } catch { return null; } }));
var so = sockets.FirstOrDefault(s => s != null && s.SocketName.Text.Equals(socket, StringComparison.OrdinalIgnoreCase));
var boneName = so?.BoneName.Text ?? socket;
var bi = Array.FindIndex(bones, b => b.Name.Text.Equals(boneName, StringComparison.OrdinalIgnoreCase));
if (bi < 0) return FTransform.Identity;
var local = so != null ? new FTransform(so.RelativeRotation, so.RelativeLocation, so.RelativeScale) : FTransform.Identity;
return local * Bone(bi);
}
catch { return FTransform.Identity; }
};
}
// ---------- 클래스 항목 ----------
private static readonly Regex HiddenTeam = new(@"Enemy|Ally|Friend|Foe", RegexOptions.IgnoreCase);
private static readonly Regex NotVisualComp = new(@"Collision|Overlap|Blocker|VisionBlock|Trigger|Hitbox|HitBox|Bounds|Proxy|Debug|Placement|Preview|Ghost|1P|FirstPerson|Minimap", RegexOptions.IgnoreCase);
private static readonly Regex NotVisualMesh = new(@"^/Engine/BasicShapes/|^/Engine/EngineMeshes/|^/Engine/EditorMeshes/|^/Game/TEMPASSETS/|Briefcase_Bomb|/_Core/1P/|/Characters/_Core/|/Equippables/Melee/", RegexOptions.IgnoreCase);
private static readonly Regex ParamName = new(@"Duration|Radius|Delay|Time|Lifetime|Range|Size|Speed", RegexOptions.IgnoreCase);
private static readonly Regex ParamSkip = new(@"Tick|Timeline|Handle|Timer|Montage|Anim|Audio|Sound|UI|HUD|Widget|Camera|LastTime|Last_|Cached|Net|Replicat|Debug", RegexOptions.IgnoreCase);
private JsonObject? BuildClassEntry(ClassInfo c)
{
var m = BuildModel(c.Package, c.Class);
if (m == null) return null;
var meshes = new JsonArray();
var decals = new JsonArray();
var lights = new JsonArray();
var fx = new List();
foreach (var comp in m.Comps.Values.OrderBy(x => x.Name, StringComparer.Ordinal))
{
var p = comp.Props;
var hidden = p.GetValueOrDefault("bVisible") is { Type: JTokenType.Boolean } v && !(bool)v || p.GetValueOrDefault("bHiddenInGame") is { Type: JTokenType.Boolean } h && (bool)h;
var editorOnly = p.GetValueOrDefault("bIsEditorOnly") is { Type: JTokenType.Boolean } eo && (bool)eo;
var onlyOwner = p.GetValueOrDefault("bOnlyOwnerSee") is { Type: JTokenType.Boolean } oo && (bool)oo;
if (editorOnly || onlyOwner) continue;
var meshRef = ParseRef(p.GetValueOrDefault("StaticMesh") ?? p.GetValueOrDefault("SkeletalMesh") ?? p.GetValueOrDefault("SkinnedAsset"));
var type = comp.Type;
if (meshRef is { Native: false } mr && !type.Contains("Particle"))
{
if (NotVisualComp.IsMatch(comp.Name) || NotVisualMesh.IsMatch(mr.Pkg)) continue;
var team = HiddenTeam.Match(comp.Name);
if (hidden && !team.Success) continue;
var collisionOnly = p.GetValueOrDefault("BodyInstance")?["CollisionProfileName"] is { } cp && ((string?)cp ?? "").Contains("Trigger", StringComparison.OrdinalIgnoreCase);
if (collisionOnly) continue;
var file = MeshFile(mr.ObjectPath, out var skeletal, out var slotMats);
if (file == null) continue;
var w = World(m, comp.Name);
var e = new JsonObject { ["name"] = comp.Name, ["file"] = file };
PutTransform(e, w);
e["skeletal"] = skeletal;
// 재질: 컴포넌트가 바꾼 것 먼저, 없으면 메시 기본
var over = p.GetValueOrDefault("OverrideMaterials") as JArray;
var mats = new JsonArray();
for (var i = 0; i < slotMats.Count; i++)
{
var ov = over != null && i < over.Count ? ParseRef(over[i]) : null;
mats.Add(ov is { Native: false } o ? MatKey(o.ObjectPath) : slotMats[i]);
}
e["materials"] = mats;
if (hidden)
{
e["hidden"] = true;
e["team"] = team.Value.ToLowerInvariant() is "enemy" or "foe" ? "enemy" : "ally";
}
meshes.Add(e);
}
else if (type.Contains("DecalComponent") && ParseRef(p.GetValueOrDefault("DecalMaterial")) is { Native: false } dm && !hidden)
{
var e = new JsonObject { ["name"] = comp.Name, ["material"] = MatKey(dm.ObjectPath) };
e["size"] = V3(p.GetValueOrDefault("DecalSize") is JObject ds ? Vec(ds) : new FVector(128, 256, 256));
PutTransform(e, World(m, comp.Name));
decals.Add(e);
}
else if (type.Contains("LightComponent") && !hidden)
{
var e = new JsonObject { ["name"] = comp.Name, ["type"] = type };
if (p.GetValueOrDefault("LightColor") is JObject lc) e["color"] = Arr(F(lc["R"], 255) / 255.0, F(lc["G"], 255) / 255.0, F(lc["B"], 255) / 255.0);
if (p.GetValueOrDefault("Intensity") is { } it) e["intensity"] = N((double)it);
if (p.GetValueOrDefault("AttenuationRadius") is { } ar) e["radius"] = N((double)ar);
PutTransform(e, World(m, comp.Name));
lights.Add(e);
}
}
CollectFx(m, FTransform.Identity, "", 0, fx, new HashSet(StringComparer.OrdinalIgnoreCase));
var prm = new JsonObject();
foreach (var (k, v) in m.Cdo.OrderBy(x => x.Key, StringComparer.Ordinal))
if (v.Type is JTokenType.Float or JTokenType.Integer && ParamName.IsMatch(k) && !ParamSkip.IsMatch(k)) prm[k] = N((double)v);
foreach (var comp in m.Comps.Values.OrderBy(x => x.Name, StringComparer.Ordinal))
foreach (var (k, v) in comp.Props.OrderBy(x => x.Key, StringComparer.Ordinal))
if (v.Type is JTokenType.Float or JTokenType.Integer && ParamName.IsMatch(k) && !ParamSkip.IsMatch(k) && !ParamSkip.IsMatch(comp.Name)) prm[comp.Name + "." + k] = N((double)v);
var entry = new JsonObject
{
["agent"] = c.Agent,
["blueprint"] = c.Package,
["parents"] = new JsonArray(m.Chain.Take(m.Chain.Count - 1).Reverse().Select(x => (JsonNode)x).ToArray()),
["meshes"] = meshes,
["fx"] = new JsonArray(fx.Select(x => (JsonNode)x).ToArray()),
["params"] = prm,
};
if (m.NativeBase != null) entry["native"] = m.NativeBase;
if (decals.Count > 0) entry["decals"] = decals;
if (lights.Count > 0) entry["lights"] = lights;
return entry;
}
private static void PutTransform(JsonObject e, FTransform w)
{
e["pos"] = V3(w.Translation);
var r = w.Rotator();
e["rot"] = Arr(r.Pitch, r.Yaw, r.Roll);
e["scale"] = V3(w.Scale3D);
}
// ---------- 효과 (파티클 · FXC) ----------
private static readonly Regex SkipFxComp = new(@"HUD|Audio|Sound|Animation|CameraShake|Widget|Minimap|Footstep|Voice|Ak", RegexOptions.IgnoreCase);
private static readonly Regex SkipFxProp = new(@"1P|FirstPerson|HUD|Audio|Sound|Anim|Shake|Icon|Widget|Minimap|Buff|Footstep|Death|Corpse", RegexOptions.IgnoreCase);
private static readonly Regex TeamToken = new(@"Allied|Ally|Friendly|Friend|Enemy|Foe", RegexOptions.IgnoreCase);
private static readonly HashSet NoScanKeys = new(StringComparer.Ordinal)
{
"AttachParent", "StaticMesh", "SkeletalMesh", "SkinnedAsset", "OverrideMaterials", "BodyInstance", "UberGraphFrame", "PrimaryComponentTick", "PrimaryActorTick",
"Mesh", "RootComponent", "AnimClass", "PhysicsAssetOverride", "AssetUserData", "MaterialSlotsOverride", "Instigator", "Owner",
};
private void CollectFx(Model m, FTransform baseT, string src, int depth, List outList, HashSet visited)
{
// 파티클 컴포넌트: 이름의 Ally/Enemy/FOE 로 짝 (같은 자리 · 같은 상태끼리)
var psc = new Dictionary(StringComparer.OrdinalIgnoreCase);
foreach (var comp in m.Comps.Values.OrderBy(x => x.Name, StringComparer.Ordinal))
{
if (SkipFxComp.IsMatch(comp.Type) || SkipFxComp.IsMatch(comp.Name)) continue;
var w = World(m, comp.Name) * baseT;
var p = comp.Props;
if (comp.Type.Contains("ParticleSystemComponent") && ParseRef(p.GetValueOrDefault("Template")) is { Native: false } ps)
{
if (SkipFxProp.IsMatch(comp.Name)) continue;
var key = PsKey(ps.ObjectPath);
if (key == null) continue;
var auto = !(p.GetValueOrDefault("bAutoActivate") is { Type: JTokenType.Boolean } aa && !(bool)aa);
var hidden = p.GetValueOrDefault("bVisible") is { Type: JTokenType.Boolean } vv && !(bool)vv || p.GetValueOrDefault("bHiddenInGame") is { Type: JTokenType.Boolean } hh && (bool)hh;
var tm = TeamToken.Match(comp.Name);
var g = Regex.Replace(TeamToken.Replace(comp.Name, ""), "_+", "_").Trim('_') + "|" + V3(w.Translation).ToJsonString() + "|" + w.Rotator() + "|" + auto;
psc.TryGetValue(g, out var cur);
if (!tm.Success) cur = (key, key, w, comp.Name, auto, hidden);
else if (IsEnemy(tm.Value)) cur = (cur.Ally, key, w, cur.Name ?? comp.Name, auto, cur.Name == null ? hidden : cur.Hidden && hidden);
else cur = (key, cur.Enemy, w, cur.Name ?? comp.Name, auto, cur.Name == null ? hidden : cur.Hidden && hidden);
psc[g] = cur;
}
ScanProps(p, src + comp.Name, w, baseT, depth, outList, visited);
}
foreach (var (_, c) in psc)
{
var e = FxEntry(src + c.Name, c.Ally, c.Enemy, c.T);
if (!c.Auto) e["auto"] = false;
if (c.Hidden) e["hidden"] = true;
Add(outList, e);
}
ScanProps(m.Cdo, src, baseT, baseT, depth, outList, visited);
}
private static void Add(List list, JsonObject e)
{
var s = e.ToJsonString();
if (!list.Any(x => x.ToJsonString() == s)) list.Add(e);
}
/// 속성 안 참조: 파티클 시스템 → 효과 (이름의 Ally/Enemy 로 짝), FXC 클래스 → 펼침
private void ScanProps(Dictionary props, string owner, FTransform ownerT, FTransform baseT, int depth, List outList, HashSet visited)
{
var found = new List<(string Prop, Ref R)>();
foreach (var (k, v) in props)
{
if (NoScanKeys.Contains(k) || SkipFxProp.IsMatch(k) || owner.Length > 0 && k == "Template") continue;
foreach (var r in Refs(v, 0)) found.Add((k, r));
}
if (found.Count == 0) return;
var scale = props.GetValueOrDefault("Scale") is JObject sc ? Vec(sc, 1) : props.GetValueOrDefault("Scale") is { Type: JTokenType.Float or JTokenType.Integer } sf ? new FVector((float)sf, (float)sf, (float)sf) : new FVector(1, 1, 1);
var offset = props.GetValueOrDefault("Offset") is JObject of ? Vec(of) : new FVector(0, 0, 0);
var t = new FTransform(FQuat.Identity, offset, scale) * ownerT;
var groups = new Dictionary(StringComparer.OrdinalIgnoreCase);
foreach (var (prop, r) in found)
{
if (r.Type == "ParticleSystem" || r.Type == "" && LooksLikePs(r))
{
var key = PsKey(r.ObjectPath);
if (key == null) continue;
var tm = TeamToken.Match(prop);
var g = TeamToken.Replace(prop, "");
groups.TryGetValue(g, out var cur);
if (!tm.Success) cur = (key, key, prop);
else if (IsEnemy(tm.Value)) cur = (cur.Ally, key, cur.Prop ?? prop);
else cur = (key, cur.Enemy, cur.Prop ?? prop);
groups[g] = cur;
}
else if (r.Type.Contains("BlueprintGeneratedClass") && depth < 3 && IsFxcRef(prop, r) && visited.Add(r.Pkg))
{
var fm = BuildModel(r.Pkg, r.Name.EndsWith("_C") ? r.Name : r.Name + "_C");
if (fm != null && (r.Name.StartsWith("FXC_", StringComparison.OrdinalIgnoreCase) || fm.NativeBase?.Contains("EffectContainer") == true))
CollectFx(fm, baseT, (owner.Length > 0 ? owner + "." : "") + prop + ">" + fm.Class.Replace("_C", "") + ">", depth + 1, outList, visited);
visited.Remove(r.Pkg);
}
}
foreach (var (g, (ally, enemy, _)) in groups)
Add(outList, FxEntry((owner.Length > 0 ? owner + "." : "") + g, ally, enemy, t));
}
private static bool IsEnemy(string token) => token.Equals("Enemy", StringComparison.OrdinalIgnoreCase) || token.Equals("Foe", StringComparison.OrdinalIgnoreCase);
private bool LooksLikePs(Ref r)
{
// 약한 참조(경로만): 패키지를 열어 종류 확인
try { return provider.LoadPackageObject(r.ObjectPath).ExportType == "ParticleSystem"; } catch { return false; }
}
private static bool IsFxcRef(string prop, Ref r) =>
r.Name.StartsWith("FXC_", StringComparison.OrdinalIgnoreCase) ||
Regex.IsMatch(prop, "FXC|Effect", RegexOptions.IgnoreCase) && !Regex.IsMatch(r.Name, "^(GameObject_|Projectile_|Patch_|Pawn_|Buff_|Ability_|Equippable_|Damage)", RegexOptions.IgnoreCase);
private static IEnumerable[ Refs(JToken t, int depth)
{
if (depth > 6) yield break;
if (t is JObject o)
{
if (o.ContainsKey("ObjectPath") || o.ContainsKey("AssetPathName"))
{
if (ParseRef(o) is { Native: false } r) yield return r;
yield break;
}
foreach (var (_, v) in o)
if (v != null)
foreach (var r in Refs(v, depth + 1)) yield return r;
}
else if (t is JArray a)
foreach (var v in a)
foreach (var r in Refs(v, depth + 1)) yield return r;
}
private static readonly (string Role, Regex Re)[] Roles =
[
("decal", new Regex("Decal", RegexOptions.IgnoreCase)),
("patch", new Regex("Patch", RegexOptions.IgnoreCase)),
("disabled", new Regex("Disable|Suppress", RegexOptions.IgnoreCase)),
("target", new Regex("AppliedFXC|MultiTarget|Blind|Nearsight|Reveal(ed)?Target", RegexOptions.IgnoreCase)),
("warn", new Regex("Telegraph|Warn|Incoming|Indicator", RegexOptions.IgnoreCase)),
("outro", new Regex("Outro|Expire|Destroy|Dissipat|TimeOut|Timeout|Fade|End(?=[A-Z_>.]|$)", RegexOptions.None)),
("trail", new Regex("Trail|Travel|Projectile|_Proj(?=[A-Z_>.]|$)|Proj_", RegexOptions.IgnoreCase)),
("explode", new Regex("Explo|Impact|Hit(?=[A-Z_>.]|$)|Detonat|Burst|Bang|Pop(?=[A-Z_>.]|$)|Bounce|Blast", RegexOptions.None)),
("loop", new Regex("Loop|Idle|Constant|Active(?!at)|Zone|Sustain|Body", RegexOptions.IgnoreCase)),
("intro", new Regex("Intro|Spawn|Start|Birth|Activat|Deploy|Cast|Land|Enable|Form", RegexOptions.IgnoreCase)),
];
private static string Role(string src, string? ps)
{
foreach (var (role, re) in Roles)
if (re.IsMatch(src)) return role;
foreach (var (role, re) in Roles)
if (ps != null && re.IsMatch(ps)) return role;
return "other";
}
private static JsonObject FxEntry(string src, string? ally, string? enemy, FTransform t)
{
var e = new JsonObject
{
["role"] = Role(src, ally ?? enemy),
["ally"] = ally,
["enemy"] = enemy,
};
var s = t.Scale3D;
e["scale"] = Math.Abs(s.X - s.Y) < 1e-4 && Math.Abs(s.X - s.Z) < 1e-4 ? N(s.X) : V3(s);
e["pos"] = V3(t.Translation);
var r = t.Rotator();
if (Math.Abs(r.Pitch) + Math.Abs(r.Yaw) + Math.Abs(r.Roll) > 0.01) e["rot"] = Arr(r.Pitch, r.Yaw, r.Roll);
e["src"] = src;
return e;
}
// ---------- 파티클 시스템 (Cascade) ----------
private string? PsKey(string objectPath)
{
if (_psKey.TryGetValue(objectPath, out var k)) return k;
_psKey[objectPath] = null;
var pkgPath = objectPath[..objectPath.LastIndexOf('.')];
var pkg = LoadPkg(pkgPath, cache: false);
var ps = pkg?.Ex.FirstOrDefault(e => (string?)e?["Type"] == "ParticleSystem");
if (pkg == null || ps == null) { _psFail++; return null; }
k = UniqueName("ps", pkgPath, objectPath[(objectPath.LastIndexOf('.') + 1)..]);
_psKey[objectPath] = k;
try { _systems[k] = Cascade(pkg, ps, pkgPath); }
catch (Exception e)
{
_psFail++;
Console.Error.WriteLine($" 파티클 시스템 실패 {pkgPath}: {e.GetType().Name} {e.Message}");
_systems[k] = new JsonObject { ["path"] = pkgPath, ["emitters"] = new JsonArray(), ["error"] = e.Message };
}
return k;
}
private JsonObject Cascade(Pkg pkg, JObject ps, string path)
{
JObject? Get(JToken? r) => ParseRef(r) is { Native: false } x ? (x.Pkg.Equals(pkg.Path, StringComparison.OrdinalIgnoreCase) ? pkg.Get(x.Index, x.Name) : Resolve(x)) : null;
var pp = Props(ps);
var res = new JsonObject { ["path"] = path };
if (pp.GetValueOrDefault("WarmupTime") is { } wu) res["warmup"] = N((double)wu);
if (pp.GetValueOrDefault("Delay") is { } dl) res["delay"] = N((double)dl);
var ems = new JsonArray();
if (pp.GetValueOrDefault("Emitters") is JArray list)
foreach (var er in list)
{
var em = Get(er);
if (em == null) continue;
var ep = Props(em);
var mask = ep.GetValueOrDefault("DetailModeBitmask") is { } dm ? (int)dm : 15;
if ((mask & 4) == 0) { _emittersSkippedDetail++; continue; } // 높음 품질에서 꺼짐
var lod = ep.GetValueOrDefault("LODLevels") is JArray lods && lods.Count > 0 ? Get(lods[0]) : null;
if (lod == null) continue;
var lp = Props(lod);
if (lp.GetValueOrDefault("bEnabled") is { Type: JTokenType.Boolean } en && !(bool)en) { _emittersDisabled++; continue; }
var mods = new List();
if (Get(lp.GetValueOrDefault("SpawnModule")) is { } sm) mods.Add(sm);
if (lp.GetValueOrDefault("Modules") is JArray ml)
foreach (var mr in ml)
if (Get(mr) is { } mo && !(Props(mo).GetValueOrDefault("bEnabled") is { Type: JTokenType.Boolean } me && !(bool)me)) mods.Add(mo);
ems.Add(Emitter((string?)ep.GetValueOrDefault("EmitterName") ?? (string?)em["Name"] ?? "?", Get(lp.GetValueOrDefault("RequiredModule")), Get(lp.GetValueOrDefault("TypeDataModule")), mods, Get));
}
res["emitters"] = ems;
return res;
}
private JsonObject Emitter(string name, JObject? req, JObject? td, List mods, Func get)
{
var e = new JsonObject { ["name"] = name };
var rp = Props(req);
var tp = Props(td);
var tdType = (string?)td?["Type"] ?? "";
e["type"] = tdType switch
{
"ParticleModuleTypeDataMesh" => tp.GetValueOrDefault("bIsDecal") is { Type: JTokenType.Boolean } d && (bool)d ? "decal" : "mesh",
"ParticleModuleTypeDataRibbon" or "ParticleModuleTypeDataAnimTrail" => "ribbon",
"ParticleModuleTypeDataBeam2" => "beam",
_ => "sprite",
};
if (tdType == "ParticleModuleTypeDataPatch") e["patch"] = true;
if (tdType == "ParticleModuleTypeDataGpu") e["gpu"] = true;
string? matKey = null;
if (ParseRef(rp.GetValueOrDefault("Material")) is { Native: false } mr) e["material"] = matKey = MatKey(mr.ObjectPath);
else e["material"] = null;
if (tdType == "ParticleModuleTypeDataMesh")
{
if (ParseRef(tp.GetValueOrDefault("Mesh")) is { Native: false } mesh) e["mesh"] = MeshFile(mesh.ObjectPath, out _, out _);
e["meshCameraFacing"] = tp.GetValueOrDefault("bCameraFacing") is { Type: JTokenType.Boolean } cf && (bool)cf;
e["overrideMaterial"] = tp.GetValueOrDefault("bOverrideMaterial") is { Type: JTokenType.Boolean } om && (bool)om;
foreach (var k in new[] { "CameraFacingOption", "MeshAlignment", "AxisLockOption", "DecalColorName", "bApplyParticleRotationAsSpin", "bFaceCameraDirectionRatherThanPosition" })
if (tp.GetValueOrDefault(k) is { } v) e[Lc(k)] = Simple(v);
}
else if (tdType is "ParticleModuleTypeDataRibbon" or "ParticleModuleTypeDataBeam2" or "ParticleModuleTypeDataAnimTrail")
{
var o = new JsonObject();
foreach (var (k, v) in tp)
if (k != "LODValidity" && Simple(v) is { } sv) o[k] = sv;
else if (k != "LODValidity" && v is JObject dj && dj.ContainsKey("Table")) o[k] = Dist(dj, get)?.Out();
e[tdType == "ParticleModuleTypeDataBeam2" ? "beam" : "ribbon"] = o;
}
var h = rp.GetValueOrDefault("SubImages_Horizontal") is { } sh ? (int)sh : 1;
var vv = rp.GetValueOrDefault("SubImages_Vertical") is { } sv2 ? (int)sv2 : 1;
e["subUV"] = new JsonArray(h, vv);
if (h * vv > 1 && matKey != null) MarkBig(matKey);
if (rp.GetValueOrDefault("InterpolationMethod") is { } im) e["subUVMode"] = Enum(im);
e["delay"] = N(rp.GetValueOrDefault("EmitterDelay") is { } ed ? (double)ed : 0);
if (Bool(rp, "bEmitterDelayUseRange")) e["delayLow"] = N(rp.GetValueOrDefault("EmitterDelayLow") is { } edl ? (double)edl : 0);
if (Bool(rp, "bDelayFirstLoopOnly")) e["delayFirstLoopOnly"] = true;
e["duration"] = N(rp.GetValueOrDefault("EmitterDuration") is { } du ? (double)du : 1.0);
if (Bool(rp, "bEmitterDurationUseRange")) e["durationLow"] = N(rp.GetValueOrDefault("EmitterDurationLow") is { } dul ? (double)dul : 0);
e["loops"] = rp.GetValueOrDefault("EmitterLoops") is { } lo ? (int)lo : 0;
e["local"] = Bool(rp, "bUseLocalSpace");
e["screenAlign"] = rp.GetValueOrDefault("ScreenAlignment") is { } sa ? Enum(sa) : "PSA_Square";
e["sort"] = rp.GetValueOrDefault("SortMode") is { } so ? Enum(so) : "PSORTMODE_None";
if (Bool(rp, "bKillOnDeactivate")) e["killOnDeactivate"] = true;
if (Bool(rp, "bKillOnCompleted")) e["killOnCompleted"] = true;
if (rp.GetValueOrDefault("EmitterOrigin") is JObject eo) e["origin"] = V3(Vec(eo));
if (rp.GetValueOrDefault("EmitterRotation") is JObject er) e["emitterRot"] = Arr(F(er["Pitch"]), F(er["Yaw"]), F(er["Roll"]));
if (rp.GetValueOrDefault("UVFlippingMode") is { } uvf) e["uvFlip"] = Enum(uvf);
if (Bool(rp, "bOrientZAxisTowardCamera")) e["orientZToCamera"] = true;
e["spawnRate"] = null;
e["bursts"] = new JsonArray();
e["life"] = null;
e["size"] = null; e["sizeLife"] = null; e["sizeScale"] = null;
e["color"] = null; e["alpha"] = null; e["colorLife"] = null; e["alphaLife"] = null; e["colorScaleLife"] = null; e["alphaScaleLife"] = null;
e["vel"] = null; e["velCone"] = null; e["accel"] = null; e["drag"] = null;
e["locSphere"] = null; e["locBox"] = null; e["locCylinder"] = null;
e["rot"] = null; e["rotRate"] = null; e["meshRot"] = null;
e["teamColor"] = null; e["light"] = null;
var other = new JsonArray();
double[]? sizeMin = null, sizeMax = null;
foreach (var mo in mods)
{
var type = ((string?)mo["Type"] ?? "").Replace("ParticleModule", "");
var baseType = type.EndsWith("_Seeded") ? type[..^"_Seeded".Length] : type;
var p = Props(mo);
D? Dd(string k) => p.GetValueOrDefault(k) is JObject o ? Dist(o, get) : null;
switch (baseType)
{
case "Spawn":
{
var rate = Dd("Rate");
var scale = Dd("RateScale");
if (!(p.GetValueOrDefault("bProcessSpawnRate") is { Type: JTokenType.Boolean } ps && !(bool)ps) && rate != null && !rate.IsZero) e["spawnRate"] = rate.Out();
if (scale != null && !scale.IsOne) e["rateScale"] = scale.Out();
if (p.GetValueOrDefault("BurstList") is JArray bl && !(p.GetValueOrDefault("bProcessBurstList") is { Type: JTokenType.Boolean } pb && !(bool)pb))
{
var arr = new JsonArray();
foreach (var b in bl)
{
var cnt = (int?)b["Count"] ?? 0;
var low = (int?)b["CountLow"] ?? -1;
var item = new JsonArray(N(F(b["Time"])), cnt);
if (low >= 0) item.Add(low);
arr.Add(item);
}
e["bursts"] = arr;
}
if (Dd("BurstScale") is { IsOne: false } bs) e["burstScale"] = bs.Out();
break;
}
case "SpawnPerUnit":
e["spawnPerUnit"] = new JsonObject
{
["n"] = Dd("SpawnPerUnit")?.Out(),
["unit"] = N(p.GetValueOrDefault("UnitScalar") is { } us ? (double)us : 50),
["ignoreRateWhenMoving"] = Bool(p, "bIgnoreSpawnRateWhenMoving"),
["processRate"] = !(p.GetValueOrDefault("bProcessSpawnRate") is { Type: JTokenType.Boolean } pr && !(bool)pr),
};
break;
case "Lifetime":
PutRange(e, "life", Dd("Lifetime"), scalar: true);
break;
case "Size":
{
var d = Dd("StartSize");
if (d == null) break;
var (mn, mx) = d.Range();
sizeMin = sizeMin == null ? mn : sizeMin.Zip(mn, (a, b) => a + b).ToArray();
sizeMax = sizeMax == null ? mx : sizeMax.Zip(mx, (a, b) => a + b).ToArray();
if (!d.IsConst) e["sizeT"] = d.Out();
break;
}
case "SizeMultiplyLife":
e["sizeLife"] = Dd("LifeMultiplier")?.Out();
if (!Bool(p, "MultiplyX", true) || !Bool(p, "MultiplyY", true) || !Bool(p, "MultiplyZ", true))
e["sizeLifeAxes"] = new JsonArray(Bool(p, "MultiplyX", true), Bool(p, "MultiplyY", true), Bool(p, "MultiplyZ", true));
break;
case "SizeScale":
e["sizeScale"] = Dd("SizeScale")?.Out();
break;
case "Color":
PutRange(e, "color", Dd("StartColor"), scalar: false);
PutRange(e, "alpha", Dd("StartAlpha"), scalar: true);
break;
case "ColorOverLife":
e["colorLife"] = Dd("ColorOverLife")?.Out();
e["alphaLife"] = Dd("AlphaOverLife")?.Out();
break;
case "ColorScaleOverLife":
e["colorScaleLife"] = Dd("ColorScaleOverLife")?.Out();
e["alphaScaleLife"] = Dd("AlphaScaleOverLife")?.Out();
if (Bool(p, "bEmitterTime")) e["colorScaleEmitterTime"] = true;
break;
case "Velocity":
PutRange(e, "vel", Dd("StartVelocity"), scalar: false, pair: true);
if (Dd("StartVelocityRadial") is { IsZero: false } vr) PutRange(e, "velRadial", vr, scalar: true);
if (Bool(p, "bInWorldSpace")) e["velWorld"] = true;
break;
case "VelocityCone":
e["velCone"] = new JsonObject
{
["angle"] = Dd("Angle")?.Out(),
["speed"] = Dd("Velocity")?.Out(),
["dir"] = p.GetValueOrDefault("Direction") is JObject dir ? V3(Vec(dir)) : Arr(0, 0, 1),
["world"] = Bool(p, "bInWorldSpace"),
};
break;
case "VelocityOverLifetime":
e["velLife"] = Dd("VelOverLife")?.Out();
if (Bool(p, "Absolute")) e["velLifeAbsolute"] = true;
break;
case "Acceleration":
PutRange(e, "accel", Dd("Acceleration"), scalar: false);
if (Bool(p, "bAlwaysInWorldSpace")) e["accelWorld"] = true;
break;
case "AccelerationConstant":
if (p.GetValueOrDefault("Acceleration") is JObject ac) e["accel"] = V3(Vec(ac));
if (Bool(p, "bAlwaysInWorldSpace")) e["accelWorld"] = true;
break;
case "AccelerationDrag":
PutRange(e, "drag", Dd("DragCoefficientRaw") ?? Dd("DragCoefficient"), scalar: true);
break;
case "AccelerationOverLifetime":
e["accelLife"] = Dd("AccelOverLife")?.Out();
break;
case "Location":
{
var d = Dd("StartLocation");
if (d == null) break;
var (mn, mx) = d.Range();
e["locBox"] = new JsonArray(Arr(mn), Arr(mx));
if (!d.IsConst) e["locBoxT"] = d.Out();
break;
}
case "LocationPrimitiveSphere":
case "LocationPrimitiveCylinder":
{
var o = new JsonObject();
var r = Dd("StartRadius");
if (r != null) { var (mn, mx) = r.Range(); o["r"] = new JsonArray(N(mn[0]), N(mx[0])); if (!r.IsConst) o["rT"] = r.Out(); }
if (baseType.EndsWith("Cylinder") && Dd("StartHeight") is { } hh)
{
var (mn, mx) = hh.Range();
o["h"] = new JsonArray(N(mn[0]), N(mx[0]));
o["axis"] = p.GetValueOrDefault("HeightAxis") is { } ha ? Enum(ha) : "PMLPC_HEIGHTAXIS_Z";
o["radialVel"] = Bool(p, "RadialVelocity", true);
}
if (Dd("StartLocation") is { } sl) o["center"] = Arr(sl.Range().Min);
o["surface"] = Bool(p, "SurfaceOnly");
o["vel"] = Bool(p, "Velocity");
if (Dd("VelocityScale") is { } vs) o["velScale"] = vs.Out();
var axes = "";
foreach (var (k, s) in new[] { ("Positive_X", "+x"), ("Negative_X", "-x"), ("Positive_Y", "+y"), ("Negative_Y", "-y"), ("Positive_Z", "+z"), ("Negative_Z", "-z") })
if (Bool(p, k, true)) axes += s;
o["axes"] = axes;
e[baseType.EndsWith("Sphere") ? "locSphere" : "locCylinder"] = o;
break;
}
case "Rotation":
PutRange(e, "rot", Dd("StartRotation"), scalar: true);
break;
case "RotationRate":
PutRange(e, "rotRate", Dd("StartRotationRate"), scalar: true);
break;
case "RotationRateMultiplyLife":
e["rotRateLife"] = Dd("LifeMultiplier")?.Out();
break;
case "RotationOverLifetime":
e["rotLife"] = Dd("RotationOverLife")?.Out();
e["rotLifeScale"] = Bool(p, "Scale", true);
break;
case "MeshRotation":
PutRange(e, "meshRot", Dd("StartRotation"), scalar: false, pair: true);
if (Bool(p, "bInheritParent")) e["meshRotInherit"] = true;
break;
case "MeshRotationRate":
PutRange(e, "meshRotRate", Dd("StartRotationRate"), scalar: false, pair: true);
break;
case "MeshRotationRateMultiplyLife":
e["meshRotRateLife"] = Dd("LifeMultiplier")?.Out();
break;
case "MeshRotationRateOverLife":
e["meshRotRateOverLife"] = Dd("RotRate")?.Out();
e["meshRotRateOverLifeScale"] = Bool(p, "bScaleRotRate");
break;
case "SubUV":
e["subUVIndex"] = Dd("SubImageIndex")?.Out();
if (Bool(p, "bUseRealTime")) e["subUVRealTime"] = true;
break;
case "SubUVMovie":
e["subUVMovie"] = new JsonObject { ["fps"] = Dd("FrameRate")?.Out(), ["start"] = p.GetValueOrDefault("StartingFrame") is { } sf ? (int)sf : 1, ["index"] = Dd("SubImageIndex")?.Out() };
break;
case "TeamColor":
{
JsonNode? C(string k) => p.GetValueOrDefault(k) is JObject c ? Arr(F(c["R"]), F(c["G"]), F(c["B"]), F(c["A"], 1)) : null;
e["teamColor"] = new JsonObject { ["ally"] = C("BaseColor") ?? C("DefenderColor"), ["enemy"] = C("DefaultEnemyColor"), ["param"] = (string?)p.GetValueOrDefault("MaterialParameter") };
break;
}
case "Light":
e["light"] = new JsonObject
{
["colorScaleLife"] = Dd("ColorScaleOverLife")?.Out(),
["brightnessLife"] = Dd("BrightnessOverLife")?.Out(),
["radiusScale"] = Dd("RadiusScale")?.Out(),
["exponent"] = Dd("LightExponent")?.Out(),
["inverseSquared"] = Bool(p, "bUseInverseSquaredFalloff", true),
["spawnFraction"] = N(p.GetValueOrDefault("SpawnFraction") is { } sfr ? (double)sfr : 1),
};
break;
case "ParameterDynamic":
if (p.GetValueOrDefault("DynamicParams") is JArray dps)
{
var arr = new JsonArray();
foreach (var dp in dps)
{
var pv = dp["ParamValue"] is JObject pvo ? Dist(pvo, get) : null;
arr.Add(new JsonObject
{
["name"] = (string?)dp["ParamName"],
["value"] = pv?.Out(),
["emitterTime"] = (bool?)dp["bUseEmitterTime"] ?? false,
["spawnOnly"] = (bool?)dp["bSpawnTimeOnly"] ?? false,
["method"] = Enum(dp["ValueMethod"]),
});
}
e["dynamic"] = arr;
}
break;
case "CameraOffset":
e["cameraOffset"] = Dd("CameraOffset")?.Out();
if (Bool(p, "bSpawnTimeOnly")) e["cameraOffsetSpawnOnly"] = true;
break;
case "PivotOffset":
if (p.GetValueOrDefault("PivotOffset") is JObject po) e["pivot"] = Arr(F(po["X"]), F(po["Y"]));
break;
case "OrientationAxisLock":
e["axisLock"] = p.GetValueOrDefault("LockAxisFlags") is { } la ? Enum(la) : "EPAL_NONE";
break;
case "Orbit":
{
var o = new JsonObject();
foreach (var (k, key) in new[] { ("OffsetAmount", "offset"), ("RotationAmount", "rot"), ("RotationRateAmount", "rotRate") })
if (Dd(k) is { } d) { var (mn, mx) = d.Range(); o[key] = new JsonArray(Arr(mn), Arr(mx)); }
e["orbit"] = o;
break;
}
case "MeshMaterial":
if (p.GetValueOrDefault("MeshMaterials") is JArray mm)
e["meshMaterials"] = new JsonArray(mm.Select(x => ParseRef(x) is { Native: false } r ? (JsonNode?)MatKey(r.ObjectPath) : null).ToArray());
break;
default:
other.Add(type);
break;
}
}
if (sizeMin != null) e["size"] = new JsonArray(Arr(sizeMin), Arr(sizeMax!));
e["other"] = other;
return e;
}
private static void PutRange(JsonObject e, string key, D? d, bool scalar, bool pair = false)
{
if (d == null) return;
var (mn, mx) = d.Range();
if (scalar) e[key] = new JsonArray(N(mn[0]), N(mx[0]));
else if (pair) e[key] = new JsonArray(Arr(mn), Arr(mx));
else e[key] = Arr(mn);
if (!d.IsConst) e[key + "T"] = d.Out();
}
private static bool Bool(Dictionary p, string k, bool def = false) => p.GetValueOrDefault(k) is { Type: JTokenType.Boolean } b ? (bool)b : def;
private static string Enum(JToken? t)
{
var s = (string?)t ?? "";
var i = s.LastIndexOf("::", StringComparison.Ordinal);
return i >= 0 ? s[(i + 2)..] : s;
}
private static JsonNode? Simple(JToken v) => v.Type switch
{
JTokenType.Float => N((double)v),
JTokenType.Integer => (long)v,
JTokenType.Boolean => (bool)v,
JTokenType.String => Enum(v),
_ => null,
};
private static string Lc(string k)
{
if (k.StartsWith('b') && k.Length > 1 && char.IsUpper(k[1])) k = k[1..];
return char.ToLowerInvariant(k[0]) + k[1..];
}
// ---------- 분포 (FRawDistribution 구운 표) ----------
private sealed class D
{
public int Op = 1, N = 1, Count = 1, Lock;
public double Tb, Ts;
public double[] V = [];
public JsonNode? Special;
public int Stride => Op >= 2 ? N * 2 : N;
public bool IsConst => Special == null && Op <= 1 && Count <= 1;
public bool IsZero => Special == null && V.All(x => x == 0);
public bool IsOne => Special == null && V.All(x => Math.Abs(x - 1) < 1e-9);
public (double[] Min, double[] Max) Range()
{
var mn = Enumerable.Repeat(double.MaxValue, N).ToArray();
var mx = Enumerable.Repeat(double.MinValue, N).ToArray();
if (V.Length == 0) return (new double[N], new double[N]);
for (var i = 0; i + N <= V.Length; i += N)
for (var c = 0; c < N; c++)
{
mn[c] = Math.Min(mn[c], V[i + c]);
mx[c] = Math.Max(mx[c], V[i + c]);
}
return (mn, mx);
}
public JsonNode? Out()
{
if (Special != null) return Special.DeepClone();
if (IsConst) return N == 1 ? AbilityExtractor.N(V.Length > 0 ? V[0] : 0) : Arr(V.Take(N));
var o = new JsonObject { ["op"] = Op, ["n"] = N };
if (Tb != 0) o["tb"] = AbilityExtractor.N(Tb);
o["ts"] = AbilityExtractor.N(Ts);
o["v"] = Arr(V);
if (Lock != 0 && Op >= 2) o["lock"] = Lock;
return o;
}
}
private D? Dist(JObject o, Func get)
{
if (o["Table"] is JObject t && t["Values"] is JArray vals && vals.Count > 0)
{
var d = new D
{
Op = (int?)t["Op"] ?? 1,
Count = (int?)t["EntryCount"] ?? 1,
Tb = (double?)t["TimeBias"] ?? 0,
Ts = (double?)t["TimeScale"] ?? 0,
Lock = (int?)t["LockFlag"] ?? 0,
V = vals.Select(x => (double)x).ToArray(),
};
var stride = (int?)t["EntryStride"] ?? 1;
var sub = (int?)t["SubEntryStride"] ?? 0;
d.N = d.Op >= 2 ? (sub > 0 ? sub : Math.Max(1, stride / 2)) : stride;
if (d.Op <= 1 && d.N == 3 && d.Lock is >= 1 and <= 4)
for (var i = 0; i + 3 <= d.V.Length; i += 3)
switch (d.Lock)
{
case 1: d.V[i + 1] = d.V[i]; break;
case 2: d.V[i + 2] = d.V[i]; break;
case 3: d.V[i + 2] = d.V[i + 1]; break;
case 4: d.V[i + 1] = d.V[i + 2] = d.V[i]; break;
}
return d;
}
// 구워지지 않은 분포 (매개변수 · 곡선): 원본 분포 객체
var dist = get(o["Distribution"]);
if (dist == null) return null;
var dp = Props(dist);
var type = (string?)dist["Type"] ?? "";
double[] Num(JToken? x) => x is JObject v ? [F(v["X"]), F(v["Y"]), F(v["Z"])] : x != null ? [(double)x] : [0];
if (type.EndsWith("Constant")) { var v = Num(dp.GetValueOrDefault("Constant")); return new D { N = v.Length, V = v }; }
if (type.EndsWith("Uniform")) { var a = Num(dp.GetValueOrDefault("Min")); var b = Num(dp.GetValueOrDefault("Max")); return new D { Op = 2, N = a.Length, V = a.Concat(b).ToArray() }; }
if (type.Contains("ParticleParameter"))
{
var c = Num(dp.GetValueOrDefault("Constant"));
return new D { N = c.Length, V = c, Special = new JsonObject { ["param"] = (string?)dp.GetValueOrDefault("ParameterName"), ["default"] = c.Length == 1 ? N(c[0]) : Arr(c) } };
}
if (dp.GetValueOrDefault("ConstantCurve") is JObject cc && cc["Points"] is JArray pts)
{
var arr = new JsonArray();
foreach (var pt in pts) arr.Add(new JsonArray(N(F(pt["InVal"])), pt["OutVal"] is JObject ov ? Arr(F(ov["X"]), F(ov["Y"]), F(ov["Z"])) : N(F(pt["OutVal"]))));
var first = pts.Count > 0 ? Num(pts[0]["OutVal"]) : [0];
return new D { N = first.Length, V = first, Special = new JsonObject { ["curve"] = arr } };
}
return null;
}
// ---------- 재질 ----------
private string? MatKey(string objectPath)
{
if (_matKey.TryGetValue(objectPath, out var k)) return k;
_matKey[objectPath] = null;
UMaterialInterface m;
try { m = provider.LoadPackageObject(objectPath); }
catch { return null; }
var p = MatParams.Resolve(m);
k = UniqueName("mat", objectPath, m.Name);
_matKey[objectPath] = k;
var texFiles = new List();
var e = new JsonObject { ["name"] = m.Name, ["path"] = objectPath[..objectPath.LastIndexOf('.')], ["base"] = p.Base, ["blend"] = p.BlendMode ?? "BLEND_Opaque", ["twoSided"] = p.TwoSided };
if (p.ShadingModel != null) e["shading"] = p.ShadingModel;
var tex = new JsonObject();
foreach (var (n, path) in p.Textures.OrderBy(x => x.Key, StringComparer.Ordinal))
if (TexFile(path) is { } f) { tex[n] = f; texFiles.Add(path); }
var master = Master(p.Base);
if (p.Textures.Count == 0 && master != null)
{
// 인스턴스가 텍스처를 하나도 안 바꾸면 기반 재질이 쓰는 텍스처 (클로브 연막 LUT 처럼 색이 기반 재질에만 있다)
foreach (var (n, path) in master.Value.TexDefaults)
if (TexFile(path) is { } f) { tex[n] = f; texFiles.Add(path); }
var refs = new JsonArray();
foreach (var path in master.Value.Referenced.Where(r => !master.Value.TexDefaults.Values.Contains(r, StringComparer.OrdinalIgnoreCase)))
if (TexFile(path) is { } f) { refs.Add(f); texFiles.Add(path); }
if (refs.Count > 0) e["refTex"] = refs;
}
e["tex"] = tex;
var vec = new JsonObject();
foreach (var (n, c) in p.Vectors.OrderBy(x => x.Key, StringComparer.Ordinal)) vec[n] = Arr(c.R, c.G, c.B, c.A);
e["vec"] = vec;
var sc = new JsonObject();
foreach (var (n, v) in p.Scalars.OrderBy(x => x.Key, StringComparer.Ordinal)) sc[n] = N(v);
e["scalar"] = sc;
var sw = new JsonObject();
foreach (var (n, v) in p.Switches.OrderBy(x => x.Key, StringComparer.Ordinal)) sw[n] = v;
e["switches"] = sw;
_materials[k] = e;
_matTex[k] = texFiles;
return k;
}
private void MarkBig(string matKey)
{
if (!_matTex.TryGetValue(matKey, out var list)) return;
foreach (var t in list)
if (_tex.TryGetValue(t, out var v)) _tex[t] = (v.File, true);
}
private readonly Dictionary TexDefaults, List Referenced)?> _masterInfo = new(StringComparer.OrdinalIgnoreCase);
/// 기반 재질 기본값 (CachedExpressionData: 매개변수 이름 표 + 값 표). masters[경로] 에 쓴다
private (Dictionary TexDefaults, List Referenced)? Master(string basePath)
{
if (string.IsNullOrEmpty(basePath)) return null;
if (_masterInfo.TryGetValue(basePath, out var hit)) return hit;
_masterInfo[basePath] = null;
JObject j;
UMaterial mat;
try
{
mat = provider.LoadPackageObject(basePath);
j = JObject.FromObject(mat, _ser);
}
catch { return null; }
var texDefaults = new Dictionary(StringComparer.OrdinalIgnoreCase);
var referenced = new List();
var o = new JsonObject
{
["blend"] = mat.BlendMode.ToString(),
["twoSided"] = mat.TwoSided,
["shading"] = mat.ShadingModel.ToString(),
};
if (j["CachedExpressionData"] is JObject ced)
{
JArray? Names(int i) => (ced[i == 0 ? "RuntimeEntries" : $"RuntimeEntries[{i}]"]?["ParameterInfoSet"] as JArray);
void Pair(int i, string valuesKey, string outKey, Func conv)
{
var names = Names(i);
var vals = ced[valuesKey] as JArray;
if (names == null || vals == null || names.Count != vals.Count || names.Count == 0) return;
var d = new JsonObject();
for (var k = 0; k < names.Count; k++)
{
var n = (string?)names[k]["Name"];
if (n != null && !d.ContainsKey(n)) d[n] = conv(vals[k]);
}
o[outKey] = d;
}
Pair(0, "ScalarValues", "scalar", v => N((double)v));
Pair(1, "VectorValues", "vec", v => Arr(F(v["R"]), F(v["G"]), F(v["B"]), F(v["A"])));
Pair(7, "StaticSwitchValues", "switches", v => (bool)v);
var tn = Names(3);
if (tn != null && ced["TextureValues"] is JArray tv && tn.Count == tv.Count)
{
var d = new JsonObject();
for (var k = 0; k < tn.Count; k++)
if ((string?)tn[k]["Name"] is { } n && ParseRef(tv[k]) is { Native: false } r)
{
texDefaults[n] = r.ObjectPath;
d[n] = r.Pkg;
}
o["tex"] = d;
}
if (ced["DynamicParameterNames"] is JArray dn) o["dynamicNames"] = new JsonArray(dn.Select(x => (JsonNode?)(string?)x).ToArray());
}
foreach (var t in mat.ReferencedTextures)
if (t?.ResolvedObject?.GetPathName() is { } tp && !referenced.Contains(tp)) referenced.Add(tp);
o["referenced"] = new JsonArray(referenced.Select(x => (JsonNode?)x[..x.LastIndexOf('.')]).ToArray());
_masters[basePath] = o;
var res = (texDefaults, referenced);
_masterInfo[basePath] = res;
return res;
}
// ---------- 텍스처 ----------
private string? TexFile(string objectPath)
{
if (string.IsNullOrEmpty(objectPath)) return null;
if (_tex.TryGetValue(objectPath, out var v)) return v.File;
var name = objectPath[(objectPath.LastIndexOf('.') + 1)..];
var file = "t_" + UniqueName("tex", objectPath, name) + ".png";
_tex[objectPath] = (file, false);
return file;
}
private void ExportTextures()
{
foreach (var (path, (file, big)) in _tex.OrderBy(x => x.Value.File, StringComparer.Ordinal))
{
try
{
var t = provider.LoadPackageObject(path);
var w = t is UTexture2D t2 ? t2.PlatformData?.SizeX ?? 0 : 0;
var h = t is UTexture2D t3 ? t3.PlatformData?.SizeY ?? 0 : 0;
var lut = path.Contains("LUT", StringComparison.OrdinalIgnoreCase) || Math.Min(w, h) is > 0 and <= 16;
var max = big || lut ? Math.Max(_texMax, BigTex) : _texMax;
var c = t.Decode(max);
using var img = c == null ? null : ToImage(c);
if (img == null) { _texFail++; Console.Error.WriteLine($" 텍스처 형식 못 읽음 {path} ({c?.PixelFormat.ToString() ?? t.ExportType})"); continue; }
if (img.Width > max || img.Height > max)
img.Mutate(x => x.Resize(new ResizeOptions { Size = new Size(max, max), Mode = ResizeMode.Max }));
img.SaveAsPng(Path.Combine(outDir, file), new PngEncoder { CompressionLevel = PngCompressionLevel.BestCompression });
_texOk++;
}
catch (Exception e)
{
_texFail++;
Console.Error.WriteLine($" 텍스처 실패 {path}: {e.GetType().Name} {e.Message}");
}
}
}
internal static Image? ToImage(CTexture c)
{
var d = c.Data;
var n = c.Width * c.Height;
switch (c.PixelFormat)
{
case EPixelFormat.PF_R8G8B8A8:
return d.Length >= n * 4 ? Image.LoadPixelData(d.AsSpan(0, n * 4), c.Width, c.Height) : null;
case EPixelFormat.PF_B8G8R8A8:
return d.Length >= n * 4 ? Image.LoadPixelData(d.AsSpan(0, n * 4), c.Width, c.Height).CloneAs() : null;
case EPixelFormat.PF_G8:
return d.Length >= n ? Image.LoadPixelData(d.AsSpan(0, n), c.Width, c.Height).CloneAs() : null;
case EPixelFormat.PF_FloatRGBA:
{
// HDR (half float) → 0~1 로 자름
if (d.Length < n * 8) return null;
var px = new Rgba32[n];
for (var i = 0; i < n; i++)
{
byte H(int k) => (byte)Math.Clamp((int)Math.Round((float)BitConverter.ToHalf(d, i * 8 + k * 2) * 255f), 0, 255);
px[i] = new Rgba32(H(0), H(1), H(2), H(3));
}
return Image.LoadPixelData(px, c.Width, c.Height);
}
case EPixelFormat.PF_R16F:
{
if (d.Length < n * 2) return null;
var px = new L8[n];
for (var i = 0; i < n; i++) px[i] = new L8((byte)Math.Clamp((int)Math.Round((float)BitConverter.ToHalf(d, i * 2) * 255f), 0, 255));
return Image.LoadPixelData(px, c.Width, c.Height).CloneAs();
}
case EPixelFormat.PF_G16:
{
if (d.Length < n * 2) return null;
var px = new L8[n];
for (var i = 0; i < n; i++) px[i] = new L8((byte)(BitConverter.ToUInt16(d, i * 2) >> 8));
return Image.LoadPixelData(px, c.Width, c.Height).CloneAs();
}
default:
return null;
}
}
// ---------- 메시 (glb) ----------
private readonly Dictionary Mats)> _meshInfo = new(StringComparer.OrdinalIgnoreCase);
/// 메시 → m_이름.glb (한 번만). 삼각형 5천 개 이하인 가장 자세한 LOD (없으면 가장 가벼운 LOD)
private string? MeshFile(string objectPath, out bool skeletal, out List slotMats)
{
skeletal = false;
slotMats = [];
if (_meshFile.TryGetValue(objectPath, out var f))
{
if (_meshInfo.TryGetValue(objectPath, out var inf)) { skeletal = inf.Skeletal; slotMats = inf.Mats; }
return f;
}
_meshFile[objectPath] = null;
try
{
var o = provider.LoadPackageObject(objectPath);
var name = "m_" + UniqueName("mesh", objectPath, o.Name) + ".glb";
var glb = new Glb();
var tex = new TexStore(provider, glb, _texMax);
var prims = new JsonArray();
List mats;
if (o is UStaticMesh sm)
{
var lods = sm.RenderData?.LODs?.Where(l => !l.SkipLod && l.PositionVertexBuffer?.Verts is { Length: > 0 } && l.IndexBuffer?.Buffer is { Length: > 0 }).ToList() ?? [];
if (lods.Count == 0) throw new InvalidDataException("LOD 없음");
var lod = lods.FirstOrDefault(l => l.Sections.Sum(s => s.NumTriangles) <= TriBudget) ?? lods[^1];
var verts = lod.PositionVertexBuffer!.Verts;
var pos = new float[verts.Length * 3];
var nrm = new float[verts.Length * 3];
var uv = new float[verts.Length * 2];
var uvItems = lod.VertexBuffer?.UV;
for (var i = 0; i < verts.Length; i++)
{
pos[i * 3] = verts[i].X; pos[i * 3 + 1] = verts[i].Y; pos[i * 3 + 2] = verts[i].Z;
var it = uvItems != null && i < uvItems.Length ? uvItems[i] : null;
var n = it?.Normal is { Length: >= 3 } nn ? (FVector)nn[2] : new FVector(0, 0, 1);
nrm[i * 3] = n.X; nrm[i * 3 + 1] = n.Y; nrm[i * 3 + 2] = n.Z;
if (it?.UV is { Length: > 0 } uu) { uv[i * 2] = uu[0].U; uv[i * 2 + 1] = uu[0].V; }
}
mats = sm.StaticMaterials.Select(x => x.MaterialInterface is { IsNull: false } mi && mi.ResolvedObject?.GetPathName() is { } mp ? MatKey(mp) : null).ToList();
var ib = lod.IndexBuffer!.Buffer!;
var secs = lod.Sections.Select(s => (s.FirstIndex, s.NumTriangles, s.MaterialIndex)).ToList();
AddPrims(glb, tex, prims, pos, nrm, uv, i => (uint)ib[i], secs, mats);
}
else if (o is USkeletalMesh sk)
{
skeletal = true;
var dto = new SkeletalMeshDto(sk, EMeshQuality.All);
var lods = dto.LODs.Where(l => l.Vertices.Length > 0 && l.Indices.Length > 0).ToList();
if (lods.Count == 0) throw new InvalidDataException("LOD 없음");
var lod = lods.FirstOrDefault(l => l.Indices.Length / 3 <= TriBudget) ?? lods[^1];
var vs = lod.Vertices;
var pos = new float[vs.Length * 3];
var nrm = new float[vs.Length * 3];
var uv = new float[vs.Length * 2];
for (var i = 0; i < vs.Length; i++)
{
var v = vs[i];
pos[i * 3] = v.Position.X; pos[i * 3 + 1] = v.Position.Y; pos[i * 3 + 2] = v.Position.Z;
var n = new FVector(v.Normal.X, v.Normal.Y, v.Normal.Z);
if (n.Size() > 1e-6f) n /= n.Size();
nrm[i * 3] = n.X; nrm[i * 3 + 1] = n.Y; nrm[i * 3 + 2] = n.Z;
uv[i * 2] = v.Uv.U; uv[i * 2 + 1] = v.Uv.V;
}
mats = dto.Materials.Select(x => x.Material is { IsNull: false } mi && mi.ResolvedObject?.GetPathName() is { } mp ? MatKey(mp) : null).ToList();
var idx = lod.Indices;
var secs = lod.Sections.Where(s => s.IsValid && s.NumFaces > 0).Select(s => (s.FirstIndex, s.NumFaces, s.MaterialIndex)).ToList();
AddPrims(glb, tex, prims, pos, nrm, uv, i => idx[i], secs, mats);
}
else throw new InvalidDataException("메시 아님 " + o.ExportType);
glb.Meshes.Add(new JsonObject { ["name"] = o.Name, ["primitives"] = prims });
glb.Nodes.Add(new JsonObject { ["name"] = o.Name, ["mesh"] = 0 });
glb.Write(Path.Combine(outDir, name));
_meshFile[objectPath] = name;
_meshInfo[objectPath] = (skeletal, mats);
slotMats = mats;
return name;
}
catch (Exception e)
{
_meshFail++;
Console.Error.WriteLine($" 메시 실패 {objectPath}: {e.GetType().Name} {e.Message}");
return null;
}
}
private static readonly string[] MainTexNames = ["Diffuse", "DF", "Albedo", "Base Color", "BaseColor", "Diffuse A", "Diffuse Texture", "DiffuseTexture", "Color", "Texture", "MainTexture"];
private void AddPrims(Glb glb, TexStore tex, JsonArray prims, float[] pos, float[] nrm, float[] uv, Func index, List<(int First, int Tris, int Mat)> secs, List mats)
{
var aPos = glb.Floats(pos, 3, bounds: true);
var aNrm = glb.Floats(nrm, 3);
var aUv = glb.Floats(uv, 2);
var matIdx = new Dictionary();
foreach (var (first, tris, mi) in secs)
{
if (!matIdx.TryGetValue(mi, out var gm))
{
var key = mi < mats.Count ? mats[mi] : null;
var me = key != null ? _materials[key] as JsonObject : null;
var pbr = new JsonObject { ["metallicFactor"] = 0.1, ["roughnessFactor"] = 0.7 };
string? main = null;
if (me?["tex"] is JsonObject tx)
{
main = MainTexNames.Select(n => (string?)tx[n]).FirstOrDefault(x => x != null)
?? tx.Select(kv => (string?)kv.Value).FirstOrDefault(v => v != null && Regex.IsMatch(v, @"_(DF|D|BaseColor|Albedo)(_|\.|\d)", RegexOptions.IgnoreCase));
}
var texPath = main == null ? null : _tex.FirstOrDefault(kv => kv.Value.File == main).Key;
if (tex.Get(texPath) is { } tt) pbr["baseColorTexture"] = new JsonObject { ["index"] = tt.tex };
var gmat = new JsonObject { ["name"] = key ?? "none", ["pbrMetallicRoughness"] = pbr, ["extras"] = new JsonObject { ["mat"] = key } };
var blend = (string?)me?["blend"];
if (blend is "BLEND_Translucent" or "BLEND_Additive" or "BLEND_Modulate") gmat["alphaMode"] = "BLEND";
else if (blend == "BLEND_Masked") { gmat["alphaMode"] = "MASK"; gmat["alphaCutoff"] = 0.333; }
if ((bool?)me?["twoSided"] == true) gmat["doubleSided"] = true;
glb.Materials.Add(gmat);
matIdx[mi] = gm = glb.Materials.Count - 1;
}
var idx = new uint[tris * 3];
for (var f = 0; f < tris; f++)
{
idx[f * 3] = index(first + f * 3);
idx[f * 3 + 1] = index(first + f * 3 + 2);
idx[f * 3 + 2] = index(first + f * 3 + 1);
}
prims.Add(new JsonObject
{
["attributes"] = new JsonObject { ["POSITION"] = aPos, ["NORMAL"] = aNrm, ["TEXCOORD_0"] = aUv },
["indices"] = glb.Indices(idx),
["material"] = gm,
});
}
}
// ---------- 이름 · 숫자 ----------
private string UniqueName(string kind, string path, string name)
{
if (!_usedNames.TryGetValue(kind, out var used)) _usedNames[kind] = used = new HashSet(StringComparer.OrdinalIgnoreCase);
var safe = Regex.Replace(name, @"[^A-Za-z0-9_\-]", "_");
var r = safe;
for (var i = 2; !used.Add(r); i++) r = safe + "_" + i;
return r;
}
internal static JsonNode N(double v)
{
if (double.IsNaN(v) || double.IsInfinity(v)) return JsonValue.Create(0.0);
if (Math.Abs(v) < 1e-7) return JsonValue.Create(0.0);
return JsonValue.Create(double.Parse(v.ToString("G6", CultureInfo.InvariantCulture), CultureInfo.InvariantCulture));
}
internal static JsonArray Arr(params double[] v) => new(v.Select(x => (JsonNode?)N(x)).ToArray());
internal static JsonArray Arr(IEnumerable v) => new(v.Select(x => (JsonNode?)N(x)).ToArray());
private static JsonArray V3(FVector v) => Arr(v.X, v.Y, v.Z);
}
]