3D 리플레이 실감 4단계: 1인칭 팔 · 총 · 동작 · 발로란트 조준점

- 추출기 viewmodels: 요원 1인칭 팔 fparms_* (30명) · 무기 1인칭 fpweapon_* (22종, 탄창 · 총 동작) · 팔 동작 fpanim_* (대기 · 사격 · 재장전 · 꺼내기 · 정조준 · 걷기 · 스파이크 작동). Agents.Skinned 로 스켈레탈 메시 내보내기를 나눠 3인칭 요원과 같이 쓴다
- pack.py · update.sh: viewmodels 압축 · index.json viewmodels, 갱신 때 같이 뽑는다
- 사이트 lib/viewmodel.ts: 카메라 공간 장면으로 맵 위에 그린다. 꺼내기 > 재장전 > 사격(총구 불꽃) > 걷기 > 정조준 > 대기를 리플레이 시각만으로 고른다
- 1인칭: 줌(소총 1.25배 · 저격 2.5/5배 + 조준경), 조준점을 발로란트 기본 십자(흰 선 · 틈 · 외곽선)로
- 작업 노트 docs/dev/replay-3d.md

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-29 18:21:47 +09:00
parent 88e043da28
commit 1fb8821663
11 changed files with 677 additions and 46 deletions

View File

@@ -65,6 +65,19 @@
- 13.09 전체 (2026-10-29 반영): 맵 23개 중 22개에 조명 (아이스박스 Port 는 BuiltData 에 라이트맵이 없어 예전 장면 조명), 아틀라스 1.2~4.7MB, 사이트 폴더 303 → 403MB. 맵 추출 26분 · 서비스 최대 메모리 5.9GB(스킬 재료 단계 포함).
- 한계: 1/4 로 줄여 그림자 가장자리가 흐리다. 움직이는 것(요원)은 구운 조명을 받지 않는다 (볼륨 라이트맵은 아직 안 씀). 어비스 낭떠러지처럼 게임에서 어두운 곳은 그대로 어둡다.
## 1인칭 팔 · 총 · 조준점 (2026-10-29, 실감 4단계)
- 계기: aim.sheepu.dev 훈련 화면(밴달 + 피닉스 팔 1인칭, 흰 십자 조준점, 탄흔 · 총소리)을 보고 우리 1인칭에 없던 것을 게임 파일에서 직접 뽑았다 (그 사이트 파일은 쓰지 않음).
- 추출 `gvr-map-extract viewmodels <폴더>` (`src/Viewmodels.cs`, 13.09 전체 39초 · 최대 1.1GB):
- `fparms_<코드>.glb` 요원 1인칭 팔 `Characters/<코드>/S0/1P/Models/FP_<코드>[_New]_S0_Skelmesh` (30명, 브리치는 `_New`). 팔 메시에 같이 든 스킬 · 3인칭 조각(재질 AB_ · ABTP_ · CS_ · TP_)은 뺀다 (네온 칼날 모양, 소바 활 장갑 등).
- `fpweapon_<이름>.glb` 무기 1인칭 `<무기 폴더>/S0/1P/Models/(GN|EQ)_*_S0_Skelmesh` + 탄창(Magazine_Main 뼈 자식) + `GN_Core_*_S0_{Fire,Reload,Equip}` → gun_fire · gun_reload · gun_equip (22종, 칼 · 스파이크 포함).
- `fpanim_<이름>.glb` 팔 동작(뼈 노드만, 공용 뼈대 `FP_Core_Retarget_Skelmesh`): `FP_Core_*_S0_` IdlePose|Idle · Fire|FireAdd · Reload · Equip · AltIdlePose(정조준) · WalkAdd · Activate(스파이크). 덧셈 동작은 CUE4Parse 가 기준 자세에 더해 준다.
- 압축 합계 7.4MB, index.json `viewmodels`. update.sh 가 anims 다음에 돌린다.
- 사이트 `lib/viewmodel.ts`: 맵과 따로 장면 하나(카메라 공간, 깊이를 지우고 맵 위에 그림). 무기 뿌리 = 팔 뼈 MasterWeapon × 회전 (0.5,−0.5,0.5,0.5) (총구 → 팔 앞, 탄창 → 아래가 되는 축 맞춤, 모든 총 같음). 눈 = 팔 Camera 뼈(대기 자세).
- 자세는 시각만으로: 꺼내기(equips) > 재장전(states ReloadState) > 사격(shots, 60ms 총구 불꽃) > 걷기(0.2초에 30cm 넘게 움직임) > 정조준(ZoomState*) > 대기. 죽었거나 스킬 · 맨손이면 숨긴다.
- 줌: 소총 등 1.25배, 저격총 2.5배(2단 5배) + 조준경 테두리(검은 원 · 가는 십자선), 저격 줌 중에는 팔 · 총을 숨긴다.
- 조준점: 녹색 점 → 발로란트 기본 (흰 선 4개 · 가운데 틈 · 검은 외곽선, `.r3d-cross`).
- 안 한 것: 총소리 · 발소리(Wwise 사운드뱅크라 따로 풀어야 함), HUD 체력 · 탄약(리플레이에 값 없음), 탄흔(맞은 자리 `hits` 로 가능), 스킨(기본 스킨만), 스킬 1인칭 동작, 재장전 중 탄창이 손으로 옮겨 가는 것(소켓 바꾸기라 탄창이 잠깐 안 보임).
## 남은 일
- 실제 경기로 동기화 오차 확인 (사이트 아래 줄 "킬 N개로 맞춤 (최대 오차 X초)")

View File

