diff --git a/docs/dev/replay-3d.md b/docs/dev/replay-3d.md index ac3a3ae..3628b59 100644 --- a/docs/dev/replay-3d.md +++ b/docs/dev/replay-3d.md @@ -37,6 +37,20 @@ - 재생기: 카메라 위에서 / 1인칭(고른 선수 눈 + 60cm, pitch) / 자유시점(WASD · Q/E · Shift, 끌어서 둘러보기). 요원은 이동 방향 · 속도로 아래 몸 애니메이션을 섞는다. 스킬은 `lib/abilities.ts` 가 클래스 이름으로 연막(요원 색 구) · 장판 · 폭발 · 정찰 고리 · 설치물 · 스파이크로 나눈다. - 한계: 스킬 효과(파티클) · 벽 스킬 방향 · 앉기 · 점프 자세 · 스킨은 없다. 리플레이 위치는 10Hz 라 빠른 움직임은 보간이다. +## 스킬 효과 (2026-10-18, 실감 2단계) +- 추출: `gvr-map-extract abilities <폴더>` (`src/Abilities.cs`) → `abilities.json` + `m_*.glb`(스킬 · 투사체 · 설치물 메시, 파티클 메시) + `t_*.png`(256px, 큰 것 512px). 13.08 전체: 스킬 클래스 217 · 파티클 시스템 520 · 메시 373 · 텍스처 1054, 받은 양 341MB · 3.9분 · 최대 메모리 1.7GB, gzip 합계 약 40MB (json 0.8MB). + - 발로란트 효과는 전부 Cascade `ParticleSystem` 이다 (Niagara 0개). 이미터마다 모양(sprite · mesh · decal · ribbon) · 재질 · 분포 표(구운 FRawDistribution) 를 그대로 옮긴다. 형식 설명은 `Abilities.cs` 머리말. + - 클래스(리플레이 objectKinds) → 블루프린트 → FXC 효과 묶음 · 패치 · 투사체 컴포넌트에서 역할(loop · intro · outro · warn · trail · explode · patch · decal) 별 시스템(아군 · 적 따로). + - `update.sh` 가 맵 · 요원 · 애니메이션 다음에 돌리고 `pack.py` 가 `abilities/` 를 gzip 해 index.json `abilities` 로 올린다. +- 사이트 `lib/vfx.ts`: 입자 상태를 "켜진 뒤 지난 시간" 만으로 계산 (입자마다 고정 난수) → 되감기 · 배속에도 같은 장면. 이미터 종류별로 인스턴스 사각형 · 인스턴스 메시 · 바닥에 눕힌 사각형 · 지나간 길(리본). + - 재질 그래프는 쿡된 파일에 없다(매개변수 · 텍스처만). 이름 점수로 색 · 알파 텍스처를 고르고, 텍스처 채널 상관으로 색 그림 · 흑백/묶음 마스크(R)를 가린다. UE 반투명처럼 (HDR 색 × 불투명도) 를 미리 곱한 알파로 더하고 채널마다 0.8 위를 눌러 불꽃이 주황 · 노랑이 된다. + - 연막 돔(불투명 · 마스크 큰 구)은 요원별 색(`DOME`) + noise + 가장자리 빛(게임 팀 색). 돔 위 반투명 층은 돔 색으로 옅게. + - 장판(CellularPatch): 게임처럼 반지름 안 칸마다 불 효과 하나, 가운데서 SpreadSpeed 로 번진다. 그을음은 반지름 크기. + - 뺀 것: 벽 너머 표시 · HUD · 1인칭 · 사거리 표시 · 팀 구별 층(FoF) · beam · 화면 아이콘 메시. 데이터가 예상과 다른 이미터는 그 이미터만 끈다. + - 효과가 없는 클래스는 예전 종류별 모양, 날아가는 모습이 없는 투사체(요루 섬광 등)는 예전 빛 구 + 터지는 효과. 요루 분신 · 스파이크는 원래 그리던 것 + 효과. +- 개발 확인: 효과 하나만 따로 그리는 판(`~/.tmp/gvr/vfxHarness.ts` 를 `site/web/src/dev/` 에 잠시 두고 vite dev 에서 `import('/src/dev/vfxHarness.ts')`). 저장소에는 넣지 않았다. +- 한계: 재질 그래프 근사라 색 · 무늬가 게임과 조금 다르다. 리본 · beam 일부, 화면 효과(섬광 눈부심 등)는 없다. 오멘 연막처럼 추출기가 클래스를 못 찾은 것은 예전 모양. + ## 남은 일 - 실제 경기로 동기화 오차 확인 (사이트 아래 줄 "킬 N개로 맞춤 (최대 오차 X초)") diff --git a/site/server/src/maps3d.ts b/site/server/src/maps3d.ts index 7f16b18..568c68b 100644 --- a/site/server/src/maps3d.ts +++ b/site/server/src/maps3d.ts @@ -9,9 +9,10 @@ import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'; * * /maps3d/index.json {version, dir, updatedAt, maps:{<맵 경로>:{code,file,bytes,triangles}}} * /maps3d//.glb.gz meshopt 압축 glb 를 gzip 한 것. 위치는 UE 월드 좌표(cm) + * /maps3d//abilities.json.gz · m_*.glb.gz · t_*.png.gz 스킬 목록 · 모델 · 텍스처 (모두 gzip) * * GET /site/maps3d → index.json (없으면 {maps:{}}) - * GET /site/maps3d/:dir/:f → glb (content-encoding gzip). 폴더 이름이 패치마다 바뀌므로 오래 캐시한다 + * GET /site/maps3d/:dir/:f → glb · json · png · jpg (content-encoding gzip). 폴더 이름이 패치마다 바뀌므로 오래 캐시한다 */ export interface Maps3dIndex { version: string; @@ -20,6 +21,9 @@ export interface Maps3dIndex { maps: Record; } +/** 보내는 파일 종류: 3D (맵 · 요원 · 무기 · 스킬 모델 · 공용 애니메이션) · 스킬 목록 · 스킬 텍스처 */ +const TYPES: Record = { '.glb': 'model/gltf-binary', '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg' }; + export function registerMaps3d(app: FastifyInstance, dataDir: string, requireSession: (req: FastifyRequest, reply: FastifyReply) => Promise) { const root = path.join(dataDir, 'maps3d'); let cache: { mtime: number; data: Maps3dIndex | null } = { mtime: -1, data: null }; @@ -50,10 +54,11 @@ export function registerMaps3d(app: FastifyInstance, dataDir: string, requireSes app.get<{ Params: { dir: string; file: string } }>('/site/maps3d/:dir/:file', async (req, reply) => { if (!(await requireSession(req, reply))) return; const { dir, file } = req.params; - if (!/^[\w.-]+$/.test(dir) || !/^[\w.-]+\.glb$/.test(file) || dir.includes('..')) return reply.code(404).send({ error: 'not_found' }); + const type = TYPES[path.extname(file).toLowerCase()]; + if (!/^[\w.-]+$/.test(dir) || !/^[\w.-]+$/.test(file) || !type || dir.includes('..')) return reply.code(404).send({ error: 'not_found' }); const gz = path.join(root, dir, file + '.gz'); if (!fs.existsSync(gz)) return reply.code(404).send({ error: 'not_found' }); - reply.header('cache-control', 'private, max-age=31536000, immutable').type('model/gltf-binary'); + reply.header('cache-control', 'private, max-age=31536000, immutable').type(type); if (/\bgzip\b/.test(String(req.headers['accept-encoding'] ?? ''))) { reply.header('content-encoding', 'gzip').header('content-length', fs.statSync(gz).size); return reply.send(fs.createReadStream(gz)); diff --git a/site/server/test/maps3d.test.ts b/site/server/test/maps3d.test.ts index 3b1ce0b..716c486 100644 --- a/site/server/test/maps3d.test.ts +++ b/site/server/test/maps3d.test.ts @@ -38,6 +38,9 @@ async function stack() { const dir = path.join(cfg.dataDir, 'maps3d', 'V1-1'); fs.mkdirSync(dir, { recursive: true }); fs.writeFileSync(path.join(dir, 'Ascent.glb.gz'), zlib.gzipSync(Buffer.from('glTF-test'))); + fs.writeFileSync(path.join(dir, 'abilities.json.gz'), zlib.gzipSync(Buffer.from('{"classes":{}}'))); + fs.writeFileSync(path.join(dir, 't_Smoke.png.gz'), zlib.gzipSync(Buffer.from('png-test'))); + fs.writeFileSync(path.join(dir, 'secret.txt.gz'), zlib.gzipSync(Buffer.from('no'))); fs.writeFileSync(path.join(cfg.dataDir, 'maps3d', 'index.json'), JSON.stringify({ version: 'V1', dir: 'V1-1', updatedAt: 'x', maps: { '/Game/Maps/Ascent/Ascent': { code: 'Ascent', file: 'Ascent.glb', bytes: 1, triangles: 1 } } })); const { app, store } = await buildServer(cfg); await app.listen({ host: '127.0.0.1', port: 0 }); @@ -72,6 +75,16 @@ test('맵 3D: 로그인하면 목록과 glb 를 받는다 (gzip), 이상한 경 assert.equal(r.status, 200); assert.equal(r.headers.get('content-encoding'), 'gzip'); assert.equal(await r.text(), 'glTF-test'); // fetch 가 gzip 을 풀어 준다 + // 스킬 목록 · 텍스처도 같은 폴더에서 (gzip, 종류에 맞는 content-type) + const j = await fetch(s.base + '/site/maps3d/V1-1/abilities.json', { headers: { cookie, 'accept-encoding': 'gzip' } }); + assert.equal(j.status, 200); + assert.match(j.headers.get('content-type') ?? '', /application\/json/); + assert.deepEqual(await j.json(), { classes: {} }); + const t = await fetch(s.base + '/site/maps3d/V1-1/t_Smoke.png', { headers: { cookie, 'accept-encoding': 'gzip' } }); + assert.equal(t.status, 200); + assert.equal(t.headers.get('content-type'), 'image/png'); + // 정해진 종류(glb · json · png · jpg)가 아니면 404 + assert.equal((await fetch(s.base + '/site/maps3d/V1-1/secret.txt', { headers: { cookie } })).status, 404); assert.equal((await fetch(s.base + '/site/maps3d/V1-1/..%2Findex.json', { headers: { cookie } })).status, 404); assert.equal((await fetch(s.base + '/site/maps3d/V1-1/Nope.glb', { headers: { cookie } })).status, 404); } finally { diff --git a/site/web/mock/server.mjs b/site/web/mock/server.mjs index 5b412b8..897337b 100644 --- a/site/web/mock/server.mjs +++ b/site/web/mock/server.mjs @@ -202,8 +202,9 @@ async function handle(req, res) { if (p === '/site/maps3d') return json(res, 200, JSON.parse(fs.readFileSync(path.join(root, 'index.json'), 'utf8'))); const [dir, file] = p.slice('/site/maps3d/'.length).split('/').map(decodeURIComponent); const f = path.join(root, dir ?? '', (file ?? '') + '.gz'); - if (!/^[\w.-]+$/.test(dir ?? '') || !/^[\w.-]+\.glb$/.test(file ?? '') || !fs.existsSync(f)) return json(res, 404, { error: 'not_found' }); - res.writeHead(200, { 'content-type': 'model/gltf-binary', 'content-encoding': 'gzip', 'content-length': fs.statSync(f).size }); + const type = { '.glb': 'model/gltf-binary', '.json': 'application/json', '.png': 'image/png', '.jpg': 'image/jpeg' }[path.extname(file ?? '').toLowerCase()]; + if (!/^[\w.-]+$/.test(dir ?? '') || !/^[\w.-]+$/.test(file ?? '') || !type || !fs.existsSync(f)) return json(res, 404, { error: 'not_found' }); + res.writeHead(200, { 'content-type': type, 'content-encoding': 'gzip', 'content-length': fs.statSync(f).size }); return fs.createReadStream(f).pipe(res); } diff --git a/site/web/src/components/ReplayViewer.tsx b/site/web/src/components/ReplayViewer.tsx index d405f11..d23b487 100644 --- a/site/web/src/components/ReplayViewer.tsx +++ b/site/web/src/components/ReplayViewer.tsx @@ -11,6 +11,7 @@ import { findMap3d, loadMap3d, mapMaterial, worldMatrix } from '../lib/map3d'; import { AgentRig, isGun, loadAgent, loadAnims, loadWeapon } from '../lib/agents3d'; import { buildAnimIndex, rigInput } from '../lib/replayAnim'; import { abilityLook, type AbilityLook } from '../lib/abilities'; +import { loadVfxDb, vfxCoverage, VfxObject, type Place, type VfxDb } from '../lib/vfx'; /** * 3D 리플레이 (발로란트 .vrf → tools/replay-extract → gvr-replay JSON). @@ -472,6 +473,40 @@ export default function ReplayViewer({ m, replay, sync }: Props) { }; // 움직이는 스킬 경로 (투사체 · 드론 · 분신): objects 번호 → 경로 const pathOf = new Map((replay.objectPaths ?? []).map((p) => [p.o, p])); + // 게임 파일 스킬 효과 (lib/vfx.ts: 메시 · 파티클). 받으면 종류별 모양 대신 쓴다. + // 요루 분신 · 스파이크는 지금 그리는 것(요원 몸 애니메이션 · 스파이크 3D)을 두고 효과만 더한다 + let vfxDb: VfxDb | null = null; + let vfxKinds: ('full' | 'partial' | 'none')[] = []; + const vfxObjs = new Map(); + const vfxGroup = new THREE.Group(); + agentsGroup.add(vfxGroup); + void loadVfxDb().then((db) => { + if (!db || disposed) return; + vfxDb = db; + vfxKinds = replay.objectKinds.map((k) => vfxCoverage(db, k)); + }); + const KEEP_OWN = /^(Pawn_Stealth_4_Decoy|TimedBomb_C)/; + const camUE = new THREE.Vector3(); + const invAgents = new THREE.Matrix4(); + const deg = (r: number) => (r * 180) / Math.PI; + const placeOf = (i: number) => { + const o = replay.objects[i]; + const path = pathOf.get(i); + const still: Place = { x: o[3], y: o[4], z: o[5], yaw: o[7] ?? 0, pitch: 0 }; + if (!path || path.t.length < 2) return { at: (_t: number) => still, speed: 0 }; + const n = path.t.length; + const dist = path.x.slice(1).reduce((d, x, k) => d + Math.hypot(x - path.x[k], path.y[k + 1] - path.y[k], path.z[k + 1] - path.z[k]), 0); + const speed = dist / Math.max(0.05, (path.t[n - 1] - path.t[0]) / 1000); + return { + speed, + at: (tMs: number): Place => { + const pp = samplePath(path, Math.max(path.t[0], Math.min(path.t[n - 1], tMs))); + if (!pp) return still; + const h = Math.hypot(pp.vx, pp.vy); + return { x: pp.x, y: pp.y, z: pp.z, yaw: pp.yaw ?? (h > 1 ? deg(Math.atan2(pp.vy, pp.vx)) : still.yaw), pitch: h > 1 || Math.abs(pp.vz) > 1 ? deg(Math.atan2(pp.vz, h)) : 0 }; + }, + }; + }; const setOpacity = (ov: ObjView, k: number) => { for (const m of ov.mats) { const base = (m.userData.baseOpacity ??= m.opacity) as number; @@ -722,10 +757,33 @@ export default function ReplayViewer({ m, replay, sync }: Props) { } } // 스킬 · 설치물: 생긴 뒤 사라질 때까지 (모르면 종류별 기본 시간). 날아가는 것은 던진 자리에 잠깐만 + invAgents.copy(agentsGroup.matrixWorld).invert(); + camUE.copy(camera.position).applyMatrix4(invAgents); for (let i = 0; i < replay.objects.length; i++) { const [t0, t1, kind] = replay.objects[i]; const ov0 = objViews.get(i); const end = ov0 ? ov0.end : t1 >= t0 ? t1 : t0 + abilityLook(replay.objectKinds[kind] ?? '').defaultMs; + if (vfxDb && vfxKinds[kind] && vfxKinds[kind] !== 'none') { + const cls = replay.objectKinds[kind] ?? ''; + const own = KEEP_OWN.test(cls) || vfxKinds[kind] === 'partial'; + let vo = vfxObjs.get(i); + const near = t >= t0 - 100 && t <= end + 6000; + if (near && !vo) { + const pl = placeOf(i); + const owner = replay.objects[i][6]; + vo = new VfxObject(vfxDb, { cls, t0, end, team: roster[owner]?.ally ? 'ally' : 'enemy', projectile: /^Projectile_/.test(cls), placeAt: pl.at, speed: pl.speed }, vfxGroup, i + 1, !own); + vfxObjs.set(i, vo); + } else if (!near && vo) { + vo.dispose(); + vfxObjs.delete(i); + vo = undefined; + } + vo?.update(t, camUE); + if (!own) { + if (ov0) ov0.obj.visible = false; + continue; + } + } const on = t >= t0 && t <= end; if (!on) { if (ov0) { @@ -829,6 +887,7 @@ export default function ReplayViewer({ m, replay, sync }: Props) { renderer.domElement.removeEventListener('blur', onBlur); controls.dispose(); for (const v of views) v.rig?.dispose(); + for (const vo of vfxObjs.values()) vo.dispose(); scene.traverse((o) => { const mesh = o as THREE.Mesh; mesh.geometry?.dispose?.(); diff --git a/site/web/src/lib/vfx.ts b/site/web/src/lib/vfx.ts new file mode 100644 index 0000000..c4cb417 --- /dev/null +++ b/site/web/src/lib/vfx.ts @@ -0,0 +1,1824 @@ +import * as THREE from 'three'; +import { GLTFLoader, type GLTF } from 'three/examples/jsm/loaders/GLTFLoader.js'; +import { MeshoptDecoder } from 'three/examples/jsm/libs/meshopt_decoder.module.js'; +import { loadIndex } from './map3d'; + +/** + * 스킬 효과 재생기: 게임 파일에서 뽑은 스킬 재료(tools/map-extract abilities → abilities.json + m_*.glb + t_*.png)로 + * 발로란트의 Cascade 파티클 시스템을 three.js 로 다시 그린다. + * + * - 입자 상태는 "시스템이 켜진 뒤 지난 시간" 만으로 계산한다 (매 프레임 쌓지 않음) → 되감기 · 배속 · 건너뛰기에도 같은 장면. + * 입자마다 고정 난수(이미터 · 생성 번호 해시)를 쓰므로 같은 시각이면 언제나 같은 모양이다. + * - 이미터 종류: sprite(카메라를 보는 사각형, SubUV 플립북) · mesh(입자 하나 = 메시 하나, 연막 돔 등) · decal(바닥에 눕힌 사각형) · ribbon(지나간 길). + * - 재질 그래프는 쿡된 파일에 없어서(텍스처 · 색 · 숫자 매개변수만 있다) 이름으로 고른 색 · 알파 텍스처 + 흐름(스크롤) + 입자 색으로 근사한다. + * 크게 보이는 연막 돔은 요원별 색으로 따로 칠한다 (noise 텍스처 + 가장자리 빛, 적이면 붉은 테두리). + * 좌표는 게임(UE) 그대로(cm, Z 위) — 뷰어의 UE 좌표 묶음(agentsGroup)에 넣는다. + */ + +// ---------- abilities.json 형식 (tools/map-extract/src/Abilities.cs) ---------- +/** 구운 분포 표: x = max(0,(t - tb) * ts), 항목 i · i+1 을 섞는다. op 1 값 · 2 최소/최대 난수 · 3 최소나 최대 */ +export interface Tab { + op: 1 | 2 | 3; + n: number; + tb?: number; + ts?: number; + v: number[]; + lock?: number; +} +type Num = number | Tab; + +export interface VEmitter { + name: string; + type: 'sprite' | 'mesh' | 'decal' | 'ribbon' | 'beam'; + material: string; + mesh?: string; + meshMaterials?: string[]; + subUV: [number, number]; + subUVMode?: string; + subUVIndex?: Num; + subUVMovie?: { fps: number; start: number }; + delay: number; + duration: number; + loops: number; + local: boolean; + screenAlign?: string; + axisLock?: string; + killOnDeactivate?: boolean; + spawnRate?: Num; + rateScale?: Num; + bursts?: [number, number][]; + spawnPerUnit?: { n: number; unit: number }; + life?: [number, number]; + lifeT?: Tab; + size?: number[][]; + sizeT?: Tab; + sizeLife?: Tab; + sizeScale?: Num | number[]; + color?: number[]; + colorT?: Tab; + alpha?: [number, number]; + alphaT?: Tab; + colorLife?: Tab | number[]; + alphaLife?: Num; + colorScaleLife?: Num | number[]; + alphaScaleLife?: Num; + colorScaleEmitterTime?: boolean; + vel?: number[][]; + velT?: Tab; + velLife?: Num; + velRadial?: [number, number]; + velRadialT?: Tab; + velCone?: { angle: Num; speed: Num; dir: number[] }; + accel?: number[]; + accelT?: Tab; + drag?: [number, number]; + dragT?: Tab; + locBox?: number[][]; + locBoxT?: Tab; + locSphere?: { + r: number[]; + center: number[]; + surface: boolean; + vel: boolean; + velScale: number; + }; + locCylinder?: { + r: number[]; + h: number[]; + surface: boolean; + vel: boolean; + velScale: number; + radialVel: boolean; + }; + orbit?: { offset: number[][]; rot: number[][]; rotRate: number[][] }; + rot?: [number, number]; + rotT?: Tab; + rotRate?: [number, number]; + rotRateT?: Tab; + meshRot?: number[][]; + meshRotT?: Tab; + meshRotRate?: number[][]; + meshRotRateT?: Tab; + teamColor?: { ally: number[]; enemy: number[]; param: string }; + emitterRot?: number[]; + ribbon?: Record; +} + +export interface VSystem { + path: string; + emitters: VEmitter[]; +} + +export interface VMaterial { + name: string; + path?: string; + base?: string; + blend: string; + twoSided?: boolean; + tex: Record; + vec: Record; + scalar: Record; + refTex?: string[]; +} + +export interface VMaster { + blend?: string; + tex?: Record; + vec?: Record; + scalar?: Record; +} + +export interface VFx { + role: string; + ally: string | null; + enemy: string | null; + scale: number | number[]; + pos: number[]; + rot?: number[]; + src?: string; + auto?: boolean; + hidden?: boolean; +} + +export interface VClass { + agent: string; + blueprint: string; + meshes: { + name: string; + file: string; + pos: number[]; + rot: number[]; + scale: number[]; + skeletal: boolean; + materials?: string[]; + }[]; + fx: VFx[]; + params: Record; + native?: string; +} + +export interface VfxDb { + dir: string; + classes: Record; + systems: Record; + materials: Record; + masters: Record; + /** 내보낸 텍스처 파일 이름 (t_*.png) */ + files: Set; +} + +let dbP: Promise | null = null; +/** 스킬 재료. 옛 index(abilities 없음)나 실패면 null */ +export function loadVfxDb(): Promise { + dbP ??= (async () => { + const idx = await loadIndex(); + if (!idx?.dir || !idx.abilities) return null; + const r = await fetch(assetPath(idx.dir, idx.abilities.file), { + credentials: 'same-origin', + }); + if (!r.ok) throw new Error(`abilities ${r.status}`); + const d = (await r.json()) as Omit; + const files = new Set(); + for (const m of Object.values(d.materials)) { + for (const f of Object.values(m.tex ?? {})) files.add(f); + for (const f of m.refTex ?? []) files.add(f); + } + return { ...d, dir: idx.dir, files }; + })().catch(() => { + dbP = null; + return null; + }); + return dbP; +} + +function assetPath(dir: string, file: string) { + return `/site/maps3d/${encodeURIComponent(dir)}/${encodeURIComponent(file)}`; +} + +// ---------- 난수 · 분포 표 ---------- +/** 정수 둘 → 0~1 (같은 입력이면 같은 값) */ +function hash01(a: number, b: number): number { + let h = Math.imul(a ^ 0x9e3779b9, 0x85ebca6b) ^ Math.imul(b + 0x7f4a7c15, 0xc2b2ae35); + h ^= h >>> 15; + h = Math.imul(h, 0x2c1b3c6d); + h ^= h >>> 12; + h = Math.imul(h, 0x297a2d39); + h ^= h >>> 15; + return (h >>> 0) / 4294967296; +} + +/** 표 t 시점 값 (n 개). r: 입자 난수 3개 (op 2 · 3) */ +function evTab(tab: Tab, t: number, r: readonly number[], out: number[] = []): number[] { + const cv = (tab as unknown as { curve?: number[][] }).curve; + if (cv) { + // 굽지 않은 곡선 [[t, 값], ...]: 직선으로 잇는다 + let v = cv[0]?.[1] ?? 0; + for (let i = 0; i < cv.length; i++) { + if (t <= cv[i][0]) { + const a = cv[i - 1]; + v = a ? a[1] + ((cv[i][1] - a[1]) * (t - a[0])) / (cv[i][0] - a[0] || 1) : cv[i][1]; + break; + } + v = cv[i][1]; + } + out[0] = v; + out.length = 1; + return out; + } + const n = tab.n; + const per = tab.op === 1 ? n : n * 2; + const entries = Math.max(1, Math.floor(tab.v.length / per)); + const x = Math.max(0, (t - (tab.tb ?? 0)) * (tab.ts ?? 0)); + const i = Math.min(Math.floor(x), entries - 1); + const j = Math.min(i + 1, entries - 1); + const a = i === j ? 0 : x - i; + for (let c = 0; c < n; c++) { + const rc = tab.lock ? r[0] : r[c % 3]; + const at = (e: number) => { + if (tab.op === 1) return tab.v[e * per + c]; + const lo = tab.v[e * per + c]; + const hi = tab.v[e * per + n + c]; + return tab.op === 2 ? lo + (hi - lo) * rc : rc < 0.5 ? lo : hi; + }; + out[c] = at(i) + (at(j) - at(i)) * a; + } + out.length = n; + return out; +} + +const isTab = (v: unknown): v is Tab => !!v && typeof v === 'object' && !Array.isArray(v) && ('v' in (v as object) || 'curve' in (v as object)); + +/** 숫자 · 표 하나짜리 값 */ +function num(v: Num | undefined, t: number, r: readonly number[], def: number): number { + if (v == null) return def; + if (typeof v === 'number') return v; + return evTab(v, t, r)[0] ?? def; +} + +/** 벡터 값: [x,y,z] 상수 · [[최소],[최대]] 범위 · 표. 하나짜리는 세 축에 같이 */ +function vec3(v: number[] | number[][] | Num | undefined, t: number, r: readonly number[], def: number, out: number[]): number[] { + if (v == null) { + out[0] = out[1] = out[2] = def; + } else if (typeof v === 'number') { + out[0] = out[1] = out[2] = v; + } else if (isTab(v)) { + evTab(v, t, r, out); + if (out.length === 1) out[1] = out[2] = out[0]; + } else if (Array.isArray(v[0])) { + const lo = v[0] as number[]; + const hi = (v[1] as number[]) ?? lo; + for (let c = 0; c < 3; c++) { + const l = lo[c] ?? lo[0]; + const h = hi[c] ?? hi[0]; + out[c] = l + (h - l) * r[c]; + } + } else { + const a = v as number[]; + out[0] = a[0]; + out[1] = a[1] ?? a[0]; + out[2] = a[2] ?? a[0]; + } + out.length = 3; + return out; +} + +/** [최소, 최대] 범위 · 표 */ +function range(v: [number, number] | undefined, tab: Tab | undefined, t: number, r: number, def: number): number { + if (typeof tab === 'number') return tab; + if (tab) return evTab(tab, t, [r, r, r])[0]; + if (!v) return def; + return v[0] + (v[1] - v[0]) * r; +} + +// ---------- 텍스처 · 재질 ---------- +const texLoader = new THREE.TextureLoader(); +const texCache = new Map(); +/** + * 텍스처 종류: 0 색 그림(불꽃 플립북 등, RGB 를 색으로) · 1 흑백이나 채널마다 다른 마스크를 묶은 것(R 만 모양으로). + * 쿡된 재질에 채널 쓰임이 없어서 그림을 보고 고른다 (채널끼리 상관이 낮으면 묶음) + */ +function classify(img: CanvasImageSource & { width: number; height: number }): number { + const w = Math.min(64, img.width), + h = Math.min(64, img.height); + if (!w || !h) return 1; + const c = document.createElement('canvas'); + c.width = w; + c.height = h; + const g = c.getContext('2d', { willReadFrequently: true }); + if (!g) return 0; + g.drawImage(img, 0, 0, w, h); + const d = g.getImageData(0, 0, w, h).data; + const n = w * h; + const m = [0, 0, 0]; + let sat = 0; + for (let i = 0; i < n; i++) { + const r = d[i * 4], + gg = d[i * 4 + 1], + b = d[i * 4 + 2]; + m[0] += r; + m[1] += gg; + m[2] += b; + sat += Math.max(r, gg, b) - Math.min(r, gg, b); + } + if (sat / n / 255 < 0.06) return 1; + m[0] /= n; + m[1] /= n; + m[2] /= n; + const v = [0, 0, 0], + cv = [0, 0, 0]; + for (let i = 0; i < n; i++) { + const a = d[i * 4] - m[0], + b = d[i * 4 + 1] - m[1], + cc = d[i * 4 + 2] - m[2]; + v[0] += a * a; + v[1] += b * b; + v[2] += cc * cc; + cv[0] += a * b; + cv[1] += a * cc; + cv[2] += b * cc; + } + const corr = (x: number, i: number, j: number) => (v[i] > 1 && v[j] > 1 ? x / Math.sqrt(v[i] * v[j]) : 1); + const avg = (corr(cv[0], 0, 1) + corr(cv[1], 0, 2) + corr(cv[2], 1, 2)) / 3; + return avg < 0.75 ? 1 : 0; +} + +function texture(dir: string, file: string): THREE.Texture { + const key = `${dir}/${file}`; + let t = texCache.get(key); + if (!t) { + t = texLoader.load(assetPath(dir, file), (tx) => { + try { + tx.userData.mode = classify(tx.image as HTMLImageElement); + } catch { + tx.userData.mode = 0; + } + }); + t.userData.mode = -1; // 아직 모름 (받는 중) + t.flipY = false; // UE UV (위 = 0) + t.wrapS = t.wrapT = THREE.RepeatWrapping; + t.colorSpace = THREE.SRGBColorSpace; + texCache.set(key, t); + } + return t; +} + +const COLOR_TEX = [ + 'FB', + 'Emissive_Base', + 'EmissiveA Texture', + 'Texture', + 'TextureA', + 'ColorTex', + 'SpriteSheet', + 'Flipbook', + 'flipbook', + 'Main Tex', + 'Albedo', + 'Emissive Color', + 'SmokeTex', + 'Tx', + 'Decal Color Texture', + 'Diffuse', + 'Param', + 'TextureB', + 'TextureC', +]; +const ALPHA_TEX = ['Alpha_Base', 'Opacity', 'Alpha', 'AlphaA', 'Opacity Mask', 'Decal Mask Texture', 'Alpha_Layer1_Base', 'Floor Opacity Mask']; +const SKIP_TEX = /normal|nrm|_n$|distort|refract|flow|lut|matcap|cube|dissolve|wpo|vertexoffset|depth|mrae|gradient|patch|noise_n|reflection/i; +const TINT_VEC = ['Color', 'Emissive_Color', 'Emissive_ColorMult', 'ColorMultiply', 'GlowColor', 'Energy_Color']; + +interface MatInfo { + blend: string; + twoSided: boolean; + map: string | null; + mapST: [number, number, number, number]; + alphaMap: string | null; + alphaST: [number, number, number, number]; + tint: [number, number, number]; + rim: [number, number, number, number] | null; + /** 색 거듭제곱 (ColorPower 등) */ + pow: number; + /** ColorA · ColorB 둘 다 있는 재질 */ + grad: [[number, number, number], [number, number, number]] | null; +} + +const norm = (s: string) => s.toLowerCase().replace(/[\s_]/g, ''); + +/** 재질 인스턴스 → 고른 색 · 알파 텍스처, 흐름(배율 · 스크롤), 색 */ +function matInfo(db: VfxDb, name: string): MatInfo { + const m = db.materials[name]; + const master = m?.base ? db.masters[m.base] : undefined; + const texOf = (p: string): string | null => { + const f = m?.tex?.[p]; + if (f && db.files.has(f)) return f; + const g = master?.tex?.[p]; + if (g) { + const b = `t_${g.split('/').pop()}.png`; + if (db.files.has(b)) return b; + } + return null; + }; + const scalars = { ...(master?.scalar ?? {}), ...(m?.scalar ?? {}) }; + const sc = new Map(Object.entries(scalars).map(([k, v]) => [norm(k), v])); + const st = (param: string | null): [number, number, number, number] => { + if (!param) return [1, 1, 0, 0]; + const p = norm(param.replace(/_?Base$|\s*Texture$/, '')); + const g = (k: string, d: number) => sc.get(p + k) ?? d; + const speed = g('scrollspeed', 1) || 1; + return [g('scaleu', g('tileu', 1)), g('scalev', g('tilev', 1)), g('scrollu', 0) * speed, g('scrollv', 0) * speed]; + }; + // 색 텍스처 고르기: 이름표(COLOR_TEX 순서)에 점수, 파일 이름이 noise · 타일 · 흐름 같은 보조 텍스처면 깎는다 + let mapParam: string | null = null; + let map: string | null = null; + let best = -Infinity; + const params = new Set([...Object.keys(master?.tex ?? {}), ...Object.keys(m?.tex ?? {})]); + for (const p of params) { + if (SKIP_TEX.test(p) || ALPHA_TEX.includes(p)) continue; + const f = texOf(p); + if (!f) continue; + const ci = COLOR_TEX.indexOf(p); + let score = ci >= 0 ? 40 - ci : 0; + if (/flame|fire|fb|flipbook|sprite|spark|glow|smoke|poof|burst|ring|star|shape|main/i.test(f)) score += 30; + if (/noise|pan_?tfx|tile|dissolve|erosion|distort|flow|gradient|mask|lut|debug|default/i.test(f)) score -= 50; + if (score > best) { + best = score; + mapParam = p; + map = f; + } + } + // 기반 재질이 쓰는 텍스처도 후보 (LUT 처럼 색 표만 있는 재질은 이쪽 모양 텍스처가 낫다) + for (const f of m?.refTex ?? []) { + if (!db.files.has(f) || SKIP_TEX.test(f.replace(/^t_/, ''))) continue; + let score = -5; + if (/flame|fire|fb|flipbook|sprite|spark|glow|smoke|poof|burst|ring|star|shape|main|stripe/i.test(f)) score += 30; + if (/noise|pan_?tfx|tile|dissolve|erosion|distort|flow|gradient|mask|lut|debug|default/i.test(f)) score -= 50; + if (score > best) { + best = score; + mapParam = null; + map = f; + } + } + let alphaParam: string | null = null; + let alphaMap: string | null = null; + for (const p of ALPHA_TEX) { + const f = texOf(p); + if (f && f !== map) { + alphaParam = p; + alphaMap = f; + break; + } + } + const vecs = { ...(master?.vec ?? {}), ...(m?.vec ?? {}) }; + let tint: [number, number, number] = [1, 1, 1]; + for (const k of TINT_VEC) { + const v = m?.vec?.[k]; + if (v) { + tint = [v[0], v[1], v[2]]; + break; + } + } + let rim: MatInfo['rim'] = null; + for (const [k, v] of Object.entries(vecs)) { + if (/fresnel|rim/i.test(k) && v.some((x) => x > 0.01)) { + const pw = sc.get(norm(k.replace(/color/i, '') + 'power')) ?? sc.get('fresnelcolorpower') ?? 3; + rim = [v[0], v[1], v[2], pw]; + break; + } + } + const ca = m?.vec?.ColorA, + cb = m?.vec?.ColorB; + const lum = (v: number[]) => v[0] + v[1] + v[2]; + const grad: MatInfo['grad'] = + ca && cb && lum(ca) + lum(cb) > 0.05 && TINT_VEC.every((k) => !m?.vec?.[k]) + ? [ + [ca[0], ca[1], ca[2]], + [cb[0], cb[1], cb[2]], + ] + : null; + const pw = sc.get('colorpower') ?? sc.get('emissivepower') ?? sc.get('emissiveapower') ?? 1; + return { + pow: Math.max(0.2, Math.min(4, pw)), + grad, + blend: m?.blend ?? master?.blend ?? 'BLEND_Translucent', + twoSided: m?.twoSided ?? false, + map, + mapST: st(mapParam), + alphaMap, + alphaST: st(alphaParam), + tint, + rim, + }; +} + +/** 연막 돔 색 (요원 → 몸 색 · 어두운 색). 쿡된 재질 그래프가 없어 게임 화면에 맞춰 고른 값 */ +const DOME: Record = { + Sarge: { base: 0xb07a52, dark: 0x4a2a18 }, // 브림스톤: 주황 갈색 + Wraith: { base: 0x3a2a55, dark: 0x120a1e }, // 오멘: 검보라 + Rift: { base: 0x7a3fb0, dark: 0x2a0f45 }, // 아스트라: 보라 + Smonk: { base: 0xe07ab8, dark: 0x6a2a6a }, // 클로브: 분홍 + Wushu: { base: 0xe8f0f8, dark: 0x9fb4c8 }, // 제트: 흰 바람 + Mage: { base: 0x3a9fc8, dark: 0x0f4a66 }, // 하버: 물 + Pandemic: { base: 0x3fb04a, dark: 0x0f4a1a }, // 바이퍼: 초록 + Iris: { base: 0x9a7ad8, dark: 0x3a2a66 }, +}; + +const VERT_SPRITE = /* glsl */ ` +attribute vec3 iPos; +attribute vec2 iSize; +attribute float iRot; +attribute vec4 iColor; +attribute float iFrame; +attribute vec3 iVel; +uniform vec2 uSub; +uniform float uMode; // 0 카메라 · 1 바닥(XY 평면) · 2 속도 방향 · 3 Z 축만 돈다 +varying vec2 vUv; +varying vec4 vColor; +varying vec2 vQuad; +void main() { + vec2 c = position.xy; + float cr = cos(iRot), sr = sin(iRot); + vec2 cs = c * iSize; + vec2 rc = vec2(cs.x * cr - cs.y * sr, cs.x * sr + cs.y * cr); + vec4 mv; + if (uMode > 0.5 && uMode < 1.5) { + mv = modelViewMatrix * vec4(iPos + vec3(rc, 0.0), 1.0); + } else if (uMode > 2.5) { + vec3 camL = (inverse(modelMatrix) * vec4(cameraPosition, 1.0)).xyz; + vec2 d = normalize(camL.xy - iPos.xy + vec2(1e-4, 0.0)); + vec3 side = vec3(-d.y, d.x, 0.0); + mv = modelViewMatrix * vec4(iPos + side * rc.x + vec3(0.0, 0.0, rc.y), 1.0); + } else { + mv = modelViewMatrix * vec4(iPos, 1.0); + float s = length(modelMatrix[0].xyz) * length(viewMatrix[0].xyz); + if (uMode > 1.5) { + vec4 m2 = modelViewMatrix * vec4(iPos + iVel * 0.05, 1.0); + vec2 dir = m2.xy - mv.xy; + float l = length(dir); + dir = l > 1e-6 ? dir / l : vec2(0.0, 1.0); + vec2 perp = vec2(-dir.y, dir.x); + mv.xy += (perp * c.x * iSize.x + dir * c.y * iSize.y) * s; + } else { + mv.xy += rc * s; + } + } + gl_Position = projectionMatrix * mv; + float f = floor(iFrame + 0.001); + vec2 cell = vec2(mod(f, uSub.x), floor(f / uSub.x)); + vUv = (vec2(c.x + 0.5, 0.5 - c.y) + cell) / uSub; + vColor = iColor; + vQuad = c; +} +`; + +const VERT_MESH = /* glsl */ ` +attribute vec4 iColor; +attribute float iFrame; +uniform vec2 uSub; +varying vec2 vUv; +varying vec4 vColor; +varying vec2 vQuad; +varying vec3 vN; +varying vec3 vV; +void main() { + mat4 mm = modelMatrix * instanceMatrix; + vec4 wp = mm * vec4(position, 1.0); + vec4 mv = viewMatrix * wp; + gl_Position = projectionMatrix * mv; + vN = normalize(mat3(viewMatrix) * mat3(mm) * normal); + vV = normalize(-mv.xyz); + float f = floor(iFrame + 0.001); + vec2 cell = vec2(mod(f, uSub.x), floor(f / uSub.x)); + vUv = (uv + cell) / uSub; + vColor = iColor; + vQuad = uv - 0.5; +} +`; + +/** 리본은 메시용 셰이더(정점 색)를 인스턴스 없이 쓴다 */ +const VERT_RIBBON = VERT_MESH.replace('mat4 mm = modelMatrix * instanceMatrix;', 'mat4 mm = modelMatrix;'); + +const FRAG = /* glsl */ ` +uniform sampler2D uMap; +uniform sampler2D uAMap; +uniform float uHasMap; +uniform float uHasAMap; +uniform float uMapMode; +uniform float uAMode; +uniform float uDecal; +uniform vec4 uMapST; +uniform vec4 uAST; +uniform float uTime; +uniform vec3 uTint; +uniform vec3 uGradA; +uniform vec3 uGradB; +uniform float uGrad; +uniform float uPow; +uniform float uSoft; +uniform float uMasked; +uniform float uOpaque; +uniform float uSolid; +uniform float uFade; +uniform vec4 uRim; +uniform vec3 uRimColor; +uniform float uDome; +uniform vec3 uDomeBase; +uniform vec3 uDomeDark; +uniform vec3 uDomeEdge; +varying vec2 vUv; +varying vec4 vColor; +varying vec2 vQuad; +#ifdef MESH +varying vec3 vN; +varying vec3 vV; +#endif +void main() { + vec3 rgb = vColor.rgb * uTint; + float a = vColor.a; + float shape = 1.0; + if (uHasMap > 0.5) { + vec4 t = texture2D(uMap, vUv * uMapST.xy + uMapST.zw * uTime); + if (uMapMode > 0.5) { + rgb *= pow(t.r, uPow); + shape = t.r * t.a; + } else { + rgb *= t.rgb; + shape = max(t.r, max(t.g, t.b)) * t.a; + } + } else if (uSoft > 0.5) { + shape = smoothstep(0.5, 0.05, length(vQuad)); + } + if (uHasAMap > 0.5) { + vec4 t2 = texture2D(uAMap, vUv * uAST.xy + uAST.zw * uTime); + shape = (uAMode > 0.5 ? t2.r : max(t2.r, max(t2.g, t2.b))) * t2.a; + } + if (uHasMap < 0.5 && uDecal > 0.5) rgb = vec3(0.08); // 색 텍스처 없는 바닥 얼룩은 그을음 · 그림자처럼 + a *= shape; + // 바닥 얼룩은 네모 끝이 보이지 않게 둥글게 + if (uDecal > 0.5) a *= smoothstep(0.5, 0.36, length(vQuad)); + // 두 색 재질(ColorA → ColorB): 모양 값으로 섞는다 + if (uGrad > 0.5) rgb = vColor.rgb * mix(uGradA, uGradB, clamp(shape, 0.0, 1.0)); +#ifdef MESH + float fres = 1.0 - abs(dot(normalize(vN), normalize(vV))); + if (uDome > 0.5) { + // 연막 돔: noise 로 어두운 색 ~ 몸 색, 가장자리 빛 (적이면 붉게) + float nz = uHasMap > 0.5 ? shape : 0.6; + rgb = mix(uDomeDark, uDomeBase, clamp(0.35 + nz * 0.9, 0.0, 1.0)); + rgb += uDomeEdge * pow(fres, 2.5) * 1.4; + a = vColor.a; + } else if (uRim.w > 0.0) { + rgb += uRimColor * pow(fres, uRim.w); + } +#endif + if (uMasked > 0.5) { + if (a < 0.33) discard; + a = 1.0; + } + if (uOpaque > 0.5) a = 1.0; + a = clamp(a, 0.0, 1.0) * uFade; + // UE 반투명처럼 (빛나는 색 × 불투명도) 를 더한다: 미리 곱한 알파. + // HDR 색은 채널마다 0.8 위를 부드럽게 1 로 누른다 (아주 밝은 빨강 → 주황 · 노랑, 게임 톤매핑처럼) + vec3 c = max(rgb, 0.0) * (uSolid > 0.5 ? 1.0 : a); + c = mix(c, 0.8 + 0.2 * (1.0 - exp(-(c - 0.8) / 0.2)), step(0.8, c)); + gl_FragColor = vec4(c, uSolid > 0.5 ? 1.0 : a); + #include +} +`; + +interface MatOpts { + kind: 'sprite' | 'mesh' | 'ribbon'; + decal?: boolean; + /** 연막 돔 위에 덮는 반투명 층: 돔 색으로 칠하고 옅게 */ + overlay?: number; + sub: [number, number]; + dome: { base: number; dark: number; edge: number } | null; + rimColor: [number, number, number] | null; +} + +function makeMaterial(db: VfxDb, name: string, o: MatOpts): THREE.ShaderMaterial | null { + const mi = matInfo(db, name); + if (mi.blend === 'BLEND_Modulate') return null; // 어둡게 곱하는 것(그림자 얼룩)은 뺀다 + // 바닥 얼룩(decal)은 불투명 재질이어도 마스크로 비친다 + const masked = mi.blend === 'BLEND_Masked' && !o.decal; + const opaque = mi.blend === 'BLEND_Opaque' && !o.decal; + const additive = mi.blend === 'BLEND_Additive'; + const uniforms = { + uMap: { value: mi.map ? texture(db.dir, mi.map) : null }, + uAMap: { value: mi.alphaMap ? texture(db.dir, mi.alphaMap) : null }, + uHasMap: { value: mi.map ? 1 : 0 }, + uHasAMap: { value: mi.alphaMap ? 1 : 0 }, + uMapMode: { value: 0 }, + uAMode: { value: 0 }, + uDecal: { value: o.decal ? 1 : 0 }, + uMapST: { value: new THREE.Vector4(...mi.mapST) }, + uAST: { value: new THREE.Vector4(...mi.alphaST) }, + uTime: { value: 0 }, + uTint: { + value: o.overlay != null ? new THREE.Vector3().setFromColor(new THREE.Color(o.overlay)).multiplyScalar(1.6) : new THREE.Vector3(...mi.tint), + }, + uFade: { value: o.overlay != null ? 0.35 : 1 }, + uGrad: { value: mi.grad && !opaque ? 1 : 0 }, + uPow: { value: mi.pow }, + uGradA: { value: new THREE.Vector3(...(mi.grad?.[0] ?? [1, 1, 1])) }, + uGradB: { value: new THREE.Vector3(...(mi.grad?.[1] ?? [1, 1, 1])) }, + uSoft: { value: o.kind === 'sprite' ? 1 : 0 }, + uMasked: { value: masked && !o.dome ? 1 : 0 }, + uOpaque: { value: opaque ? 1 : 0 }, + uSolid: { value: 0 }, + uRim: { value: new THREE.Vector4(0, 0, 0, mi.rim ? mi.rim[3] : 0) }, + uRimColor: { + value: new THREE.Vector3(...(o.rimColor ?? (mi.rim ? [mi.rim[0], mi.rim[1], mi.rim[2]] : [0, 0, 0]))), + }, + uDome: { value: o.dome ? 1 : 0 }, + uDomeBase: { value: new THREE.Color(o.dome?.base ?? 0) }, + uDomeDark: { value: new THREE.Color(o.dome?.dark ?? 0) }, + uDomeEdge: { value: new THREE.Color(o.dome?.edge ?? 0) }, + uSub: { + value: new THREE.Vector2(Math.max(1, o.sub[0]), Math.max(1, o.sub[1])), + }, + uMode: { value: 0 }, + }; + const solid = (opaque || masked || !!o.dome) && o.kind === 'mesh'; + uniforms.uSolid.value = solid ? 1 : 0; + const mat = new THREE.ShaderMaterial({ + uniforms, + vertexShader: o.kind === 'mesh' ? VERT_MESH : o.kind === 'ribbon' ? VERT_RIBBON : VERT_SPRITE, + fragmentShader: FRAG, + defines: o.kind === 'sprite' ? {} : { MESH: '' }, + transparent: !solid, + depthWrite: solid, + // 미리 곱한 알파: 반투명 = 1 · (1 - a), 더하기 = 1 · 1 + blending: solid ? THREE.NormalBlending : THREE.CustomBlending, + blendSrc: THREE.OneFactor, + blendDst: additive ? THREE.OneFactor : THREE.OneMinusSrcAlphaFactor, + side: o.kind !== 'mesh' || mi.twoSided || !!o.dome ? THREE.DoubleSide : THREE.FrontSide, + }); + mat.userData.sub = [Math.max(1, o.sub[0]), Math.max(1, o.sub[1])]; + return mat; +} + +/** 매 프레임: 시간 · 텍스처 종류(받은 뒤 정해진다) */ +function syncMat(mat: THREE.ShaderMaterial, time: number) { + const u = mat.uniforms; + u.uTime.value = time; + // 플립북 칸 나누기는 텍스처 칸이 대략 정사각형일 때만 (길쭉한 한 장 그림을 칸으로 자르지 않게) + const img = (u.uMap.value as THREE.Texture | null)?.image as { width: number; height: number } | undefined; + const sub = mat.userData.sub as [number, number] | undefined; + if (img?.width && sub) { + const asp = img.width / sub[0] / (img.height / sub[1]); + const ok = asp > 0.5 && asp < 2; + (u.uSub.value as THREE.Vector2).set(ok ? sub[0] : 1, ok ? sub[1] : 1); + } + u.uMapMode.value = (u.uMap.value as THREE.Texture | null)?.userData.mode === 1 ? 1 : 0; + u.uAMode.value = (u.uAMap.value as THREE.Texture | null)?.userData.mode === 1 ? 1 : 0; +} + +// ---------- 메시 (m_*.glb) ---------- +const gltfCache = new Map>(); +function loadGlb(dir: string, file: string): Promise { + const url = assetPath(dir, file); + let p = gltfCache.get(url); + if (!p) { + const loader = new GLTFLoader(); + loader.setMeshoptDecoder(MeshoptDecoder); + p = loader.loadAsync(url); + p.catch(() => gltfCache.delete(url)); + gltfCache.set(url, p); + } + return p; +} + +/** glb 안 첫 메시 모양 (UE 메시 공간). 없으면 null */ +async function meshGeometry(dir: string, file: string): Promise { + const g = await loadGlb(dir, file); + let geo: THREE.BufferGeometry | null = null; + g.scene.updateMatrixWorld(true); + g.scene.traverse((o) => { + if (!geo && (o as THREE.Mesh).isMesh) { + const g2 = (o as THREE.Mesh).geometry.clone(); + g2.applyMatrix4(o.matrixWorld); + // 셰이더가 쓰는 속성이 없으면 채운다 + const n = g2.getAttribute('position').count; + if (!g2.getAttribute('uv')) g2.setAttribute('uv', new THREE.Float32BufferAttribute(new Float32Array(n * 2), 2)); + if (!g2.getAttribute('normal')) g2.computeVertexNormals(); + geo = g2; + } + }); + return geo; +} + +// ---------- 입자 계산 ---------- +const MAX_PARTICLES = 160; +const MAX_MESH_PARTICLES = 12; + +export interface Particle { + x: number; + y: number; + z: number; + sx: number; + sy: number; + sz: number; + r: number; + g: number; + b: number; + a: number; + rot: number; + frame: number; + vx: number; + vy: number; + vz: number; + mrx: number; + mry: number; + mrz: number; + /** 생긴 이미터 시간 (초) */ + st: number; +} + +/** 시스템 자리 (UE 좌표 · 도). 움직이는 것(투사체)은 시각마다 다르다 */ +export interface Place { + x: number; + y: number; + z: number; + yaw: number; + pitch: number; +} + +const tmp3: number[] = [0, 0, 0]; +const tmp3b: number[] = [0, 0, 0]; + +/** + * 이미터 하나의 t(이미터 시간, 초) 시점 입자들. + * stopE: 꺼진 이미터 시간 (null = 아직 켜짐). worldAt: 월드 공간 입자(local=false)가 생길 때 시스템 자리 + */ +export function emitParticles(e: VEmitter, seed: number, t: number, stopE: number | null, speedCmS: number, out: Particle[]): Particle[] { + out.length = 0; + if (t < 0) return out; + const D = e.duration > 0 ? e.duration : 1e9; + const loops = e.loops > 0 ? e.loops : Infinity; + const loopEnd = loops === Infinity ? Infinity : loops * D; + const spawnEnd = Math.min(stopE ?? Infinity, loopEnd, t); + if (stopE != null && t >= stopE && e.killOnDeactivate) return out; + const maxLife = e.lifeT ? Math.max(...lifeBounds(e.lifeT)) : Math.max(e.life?.[0] ?? 1, e.life?.[1] ?? 1); + const infinite = maxLife <= 0; + const from = infinite ? 0 : Math.max(0, t - maxLife); + const spawns: { s: number; id: number }[] = []; + // 터뜨리기 (루프마다) + if (e.bursts?.length) { + const k0 = Math.max(0, Math.floor(from / D)); + const k1 = Math.min(Math.floor(spawnEnd / D), loops - 1, k0 + 200); + for (let k = k0; k <= k1; k++) { + e.bursts.forEach(([bt, cnt], bi) => { + const s = k * D + bt; + if (s < from || s > spawnEnd) return; + for (let c = 0; c < Math.min(cnt, MAX_PARTICLES); c++) spawns.push({ s, id: (k * 64 + bi) * 1024 + c }); + }); + } + } + // 초당 생성 (거리당 생성은 투사체 속도로 근사) + let rate = num(e.spawnRate, 0, [0.5, 0.5, 0.5], 0) * num(e.rateScale, 0, [0.5, 0.5, 0.5], 1); + if (e.spawnPerUnit && speedCmS > 0) rate += (e.spawnPerUnit.n * speedCmS) / Math.max(1, e.spawnPerUnit.unit); + if (rate > 0 && spawnEnd > from) { + const j1 = Math.floor(spawnEnd * rate); + const j0 = Math.max(Math.ceil(from * rate), j1 - MAX_PARTICLES); + for (let j = j0; j <= j1; j++) spawns.push({ s: j / rate, id: 0x40000000 + j }); + } + if (spawns.length > MAX_PARTICLES) spawns.splice(0, spawns.length - MAX_PARTICLES); + const r = [0, 0, 0]; + for (const { s, id } of spawns) { + const h = (k: number) => hash01(seed + id * 31, k); + r[0] = h(1); + r[1] = h(2); + r[2] = h(3); + const L = range(e.life, e.lifeT, s, h(4), 1); + const age = t - s; + if (L > 0 ? age >= L : stopE != null && t >= stopE) continue; + const x = L > 0 ? age / L : 0; + const p: Particle = { + x: 0, + y: 0, + z: 0, + sx: 1, + sy: 1, + sz: 1, + r: 1, + g: 1, + b: 1, + a: 1, + rot: 0, + frame: 0, + vx: 0, + vy: 0, + vz: 0, + mrx: 0, + mry: 0, + mrz: 0, + st: s, + }; + // 크기 + vec3(e.sizeT ?? (e.size as number[][]), s, [r[0], r[0], r[0]], 1, tmp3); + if (e.size && e.size[0]?.length === 1 && !e.sizeT) tmp3[1] = tmp3[2] = tmp3[0]; + let sx = tmp3[0], + sy = tmp3[1], + sz = tmp3[2]; + if (e.sizeLife) { + vec3(e.sizeLife, x, r, 1, tmp3); + sx *= tmp3[0]; + sy *= tmp3[1]; + sz *= tmp3[2]; + } + if (e.sizeScale != null) { + vec3(e.sizeScale as Num, x, r, 1, tmp3); + sx *= tmp3[0]; + sy *= tmp3[1]; + sz *= tmp3[2]; + } + p.sx = sx; + // PSA_Square(기본)는 X 크기 하나로 정사각형 + p.sy = !e.screenAlign || e.screenAlign === 'PSA_Square' || e.screenAlign === 'PSA_FacingCameraPosition' ? sx : sy; + p.sz = sz; + // 색 · 알파: ColorOverLife 는 덮어쓰고, ScaleOverLife 는 곱한다 + if (e.colorLife) vec3(e.colorLife, x, r, 1, tmp3); + else if (e.colorT) vec3(e.colorT, s, r, 1, tmp3); + else vec3(e.color, 0, r, 1, tmp3); + let a = e.alphaLife != null ? num(e.alphaLife, x, r, 1) : range(e.alpha, e.alphaT, s, h(5), 1); + const cx = e.colorScaleEmitterTime ? t : x; + if (e.colorScaleLife != null) { + vec3(e.colorScaleLife as Num, cx, r, 1, tmp3b); + tmp3[0] *= tmp3b[0]; + tmp3[1] *= tmp3b[1]; + tmp3[2] *= tmp3b[2]; + } + if (e.alphaScaleLife != null) a *= num(e.alphaScaleLife, cx, r, 1); + p.r = tmp3[0]; + p.g = tmp3[1]; + p.b = tmp3[2]; + p.a = a; + // 처음 자리 + let lx = 0, + ly = 0, + lz = 0; + if (e.locBox || e.locBoxT) { + vec3(e.locBoxT ?? e.locBox, s, [h(6), h(7), h(8)], 0, tmp3); + lx += tmp3[0]; + ly += tmp3[1]; + lz += tmp3[2]; + } + let svx = 0, + svy = 0, + svz = 0; + if (e.locSphere) { + const rad = e.locSphere.r[0] + ((e.locSphere.r[1] ?? e.locSphere.r[0]) - e.locSphere.r[0]) * h(9); + const u = h(10) * 2 - 1; + const ph = h(11) * Math.PI * 2; + const q = Math.sqrt(1 - u * u); + const k = e.locSphere.surface ? 1 : Math.cbrt(h(12)); + const dx = q * Math.cos(ph), + dy = q * Math.sin(ph), + dz = u; + lx += (e.locSphere.center?.[0] ?? 0) + dx * rad * k; + ly += (e.locSphere.center?.[1] ?? 0) + dy * rad * k; + lz += (e.locSphere.center?.[2] ?? 0) + dz * rad * k; + if (e.locSphere.vel) { + svx += dx * rad * (e.locSphere.velScale ?? 1); + svy += dy * rad * (e.locSphere.velScale ?? 1); + svz += dz * rad * (e.locSphere.velScale ?? 1); + } + } + if (e.locCylinder) { + const c = e.locCylinder; + const rad = (c.r[0] + ((c.r[1] ?? c.r[0]) - c.r[0]) * h(13)) * (c.surface ? 1 : Math.sqrt(h(14))); + const hh = c.h[0] + ((c.h[1] ?? c.h[0]) - c.h[0]) * h(15); + const ph = h(16) * Math.PI * 2; + const dx = Math.cos(ph), + dy = Math.sin(ph); + lx += dx * rad; + ly += dy * rad; + lz += (h(17) - 0.5) * hh; + if (c.vel) { + svx += dx * rad * (c.velScale ?? 1); + svy += dy * rad * (c.velScale ?? 1); + } + } + // 속도 · 가속 · 끌림 + vec3(e.velT ?? e.vel, s, [h(18), h(19), h(20)], 0, tmp3); + let vx = tmp3[0] + svx, + vy = tmp3[1] + svy, + vz = tmp3[2] + svz; + if (e.velRadial || e.velRadialT) { + const sp = range(e.velRadial, e.velRadialT, s, h(21), 0); + const l = Math.hypot(lx, ly, lz) || 1; + vx += (lx / l) * sp; + vy += (ly / l) * sp; + vz += (lz / l) * sp; + } + if (e.velCone) { + const ang = num(e.velCone.angle, s, [h(22), h(22), h(22)], 0) * Math.PI; + const sp = num(e.velCone.speed, s, [h(23), h(23), h(23)], 0); + const ph = h(24) * Math.PI * 2; + const d = e.velCone.dir ?? [0, 0, 1]; + const dl = Math.hypot(d[0], d[1], d[2]) || 1; + const [ax, ay, az] = [d[0] / dl, d[1] / dl, d[2] / dl]; + // 축에 수직인 두 벡터 + const [px, py, pz] = Math.abs(az) < 0.9 ? [-ay, ax, 0] : [0, -az, ay]; + const pl = Math.hypot(px, py, pz) || 1; + const [ux, uy, uz] = [px / pl, py / pl, pz / pl]; + const [wx, wy, wz] = [ay * uz - az * uy, az * ux - ax * uz, ax * uy - ay * ux]; + const ca = Math.cos(ang), + sa = Math.sin(ang); + vx += (ax * ca + (ux * Math.cos(ph) + wx * Math.sin(ph)) * sa) * sp; + vy += (ay * ca + (uy * Math.cos(ph) + wy * Math.sin(ph)) * sa) * sp; + vz += (az * ca + (uz * Math.cos(ph) + wz * Math.sin(ph)) * sa) * sp; + } + vec3(e.accelT ?? e.accel, s, [h(25), h(26), h(27)], 0, tmp3); + const ax = tmp3[0], + ay = tmp3[1], + az = tmp3[2]; + const drag = range(e.drag, e.dragT, s, h(28), 0); + // 나이까지 몇 걸음으로 나눠 적분 (속도 배율 · 끌림이 있어도 맞게) + const steps = e.velLife || drag > 0 ? 8 : 1; + const dt = age / steps; + let px = lx, + py = ly, + pz = lz; + let cvx = vx, + cvy = vy, + cvz = vz; + for (let k = 0; k < steps; k++) { + let m = 1; + if (e.velLife != null && L > 0) m = num(e.velLife, ((k + 0.5) * dt) / L, r, 1); + if (steps === 1) { + px += cvx * dt + 0.5 * ax * dt * dt; + py += cvy * dt + 0.5 * ay * dt * dt; + pz += cvz * dt + 0.5 * az * dt * dt; + } else { + px += cvx * m * dt; + py += cvy * m * dt; + pz += cvz * m * dt; + const dk = Math.exp(-drag * dt); + cvx = cvx * dk + ax * dt; + cvy = cvy * dk + ay * dt; + cvz = cvz * dk + az * dt; + } + } + // 궤도: 오프셋을 (처음 각 + 각속도 × 나이) 만큼 X · Y · Z 축으로 돌린다 (1 = 한 바퀴) + if (e.orbit) { + const o = e.orbit; + vec3(o.offset, 0, [h(29), h(30), h(31)], 0, tmp3); + let ox = tmp3[0], + oy = tmp3[1], + oz = tmp3[2]; + vec3(o.rot, 0, [h(32), h(33), h(34)], 0, tmp3); + vec3(o.rotRate, 0, [h(35), h(36), h(37)], 0, tmp3b); + const rx = (tmp3[0] + tmp3b[0] * age) * Math.PI * 2; + const ry = (tmp3[1] + tmp3b[1] * age) * Math.PI * 2; + const rz = (tmp3[2] + tmp3b[2] * age) * Math.PI * 2; + let c = Math.cos(rx), + sn = Math.sin(rx); + [oy, oz] = [oy * c - oz * sn, oy * sn + oz * c]; + c = Math.cos(ry); + sn = Math.sin(ry); + [ox, oz] = [ox * c + oz * sn, -ox * sn + oz * c]; + c = Math.cos(rz); + sn = Math.sin(rz); + [ox, oy] = [ox * c - oy * sn, ox * sn + oy * c]; + px += ox; + py += oy; + pz += oz; + } + p.x = px; + p.y = py; + p.z = pz; + p.vx = cvx; + p.vy = cvy; + p.vz = cvz; + // 회전 (바퀴 → 라디안) + const rot0 = range(e.rot, e.rotT, s, h(38), 0); + const rr = range(e.rotRate, e.rotRateT, s, h(39), 0); + p.rot = (rot0 + rr * age) * Math.PI * 2; + if (e.meshRot || e.meshRotT || e.meshRotRate || e.meshRotRateT) { + vec3(e.meshRotT ?? e.meshRot, s, [h(40), h(41), h(42)], 0, tmp3); + vec3(e.meshRotRateT ?? e.meshRotRate, s, [h(43), h(44), h(45)], 0, tmp3b); + p.mrx = (tmp3[0] + tmp3b[0] * age) * Math.PI * 2; + p.mry = (tmp3[1] + tmp3b[1] * age) * Math.PI * 2; + p.mrz = (tmp3[2] + tmp3b[2] * age) * Math.PI * 2; + } + // 플립북 칸 + const frames = Math.max(1, e.subUV[0] * e.subUV[1]); + if (frames > 1) { + if (e.subUVMovie) p.frame = Math.floor(age * Math.abs(e.subUVMovie.fps || 30) + (e.subUVMovie.start ?? 0)) % frames; + else if (e.subUVIndex != null) p.frame = Math.min(frames - 1, Math.max(0, num(e.subUVIndex, x, [h(46), h(46), h(46)], 0))); + else if (/Random/.test(e.subUVMode ?? '')) p.frame = Math.floor(h(47) * frames); + else p.frame = Math.min(frames - 1, Math.floor(x * frames)); + } + out.push(p); + } + return out; +} + +function lifeBounds(t: Tab): number[] { + return t.v.length ? [Math.min(...t.v), Math.max(...t.v)] : [1]; +} + +// ---------- 그리기 ---------- +const QUAD = (() => { + const g = new THREE.InstancedBufferGeometry(); + g.setAttribute('position', new THREE.Float32BufferAttribute([-0.5, -0.5, 0, 0.5, -0.5, 0, 0.5, 0.5, 0, -0.5, 0.5, 0], 3)); + g.setIndex([0, 1, 2, 0, 2, 3]); + return g; +})(); + +interface Drawer { + update(ps: Particle[], time: number): void; + object: THREE.Object3D; + dispose(): void; +} + +class SpriteDrawer implements Drawer { + object: THREE.Mesh; + private pos = new Float32Array(MAX_PARTICLES * 3); + private size = new Float32Array(MAX_PARTICLES * 2); + private rot = new Float32Array(MAX_PARTICLES); + private col = new Float32Array(MAX_PARTICLES * 4); + private frame = new Float32Array(MAX_PARTICLES); + private vel = new Float32Array(MAX_PARTICLES * 3); + private geo: THREE.InstancedBufferGeometry; + constructor( + private mat: THREE.ShaderMaterial, + private decal: boolean, + ) { + const g = new THREE.InstancedBufferGeometry(); + g.index = QUAD.index; + g.setAttribute('position', QUAD.getAttribute('position')); + const ia = (a: Float32Array, n: number) => new THREE.InstancedBufferAttribute(a, n).setUsage(THREE.DynamicDrawUsage); + g.setAttribute('iPos', ia(this.pos, 3)); + g.setAttribute('iSize', ia(this.size, 2)); + g.setAttribute('iRot', ia(this.rot, 1)); + g.setAttribute('iColor', ia(this.col, 4)); + g.setAttribute('iFrame', ia(this.frame, 1)); + g.setAttribute('iVel', ia(this.vel, 3)); + g.instanceCount = 0; + this.geo = g; + this.object = new THREE.Mesh(g, mat); + this.object.frustumCulled = false; + this.object.renderOrder = decal ? 1 : 3; + if (decal) { + mat.polygonOffset = true; + mat.polygonOffsetFactor = -4; + } + } + update(ps: Particle[], time: number) { + const n = Math.min(ps.length, MAX_PARTICLES); + // 길쭉한 그림(불꽃 한 장)을 납작한 사각형에 그리라고 하면 세운다 (재질 그래프가 돌려 쓰는 것으로 보인다) + const img = (this.mat.uniforms.uMap.value as THREE.Texture | null)?.image as { width: number; height: number } | undefined; + const sub = this.mat.uniforms.uSub.value as THREE.Vector2; + const tall = !!img?.width && img.height / sub.y / (img.width / sub.x) > 2; + for (let i = 0; i < n; i++) { + const p = ps[i]; + if (tall && p.sx > p.sy) [p.sx, p.sy] = [p.sy, p.sx]; + this.pos.set([p.x, p.y, this.decal ? p.z + 4 : p.z], i * 3); + // 바닥 얼룩은 크기가 반지름이다 + const dr = this.decal ? Math.max(p.sy, p.sz, 1) : 0; + this.size.set(this.decal ? [dr * 2, dr * 2] : [p.sx, p.sy], i * 2); + this.rot[i] = this.decal ? p.mrz || p.rot : p.rot; + this.col.set([p.r, p.g, p.b, p.a], i * 4); + this.frame[i] = p.frame; + this.vel.set([p.vx, p.vy, p.vz], i * 3); + } + this.geo.instanceCount = n; + for (const k of ['iPos', 'iSize', 'iRot', 'iColor', 'iFrame', 'iVel']) (this.geo.getAttribute(k) as THREE.InstancedBufferAttribute).needsUpdate = true; + syncMat(this.mat, time); + this.object.visible = n > 0; + } + dispose() { + this.geo.dispose(); + this.mat.dispose(); + } +} + +class MeshDrawer implements Drawer { + object: THREE.InstancedMesh; + private col = new Float32Array(MAX_MESH_PARTICLES * 4); + private frame = new Float32Array(MAX_MESH_PARTICLES); + private m = new THREE.Matrix4(); + private q = new THREE.Quaternion(); + private eu = new THREE.Euler(0, 0, 0, 'ZYX'); + private v = new THREE.Vector3(); + private s = new THREE.Vector3(); + constructor( + geo: THREE.BufferGeometry, + private mat: THREE.ShaderMaterial, + private extraRot: THREE.Quaternion | null, + ) { + const g = geo.clone(); + g.setAttribute('iColor', new THREE.InstancedBufferAttribute(this.col, 4).setUsage(THREE.DynamicDrawUsage)); + g.setAttribute('iFrame', new THREE.InstancedBufferAttribute(this.frame, 1).setUsage(THREE.DynamicDrawUsage)); + this.object = new THREE.InstancedMesh(g, mat, MAX_MESH_PARTICLES); + this.object.frustumCulled = false; + this.object.count = 0; + this.object.renderOrder = mat.transparent ? 2 : 0; + } + update(ps: Particle[], time: number) { + const n = Math.min(ps.length, MAX_MESH_PARTICLES); + for (let i = 0; i < n; i++) { + const p = ps[i]; + // UE 메시 회전 (바퀴): X 굴림 · Y 숙임 · Z 돌림 + this.eu.set(p.mrx, -p.mry, p.mrz + p.rot, 'ZYX'); + this.q.setFromEuler(this.eu); + if (this.extraRot) this.q.multiply(this.extraRot); + this.m.compose(this.v.set(p.x, p.y, p.z), this.q, this.s.set(p.sx, p.sy, p.sz)); + this.object.setMatrixAt(i, this.m); + this.col.set([p.r, p.g, p.b, p.a], i * 4); + this.frame[i] = p.frame; + } + this.object.count = n; + this.object.instanceMatrix.needsUpdate = true; + (this.object.geometry.getAttribute('iColor') as THREE.InstancedBufferAttribute).needsUpdate = true; + (this.object.geometry.getAttribute('iFrame') as THREE.InstancedBufferAttribute).needsUpdate = true; + syncMat(this.mat, time); + this.object.visible = n > 0; + } + dispose() { + this.object.geometry.dispose(); + this.mat.dispose(); + } +} + +/** 지나간 길 (리본): 시스템이 움직인 자리를 이어 띠로. 카메라를 향해 편다 */ +class RibbonDrawer implements Drawer { + object: THREE.Mesh; + private K = 24; + private pos: Float32Array; + private col: Float32Array; + private geo = new THREE.BufferGeometry(); + constructor(private mat: THREE.ShaderMaterial) { + this.pos = new Float32Array((this.K + 1) * 2 * 3); + this.col = new Float32Array((this.K + 1) * 2 * 4); + const uv = new Float32Array((this.K + 1) * 2 * 2); + const idx: number[] = []; + for (let k = 0; k <= this.K; k++) { + uv.set([k / this.K, 0, k / this.K, 1], k * 4); + if (k < this.K) idx.push(k * 2, k * 2 + 1, k * 2 + 2, k * 2 + 1, k * 2 + 3, k * 2 + 2); + } + this.geo.setAttribute('position', new THREE.BufferAttribute(this.pos, 3).setUsage(THREE.DynamicDrawUsage)); + this.geo.setAttribute('uv', new THREE.BufferAttribute(uv, 2)); + this.geo.setAttribute('normal', new THREE.BufferAttribute(new Float32Array((this.K + 1) * 2 * 3).fill(0), 3)); + this.geo.setAttribute('iColor', new THREE.BufferAttribute(this.col, 4).setUsage(THREE.DynamicDrawUsage)); + this.geo.setAttribute('iFrame', new THREE.BufferAttribute(new Float32Array((this.K + 1) * 2), 1)); + this.geo.setIndex(idx); + this.object = new THREE.Mesh(this.geo, mat); + this.object.frustumCulled = false; + this.object.renderOrder = 3; + } + /** pts: 새것 → 옛것 순서 자리 (UE), w: 폭, c: 색 */ + updateTrail(pts: { x: number; y: number; z: number }[], w: number, c: [number, number, number, number], cam: THREE.Vector3, time: number) { + const n = Math.min(pts.length, this.K + 1); + if (n < 2) { + this.object.visible = false; + return; + } + for (let k = 0; k <= this.K; k++) { + const i = Math.min(k, n - 1); + const p = pts[i]; + const q = pts[Math.min(i + 1, n - 1)]; + const o = pts[Math.max(i - 1, 0)]; + const tx = q.x - o.x, + ty = q.y - o.y, + tz = q.z - o.z; + const vx = cam.x - p.x, + vy = cam.y - p.y, + vz = cam.z - p.z; + let sx = ty * vz - tz * vy, + sy = tz * vx - tx * vz, + sz = tx * vy - ty * vx; + const l = Math.hypot(sx, sy, sz) || 1; + const ww = (w / 2) * (1 - k / (this.K + 1)); + sx = (sx / l) * ww; + sy = (sy / l) * ww; + sz = (sz / l) * ww; + this.pos.set([p.x + sx, p.y + sy, p.z + sz, p.x - sx, p.y - sy, p.z - sz], k * 6); + const fade = 1 - k / this.K; + this.col.set([c[0], c[1], c[2], c[3] * fade, c[0], c[1], c[2], c[3] * fade], k * 8); + } + (this.geo.getAttribute('position') as THREE.BufferAttribute).needsUpdate = true; + (this.geo.getAttribute('iColor') as THREE.BufferAttribute).needsUpdate = true; + syncMat(this.mat, time); + this.object.visible = true; + } + update() {} + dispose() { + this.geo.dispose(); + this.mat.dispose(); + } +} + +// ---------- 시스템 · 장면 ---------- +type Team = 'ally' | 'enemy'; + +interface EmitterInst { + dead?: boolean; + e: VEmitter; + seed: number; + drawer: Drawer | null; + ribbon: RibbonDrawer | null; + ps: Particle[]; +} + +/** 파티클 시스템 하나 (켜진 시각 · 꺼진 시각 · 자리) */ +class SystemInst { + readonly local = new THREE.Group(); + private emitters: EmitterInst[] = []; + private readonly worldGroup = new THREE.Group(); + constructor( + db: VfxDb, + sys: VSystem, + readonly key: string, + team: Team, + private readonly fx: VFx, + parent: THREE.Object3D, + seed: number, + loopForever = false, + ) { + parent.add(this.local); + parent.add(this.worldGroup); + const agent = /\/Characters\/([^/]+)\//.exec(sys.path)?.[1] ?? ''; + const sc = Array.isArray(fx.scale) ? fx.scale : [fx.scale, fx.scale, fx.scale]; + this.scale = sc; + const bigOf = (e: VEmitter) => (e.size?.[1]?.[0] ?? e.size?.[0]?.[0] ?? 0) * (sc[0] ?? 1); + const domeLike = (e: VEmitter) => e.type === 'mesh' && bigOf(e) >= 5 && /smoke|nebula|dome|cover|wisp|sphere|shell/i.test(e.name + (e.mesh ?? '')); + const hasDome = !!DOME[agent] && sys.emitters.some((e) => domeLike(e) && /Opaque|Masked/.test(matInfo(db, e.material).blend)); + sys.emitters.forEach((e0, ei) => { + // 줄기(beam)는 아직 못 그린다. 팀 구별 층(FoF)은 재질 그래프 없이는 통째로 붉게 덮여 뺀다 + if (e0.type === 'beam' || /FoF/.test(e0.name)) return; + // 장판 칸: 꺼질 때까지 계속 (처음 한 번 터지는 것은 그대로) + const e = loopForever && e0.loops > 0 && !/birth|intro|start|burst|spawn/i.test(e0.name) ? { ...e0, loops: 0 } : e0; + const inst: EmitterInst = { + e, + seed: seed * 977 + ei * 7919, + drawer: null, + ribbon: null, + ps: [], + }; + this.emitters.push(inst); + const teamCol = e.teamColor?.[team]; + if (e.type === 'ribbon') { + const mat = makeMaterial(db, e.material, { + kind: 'ribbon', + sub: e.subUV, + dome: null, + rimColor: null, + }); + if (!mat) return; + inst.ribbon = new RibbonDrawer(mat); + this.worldGroup.add(inst.ribbon.object); + return; + } + if (e.type === 'mesh' && e.mesh) { + const big = bigOf(e); + const mi = matInfo(db, e.material); + // 크게 덮는 불투명 · 가려지는 돔 = 연막 몸 + const domeC = DOME[agent]; + const dome = + domeC && + (mi.blend === 'BLEND_Opaque' || mi.blend === 'BLEND_Masked') && + big >= 5 && + /smoke|nebula|dome|cover|wisp|sphere|shell/i.test(e.name + e.mesh) + ? { + ...domeC, + // 가장자리 빛: 게임 데이터의 팀 색(적이면 붉은 것 등)이 있으면 그것, 없으면 몸 색을 밝게 + edge: teamCol ? new THREE.Color(Math.min(1, teamCol[0]), Math.min(1, teamCol[1]), Math.min(1, teamCol[2])).getHex() : new THREE.Color(domeC.base).lerp(new THREE.Color(0xffffff), 0.5).getHex(), + } + : null; + const overlay = !dome && hasDome && domeLike(e) ? DOME[agent].base : undefined; + const mat = makeMaterial(db, e.material, { + kind: 'mesh', + sub: e.subUV, + dome, + rimColor: teamCol && !dome ? [teamCol[0], teamCol[1], teamCol[2]] : null, + overlay, + }); + if (!mat) return; + // 텍스처 없는 빛 판(glow · flare)은 네모가 보이지 않게 가운데서 흐리게 + mat.uniforms.uSoft.value = !mat.uniforms.uHasMap.value && /glow|flare|light|bloom/i.test(e.name) ? 1 : 0; + void meshGeometry(db.dir, e.mesh) + .then((geo) => { + if (!geo || this.disposed) return; + inst.drawer = new MeshDrawer(geo, mat, null); + (e.local ? this.local : this.worldGroup).add(inst.drawer.object); + }) + .catch(() => {}); + return; + } + const decal = e.type === 'decal'; + const mat = makeMaterial(db, e.material, { + kind: 'sprite', + sub: e.subUV, + dome: null, + rimColor: null, + decal, + }); + if (!mat) return; + if (decal && /shadow/i.test(e.name + e.material)) { + // 그림자 얼룩: 색 텍스처를 쓰지 않고 옅은 어둠으로 + mat.uniforms.uHasMap.value = 0; + mat.uniforms.uFade.value = 0.5; + } + mat.uniforms.uMode.value = + decal || e.axisLock === 'EPAL_Z' || e.axisLock === 'EPAL_NEGATIVE_Z' + ? 1 + : e.screenAlign === 'PSA_Velocity' + ? 2 + : /ROTATE_Z/.test(e.axisLock ?? '') + ? 3 + : 0; + inst.drawer = new SpriteDrawer(mat, decal); + (e.local ? this.local : this.worldGroup).add(inst.drawer.object); + }); + } + private scale: number[]; + private disposed = false; + + /** + * tau: 켜진 뒤 초, stop: 꺼진 시각(켜진 뒤 초, 없으면 null), placeAt(초): 그때 시스템 자리(UE), + * cam: 카메라 (UE 좌표), speed: 움직이는 속도(cm/s) + */ + update(tau: number, stop: number | null, placeAt: (sec: number) => Place, cam: THREE.Vector3, speed: number) { + const here = placeAt(tau); + setPlace(this.local, here, this.fx, this.scale); + let any = false; + for (const it of this.emitters) { + if (it.dead) continue; + try { + const e = it.e; + const et = tau - e.delay; + const stopE = stop == null ? null : stop - e.delay; + if (it.ribbon) { + // 지나간 길: 수명만큼 뒤의 자리들을 잇는다 + if (et < 0 || (stopE != null && et > stopE + 0.3)) { + it.ribbon.object.visible = false; + continue; + } + const life = Math.max(0.05, Math.min(2, e.life?.[1] ?? 0.5)); + const pts: Place[] = []; + for (let k = 0; k <= 24; k++) { + const tt = Math.min(tau, stop ?? tau) - (k / 24) * life; + if (tt < e.delay) break; + pts.push(placeAt(tt)); + } + const ps = emitParticles( + { + ...e, + bursts: [[0, 1]], + spawnRate: 0, + life: [0, 0], + lifeT: undefined, + }, + it.seed, + 0, + null, + 0, + it.ps, + ); + const p = ps[0]; + const w = (p ? p.sx : 20) * (this.scale[0] ?? 1); + it.ribbon.updateTrail(pts, w, p ? [p.r, p.g, p.b, p.a] : [1, 1, 1, 1], cam, tau); + any ||= it.ribbon.object.visible; + continue; + } + if (!it.drawer) continue; + const ps = emitParticles(e, it.seed, et, stopE, speed, it.ps); + if (!e.local && ps.length) { + // 월드 공간 입자: 생긴 때 시스템 자리에 고정 (투사체 꼬리) + for (const p of ps) { + const pl = placeAt(p.st + e.delay); + const q = rotateUE(p.x * (this.scale[0] ?? 1), p.y * (this.scale[1] ?? 1), p.z * (this.scale[2] ?? 1), pl.yaw + (this.fx.rot?.[1] ?? 0), pl.pitch); + p.x = pl.x + q[0] + (this.fx.pos?.[0] ?? 0); + p.y = pl.y + q[1] + (this.fx.pos?.[1] ?? 0); + p.z = pl.z + q[2] + (this.fx.pos?.[2] ?? 0); + p.sx *= this.scale[0] ?? 1; + p.sy *= this.scale[1] ?? 1; + p.sz *= this.scale[2] ?? 1; + } + } + it.drawer.update(ps, Math.max(0, et)); + any ||= ps.length > 0; + } catch { + // 데이터가 예상과 다른 이미터 하나 때문에 화면 전체가 멈추지 않게: 그 이미터만 끈다 + it.dead = true; + if (it.drawer) it.drawer.object.visible = false; + if (it.ribbon) it.ribbon.object.visible = false; + } + } + return any; + } + + dispose() { + this.disposed = true; + for (const it of this.emitters) { + it.drawer?.dispose(); + it.ribbon?.dispose(); + } + this.local.removeFromParent(); + this.worldGroup.removeFromParent(); + } +} + +function rotateUE(x: number, y: number, z: number, yawDeg: number, pitchDeg: number): [number, number, number] { + const p = (pitchDeg * Math.PI) / 180; + const yw = (yawDeg * Math.PI) / 180; + // 숙임(Y 축, 앞이 위로) 뒤 돌림(Z 축) + const x1 = x * Math.cos(p) - z * Math.sin(p); + const z1 = x * Math.sin(p) + z * Math.cos(p); + return [x1 * Math.cos(yw) - y * Math.sin(yw), x1 * Math.sin(yw) + y * Math.cos(yw), z1]; +} + +const eul = new THREE.Euler(0, 0, 0, 'ZYX'); +function setPlace(g: THREE.Object3D, pl: Place, fx: VFx, scale: number[]) { + const off = rotateUE(fx.pos?.[0] ?? 0, fx.pos?.[1] ?? 0, fx.pos?.[2] ?? 0, pl.yaw, pl.pitch); + g.position.set(pl.x + off[0], pl.y + off[1], pl.z + off[2]); + const r = fx.rot ?? [0, 0, 0]; + eul.set(((r[2] ?? 0) * Math.PI) / 180, (-(pl.pitch + (r[0] ?? 0)) * Math.PI) / 180, ((pl.yaw + (r[1] ?? 0)) * Math.PI) / 180, 'ZYX'); + g.quaternion.setFromEuler(eul); + g.scale.set(scale[0] ?? 1, scale[1] ?? 1, scale[2] ?? 1); + g.updateMatrixWorld(true); +} + +/** 리플레이 물체 하나 (스킬 · 설치물 · 투사체) */ +export interface VfxObjectSpec { + cls: string; + /** 생긴 · 사라진 시각 (리플레이 ms) */ + t0: number; + end: number; + team: Team; + /** 날아가는 것 (끝 = 부딪힌 시각, 터지는 효과는 끝 자리에서) */ + projectile: boolean; + /** 리플레이 ms → 자리 */ + placeAt: (tMs: number) => Place; + /** 움직이는 속도 (cm/s, 거리당 생성용) */ + speed: number; +} + +interface Scheduled { + loop?: boolean; + key: string; + fx: VFx; + on: number; + off: number | null; + /** 끝난 뒤 남는 시간 (ms) */ + tail: number; + fixedAt: 'start' | 'end' | null; +} + +// 벽 너머 표시 · 화면 표시 · 1인칭 · 사거리 표시(쓰는 사람에게만 보이는 것)는 뺀다 +const SKIP_SYS = /Through_?Walls|HUD|_1P_|_1p_|Minimap|_UI$|Range(Zone)?_VFX|AnchorRange/i; +/** 화면 아이콘 · 디버그 메시 */ +const SKIP_MESH = /Icon|Billboard|Debug|Quad/i; + +/** + * 클래스가 그릴 것(메시 · 효과)을 얼마나 갖고 있나: full 이것만 그린다 · partial 날아가는 모습이 없어(투사체) 뷰어의 기본 모양도 같이 · none 없음 + */ +export function vfxCoverage(db: VfxDb, cls: string): 'full' | 'partial' | 'none' { + const c = db.classes[cls]; + if (!c) return 'none'; + const usable = c.fx.filter( + (f) => !f.hidden && f.role !== 'disabled' && (f.ally || f.enemy) && db.systems[(f.enemy ?? f.ally)!] && !SKIP_SYS.test((f.enemy ?? f.ally)!), + ); + const meshes = c.meshes.filter((x) => !SKIP_MESH.test(x.name + x.file)).length; + if (!meshes && !usable.length) return 'none'; + if (/^Projectile_/.test(cls) && !meshes && !usable.some((f) => f.role === 'trail')) return 'partial'; + return 'full'; +} + +/** 물체 하나: 클래스의 메시 + 역할별 파티클 시스템 시간표 */ +export class VfxObject { + private sched: Scheduled[] = []; + private live = new Map(); + private meshes: THREE.Object3D[] = []; + private meshRoot = new THREE.Group(); + constructor( + private db: VfxDb, + private spec: VfxObjectSpec, + private parent: THREE.Object3D, + private seed: number, + withMeshes = true, + ) { + const c = db.classes[spec.cls]; + if (!c) return; + const endTele = c.params[Object.keys(c.params).find((k) => /EndTelegraphDuration$/i.test(k)) ?? ''] ?? 1.5; + // 장판(CellularPatch): 게임은 칸마다 불 효과를 하나씩 켠다 → 반지름 안 칸마다, 가운데서 번져 나가게 + const cellSize = c.params.CellSize ?? 0; + const radius = c.params.ClampedRadius ?? 0; + const cellular = cellSize > 0 && radius > 0; + const cells: [number, number, number][] = []; + if (cellular) { + let step = cellSize; + while ((Math.PI * radius * radius) / (step * step) > 40) step *= 1.25; + const n = Math.ceil(radius / step); + for (let i = -n; i <= n; i++) + for (let j = -n; j <= n; j++) { + const d = Math.hypot(i * step, j * step); + if (d <= radius) cells.push([i * step, j * step, d]); + } + } + const spread = c.params.SpreadSpeed ?? 0; + const mulScale = (sc: number | number[], k: number) => (Array.isArray(sc) ? sc.map((v) => v * k) : sc * k); + for (const fx of c.fx) { + if (fx.hidden || fx.role === 'disabled' || fx.role === 'target') continue; + const key = spec.team === 'enemy' ? (fx.enemy ?? fx.ally) : (fx.ally ?? fx.enemy); + if (!key || !db.systems[key] || SKIP_SYS.test(key)) continue; + const t0 = spec.t0, + end = spec.end; + if (cellular && fx.role === 'patch') { + for (const [dx, dy, d] of cells) { + const on = t0 + (spread > 0 ? (d / spread) * 1000 : 0); + this.sched.push({ + key, + fx: { + ...fx, + pos: [(fx.pos[0] ?? 0) + dx, (fx.pos[1] ?? 0) + dy, fx.pos[2] ?? 0], + }, + on, + off: Math.max(on, end), + tail: 2500, + fixedAt: null, + loop: true, + }); + } + continue; + } + if (cellular && fx.role === 'decal') { + // 바닥 그을음: 장판 반지름만큼 (효과 크기 250 기준) + this.sched.push({ + key, + fx: { + ...fx, + scale: mulScale(fx.scale, (radius * (c.params.DecalRadiusMultiplier ?? 1)) / 250), + }, + on: t0, + off: end, + tail: 2000, + fixedAt: null, + }); + continue; + } + switch (fx.role) { + case 'loop': + case 'patch': + case 'decal': + case 'other': + this.sched.push({ + key, + fx, + on: t0, + off: end, + tail: 1500, + fixedAt: null, + }); + break; + case 'trail': + this.sched.push({ + key, + fx, + on: t0, + off: end, + tail: 1500, + fixedAt: null, + }); + break; + case 'intro': + this.sched.push({ + key, + fx, + on: t0, + off: t0 + 4000, + tail: 2000, + fixedAt: 'start', + }); + break; + case 'outro': + this.sched.push({ + key, + fx, + on: end, + off: end + 3000, + tail: 2000, + fixedAt: 'end', + }); + break; + case 'explode': + if (spec.projectile) + this.sched.push({ + key, + fx, + on: end, + off: end + 3000, + tail: 2000, + fixedAt: 'end', + }); + else + this.sched.push({ + key, + fx, + on: t0, + off: t0 + 3000, + tail: 2000, + fixedAt: 'start', + }); + break; + case 'warn': + if (/End/i.test(fx.src ?? '')) + this.sched.push({ + key, + fx, + on: end - endTele * 1000, + off: end, + tail: 500, + fixedAt: null, + }); + else + this.sched.push({ + key, + fx, + on: t0, + off: t0 + 2500, + tail: 1500, + fixedAt: 'start', + }); + break; + default: + this.sched.push({ + key, + fx, + on: t0, + off: end, + tail: 1500, + fixedAt: null, + }); + } + } + // 설치물 · 투사체 몸 (메시) + parent.add(this.meshRoot); + for (const m of withMeshes ? c.meshes.filter((x) => !SKIP_MESH.test(x.name + x.file)) : []) { + void loadGlb(db.dir, m.file) + .then((g) => { + if (this.disposed) return; + const o = g.scene.clone(true); + o.position.set(m.pos[0] ?? 0, m.pos[1] ?? 0, m.pos[2] ?? 0); + o.rotation.set(((m.rot[2] ?? 0) * Math.PI) / 180, (-(m.rot[0] ?? 0) * Math.PI) / 180, ((m.rot[1] ?? 0) * Math.PI) / 180, 'ZYX'); + o.scale.set(m.scale[0] ?? 1, m.scale[1] ?? 1, m.scale[2] ?? 1); + this.meshRoot.add(o); + this.meshes.push(o); + }) + .catch(() => {}); + } + } + private disposed = false; + + /** 그릴 것이 있는 시간 (ms) */ + get span(): [number, number] { + let a = this.spec.t0, + b = this.spec.end; + for (const s of this.sched) { + a = Math.min(a, s.on); + b = Math.max(b, (s.off ?? s.on) + s.tail); + } + return [a, b]; + } + + update(tMs: number, cam: THREE.Vector3) { + const sp = this.spec; + // 메시: 생긴 뒤 사라질 때까지 (투사체는 날아가는 동안) + const meshOn = tMs >= sp.t0 && tMs <= sp.end; + this.meshRoot.visible = meshOn; + if (meshOn) { + const pl = sp.placeAt(tMs); + this.meshRoot.position.set(pl.x, pl.y, pl.z); + eul.set(0, (-pl.pitch * Math.PI) / 180, (pl.yaw * Math.PI) / 180, 'ZYX'); + this.meshRoot.quaternion.setFromEuler(eul); + } + this.sched.forEach((s, i) => { + const inWin = tMs >= s.on && tMs <= (s.off ?? Infinity) + s.tail; + let inst = this.live.get(i); + if (!inWin) { + if (inst) { + inst.dispose(); + this.live.delete(i); + } + return; + } + if (!inst) { + inst = new SystemInst(this.db, this.db.systems[s.key], s.key, sp.team, s.fx, this.parent, this.seed * 131 + i, s.loop); + this.live.set(i, inst); + } + const tau = (tMs - s.on) / 1000; + const stop = s.off == null ? null : (s.off - s.on) / 1000; + const fixed = s.fixedAt === 'end' ? sp.placeAt(sp.end) : s.fixedAt === 'start' ? sp.placeAt(sp.t0) : null; + inst.update(tau, stop, fixed ? () => fixed : (sec) => sp.placeAt(s.on + sec * 1000), cam, s.fixedAt ? 0 : sp.speed); + }); + } + + dispose() { + this.disposed = true; + for (const inst of this.live.values()) inst.dispose(); + this.live.clear(); + this.meshRoot.removeFromParent(); + } +} diff --git a/tools/map-extract/scripts/pack.py b/tools/map-extract/scripts/pack.py index 1d6203d..35f189b 100755 --- a/tools/map-extract/scripts/pack.py +++ b/tools/map-extract/scripts/pack.py @@ -2,7 +2,7 @@ """gvr-map-extract 결과(<코드>.glb + <코드>.json)를 사이트용으로 압축한다. pack.py <추출 폴더> <출력 폴더> <버전(예: VALORANT_13.08)> (agents.json 이 있으면 요원 agent_*.glb · 무기 weapon_*.glb 도 같은 폴더에, index.json agents · weapons. - anims.glb 가 있으면 공용 애니메이션 index.json anims) + anims.glb 가 있으면 공용 애니메이션 index.json anims, abilities/abilities.json 이 있으면 스킬 재료 index.json abilities) 출력: <출력>//<코드>.glb.gz (gltfpack -cc 로 meshopt 압축 · 위치 양자화 → gzip) + <출력>/index.json -ke: 재질 extras(두 층 섞기 B 층) 유지, -vt 14: 반복 UV 가 뭉개지지 않게 사이트 서버 data/maps3d 에 그대로 올리면 된다 (site/server/src/maps3d.ts).""" @@ -59,7 +59,21 @@ if os.path.exists(os.path.join(src, 'anims.glb')): size = pack_one('anims.glb') anims = {'file': 'anims.glb', 'bytes': size} print(f'공용 애니메이션 {size / 1e6:.1f}MB') -idx = {'version': version, 'dir': d, 'updatedAt': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'maps': maps, 'agents': agents, 'weapons': weapons, 'anims': anims} +# 스킬 재료 (abilities 명령 결과 abilities/ 폴더): abilities.json · m_*.glb · t_*.png 를 gzip 만 한다 +# (메시는 작고 뼈대 · 텍스처가 든 것도 있어 gltfpack 을 거치지 않는다) +abilities = None +ad = os.path.join(src, 'abilities') +if os.path.exists(os.path.join(ad, 'abilities.json')): + total = 0 + for f in sorted(os.listdir(ad)): + if not (f == 'abilities.json' or (f.startswith(('m_', 't_')) and f.endswith(('.glb', '.png')))): + continue + with open(os.path.join(ad, f), 'rb') as fi, gzip.open(os.path.join(out, d, f + '.gz'), 'wb', 9) as g: + shutil.copyfileobj(fi, g) + total += os.path.getsize(os.path.join(out, d, f + '.gz')) + abilities = {'file': 'abilities.json', 'bytes': os.path.getsize(os.path.join(out, d, 'abilities.json.gz'))} + print(f'스킬 재료 {total / 1e6:.1f}MB') +idx = {'version': version, 'dir': d, 'updatedAt': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'maps': maps, 'agents': agents, 'weapons': weapons, 'anims': anims, 'abilities': abilities} tmp = os.path.join(out, 'index.json.tmp') json.dump(idx, open(tmp, 'w'), ensure_ascii=False, indent=1) os.replace(tmp, os.path.join(out, 'index.json')) diff --git a/tools/map-extract/scripts/update.sh b/tools/map-extract/scripts/update.sh index 4d63a62..839281a 100755 --- a/tools/map-extract/scripts/update.sh +++ b/tools/map-extract/scripts/update.sh @@ -126,6 +126,8 @@ GVR_USMAP="$usmap" GVR_MANIFEST="$manifest" "$BIN" extract "$raw" stage="요원 추출" GVR_USMAP="$usmap" GVR_MANIFEST="$manifest" "$BIN" agents "$raw" GVR_USMAP="$usmap" GVR_MANIFEST="$manifest" "$BIN" anims "$raw" +# 스킬 재료 (메시 · 파티클 · 텍스처, 사이트가 스킬 효과를 그린다) +GVR_USMAP="$usmap" GVR_MANIFEST="$manifest" "$BIN" abilities "$raw/abilities" stage="압축" python3 "$GVR_MAPS_HOME/scripts/pack.py" "$raw" "$out" "$version" dir="$(jq -r .dir "$out/index.json")" diff --git a/tools/map-extract/src/Abilities.cs b/tools/map-extract/src/Abilities.cs new file mode 100644 index 0000000..046a359 --- /dev/null +++ b/tools/map-extract/src/Abilities.cs @@ -0,0 +1,1547 @@ +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_)", 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); +} diff --git a/tools/map-extract/src/Materials.cs b/tools/map-extract/src/Materials.cs index 79d17db..d5097b2 100644 --- a/tools/map-extract/src/Materials.cs +++ b/tools/map-extract/src/Materials.cs @@ -11,11 +11,15 @@ public sealed class MatParams public readonly Dictionary Textures = new(StringComparer.OrdinalIgnoreCase); public readonly Dictionary Vectors = new(StringComparer.OrdinalIgnoreCase); public readonly Dictionary Scalars = new(StringComparer.OrdinalIgnoreCase); + public readonly Dictionary Switches = new(StringComparer.OrdinalIgnoreCase); public string? BlendMode; + public bool TwoSided; + public string? ShadingModel; public static MatParams Resolve(UMaterialInterface mat) { var r = new MatParams { Path = mat.GetPathName() }; + bool? twoSided = null; UMaterialInterface? cur = mat; for (var d = 0; d < 12 && cur != null; d++) { @@ -28,8 +32,17 @@ public sealed class MatParams if (v.ParameterValue is { } c && !r.Vectors.ContainsKey(v.Name)) r.Vectors[v.Name] = c; foreach (var s in mi.ScalarParameterValues) if (!r.Scalars.ContainsKey(s.Name)) r.Scalars[s.Name] = s.ParameterValue; - if (r.BlendMode == null && mi.TryGetValue(out CUE4Parse.UE4.Assets.Objects.FStructFallback bpo, "BasePropertyOverrides") && bpo.TryGetValue(out bool ov, "bOverride_BlendMode") && ov) - r.BlendMode = bpo.GetOrDefault("BlendMode").ToString(); + if (mi.TryGetValue(out CUE4Parse.UE4.Assets.Objects.FStructFallback bpo, "BasePropertyOverrides")) + { + if (r.BlendMode == null && bpo.TryGetValue(out bool ov, "bOverride_BlendMode") && ov) + r.BlendMode = bpo.GetOrDefault("BlendMode").ToString(); + if (twoSided == null && bpo.TryGetValue(out bool ots, "bOverride_TwoSided") && ots) + twoSided = bpo.GetOrDefault("TwoSided"); + } + // 정적 스위치 (StaticParameters): 덮어쓴 것만, 자식 값이 먼저 + if (mi.StaticParameters?.StaticSwitchParameters is { } sws) + foreach (var sp in sws) + if (sp.bOverride && !r.Switches.ContainsKey(sp.Name)) r.Switches[sp.Name] = sp.Value; UMaterialInterface? parent = null; try { parent = mi.Parent?.Load(); } catch { } cur = parent; @@ -37,10 +50,16 @@ public sealed class MatParams else { r.Base = cur.GetPathName(); - if (r.BlendMode == null && cur is UMaterial m) r.BlendMode = m.BlendMode.ToString(); + if (cur is UMaterial m) + { + r.BlendMode ??= m.BlendMode.ToString(); + twoSided ??= m.TwoSided; + r.ShadingModel = m.ShadingModel.ToString(); + } break; } } + r.TwoSided = twoSided ?? false; return r; } } diff --git a/tools/map-extract/src/Program.cs b/tools/map-extract/src/Program.cs index 7dfbe8d..a330ec1 100644 --- a/tools/map-extract/src/Program.cs +++ b/tools/map-extract/src/Program.cs @@ -17,6 +17,7 @@ using GvrMapExtract; // gvr-map-extract extract <출력 폴더> [맵...] 맵마다 <코드>.glb (UE 월드 좌표 cm, 위치 + 삼각형) + <코드>.json // gvr-map-extract agents <출력 폴더> [요원...] 요원 몸 agent_<코드>.glb · 무기 weapon_<이름>.glb + agents.json // gvr-map-extract anims <출력 폴더> 모든 요원 공용 애니메이션 anims.glb +// gvr-map-extract abilities <출력 폴더> [요원 · 클래스...] 스킬 재료 abilities.json + m_*.glb + t_*.png // // 환경변수 // GVR_USMAP 매핑 파일 (.usmap, 필수: 13.08 부터 패키지에 형 정보가 없다). uedb.dev 에서 받는다 @@ -178,6 +179,9 @@ switch (args[0]) Console.WriteLine($"끝: 공용 애니메이션 {r.Clips} · 실패 {r.Failed}{(r.Missing.Count > 0 ? " · 빠짐 " + string.Join(',', r.Missing) : "")} · 받은 양 {store.DownloadedBytes >> 20}MB · {sw.Elapsed.TotalMinutes:F1}분"); return r.Failed == 0 ? 0 : 1; } + case "abilities": + // 요원 스킬 3D 재료: abilities.json + m_*.glb + t_*.png (Abilities.cs) + return Abilities.Run(provider, args[1], args.Skip(2).ToList(), store); case "anim": foreach (var a in args.Skip(1)) ProbeAnim.Anim(provider, a); break;