@@ -6,9 +6,10 @@ import { player } from '../store/player';
import { settings, useSettings } from '../store/settings';
import { useData } from '../store/app';
import { fmtClock } from '../lib/format';
import { equipAt, equipLabel, equipTracks, isDead, roundAt, samplePath, samplePlayer, type ReplayFile, type ReplaySync } from '../lib/replay';
import { equipAt, equipLabel, equipTracks, indexAt, isDead, roundAt, samplePath, samplePlayer, type ReplayFile, type ReplaySync } from '../lib/replay';
import { findMap3d, loadMap3d, mapMaterial, worldMatrix } from '../lib/map3d';
import { AgentRig, isGun, loadAgent, loadAnims, loadWeapon } from '../lib/agents3d';
import { AgentRig, isGun, loadAgent, loadAnims, loadWeapon, weaponCat } from '../lib/agents3d';
import { Viewmodel, viewmodelIndex } from '../lib/viewmodel';
import { buildAnimIndex, rigInput } from '../lib/replayAnim';
import { abilityLook, type AbilityLook } from '../lib/abilities';
import { loadVfxDb, vfxCoverage, VfxObject, type Place, type VfxDb } from '../lib/vfx';
@@ -130,6 +131,8 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
ceilRef.current = ceil;
/** 지금 자르는 높이 (가장 낮은 층에서 cm, 화면 표시용) */
const [ceilNow, setCeilNow] = useState<number | null>(null);
// 1인칭 저격총 조준경 (줌 중)
const [scoped, setScoped] = useState(false);
// 바닥(미니맵) 높이: 선수 높이의 하위 5% (떨어져 죽은 기록은 뺀다)
const zBase = useMemo(() => {
@@ -299,6 +302,13 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
let prevT = localT.current;
const animIx = buildAnimIndex(replay, equipByPlayer);
// 1인칭 팔 · 총 (index.json viewmodels 가 있을 때만)
let vm: Viewmodel | null = null;
void viewmodelIndex().then((ix) => {
if (!disposed && ix) vm = new Viewmodel(ix);
});
let vmOn = false;
let scopedNow = false;
// 선택한 선수 이동 경로 (최근 6초)
const trailGeo = new THREE.BufferGeometry();
@@ -584,6 +594,49 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
let lastMode: CamMode = 'top';
const tmp = new THREE.Vector3();
const euler = new THREE.Euler(0, 0, 0, 'YXZ');
/** 1인칭 선수의 손 상태 (모두 리플레이 시각 t 로만 정한다) */
const fpState = (p: number, t: number) => {
const ek = equipAt(animIx.equips[p], t);
const kind = replay.equipKinds?.[ek];
const ei = indexAt(animIx.equipT[p], t);
const equipT = ei >= 0 && animIx.equips[p][ei][1] === ek ? animIx.equips[p][ei][0] : null;
// 무기 상태: 이 무기를 든 뒤의 재장전 · 줌
let reloadMs: number | null = null;
let zoom = 0;
let zoomSeen = false;
const st = animIx.states[p];
for (let i = indexAt(animIx.stateT[p], t), n = 0; i >= 0 && n < 60; i--, n++) {
const [ts, sek, name] = st[i];
if (equipT != null && ts < equipT) break;
if (sek !== ek) continue;
if (reloadMs == null && name === 'ReloadState' && !zoomSeen) reloadMs = t - ts;
if (!zoomSeen && /^(ZoomState|BufferedZoomLevel)/.test(name)) {
zoomSeen = true;
zoom = /Level2/.test(name) ? 2 : /Level1/.test(name) ? 1 : 0;
}
if (zoomSeen && reloadMs != null) break;
}
const shots = animIx.shots[p];
const si = indexAt(shots, t);
const shotT = si >= 0 ? shots[si] : null;
// 걷기: 0.2초 사이 움직인 거리
const tr = replay.players[p].track;
const a = samplePlayer(tr, t, replay.sampleMs * 6);
const b = samplePlayer(tr, t - 200, replay.sampleMs * 6);
const moving = !!a && !!b && Math.hypot(a.x - b.x, a.y - b.y) > 30;
return {
kind,
zoom,
sniper: weaponCat(kind) === 'sniper',
input: {
equipMs: equipT != null ? t - equipT : null,
shotMs: shotT != null && (equipT == null || shotT >= equipT) ? t - shotT : null,
reloadMs,
ads: zoom > 0,
walkMs: moving ? t : null,
},
};
};
const frame = (now: number) => {
raf = requestAnimationFrame(frame);
const dt = lastNow ? Math.min(0.1, (now - lastNow) / 1000) : 0;
@@ -857,6 +910,21 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
camera.position.copy(eye);
camera.lookAt(eye.x + d.x * Math.cos(pr), eye.y + Math.sin(pr), eye.z + d.z * Math.cos(pr));
}
// 1인칭 팔 · 총: 들고 있는 무기 · 꺼낸 때 · 사격 · 재장전 · 줌 · 걷기
const fp = p && !isDead(replay, selIdx, t) ? fpState(selIdx, t) : null;
const zoomFov = fp ? 70 / (fp.zoom === 0 ? 1 : fp.sniper ? (fp.zoom >= 2 ? 5 : 2.5) : 1.25) : 70;
if (camera.fov !== zoomFov) {
camera.fov = zoomFov;
camera.updateProjectionMatrix();
}
const sc = !!fp && fp.sniper && fp.zoom > 0;
if (sc !== scopedNow) setScoped((scopedNow = sc));
const chr = replay.players[selIdx].character;
vmOn = !!fp && !sc && !!vm && vm.has(chr, fp.kind);
if (vmOn && vm && chr && fp) {
vm.set(chr, fp.kind!);
vm.pose(fp.input);
}
} else if (mode === 'free') {
euler.set(free.pitch, free.yaw, 0, 'YXZ');
camera.quaternion.setFromEuler(euler);
@@ -865,7 +933,12 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
tmp.set((k.has('KeyD') || k.has('ArrowRight') ? 1 : 0) - (k.has('KeyA') || k.has('ArrowLeft') ? 1 : 0), (k.has('KeyE') ? 1 : 0) - (k.has('KeyQ') ? 1 : 0), (k.has('KeyS') || k.has('ArrowDown') ? 1 : 0) - (k.has('KeyW') || k.has('ArrowUp') ? 1 : 0));
if (tmp.lengthSq() > 0) camera.position.add(tmp.normalize().multiplyScalar(speed).applyQuaternion(camera.quaternion));
} else controls.update();
if (mode !== 'fp') {
vmOn = false;
if (scopedNow) setScoped((scopedNow = false));
}
renderer.render(scene, camera);
if (vmOn && vm?.ready) vm.render(renderer, camera.fov, camera.aspect);
if (now - lastUi > 100) {
lastUi = now;
setCeilNow((c) => {
@@ -887,6 +960,7 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
renderer.domElement.removeEventListener('keyup', onKey);
renderer.domElement.removeEventListener('blur', onBlur);
controls.dispose();
vm?.dispose();
for (const v of views) v.rig?.dispose();
for (const vo of vfxObjs.values()) vo.dispose();
scene.traverse((o) => {
@@ -975,7 +1049,15 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
))}
</div>
)}
{cam === 'fp' && <div className="r3d-cross" />}
{cam === 'fp' && scoped && <div className="r3d-scope" />}
{cam === 'fp' && !scoped && (
<div className="r3d-cross" aria-hidden>
<i />
<i />
<i />
<i />
</div>
)}
{cam === 'free' && <div className="r3d-hud bl muted small">끌기: 둘러보기 · W A S D: 이동 · Q / E: 아래 / 위 · Shift: 빠르게 (화면을 한 번 누른 뒤)</div>}
{selInfo && cam !== 'free' && (
<div className="r3d-hud bl">

View File

@@ -0,0 +1,233 @@
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 { clone as cloneSkinned } from 'three/examples/jsm/utils/SkeletonUtils.js';
import { assetUrl } from './agents3d';
import { loadIndex } from './map3d';
/**
* 1인칭 화면 팔 · 총 (tools/map-extract viewmodels → index.json viewmodels).
* arms[캐릭터 클래스] 요원 1인칭 팔 (뼈대는 모든 요원 공용, Camera 뼈 = 눈)
* weapons[무기 이름] 무기 1인칭 모델(총 동작 gun_*) + 그 무기를 든 팔 동작(idle · fire · reload · equip · ads · walk · activate)
* 좌표는 게임(UE) cm. 무기 뿌리는 팔 뼈 MasterWeapon 에 GUN_Q 만큼 돌려 붙인다 (총 몸의 앞 = 팔의 앞, 탄창 = 아래).
* 자세는 시각(ms)만으로 정한다 (되감기 · 멈춤 · 배속에도 같은 자세).
*/
export interface VmIndex {
arms: Record<string, { code: string; file: string }>;
weapons: Record<string, { file: string; anim: string; clips: string[]; gunClips: string[]; points?: { muzzle?: number[] } }>;
}
const GUN_Q = new THREE.Quaternion(0.5, -0.5, 0.5, 0.5);
/** UE(cm, X 앞 · Y 오른쪽 · Z 위) → 카메라 공간(m, -Z 앞 · X 오른쪽 · Y 위) */
const UE_TO_VIEW = new THREE.Matrix4().set(0, 0.01, 0, 0, 0, 0, 0.01, 0, -0.01, 0, 0, 0, 0, 0, 0, 1);
const cache = new Map<string, Promise<GLTF>>();
function load(url: string): Promise<GLTF> {
let p = cache.get(url);
if (!p) {
const loader = new GLTFLoader();
loader.setMeshoptDecoder(MeshoptDecoder);
p = loader.loadAsync(url);
p.catch(() => cache.delete(url));
cache.set(url, p);
}
return p;
}
export async function viewmodelIndex(): Promise<(VmIndex & { dir: string }) | null> {
const idx = (await loadIndex()) as { dir: string | null; viewmodels?: VmIndex | null } | null;
return idx?.dir && idx.viewmodels ? { ...idx.viewmodels, dir: idx.dir } : null;
}
/** 지금 자세를 정하는 입력 (모두 ms, 없으면 null) */
export interface VmInput {
/** 이 무기를 꺼낸 지 */
equipMs: number | null;
/** 마지막 사격 뒤 */
shotMs: number | null;
/** 재장전 시작 뒤 */
reloadMs: number | null;
/** 정조준(줌) 중 */
ads: boolean;
/** 걷는 중이면 걸은 시간 (반복 동작 위치) */
walkMs: number | null;
}
function findBone(root: THREE.Object3D, name: string): THREE.Object3D | null {
let b: THREE.Object3D | null = null;
root.traverse((o) => {
if (!b && o.name === name) b = o;
});
return b;
}
function prep(root: THREE.Object3D) {
root.traverse((o) => {
const m = o as THREE.Mesh;
if (!m.isMesh) return;
m.frustumCulled = false;
const mat = m.material as THREE.MeshStandardMaterial;
mat.side = THREE.DoubleSide;
});
}
/**
* 1인칭 팔 + 무기. scene 을 따로 두고 카메라 공간에서 그린다 (맵보다 앞에, 깊이 따로).
* set() 으로 요원 · 무기를 바꾸고(받는 동안은 이전 것), pose() 로 자세를 정한 뒤 render().
*/
export class Viewmodel {
readonly scene = new THREE.Scene();
readonly camera = new THREE.PerspectiveCamera(70, 1, 0.01, 20);
private root = new THREE.Group();
private arms: THREE.Object3D | null = null;
private armsMixer: THREE.AnimationMixer | null = null;
private gunMixer: THREE.AnimationMixer | null = null;
private armClips = new Map<string, THREE.AnimationClip>();
private gunClips = new Map<string, THREE.AnimationClip>();
private flash: THREE.Sprite;
private muzzle: THREE.Object3D | null = null;
private want = '';
private have = '';
private disposed = false;
constructor(private readonly idx: VmIndex & { dir: string }) {
this.root.matrixAutoUpdate = false;
this.scene.add(this.root);
this.scene.add(new THREE.HemisphereLight(0xffffff, 0x8a8f99, 2.2));
const sun = new THREE.DirectionalLight(0xfff4e0, 1.6);
sun.position.set(0.4, 1, 0.6);
this.scene.add(sun);
// 총구 불꽃 (사격 직후 잠깐)
const c = document.createElement('canvas');
c.width = c.height = 64;
const g = c.getContext('2d')!;
const grd = g.createRadialGradient(32, 32, 0, 32, 32, 32);
grd.addColorStop(0, 'rgba(255,250,220,1)');
grd.addColorStop(0.3, 'rgba(255,200,90,0.85)');
grd.addColorStop(1, 'rgba(255,120,20,0)');
g.fillStyle = grd;
g.fillRect(0, 0, 64, 64);
this.flash = new THREE.Sprite(new THREE.SpriteMaterial({ map: new THREE.CanvasTexture(c), blending: THREE.AdditiveBlending, depthTest: false, transparent: true }));
this.flash.scale.setScalar(0.12);
this.flash.visible = false;
this.scene.add(this.flash);
}
/** 이 요원 · 무기에 1인칭 모델이 있는지 */
has(character: string | null | undefined, weapon: string | null | undefined): boolean {
return !!character && !!weapon && !!this.idx.arms[character] && !!this.idx.weapons[weapon];
}
/** 요원 · 무기를 바꾼다 (같으면 그대로). 받는 동안은 이전 모델을 그린다 */
set(character: string, weapon: string) {
const key = `${character}|${weapon}`;
if (key === this.want) return;
this.want = key;
const a = this.idx.arms[character];
const w = this.idx.weapons[weapon];
if (!a || !w) return;
const url = (f: string) => assetUrl(this.idx.dir, f);
void Promise.all([load(url(a.file)), load(url(w.file)), load(url(w.anim))])
.then(([ag, wg, an]) => {
if (this.disposed || this.want !== key) return;
this.build(ag, wg, an);
this.have = key;
})
.catch(() => undefined);
}
private build(ag: GLTF, wg: GLTF, an: GLTF) {
if (this.arms) this.root.remove(this.arms);
const arms = cloneSkinned(ag.scene);
const gun = cloneSkinned(wg.scene);
prep(arms);
prep(gun);
const attach = findBone(arms, 'MasterWeapon');
if (attach) {
gun.quaternion.copy(GUN_Q);
attach.add(gun);
}
this.root.add(arms);
this.arms = arms;
this.muzzle = findBone(gun, 'Muzzle');
this.armsMixer = new THREE.AnimationMixer(arms);
this.gunMixer = new THREE.AnimationMixer(gun);
this.armClips = new Map(an.animations.map((c) => [c.name, c]));
this.gunClips = new Map(wg.animations.map((c) => [c.name, c]));
// 눈 = 팔 Camera 뼈 (대기 자세)
this.play(this.armsMixer, this.armClips.get('idle'), 0, false);
arms.updateMatrixWorld(true);
const cam = findBone(arms, 'Camera');
const cp = cam ? new THREE.Vector3().setFromMatrixPosition(cam.matrixWorld) : new THREE.Vector3(0, 0, 166);
this.root.matrix.copy(UE_TO_VIEW).multiply(new THREE.Matrix4().makeTranslation(-cp.x, -cp.y, -cp.z));
this.root.matrixWorldNeedsUpdate = true;
}
get ready() {
return this.have !== '' && this.have === this.want;
}
private play(mixer: THREE.AnimationMixer, clip: THREE.AnimationClip | undefined, ms: number, loop: boolean) {
mixer.stopAllAction();
if (!clip) return false;
const a = mixer.clipAction(clip);
a.reset();
a.setLoop(loop ? THREE.LoopRepeat : THREE.LoopOnce, Infinity);
a.clampWhenFinished = true;
a.play();
const d = Math.max(clip.duration, 1e-3);
a.time = loop ? (ms / 1000) % d : Math.min(ms / 1000, d);
mixer.update(0);
return true;
}
/** 시각만으로 자세: 꺼내기 > 재장전 > 사격 > 걷기 > 정조준 > 대기 */
pose(i: VmInput) {
if (!this.armsMixer || !this.gunMixer) return;
const dur = (n: string) => (this.armClips.get(n)?.duration ?? 0) * 1000;
let role = 'idle';
let ms = 0;
let loop = false;
if (i.equipMs != null && i.equipMs < dur('equip')) [role, ms] = ['equip', i.equipMs];
else if (i.reloadMs != null && i.reloadMs < dur('reload')) [role, ms] = ['reload', i.reloadMs];
else if (i.shotMs != null && i.shotMs < dur('fire')) [role, ms] = ['fire', i.shotMs];
else if (i.walkMs != null && this.armClips.has('walk') && !i.ads) [role, ms, loop] = ['walk', i.walkMs, true];
else if (i.ads && this.armClips.has('ads')) role = 'ads';
if (!this.play(this.armsMixer, this.armClips.get(role), ms, loop)) this.play(this.armsMixer, this.armClips.get('idle'), 0, false);
if (!this.play(this.gunMixer, this.gunClips.get('gun_' + role), ms, false)) this.gunMixer.stopAllAction();
// 총구 불꽃: 사격 뒤 60ms
const on = i.shotMs != null && i.shotMs < 60 && role === 'fire' && !!this.muzzle;
this.flash.visible = on;
if (on) {
this.root.updateMatrixWorld(true);
this.flash.position.setFromMatrixPosition(this.muzzle!.matrixWorld);
this.flash.material.rotation = (i.shotMs! * 7) % (Math.PI * 2);
}
}
/** 맵을 그린 뒤 깊이만 지우고 그 위에 그린다 */
render(renderer: THREE.WebGLRenderer, fov: number, aspect: number) {
if (!this.arms) return;
if (this.camera.fov !== fov || this.camera.aspect !== aspect) {
this.camera.fov = fov;
this.camera.aspect = aspect;
this.camera.updateProjectionMatrix();
}
const clip = renderer.localClippingEnabled;
const auto = renderer.autoClear;
renderer.localClippingEnabled = false;
renderer.autoClear = false;
renderer.clearDepth();
renderer.render(this.scene, this.camera);
renderer.autoClear = auto;
renderer.localClippingEnabled = clip;
}
dispose() {
this.disposed = true;
this.armsMixer?.stopAllAction();
this.gunMixer?.stopAllAction();
this.flash.material.map?.dispose();
this.flash.material.dispose();
}
}

View File

@@ -4084,19 +4084,56 @@ button.match:hover {
border-radius: 6px;
padding: 3px 6px;
}
/* 1인칭 조준점: 발로란트 기본 (흰 안쪽 선 4개 · 가운데 틈 · 검은 외곽선) */
.r3d-cross {
position: absolute;
left: 50%;
top: 50%;
width: 6px;
height: 6px;
margin: -3px 0 0 -3px;
border-radius: 50%;
background: #7dffb0;
box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.6);
width: 0;
height: 0;
pointer-events: none;
z-index: 2;
}
.r3d-cross i {
position: absolute;
background: #fff;
box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.5);
}
.r3d-cross i:nth-child(1),
.r3d-cross i:nth-child(2) {
width: 2px;
height: 6px;
left: -1px;
}
.r3d-cross i:nth-child(1) {
top: -9px;
}
.r3d-cross i:nth-child(2) {
top: 3px;
}
.r3d-cross i:nth-child(3),
.r3d-cross i:nth-child(4) {
width: 6px;
height: 2px;
top: -1px;
}
.r3d-cross i:nth-child(3) {
left: -9px;
}
.r3d-cross i:nth-child(4) {
left: 3px;
}
/* 저격총 줌: 둥근 조준경 밖은 검게, 가는 십자선 */
.r3d-scope {
position: absolute;
inset: 0;
pointer-events: none;
z-index: 2;
background:
linear-gradient(rgba(0, 0, 0, 0.85), rgba(0, 0, 0, 0.85)) center / 100% 1px no-repeat,
linear-gradient(rgba(0, 0, 0, 0.85), rgba(0, 0, 0, 0.85)) center / 1px 100% no-repeat,
radial-gradient(circle at center, transparent 0, transparent min(46vh, 46%), #000 calc(min(46vh, 46%) + 1px));
}
.r3d-stage canvas:focus {
outline: none;
}

View File

@@ -2,6 +2,7 @@
"""gvr-map-extract 결과(<코드>.glb + <코드>.json)를 사이트용으로 압축한다.
pack.py <추출 폴더> <출력 폴더> <버전(예: VALORANT_13.08)>
(agents.json 이 있으면 요원 agent_*.glb · 무기 weapon_*.glb 도 같은 폴더에, index.json agents · weapons.
viewmodels.json 이 있으면 1인칭 팔 fparms_*.glb · 무기 fpweapon_*.glb · 팔 동작 fpanim_*.glb, index.json viewmodels.
anims.glb 가 있으면 공용 애니메이션 index.json anims, abilities/abilities.json 이 있으면 스킬 재료 index.json abilities)
출력: <출력>/<dir>/<코드>.glb.gz (gltfpack -cc 로 meshopt 압축 · 위치 양자화 → gzip) + <출력>/index.json
-ke: 재질 extras(두 층 섞기 B 층 · 구운 조명 K) 유지
@@ -16,7 +17,7 @@ d = re.sub(r'[^\w.-]', '_', f'{version}-{stamp}')
os.makedirs(os.path.join(out, d), exist_ok=True)
maps = {}
for name in sorted(os.listdir(src)):
if not name.endswith('.json') or name == 'agents.json':
if not name.endswith('.json') or name in ('agents.json', 'viewmodels.json'):
continue
info = json.load(open(os.path.join(src, name)))
code = info['code']
@@ -55,6 +56,24 @@ if os.path.exists(aj):
if size:
weapons[name] = {'file': v['file'], 'bytes': size, 'points': v.get('points') or {}}
print(f'요원 {len(agents)} · 무기 {len(weapons)}')
# 1인칭 팔 · 무기 · 팔 동작 (viewmodels 명령 결과 viewmodels.json): 뼈대 · 동작 · 노드 이름을 지킨다 (-kn)
viewmodels = None
vj = os.path.join(src, 'viewmodels.json')
if os.path.exists(vj):
v = json.load(open(vj))
vm_arms, vm_weapons, total = {}, {}, 0
for cls, a in v.get('arms', {}).items():
size = pack_one(a['file'])
if size:
vm_arms[cls] = {'code': a['code'], 'file': a['file'], 'bytes': size}
total += size
for name, w in v.get('weapons', {}).items():
s1, s2 = pack_one(w['file']), pack_one(w['anim'])
if s1 and s2:
vm_weapons[name] = {'file': w['file'], 'anim': w['anim'], 'clips': w.get('clips') or [], 'gunClips': w.get('gunClips') or [], 'points': w.get('points') or {}, 'bytes': s1 + s2}
total += s1 + s2
viewmodels = {'arms': vm_arms, 'weapons': vm_weapons}
print(f'1인칭 팔 {len(vm_arms)} · 무기 {len(vm_weapons)} · {total / 1e6:.1f}MB')
# 공용 애니메이션 (anims 명령 결과 anims.glb): 뼈 이름으로 요원 몸에 붙인다 (-kn)
anims = None
if os.path.exists(os.path.join(src, 'anims.glb')):
@@ -75,7 +94,7 @@ if os.path.exists(os.path.join(ad, 'abilities.json')):
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}
idx = {'version': version, 'dir': d, 'updatedAt': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'maps': maps, 'agents': agents, 'weapons': weapons, 'anims': anims, 'abilities': abilities, 'viewmodels': viewmodels}
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'))

View File

@@ -18,8 +18,9 @@ E
cat > "$T/fakebin" <<'E'
#!/bin/bash
[ "$1" = manifest ] && { echo "https://x/releases/${FAKE_MANIFEST:-AAA}.manifest"; exit 0; }
# 공용 애니메이션 · 스킬 재료: 이 시험에서는 만들 것 없이 성공
# 공용 애니메이션 · 1인칭 · 스킬 재료: 이 시험에서는 만들 것 없이 성공
[ "$1" = anims ] && exit 0
[ "$1" = viewmodels ] && exit 0
[ "$1" = abilities ] && { mkdir -p "$2"; exit 0; }
if [ "$1" = agents ]; then
# 요원 · 무기: FAKE_FAIL=agents 면 아무것도 못 뽑고 실패, agents-partial 이면 하나만 뽑고 실패 (실제 추출기처럼 종료 코드 1)

View File

@@ -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"
# 1인칭 팔 · 무기 · 동작 (사이트 1인칭 화면)
GVR_USMAP="$usmap" GVR_MANIFEST="$manifest" "$BIN" viewmodels "$raw"
# 스킬 재료 (메시 · 파티클 · 텍스처, 사이트가 스킬 효과를 그린다)
GVR_USMAP="$usmap" GVR_MANIFEST="$manifest" "$BIN" abilities "$raw/abilities"
stage="압축"

View File

@@ -69,12 +69,50 @@ public static class Agents
public sealed record Result(int Triangles, int Bones, int Clips, int Textures, long TextureBytes);
public static Result Export(IFileProvider provider, USkeletalMesh mesh, string file, int maxTex, int lodWant)
{
var glb = new Glb();
var tex = new TexStore(provider, glb, maxTex);
var (boneNode, bones, skin, tris) = Skinned(provider, glb, tex, mesh, lodWant);
// 애니메이션
var nameToBone = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
for (var i = 0; i < bones.Length; i++) nameToBone.TryAdd(bones[i].Name, i);
var upperSet = Subtree(bones, "Spine1");
upperSet.UnionWith(Subtree(bones, "MasterWeaponAim")); // 총 붙는 뼈 (R_WeaponMaster) 도 위 몸 자세를 따른다
var lowerSet = Subtree(bones, "Pelvis");
if (nameToBone.TryGetValue("Splitter", out var spl)) lowerSet.Add(spl);
// Skeleton · Root 는 회전만 (애니메이션에 따라 몸 방향을 여기서 보정한다). 이동(루트 모션)은 뺀다
var rootOnlyRot = new HashSet<int>();
foreach (var n in new[] { "Skeleton", "Root" })
if (nameToBone.TryGetValue(n, out var ri)) { lowerSet.Add(ri); rootOnlyRot.Add(ri); }
var animations = new JsonArray();
foreach (var (name, path, upper) in Clips)
{
try
{
var a = provider.LoadPackageObject<UAnimSequence>(path + "." + path[(path.LastIndexOf('/') + 1)..]);
var set = a.ConvertAnims();
var seq = set.Sequences[0];
seq.RetargetTracks(mesh.ReferenceSkeleton);
var anim = Clip(glb, seq, set.Skeleton, nameToBone, upper ? upperSet : lowerSet, boneNode, bones, name, rootOnlyRot);
if (anim != null) animations.Add(anim);
}
catch (Exception e)
{
Console.Error.WriteLine($" 애니메이션 {name} 실패: {e.GetType().Name} {e.Message}");
}
}
glb.Write(file, new JsonObject { ["skins"] = new JsonArray(skin), ["animations"] = animations });
return new Result(tris, bones.Length, animations.Count, tex.Count, tex.Bytes);
}
/// <summary>스켈레탈 메시 하나를 glb 에 넣는다: 뼈 노드(참조 자세) · 피부(역바인드) · 재질별 primitive · 메시 노드(최상위).
/// 뼈 노드 번호 · 뼈 · skin 객체 · 삼각형 수를 돌려준다 (skin 은 Write 의 extra "skins" 에 넣는다)</summary>
public static (int[] BoneNode, MeshBoneDto[] Bones, JsonObject Skin, int Tris) Skinned(IFileProvider provider, Glb glb, TexStore tex, USkeletalMesh mesh, int lodWant, int skinIndex = 0, Func<string, bool>? skipMaterial = null)
{
var dto = new SkeletalMeshDto(mesh, EMeshQuality.All);
var lod = dto.LODs[Math.Min(lodWant, dto.LODs.Count - 1)];
var bones = dto.Bones;
var glb = new Glb();
var tex = new TexStore(provider, glb, maxTex);
// 뼈 노드 (참조 자세 TRS), 부모-자식
var boneNode = new int[bones.Length];
@@ -153,7 +191,7 @@ public static class Agents
try { m = dto.Materials.ElementAtOrDefault(sec.MaterialIndex).Material?.Load<UMaterialInterface>(); } catch { }
var mp = m != null ? MatParams.Resolve(m) : null;
// 반투명(눈 덧칠 · 유리 · 빛나는 껍데기) · 숨김 재질은 뺀다
if (mp != null && (mp.BlendMode is "BLEND_Additive" or "BLEND_Translucent" or "BLEND_Modulate" || m!.Name.Contains("Hidden", StringComparison.OrdinalIgnoreCase)))
if (mp != null && (mp.BlendMode is "BLEND_Additive" or "BLEND_Translucent" or "BLEND_Modulate" || m!.Name.Contains("Hidden", StringComparison.OrdinalIgnoreCase)) || (m != null && skipMaterial?.Invoke(m.Name) == true))
{
if (Environment.GetEnvironmentVariable("GVR_DEBUG") != null) Console.Error.WriteLine($" 뺀 재질 {m?.Name} {mp.BlendMode} {mp.Base} 삼각형 {sec.NumFaces}");
continue;
@@ -189,39 +227,10 @@ public static class Agents
});
}
glb.Meshes.Add(new JsonObject { ["name"] = mesh.Name, ["primitives"] = prims });
glb.Nodes.Add(new JsonObject { ["name"] = mesh.Name, ["mesh"] = 0, ["skin"] = 0 });
glb.Nodes.Add(new JsonObject { ["name"] = mesh.Name, ["mesh"] = glb.Meshes.Count - 1, ["skin"] = skinIndex });
glb.Roots.Add(glb.Nodes.Count - 1);
// 애니메이션
var nameToBone = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
for (var i = 0; i < bones.Length; i++) nameToBone.TryAdd(bones[i].Name, i);
var upperSet = Subtree(bones, "Spine1");
upperSet.UnionWith(Subtree(bones, "MasterWeaponAim")); // 총 붙는 뼈 (R_WeaponMaster) 도 위 몸 자세를 따른다
var lowerSet = Subtree(bones, "Pelvis");
if (nameToBone.TryGetValue("Splitter", out var spl)) lowerSet.Add(spl);
// Skeleton · Root 는 회전만 (애니메이션에 따라 몸 방향을 여기서 보정한다). 이동(루트 모션)은 뺀다
var rootOnlyRot = new HashSet<int>();
foreach (var n in new[] { "Skeleton", "Root" })
if (nameToBone.TryGetValue(n, out var ri)) { lowerSet.Add(ri); rootOnlyRot.Add(ri); }
var animations = new JsonArray();
foreach (var (name, path, upper) in Clips)
{
try
{
var a = provider.LoadPackageObject<UAnimSequence>(path + "." + path[(path.LastIndexOf('/') + 1)..]);
var set = a.ConvertAnims();
var seq = set.Sequences[0];
seq.RetargetTracks(mesh.ReferenceSkeleton);
var anim = Clip(glb, seq, set.Skeleton, nameToBone, upper ? upperSet : lowerSet, boneNode, bones, name, rootOnlyRot);
if (anim != null) animations.Add(anim);
}
catch (Exception e)
{
Console.Error.WriteLine($" 애니메이션 {name} 실패: {e.GetType().Name} {e.Message}");
}
}
glb.Write(file, new JsonObject { ["skins"] = new JsonArray(skin), ["animations"] = animations });
return new Result(tris, bones.Length, animations.Count, tex.Count, tex.Bytes);
return (boneNode, bones, skin, tris);
}
internal static HashSet<int> Subtree(MeshBoneDto[] bones, string rootName)

View File

@@ -18,6 +18,7 @@ using GvrMapExtract;
// 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-map-extract viewmodels <출력 폴더> [요원...|weapons] 1인칭 팔 fparms_*.glb · 무기 fpweapon_*.glb · 팔 동작 fpanim_*.glb + viewmodels.json
//
// 환경변수
// GVR_USMAP 매핑 파일 (.usmap, 필수: 13.08 부터 패키지에 형 정보가 없다). uedb.dev 에서 받는다
@@ -180,6 +181,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 "viewmodels":
// 1인칭 팔 · 무기 · 동작: fparms_*.glb · fpweapon_*.glb · fpanim_*.glb + viewmodels.json (Viewmodels.cs)
return Viewmodels.Run(provider, args[1], args.Skip(2).ToHashSet(StringComparer.OrdinalIgnoreCase), int.Parse(Environment.GetEnvironmentVariable("GVR_AGENT_TEX") ?? "512"));
case "abilities":
// 요원 스킬 3D 재료: abilities.json + m_*.glb + t_*.png (Abilities.cs)
return Abilities.Run(provider, args[1], args.Skip(2).ToList(), store);

View File

@@ -0,0 +1,203 @@
using System.Text.Json.Nodes;
using CUE4Parse.FileProvider;
using CUE4Parse.UE4.Assets.Exports.Animation;
using CUE4Parse.UE4.Assets.Exports.SkeletalMesh;
using CUE4Parse.UE4.Assets.Exports.StaticMesh;
using CUE4Parse.UE4.Objects.UObject;
using CUE4Parse_Conversion.Animations;
using CUE4Parse_Conversion.Dto;
using CUE4Parse_Conversion.Options;
namespace GvrMapExtract;
/// <summary>
/// 1인칭 화면(뷰모델): 요원 1인칭 팔 · 무기 1인칭 모델 · 동작. 좌표는 게임(UE) 그대로 cm.
/// fparms_&lt;코드&gt;.glb 요원 1인칭 팔 (Characters/&lt;코드&gt;/S0/1P/Models/FP_&lt;코드&gt;_S0_Skelmesh). 뼈대는 모든 요원 공용 (Camera 뼈 = 눈)
/// fpweapon_&lt;이름&gt;.glb 무기 1인칭 모델 (&lt;무기 폴더&gt;/S0/1P/Models/GN|EQ_*_S0_Skelmesh) + 탄창 + 총 동작(gun_fire · gun_reload · gun_equip)
/// fpanim_&lt;이름&gt;.glb 그 무기를 든 팔 동작 (뼈 노드만): idle · fire · reload · equip · ads · walk · activate
/// 사이트는 팔 뼈 MasterWeapon 에 무기 뿌리를 붙이고, 팔 Camera 뼈가 화면 카메라에 오게 놓는다.
/// 덧셈 동작(FireAdd · WalkAdd)은 CUE4Parse 가 기준 자세에 더해 온전한 자세로 바꿔 준다.
/// </summary>
public static class Viewmodels
{
private static readonly (string Role, string[] Names)[] ArmClips =
[
("idle", ["IdlePose", "Idle"]),
("fire", ["Fire", "FireAdd"]),
("reload", ["Reload"]),
("equip", ["Equip"]),
("ads", ["AltIdlePose"]),
("walk", ["WalkAdd"]),
("activate", ["Activate"]),
];
private static readonly (string Role, string[] Names)[] GunClips =
[
("gun_fire", ["Fire", "FireAdd"]),
("gun_reload", ["Reload"]),
("gun_equip", ["Equip"]),
];
private static readonly System.Text.RegularExpressions.Regex SpareMaterial = new(@"^(AB|ABTP|CS|TP)_", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
public static string ArmsFile(string code) => $"fparms_{code}.glb";
public static string WeaponFile(string name) => "fpweapon_" + name.Replace(' ', '_') + ".glb";
public static string AnimFile(string name) => "fpanim_" + name.Replace(' ', '_') + ".glb";
public static int Run(IFileProvider provider, string outDir, IReadOnlyCollection<string> want, int maxTex)
{
Directory.CreateDirectory(outDir);
var failed = 0;
var arms = new SortedDictionary<string, object>();
USkeletalMesh? refArms = null;
foreach (var (code, _) in Agents.Find(provider).Where(a => want.Count == 0 || want.Contains(a.Code)))
{
// 보통 FP_<코드>_S0_Skelmesh, 바뀐 요원은 FP_<코드>_New_S0_Skelmesh (브리치)
var mdir = $"ShooterGame/Content/Characters/{code}/S0/1P/Models/";
var mre = new System.Text.RegularExpressions.Regex($@"/FP_{code}(_[A-Za-z0-9]+)?_S0_Skelmesh\.uasset$", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
var mf = provider.Files.Keys.Where(k => k.StartsWith(mdir, StringComparison.OrdinalIgnoreCase) && mre.IsMatch(k)).OrderBy(k => k.Length).FirstOrDefault();
if (mf == null) { Console.WriteLine($"{code}: 1인칭 팔 없음 (건너뜀)"); continue; }
try
{
var mesh = provider.LoadPackageObject<USkeletalMesh>(ObjPath(mf));
refArms ??= mesh;
var glb = new Glb();
var tex = new TexStore(provider, glb, maxTex);
// 1인칭 팔 메시에 같이 든 스킬 · 3인칭 조각(AB_ · ABTP_ · CS_ · TP_ 재질)은 평소에 안 보이므로 뺀다 (모든 구간이 그런 요원은 그대로)
var names = mesh.SkeletalMaterials.Select(x => x.MaterialInterface?.Name ?? "").ToList();
var spare = SpareMaterial;
var (_, bones, skin, tris) = Agents.Skinned(provider, glb, tex, mesh, 0, 0, names.All(n => spare.IsMatch(n)) ? null : n => spare.IsMatch(n));
glb.Write(Path.Combine(outDir, ArmsFile(code)), new JsonObject { ["skins"] = new JsonArray(skin) });
arms[code + "_PC_C"] = new { code, file = ArmsFile(code), triangles = tris };
Console.WriteLine($"{code}: 1인칭 팔 삼각형 {tris} · 뼈 {bones.Length} · 텍스처 {tex.Count}");
}
catch (Exception e)
{
failed++;
Console.WriteLine($"{code}: 1인칭 팔 실패 {e.GetType().Name} {e.Message}");
}
GC.Collect();
}
// 팔 동작의 뼈 노드는 공용 뼈대 메시(없으면 처음 뽑은 요원 팔)로
try { refArms = provider.LoadPackageObject<USkeletalMesh>("/Game/Characters/_Core/1P/Models/FP_Core_Retarget_Skelmesh.FP_Core_Retarget_Skelmesh"); } catch { }
var weapons = new SortedDictionary<string, object>();
if (want.Count == 0 || want.Contains("weapons"))
foreach (var (name, bp) in Weapons.List)
{
try
{
var dir = "ShooterGame/Content" + bp["/Game".Length..bp.LastIndexOf('/')] + "/S0/1P/";
var re = new System.Text.RegularExpressions.Regex(@"/(GN|EQ)_([A-Za-z0-9]+)_S0_Skelmesh\.uasset$", System.Text.RegularExpressions.RegexOptions.IgnoreCase);
var mf = provider.Files.Keys.Where(k => k.StartsWith(dir + "Models/", StringComparison.OrdinalIgnoreCase) && re.IsMatch(k) && !k.Contains("Defuser", StringComparison.OrdinalIgnoreCase)).OrderBy(k => k.Length).FirstOrDefault();
if (mf == null) { Console.WriteLine($"무기 {name}: 1인칭 모델 없음 (건너뜀)"); continue; }
var gun = provider.LoadPackageObject<USkeletalMesh>(ObjPath(mf));
var anims = provider.Files.Keys.Where(k => k.StartsWith(dir + "Anims/", StringComparison.OrdinalIgnoreCase) && k.EndsWith(".uasset", StringComparison.OrdinalIgnoreCase)).ToList();
string? Find(string prefix, string[] names) =>
names.Select(n => anims.FirstOrDefault(k => Path.GetFileNameWithoutExtension(k) is var f && f.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) && f.EndsWith("_S0_" + n, StringComparison.OrdinalIgnoreCase))).FirstOrDefault(x => x != null);
// 무기: 몸(뼈대) + 탄창 + 총 동작
var (_, mag) = Weapons.Find(provider, bp);
var glb = new Glb();
var tex = new TexStore(provider, glb, maxTex);
var (boneNode, bones, skin, tris) = Agents.Skinned(provider, glb, tex, gun, 0);
if (mag != null) tris += Weapons.AttachStatic(provider, glb, tex, mag, boneNode, bones, "Magazine_Main");
var gunClips = Clips(provider, glb, gun, boneNode, bones, GunClips.Select(c => (c.Role, Find("GN_Core_", c.Names))));
var points = new JsonObject();
foreach (var (key, bone) in new[] { ("muzzle", "Muzzle"), ("leftHand", "Left_Hand_Target") })
{
var bi = Array.FindIndex(bones, b => b.Name.Equals(bone, StringComparison.OrdinalIgnoreCase));
if (bi < 0) continue;
var g = CUE4Parse.UE4.Objects.Core.Math.FTransform.Identity;
for (var i = bi; i >= 0; i = bones[i].ParentIndex) g = g * bones[i].Transform;
points[key] = new JsonArray(g.Translation.X, g.Translation.Y, g.Translation.Z);
}
glb.Write(Path.Combine(outDir, WeaponFile(name)), new JsonObject { ["skins"] = new JsonArray(skin), ["animations"] = gunClips.json });
// 팔 동작 (뼈 노드만)
var armRoles = new List<string>();
if (refArms != null)
{
var ag = new Glb();
var adto = new SkeletalMeshDto(refArms, EMeshQuality.All);
var aNodes = BoneNodes(ag, adto.Bones);
var ac = Clips(provider, ag, refArms, aNodes, adto.Bones, ArmClips.Select(c => (c.Role, Find("FP_Core_", c.Names))));
armRoles = ac.roles;
ag.Write(Path.Combine(outDir, AnimFile(name)), new JsonObject { ["animations"] = ac.json });
}
weapons[name] = new { file = WeaponFile(name), anim = AnimFile(name), mesh = gun.Name, triangles = tris, clips = armRoles, gunClips = gunClips.roles, points };
Console.WriteLine($"무기 {name}: {gun.Name} 삼각형 {tris} · 팔 동작 {string.Join(',', armRoles)} · 총 동작 {string.Join(',', gunClips.roles)}");
}
catch (Exception e)
{
failed++;
Console.WriteLine($"무기 {name}: 1인칭 실패 {e.GetType().Name} {e.Message}");
}
GC.Collect();
}
File.WriteAllText(Path.Combine(outDir, "viewmodels.json"), System.Text.Json.JsonSerializer.Serialize(new { arms, weapons }, new System.Text.Json.JsonSerializerOptions { WriteIndented = true }));
Console.WriteLine($"끝: 1인칭 팔 {arms.Count} · 무기 {weapons.Count} · 실패 {failed}");
return failed == 0 ? 0 : 1;
}
private static string ObjPath(string file)
{
var p = "/Game" + file["ShooterGame/Content".Length..^".uasset".Length];
return p + "." + p[(p.LastIndexOf('/') + 1)..];
}
/// <summary>뼈 노드만 (참조 자세 TRS, 부모-자식). 최상위는 Roots 에</summary>
private static int[] BoneNodes(Glb glb, MeshBoneDto[] bones)
{
var node = new int[bones.Length];
for (var i = 0; i < bones.Length; i++)
{
var t = bones[i].Transform;
glb.Nodes.Add(new JsonObject
{
["name"] = bones[i].Name,
["translation"] = new JsonArray(t.Translation.X, t.Translation.Y, t.Translation.Z),
["rotation"] = new JsonArray(t.Rotation.X, t.Rotation.Y, t.Rotation.Z, t.Rotation.W),
});
node[i] = glb.Nodes.Count - 1;
}
for (var i = 0; i < bones.Length; i++)
{
var p = bones[i].ParentIndex;
if (p < 0) { glb.Roots.Add(node[i]); continue; }
var parent = glb.Nodes[node[p]]!.AsObject();
if (parent["children"] is not JsonArray ch) parent["children"] = ch = new JsonArray();
ch.Add(node[i]);
}
return node;
}
/// <summary>역할마다 동작 하나 (모든 뼈, 움직이면 이동도). 못 찾거나 못 읽은 역할은 뺀다</summary>
private static (JsonArray json, List<string> roles) Clips(IFileProvider provider, Glb glb, USkeletalMesh mesh, int[] boneNode, MeshBoneDto[] bones, IEnumerable<(string Role, string? File)> list)
{
var json = new JsonArray();
var roles = new List<string>();
var nameToBone = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
for (var i = 0; i < bones.Length; i++) nameToBone.TryAdd(bones[i].Name, i);
var all = Enumerable.Range(0, bones.Length).ToHashSet();
foreach (var (role, file) in list)
{
if (file == null) continue;
try
{
var a = provider.LoadPackageObject<UAnimSequence>(ObjPath(file));
var set = a.ConvertAnims();
var seq = set.Sequences[0];
seq.RetargetTracks(mesh.ReferenceSkeleton);
var clip = Agents.Clip(glb, seq, set.Skeleton, nameToBone, all, boneNode, bones, role, []);
if (clip == null) continue;
json.Add(clip);
roles.Add(role);
}
catch (Exception e)
{
Console.Error.WriteLine($" 동작 {role} ({Path.GetFileNameWithoutExtension(file)}) 실패: {e.GetType().Name} {e.Message}");
}
}
return (json, roles);
}
}

View File

@@ -138,6 +138,34 @@ public static class Weapons
return tris;
}
/// <summary>정적 메시(탄창)를 뼈 노드의 자식 메시로 붙인다 (뼈 공간 그대로). 붙인 삼각형 수</summary>
public static int AttachStatic(IFileProvider provider, Glb glb, TexStore tex, UStaticMesh sm, int[] boneNode, MeshBoneDto[] bones, string bone)
{
var bi = Array.FindIndex(bones, b => b.Name.Equals(bone, StringComparison.OrdinalIgnoreCase));
if (bi < 0 || sm.RenderData?.LODs?.FirstOrDefault(l => !l.SkipLod) is not { } ml || ml.PositionVertexBuffer?.Verts is not { Length: > 0 } mv || ml.IndexBuffer?.Buffer is not { } mib) return 0;
var pos = new List<float>();
var nrm = new List<float>();
var uv = new List<float>();
for (var i = 0; i < mv.Length; i++)
{
pos.AddRange([mv[i].X, mv[i].Y, mv[i].Z]);
var it = ml.VertexBuffer?.UV is { } u && i < u.Length ? u[i] : null;
var n = it?.Normal is { Length: >= 3 } nn ? (FVector)nn[2] : new FVector(0, 0, 1);
nrm.AddRange([n.X, n.Y, n.Z]);
uv.AddRange([it?.UV is { Length: > 0 } uu ? uu[0].U : 0, it?.UV is { Length: > 0 } uv2 ? uv2[0].V : 0]);
}
var secs = ml.Sections.Select(s => (s.FirstIndex, s.NumTriangles, Mat: (FPackageIndex?)(s.MaterialIndex < sm.StaticMaterials.Length ? sm.StaticMaterials[s.MaterialIndex].MaterialInterface : null))).ToList();
var prims = new JsonArray();
var tris = AddPrims(provider, glb, tex, prims, pos, nrm, uv, mib.Select(x => (uint)x).ToArray(), secs);
if (prims.Count == 0) return 0;
glb.Meshes.Add(new JsonObject { ["name"] = sm.Name, ["primitives"] = prims });
glb.Nodes.Add(new JsonObject { ["name"] = sm.Name, ["mesh"] = glb.Meshes.Count - 1 });
var parent = glb.Nodes[boneNode[bi]]!.AsObject();
if (parent["children"] is not JsonArray ch) parent["children"] = ch = new JsonArray();
ch.Add(glb.Nodes.Count - 1);
return tris;
}
private static int AddPrims(IFileProvider provider, Glb glb, TexStore tex, JsonArray prims, List<float> pos, List<float> nrm, List<float> uv, uint[] indices, List<(int First, int Faces, FPackageIndex? Mat)> secs)
{
var aPos = glb.Floats(pos.ToArray(), 3, bounds: true);