3D 리플레이 실감 1단계: 변환기 v2 (스킬 주인 · 투사체 경로 · 앉기/점프 · 무기 상태 · 맞은 자리 · 사망 모션 · 설치/해체) · 공용 애니메이션 anims.glb · 요원 동작(앉기 · 점프 · 착지 · 조준 각 · 사격 반동 · 재장전 · 던지기 · 사망) · 예광 · 작은 이름표 · 요루 분신

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-18 00:29:09 +09:00
parent 5c8ba05da4
commit c94edac147
13 changed files with 1092 additions and 163 deletions

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, samplePlayer, type ReplayFile, type ReplaySync } from '../lib/replay';
import { equipAt, equipLabel, equipTracks, isDead, roundAt, samplePath, samplePlayer, type ReplayFile, type ReplaySync } from '../lib/replay';
import { findMap3d, loadMap3d, mapMaterial, worldMatrix } from '../lib/map3d';
import { AgentRig, loadAgent, loadWeapon } from '../lib/agents3d';
import { AgentRig, isGun, loadAgent, loadAnims, loadWeapon } from '../lib/agents3d';
import { buildAnimIndex, rigInput } from '../lib/replayAnim';
import { abilityLook, type AbilityLook } from '../lib/abilities';
/**
@@ -52,10 +53,13 @@ interface Props {
sync: ReplaySync;
}
/** 이름표: 거리와 상관없이 화면에서 같은 크기 (게임처럼 작게) */
const LABEL_H = 0.028;
function labelSprite(text: string, color: string) {
const { tex, aspect } = labelTexture(text, color);
const sp = new THREE.Sprite(new THREE.SpriteMaterial({ map: tex, depthTest: false, transparent: true }));
sp.scale.set(aspect * 2.2, 2.2, 1);
const sp = new THREE.Sprite(new THREE.SpriteMaterial({ map: tex, depthTest: false, transparent: true, sizeAttenuation: false }));
sp.scale.set(aspect * LABEL_H, LABEL_H, 1);
sp.center.set(0.5, 0);
sp.renderOrder = 10;
return sp;
}
@@ -63,22 +67,24 @@ function labelSprite(text: string, color: string) {
function labelTexture(text: string, color: string) {
const c = document.createElement('canvas');
const ctx = c.getContext('2d')!;
const font = '600 44px Pretendard, "Noto Sans KR", sans-serif';
const font = '700 40px Pretendard, "Noto Sans KR", sans-serif';
ctx.font = font;
const w = Math.ceil(ctx.measureText(text).width) + 36;
const w = Math.ceil(ctx.measureText(text).width) + 12;
c.width = w;
c.height = 68;
c.height = 56;
ctx.font = font;
ctx.fillStyle = 'rgba(8,14,20,0.78)';
ctx.beginPath();
ctx.roundRect(0, 0, w, 68, 18);
ctx.fill();
ctx.fillStyle = color;
ctx.textBaseline = 'middle';
ctx.fillText(text, 18, 36);
// 배경 상자 없이 글자 테두리만 (게임 이름표처럼)
ctx.lineWidth = 7;
ctx.strokeStyle = 'rgba(0,0,0,0.75)';
ctx.lineJoin = 'round';
ctx.strokeText(text, 6, 30);
ctx.fillStyle = color;
ctx.fillText(text, 6, 30);
const tex = new THREE.CanvasTexture(c);
tex.colorSpace = THREE.SRGBColorSpace;
return { tex, aspect: w / 68 };
tex.minFilter = THREE.LinearFilter;
return { tex, aspect: w / 56 };
}
interface PlayerView {
@@ -90,9 +96,6 @@ interface PlayerView {
body: THREE.Mesh;
cone: THREE.Mesh;
label: THREE.Sprite;
/** 들고 있는 것 (총 이름) */
weapon: THREE.Sprite;
weaponKind: number;
voice: THREE.Sprite;
ring: THREE.Mesh;
/** 바닥(미니맵)까지 내린 선과 그림자 점: 높이가 있어도 평면 위치가 보이게 */
@@ -254,21 +257,17 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
cone.geometry.rotateX(Math.PI / 2);
cone.geometry.translate(0, 0, 2.2);
cone.position.y = 1.9;
const label = labelSprite(r.info?.character?.name ? `${r.name} · ${r.info.character.name}` : r.name, r.ally ? '#8fd8ff' : '#ff9aa5');
label.position.y = 4.4;
// 이름표 · 말하는 표시는 화면에서 같은 크기라 선수 묶음(크기가 바뀐다) 밖에 둔다
const label = labelSprite(r.name, r.ally ? '#7fd3ff' : '#ff8a96');
label.userData.idx = r.idx;
const weapon = new THREE.Sprite(new THREE.SpriteMaterial({ depthTest: false, transparent: true }));
weapon.position.y = 2.75;
weapon.renderOrder = 10;
weapon.visible = false;
const voice = labelSprite('🔊 말하는 중', '#ffe08a');
voice.position.y = 6.6;
const voice = labelSprite('🔊', '#ffe08a');
voice.visible = false;
scene.add(label, voice);
const ring = new THREE.Mesh(new THREE.RingGeometry(1.4, 1.8, 32), new THREE.MeshBasicMaterial({ color: 0xffe08a, side: THREE.DoubleSide }));
ring.rotation.x = -Math.PI / 2;
ring.position.y = 0.05;
ring.visible = false;
group.add(body, cone, label, weapon, voice, ring);
group.add(body, cone, ring);
scene.add(group);
const dropGeo = new THREE.BufferGeometry().setFromPoints([new THREE.Vector3(), new THREE.Vector3()]);
const drop = new THREE.Line(dropGeo, new THREE.LineBasicMaterial({ color, transparent: true, opacity: 0.7 }));
@@ -276,7 +275,7 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
const shadow = new THREE.Mesh(new THREE.CircleGeometry(0.75, 20), new THREE.MeshBasicMaterial({ color, transparent: true, opacity: 0.85 }));
shadow.rotation.x = -Math.PI / 2;
scene.add(drop, shadow);
return { idx: r.idx, info: r.info, name: r.name, ally: r.ally, group, body, cone, label, weapon, weaponKind: -2, voice, ring, drop, shadow, rig: null };
return { idx: r.idx, info: r.info, name: r.name, ally: r.ally, group, body, cone, label, voice, ring, drop, shadow, rig: null };
});
// 요원 3D 몸: UE 좌표(cm) 그대로 두고 맵과 같은 행렬로 옮긴다
@@ -287,10 +286,10 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
for (const v of views) {
const cls = replay.players[v.idx].character;
if (!cls) continue;
void loadAgent(cls)
.then((g) => {
void Promise.all([loadAgent(cls), loadAnims()])
.then(([g, anims]) => {
if (!g || disposed) return;
v.rig = new AgentRig(g);
v.rig = new AgentRig(g, anims);
agentsGroup.add(v.rig.root);
agentsGroup.updateMatrixWorld(true);
})
@@ -298,23 +297,7 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
}
let prevT = localT.current;
// 총 이름표 (같은 글자는 텍스처 하나)
const weaponTex = new Map<string, { tex: THREE.Texture; aspect: number }>();
const setWeapon = (v: PlayerView, kind: number) => {
if (v.weaponKind === kind) return;
v.weaponKind = kind;
const text = equipLabel(replay.equipKinds?.[kind]);
if (!text) {
v.weapon.visible = false;
return;
}
let lt = weaponTex.get(text);
if (!lt) weaponTex.set(text, (lt = labelTexture(`🔫 ${text}`, '#ffe9b0')));
v.weapon.material.map = lt.tex;
v.weapon.material.needsUpdate = true;
v.weapon.scale.set(lt.aspect * 1.6, 1.6, 1);
v.weapon.visible = true;
};
const animIx = buildAnimIndex(replay, equipByPlayer);
// 선택한 선수 이동 경로 (최근 6초)
const trailGeo = new THREE.BufferGeometry();
@@ -323,13 +306,47 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
trail.frustumCulled = false;
scene.add(trail);
// 사격 궤적 (최근 150ms)
// 총알 궤적 (예광): 쏜 자리 → 맞은 자리 (맞은 기록이 없으면 보는 방향으로 50m). UE 좌표(cm), 요원과 같은 묶음
const MAX_SHOTS = 48;
const TRACER_MS = 90;
const shotGeo = new THREE.BufferGeometry();
shotGeo.setAttribute('position', new THREE.BufferAttribute(new Float32Array(MAX_SHOTS * 6), 3));
const shots = new THREE.LineSegments(shotGeo, new THREE.LineBasicMaterial({ color: 0xfff1a8, transparent: true, opacity: 0.9 }));
const shots = new THREE.LineSegments(shotGeo, new THREE.LineBasicMaterial({ color: 0xffe9a0, transparent: true, opacity: 0.95, blending: THREE.AdditiveBlending, depthWrite: false }));
shots.frustumCulled = false;
scene.add(shots);
agentsGroup.add(shots);
// 사격별 끝점 (같은 선수가 같은 때 맞힌 기록)
const hitsByShooter = new Map<number, number[][]>();
for (const h of replay.hits ?? []) {
if (h[1] < 0) continue;
let a = hitsByShooter.get(h[1]);
if (!a) hitsByShooter.set(h[1], (a = []));
a.push(h);
}
const shotEnd = replay.shots.map(([st, pl, x, y, z, yaw, pitch]) => {
const h = hitsByShooter.get(pl)?.find((q) => Math.abs(q[0] - st) <= 40);
if (h) return [h[6], h[7], h[8]];
const yr = (yaw * Math.PI) / 180;
const pr = (signed(pitch) * Math.PI) / 180;
return [x + Math.cos(pr) * Math.cos(yr) * 5000, y + Math.cos(pr) * Math.sin(yr) * 5000, z + Math.sin(pr) * 5000];
});
// 맞은 자리 튀는 것 (사람이면 붉게, 0.25초)
const sparkTex = (() => {
const c = document.createElement('canvas');
c.width = c.height = 32;
const g = c.getContext('2d')!;
const rg = g.createRadialGradient(16, 16, 0, 16, 16, 16);
rg.addColorStop(0, 'rgba(255,255,255,1)');
rg.addColorStop(1, 'rgba(255,255,255,0)');
g.fillStyle = rg;
g.fillRect(0, 0, 32, 32);
return new THREE.CanvasTexture(c);
})();
const sparks = Array.from({ length: 24 }, () => {
const sp = new THREE.Sprite(new THREE.SpriteMaterial({ map: sparkTex, transparent: true, depthWrite: false, blending: THREE.AdditiveBlending }));
sp.visible = false;
agentsGroup.add(sp);
return sp;
});
// 킬 표시 (죽은 자리 X)
const killGroup = new THREE.Group();
@@ -433,10 +450,28 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
}
obj.position.copy(toWorld(x, y, z, zBase));
scene.add(obj);
// 요루 분신: 요루 몸이 경로를 따라 달린다
if (/^Pawn_Stealth_4_Decoy/.test(replay.objectKinds[kind] ?? '')) {
const owner = replay.objects[i][6];
void Promise.all([loadAgent(replay.players[owner]?.character ?? 'Stealth_PC_C'), loadAnims()])
.then(([g, anims]) => {
if (!g || disposed) return;
const rig = new AgentRig(g, anims);
agentsGroup.add(rig.root);
const cur = objViews.get(i);
if (cur) {
cur.obj.children.forEach((c) => (c.visible = false));
cur.obj.userData.rig = rig;
}
})
.catch(() => {});
}
ov = { look, obj, mats, t0, end: t1 >= t0 ? t1 : t0 + look.defaultMs };
objViews.set(i, ov);
return ov;
};
// 움직이는 스킬 경로 (투사체 · 드론 · 분신): objects 번호 → 경로
const pathOf = new Map((replay.objectPaths ?? []).map((p) => [p.o, p]));
const setOpacity = (ov: ObjView, k: number) => {
for (const m of ov.mats) {
const base = (m.userData.baseOpacity ??= m.opacity) as number;
@@ -555,7 +590,8 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
const tr = replay.players[v.idx].track;
const p = samplePlayer(tr, t, replay.sampleMs * 6);
if (!p) {
v.group.visible = v.drop.visible = v.shadow.visible = false;
v.group.visible = v.drop.visible = v.shadow.visible = v.label.visible = v.voice.visible = false;
if (v.rig) v.rig.root.visible = false;
continue;
}
// 1인칭으로 보는 선수 자신은 숨긴다
@@ -574,28 +610,33 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
const op = dead ? 0.22 : 1;
(v.body.material as THREE.MeshStandardMaterial).opacity = op;
(v.cone.material as THREE.MeshStandardMaterial).opacity = dead ? 0 : 0.85;
v.label.material.opacity = dead ? 0.35 : 1;
(v.shadow.material as THREE.MeshBasicMaterial).opacity = dead ? 0.25 : 0.85;
v.voice.visible = speaking.has(v.idx) && !dead;
const kind = dead ? -1 : equipAt(equipByPlayer[v.idx], t);
setWeapon(v, kind);
v.weapon.material.opacity = v.label.material.opacity;
// 이름표: 머리 위 (위에서 볼 때는 몸을 키운 만큼 위로). 죽으면 숨김, 1인칭으로 보는 선수 자신도 숨김
const scaleBody = v.rig && !real ? TOP_MODEL_SCALE : 1;
v.label.position.copy(toWorld(p.x, p.y, Math.max(p.z, zBase - 400) - FOOT_CM + (v.rig ? 195 * scaleBody : 260), zBase));
v.label.visible = v.group.visible && !dead;
v.voice.position.copy(v.label.position);
v.voice.center.set(0.5, -1.05);
v.voice.visible = v.label.visible && speaking.has(v.idx);
if (v.rig) {
// 몸이 있으면 원기둥 대신. 죽으면 몸을 숨긴다 (죽은 자리는 X 표시)
// 몸이 있으면 원기둥 대신. 죽으면 사망 모션 끝 자세로 라운드 끝까지 누워 있다
v.body.visible = v.cone.visible = false;
const rr = v.rig.root;
rr.visible = v.group.visible && !dead;
rr.visible = v.group.visible;
rr.position.set(p.x, p.y, Math.max(p.z, zBase - 400) - FOOT_CM);
rr.rotation.set(0, 0, (p.yaw * Math.PI) / 180);
rr.scale.setScalar(real ? 1 : TOP_MODEL_SCALE);
rr.scale.setScalar(scaleBody);
if (rr.visible) {
const q = samplePlayer(tr, t - 150, replay.sampleMs * 6);
const vx = q ? ((p.x - q.x) * 1000) / 150 : 0;
const vy = q ? ((p.y - q.y) * 1000) / 150 : 0;
const vx = q && !dead ? ((p.x - q.x) * 1000) / 150 : 0;
const vy = q && !dead ? ((p.y - q.y) * 1000) / 150 : 0;
const a = (p.yaw * Math.PI) / 180;
const ek = replay.equipKinds?.[kind];
v.rig.setWeapon(ek && !/^Ability_|Unarmed|Bomb_Defuser/.test(ek) ? ek : null);
v.rig.update(dtR, vx * Math.cos(a) + vy * Math.sin(a), -vx * Math.sin(a) + vy * Math.cos(a), p.pitch);
v.rig.setWeapon(isGun(ek) ? ek : null);
const inp = rigInput(replay, animIx, v.idx, t, { dt: dtR, fwd: vx * Math.cos(a) + vy * Math.sin(a), right: -vx * Math.sin(a) + vy * Math.cos(a), pitch: p.pitch });
v.rig.setShot(inp.shotMs);
v.rig.update(inp);
}
} else {
v.body.visible = true;
@@ -638,25 +679,41 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
camera.position.add(tmp);
}
} else trail.visible = false;
// 사격
// 총알 궤적: 날아가는 짧은 빛줄기 (쏜 뒤 TRACER_MS 동안 끝점까지)
const sp = shotGeo.getAttribute('position') as THREE.BufferAttribute;
let ns = 0;
for (let i = lowerBound(replay.shots, t - 150); i < replay.shots.length && replay.shots[i][0] <= t && ns < MAX_SHOTS; i++) {
const [, , x, y, z, yaw, pitch] = replay.shots[i];
const a = toWorld(x, y, z, zBase);
const d = dirOf(yaw);
const len = 26;
const b = a.clone().add(d.multiplyScalar(len * Math.cos((pitch * Math.PI) / 180))).add(new THREE.Vector3(0, len * Math.sin((pitch * Math.PI) / 180) * 0.3, 0));
sp.setXYZ(ns * 2, a.x, a.y + 1.6, a.z);
sp.setXYZ(ns * 2 + 1, b.x, b.y + 1.6, b.z);
for (let i = lowerBound(replay.shots, t - TRACER_MS); i < replay.shots.length && replay.shots[i][0] <= t && ns < MAX_SHOTS; i++) {
const [st, , x, y, z] = replay.shots[i];
const e = shotEnd[i];
const k = (t - st) / TRACER_MS;
const k0 = Math.max(0, k - 0.35);
const k1 = Math.min(1, k + 0.05);
// 눈높이에서 쏜 기록 → 총구는 조금 아래
const zz = z - 12;
sp.setXYZ(ns * 2, x + (e[0] - x) * k0, y + (e[1] - y) * k0, zz + (e[2] - zz) * k0);
sp.setXYZ(ns * 2 + 1, x + (e[0] - x) * k1, y + (e[1] - y) * k1, zz + (e[2] - zz) * k1);
ns++;
}
shotGeo.setDrawRange(0, ns * 2);
sp.needsUpdate = true;
let nk = 0;
const hits = replay.hits ?? [];
for (let i = lowerBound(hits as [number, ...number[]][], t - 250); i < hits.length && hits[i][0] <= t && nk < sparks.length; i++) {
const h = hits[i];
const k = (t - h[0]) / 250;
const s = sparks[nk++];
s.visible = true;
s.position.set(h[6], h[7], h[8]);
s.scale.setScalar((h[2] >= 0 ? 34 : 22) * (0.6 + k));
s.material.color.set(h[2] >= 0 ? (h[9] === 1 ? 0xff5040 : 0xc0201a) : 0xffe0a0);
s.material.opacity = 1 - k;
}
for (let i = nk; i < sparks.length; i++) sparks[i].visible = false;
// 킬 표시: 이 라운드에서 이미 난 킬
const rd = roundAt(replay, t);
for (const k of killMarks) {
const on = !!rd && k.t >= rd.buy && k.t <= t;
// 요원 몸이 있으면 죽은 몸(사망 모션)이 그 자리에 누워 있으므로 X 는 위에서 볼 때만
const on = !!rd && k.t >= rd.buy && k.t <= t && (!views[k.victim]?.rig || mode === 'top');
k.mk.visible = on;
if (on) {
const age = t - k.t;
@@ -674,11 +731,27 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
if (ov0) {
ov0.obj.visible = false;
if (ov0.obj.userData.model) (ov0.obj.userData.model as THREE.Object3D).visible = false;
if (ov0.obj.userData.rig) (ov0.obj.userData.rig as AgentRig).root.visible = false;
}
continue;
}
const ov = objView(i);
const age = t - t0;
const path = pathOf.get(i);
const pp = path ? samplePath(path, Math.min(t, path.t[path.t.length - 1])) : null;
if (pp) ov.obj.position.copy(toWorld(pp.x, pp.y, pp.z, zBase));
const decoy = ov.obj.userData.rig as AgentRig | undefined;
if (decoy) {
decoy.root.visible = true;
if (pp) {
const yaw = ((pp.yaw ?? 0) * Math.PI) / 180;
decoy.root.position.set(pp.x, pp.y, pp.z - FOOT_CM);
decoy.root.rotation.set(0, 0, yaw);
decoy.root.scale.setScalar(real ? 1 : TOP_MODEL_SCALE);
decoy.update({ dt: dtR, fwd: pp.vx * Math.cos(yaw) + pp.vy * Math.sin(yaw), right: -pp.vx * Math.sin(yaw) + pp.vy * Math.cos(yaw), pitch: 0, crouch: false, airMs: null, landMs: null, cat: 'ability', overlay: null, death: null });
}
continue;
}
const left = ov.end - t;
ov.obj.visible = true;
const model = ov.obj.userData.model as THREE.Object3D | undefined;
@@ -706,7 +779,8 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
break;
}
case 'projectile':
ov.obj.visible = age < 400;
// 경로가 있으면 부딪힐 때까지 따라 날아간다 (옛 리플레이는 던진 자리에 잠깐)
ov.obj.visible = path ? true : age < 400;
ov.obj.scale.setScalar(big);
break;
default:
@@ -924,6 +998,12 @@ export default function ReplayViewer({ m, replay, sync }: Props) {
);
}
/** 게임 각도(0~360) → -180~180 */
function signed(a: number) {
const v = ((a % 360) + 360) % 360;
return v > 180 ? v - 360 : v;
}
function lowerBound(a: [number, ...number[]][], t: number) {
let lo = 0;
let hi = a.length;

View File

@@ -7,7 +7,10 @@ import { loadIndex } from './map3d';
/**
* 요원 3D 몸 · 총 (tools/map-extract agents → 사이트 서버 /site/maps3d, 맵과 같은 폴더).
* 좌표는 게임(UE) 그대로: cm, 발 = 원점 근처, 앞 = +X (애니메이션의 Root 회전 포함).
* 몸 애니메이션은 위(ub_rifle, 총 든 자세)와 아래(lb_idle · lb_run* · lb_walk*)를 따로 섞는다.
* 애니메이션: 요원 glb 안의 기본(ub_rifle · lb_idle/run/walk) + 공용 anims.glb (tools/map-extract anims:
* 앉기 · 점프 · 착지 · 무기별 자세 · 재장전 · 꺼내기 · 던지기 · 칼 · 해체 · 죽음). 공용 애니메이션은 뼈 이름으로 붙이고,
* 이동 트랙은 (요원 참조 자세 − 공용 파일 참조 자세)만큼 옮긴다 (요원마다 키가 달라서).
* 위 몸(ub_*) · 아래 몸(lb_*)을 따로 섞고, 죽으면 온몸(fb_*) 하나만.
*/
const cache = new Map<string, Promise<GLTF>>();
@@ -23,7 +26,7 @@ function load(url: string): Promise<GLTF> {
return p;
}
function url(dir: string, file: string) {
export function assetUrl(dir: string, file: string) {
return `/site/maps3d/${encodeURIComponent(dir)}/${encodeURIComponent(file)}`;
}
@@ -31,21 +34,119 @@ function url(dir: string, file: string) {
export async function loadAgent(characterClass: string): Promise<GLTF | null> {
const idx = await loadIndex();
const a = idx?.dir ? idx.agents?.[characterClass] : undefined;
return a && idx?.dir ? load(url(idx.dir, a.file)) : null;
return a && idx?.dir ? load(assetUrl(idx.dir, a.file)) : null;
}
/** 총 (리플레이 equipKinds 이름: Vandal · Classic · Melee …). 없으면 null */
export async function loadWeapon(name: string): Promise<GLTF | null> {
const idx = await loadIndex();
const w = idx?.dir ? idx.weapons?.[name] : undefined;
return w && idx?.dir ? load(url(idx.dir, w.file)) : null;
return w && idx?.dir ? load(assetUrl(idx.dir, w.file)) : null;
}
/** 공용 애니메이션. 없으면 null (요원 glb 안의 기본 애니메이션만 쓴다) */
export async function loadAnims(): Promise<GLTF | null> {
const idx = await loadIndex();
return idx?.dir && idx.anims ? load(assetUrl(idx.dir, idx.anims.file)).catch(() => null) : null;
}
/** 손에 든 것의 자세 종류 */
export type WeaponCat = 'rifle' | 'pistol' | 'sniper' | 'knife' | 'ability';
const PISTOLS = new Set(['Classic', 'Shorty', 'Frenzy', 'Ghost', 'Sheriff', 'Compact Pistol']);
const SNIPERS = new Set(['Marshal', 'Outlaw', 'Operator']);
/** 리플레이 equipKinds 이름 → 자세 종류 */
export function weaponCat(kind: string | undefined | null): WeaponCat {
if (!kind) return 'ability';
if (kind === 'Melee') return 'knife';
if (PISTOLS.has(kind)) return 'pistol';
if (SNIPERS.has(kind)) return 'sniper';
if (/^(Ability_|Equippable_)|Unarmed|Spike|Bomb_Defuser/.test(kind)) return 'ability';
return 'rifle';
}
/** 손에 3D 총을 그릴 것 (스킬 · 맨손 · 해체기는 없음) */
export function isGun(kind: string | undefined | null): kind is string {
return !!kind && !/^(Ability_|Equippable_)|Unarmed|Bomb_Defuser/.test(kind);
}
/** 경기 기록 사망 모션 이름 (TP_Core_Death_Head_Front_SM_Montage) → 공용 애니메이션 이름 (fb_Head_Front_SM) */
export function deathClipName(montage: string | undefined | null): string {
const m = montage?.match(/^TP_Core_Death_(.+?)(_Montage)?$/);
return m ? `fb_${m[1]}` : 'fb_Body_Front_LG';
}
const LOWER = ['lb_idle', 'lb_runN', 'lb_runS', 'lb_runE', 'lb_runW', 'lb_walkN', 'lb_walkS', 'lb_walkE', 'lb_walkW'] as const;
type Lower = (typeof LOWER)[number];
/** 애니메이션이 만든 속도 (cm/s): 이보다 빠르면 빨리 돌린다 */
const RUN_CM_S = 540;
const WALK_CM_S = 300;
const CROUCH_CM_S = 200;
/** 한 프레임의 몸 상태 (뷰어가 리플레이에서 계산해 넣는다). 시간은 모두 리플레이 기준이라 되감기 · 멈춤에도 같은 자세 */
export interface RigInput {
/** 지난 프레임부터 리플레이 시간 (초, 되감으면 0) */
dt: number;
/** 몸 기준 이동 속도 (cm/s, UE: 앞 +X · 오른쪽 +Y) */
fwd: number;
right: number;
/** 위아래 보는 각 (도) */
pitch: number;
crouch: boolean;
/** 공중에 뜬 지 (ms, 땅이면 null) · 내려앉은 지 (ms, 오래됐으면 null) */
airMs: number | null;
landMs: number | null;
cat: WeaponCat;
/** 위 몸 한 번 동작 (재장전 · 꺼내기 · 던지기 · 칼 · 해체): 공용 애니메이션 이름과 시작한 지 (ms). loop 면 반복 */
overlay: { clip: string; ms: number; loop?: boolean } | null;
/** 죽음: 온몸 애니메이션 이름과 죽은 지 (ms) */
death: { clip: string; ms: number } | null;
}
/** 공용 애니메이션을 이 요원 뼈 길이에 맞춘 복제본 (요원 glb 하나당 한 번) */
const retargeted = new WeakMap<object, Map<string, THREE.AnimationClip>>();
function sharedClips(model: THREE.Object3D, agent: GLTF, anims: GLTF | null): Map<string, THREE.AnimationClip> {
const out = new Map<string, THREE.AnimationClip>();
for (const c of agent.animations) out.set(c.name, c);
if (!anims) return out;
let cached = retargeted.get(agent);
if (!cached) {
cached = new Map();
const offset = new Map<string, THREE.Vector3>();
const delta = (bone: string) => {
let d = offset.get(bone);
if (!d) {
const mine = model.getObjectByName(bone);
const core = anims.scene.getObjectByName(bone);
d = mine && core ? mine.position.clone().sub(core.position) : new THREE.Vector3();
offset.set(bone, d);
}
return d;
};
const has = new Set<string>();
model.traverse((o) => has.add(o.name));
for (const c of anims.animations) {
// 이 요원에게 없는 뼈(눈꺼풀 · 카메라 등)는 뺀다
const own = c.tracks.filter((tr) => has.has(tr.name.slice(0, tr.name.lastIndexOf('.'))));
const tracks = own.map((tr) => {
if (!tr.name.endsWith('.position')) return tr;
const d = delta(tr.name.slice(0, -'.position'.length));
if (!d.lengthSq()) return tr;
const t2 = tr.clone();
const v = t2.values;
for (let i = 0; i < v.length; i += 3) {
v[i] += d.x;
v[i + 1] += d.y;
v[i + 2] += d.z;
}
return t2;
});
cached.set(c.name, new THREE.AnimationClip(c.name, c.duration, tracks));
}
retargeted.set(agent, cached);
}
for (const [n, c] of cached) out.set(n, c); // 공용이 있으면 공용 (ub_rifle 등 같은 이름은 공용 자세가 게임과 같다)
return out;
}
/** 선수 한 명의 몸 (복제본) · 애니메이션 · 손에 든 총 */
export class AgentRig {
@@ -53,14 +154,21 @@ export class AgentRig {
readonly root = new THREE.Group();
private readonly model: THREE.Object3D;
private readonly mixer: THREE.AnimationMixer;
private readonly lower = new Map<Lower, THREE.AnimationAction>();
private readonly clips: Map<string, THREE.AnimationClip>;
private readonly actions = new Map<string, THREE.AnimationAction>();
private readonly hand: THREE.Object3D | null;
private readonly gunSlot = new THREE.Group();
/** 총구 불꽃 (사격 순간에 잠깐) */
readonly muzzle: THREE.Sprite;
private gunName: string | null = null;
private gunReq = 0;
private gunTip = 60;
private readonly tmp = new THREE.Vector3();
/** 사격 반동 (0~1, 줄어든다) */
private kick = 0;
private shotMs: number | null = null;
constructor(gltf: GLTF) {
constructor(gltf: GLTF, anims: GLTF | null) {
this.model = cloneSkinned(gltf.scene);
this.model.traverse((o) => {
const m = o as THREE.Mesh;
@@ -68,28 +176,34 @@ export class AgentRig {
});
this.root.add(this.model);
this.root.add(this.gunSlot);
this.muzzle = new THREE.Sprite(new THREE.SpriteMaterial({ map: muzzleTexture(), color: 0xffd38a, blending: THREE.AdditiveBlending, depthWrite: false, transparent: true }));
this.muzzle.scale.setScalar(26);
this.muzzle.visible = false;
this.gunSlot.add(this.muzzle);
this.mixer = new THREE.AnimationMixer(this.model);
const clip = (n: string) => gltf.animations.find((a) => a.name === n);
const ub = clip('ub_rifle');
if (ub) this.mixer.clipAction(ub).play();
for (const n of LOWER) {
const c = clip(n);
if (!c) continue;
const a = this.mixer.clipAction(c);
a.play();
a.setEffectiveWeight(n === 'lb_idle' ? 1 : 0);
this.lower.set(n, a);
}
this.clips = sharedClips(this.model, gltf, anims);
// R_WeaponPoint 는 공용 애니메이션이 움직이지 않아 손에서 떨어져 있다 → 손목(R_Hand) 기준
this.hand = this.model.getObjectByName('R_Hand') ?? null;
}
private action(name: string): THREE.AnimationAction | null {
let a = this.actions.get(name);
if (a) return a;
const c = this.clips.get(name);
if (!c) return null;
a = this.mixer.clipAction(c);
a.play();
a.setEffectiveWeight(0);
this.actions.set(name, a);
return a;
}
/** 들고 있는 총 바꾸기 (이름 없으면 맨손) */
setWeapon(name: string | null) {
if (name === this.gunName) return;
this.gunName = name;
const req = ++this.gunReq;
this.gunSlot.clear();
for (const c of [...this.gunSlot.children]) if (c !== this.muzzle) this.gunSlot.remove(c);
if (!name) return;
void loadWeapon(name)
.then((g) => {
@@ -101,43 +215,143 @@ export class AgentRig {
});
gun.position.x = 7; // 손목 → 손바닥 (총 원점 = 손잡이)
if (name === 'Melee') gun.rotation.y = Math.PI / 2; // 칼은 날이 +Z → 앞(+X)으로
const box = new THREE.Box3().setFromObject(gun);
this.gunTip = Number.isFinite(box.max.x) ? box.max.x : 60;
this.gunSlot.add(gun);
})
.catch(() => {});
}
/**
* 애니메이션 진행. dt: 리플레이 시간(초), fwd · right: 몸 기준 이동 속도(cm/s, UE: 앞 +X · 오른쪽 +Y), pitch: 위아래 보는 각(도)
*/
update(dt: number, fwd: number, right: number, pitch: number) {
const speed = Math.hypot(fwd, right);
const moving = THREE.MathUtils.smoothstep(speed, 40, 140);
const run = speed > 400;
const sum = Math.abs(fwd) + Math.abs(right) || 1;
const w: Record<Lower, number> = {
lb_idle: 1 - moving,
lb_runN: 0, lb_runS: 0, lb_runE: 0, lb_runW: 0,
lb_walkN: 0, lb_walkS: 0, lb_walkE: 0, lb_walkW: 0,
/** 마지막 사격에서 지난 시간 (ms, 없으면 null): 반동 · 총구 불꽃 */
setShot(ms: number | null) {
this.shotMs = ms != null && ms >= 0 ? ms : null;
this.kick = this.shotMs != null && this.shotMs < 90 ? 1 - this.shotMs / 90 : 0;
}
/** 이 애니메이션이 있는지 (뷰어가 대신 할 것을 고를 때) */
has(name: string) {
return this.clips.has(name);
}
update(inp: RigInput) {
const set = (name: string, w: number, opts?: { time?: number; scale?: number }) => {
const a = w > 0.001 ? this.action(name) : this.actions.get(name);
if (!a) return w > 0.001 ? false : true;
a.setEffectiveWeight(w);
if (opts?.time != null) {
a.paused = true;
a.time = Math.min(opts.time, a.getClip().duration - 1e-3);
} else {
a.paused = false;
a.setEffectiveTimeScale(opts?.scale ?? 1);
}
return true;
};
const g = run ? 'lb_run' : 'lb_walk';
w[`${g}N` as Lower] = (moving * Math.max(0, fwd)) / sum;
w[`${g}S` as Lower] = (moving * Math.max(0, -fwd)) / sum;
w[`${g}E` as Lower] = (moving * Math.max(0, right)) / sum;
w[`${g}W` as Lower] = (moving * Math.max(0, -right)) / sum;
const scale = THREE.MathUtils.clamp(speed / (run ? RUN_CM_S : WALK_CM_S), 0.6, 1.5);
for (const [n, a] of this.lower) {
a.setEffectiveWeight(w[n]);
a.setEffectiveTimeScale(n === 'lb_idle' ? 1 : scale);
const zero = new Set(this.actions.keys());
const use = (name: string, w: number, opts?: { time?: number; scale?: number }) => {
if (w <= 0.001) return;
if (set(name, w, opts)) zero.delete(name);
};
if (inp.death && this.clips.has(inp.death.clip)) {
// 죽음: 온몸 한 번 (끝 자세로 누워 있다)
use(inp.death.clip, 1, { time: inp.death.ms / 1000 });
} else if (inp.death) {
use('fb_Body_Front_LG', 1, { time: inp.death.ms / 1000 });
} else {
this.lowerBody(inp, use);
this.upperBody(inp, use);
}
this.mixer.update(dt);
// 총: 오른손 자리에, 몸 앞(+X)을 보는 방향 + 위아래 각
if (this.hand && this.gunSlot.children.length) {
for (const n of zero) this.actions.get(n)?.setEffectiveWeight(0);
this.mixer.update(inp.dt);
// 총: 오른손 자리에, 몸 앞(+X)을 보는 방향 + 위아래 각, 사격하면 뒤로 살짝
this.muzzle.visible = this.kick > 0.55 && this.gunName != null && this.gunName !== 'Melee';
if (this.muzzle.visible) {
this.muzzle.position.set(this.gunTip + 6, 0, 2);
this.muzzle.material.rotation = Math.random() * Math.PI;
}
if (this.hand && this.gunSlot.children.length > 1) {
this.root.updateWorldMatrix(true, true);
this.hand.getWorldPosition(this.tmp);
this.root.worldToLocal(this.tmp);
this.gunSlot.position.copy(this.tmp);
this.gunSlot.rotation.set(0, (-THREE.MathUtils.clamp(pitch, -80, 80) * Math.PI) / 180, 0);
const pr = (-THREE.MathUtils.clamp(inp.pitch, -80, 80) * Math.PI) / 180;
this.gunSlot.rotation.set(0, pr - this.kick * 0.12, 0);
this.gunSlot.translateX(-this.kick * 4);
}
this.gunSlot.visible = !inp.death;
}
private lowerBody(inp: RigInput, use: (n: string, w: number, o?: { time?: number; scale?: number }) => void) {
const has = (n: string) => this.clips.has(n);
// 공중: 뛴 처음 0.45초는 점프 동작, 그 뒤는 떨어지는 자세
if (inp.airMs != null && (has('lb_fall') || has('lb_jump'))) {
const jumpW = has('lb_jump') ? 1 - THREE.MathUtils.smoothstep(inp.airMs, 300, 500) : 0;
if (jumpW > 0) use('lb_jump', jumpW, { time: inp.airMs / 1000 });
if (1 - jumpW > 0) use(has('lb_fall') ? 'lb_fall' : 'lb_jump', 1 - jumpW, has('lb_fall') ? undefined : { time: 0.45 });
return;
}
const speed = Math.hypot(inp.fwd, inp.right);
const moving = THREE.MathUtils.smoothstep(speed, 40, 140);
const sum = Math.abs(inp.fwd) + Math.abs(inp.right) || 1;
const dir = (n: number) => (moving * Math.max(0, n)) / sum;
// 내려앉음: 0.35초 동안 착지 동작을 섞는다
const landW = inp.landMs != null && has('lb_land') ? 1 - THREE.MathUtils.smoothstep(inp.landMs, 150, 450) : 0;
const rest = 1 - landW;
if (landW > 0) use('lb_land', landW, { time: inp.landMs! / 1000 });
const crouch = inp.crouch && has('lb_crouch');
let g: string;
let base: number;
if (crouch) {
g = 'lb_crouch';
base = CROUCH_CM_S;
use('lb_crouch', rest * (1 - moving));
} else {
g = speed > 400 ? 'lb_run' : 'lb_walk';
base = speed > 400 ? RUN_CM_S : WALK_CM_S;
use('lb_idle', rest * (1 - moving));
}
const scale = THREE.MathUtils.clamp(speed / base, 0.6, 1.5);
use(`${g}N`, rest * dir(inp.fwd), { scale });
use(`${g}S`, rest * dir(-inp.fwd), { scale });
use(`${g}E`, rest * dir(inp.right), { scale });
use(`${g}W`, rest * dir(-inp.right), { scale });
}
private upperBody(inp: RigInput, use: (n: string, w: number, o?: { time?: number; scale?: number }) => void) {
const has = (n: string) => this.clips.has(n);
let ow = 0;
if (inp.overlay && has(inp.overlay.clip)) {
const dur = this.clips.get(inp.overlay.clip)!.duration * 1000;
const ms = inp.overlay.loop ? inp.overlay.ms % dur : inp.overlay.ms;
if (inp.overlay.loop || ms < dur) {
// 들어갈 때 · 끝날 때 0.12초씩 섞는다
ow = inp.overlay.loop ? THREE.MathUtils.smoothstep(inp.overlay.ms, 0, 120) : Math.min(THREE.MathUtils.smoothstep(ms, 0, 120), 1 - THREE.MathUtils.smoothstep(ms, dur - 150, dur));
use(inp.overlay.clip, ow, { time: ms / 1000 });
}
}
const cat = inp.cat;
let pose = `ub_${cat}${inp.crouch ? 'Crouch' : ''}`;
if (!has(pose)) pose = `ub_${cat}`;
if (!has(pose)) pose = 'ub_rifle';
let rest = 1 - ow;
// 사격: 반동 자세 (쏜 뒤 0.35초 동안 줄어든다)
const fire = `ub_${cat}Fire`;
if (rest > 0 && this.shotMs != null && this.shotMs < 350 && has(fire)) {
const fw = rest * (1 - THREE.MathUtils.smoothstep(this.shotMs, 120, 350));
use(fire, fw, { time: this.shotMs / 1000 });
rest -= fw;
}
// 조준 각: 위(+90°) · 아래(-90°) 자세를 비율로 섞는다 (게임의 AimOffset)
const up = THREE.MathUtils.clamp(inp.pitch / 90, 0, 1);
const down = THREE.MathUtils.clamp(-inp.pitch / 90, 0, 1);
const hasUp = has(`${pose}Up`) && has(`${pose}Down`);
if (hasUp) {
use(`${pose}Up`, rest * up);
use(`${pose}Down`, rest * down);
use(pose, rest * (1 - up - down));
} else use(pose, rest);
}
dispose() {
@@ -145,3 +359,27 @@ export class AgentRig {
this.gunSlot.clear();
}
}
let muzzleTex: THREE.Texture | null = null;
/** 총구 불꽃 (가운데가 밝은 별 모양) */
function muzzleTexture() {
if (muzzleTex) return muzzleTex;
const c = document.createElement('canvas');
c.width = c.height = 64;
const g = c.getContext('2d')!;
const rg = g.createRadialGradient(32, 32, 0, 32, 32, 32);
rg.addColorStop(0, 'rgba(255,255,240,1)');
rg.addColorStop(0.25, 'rgba(255,210,120,0.9)');
rg.addColorStop(1, 'rgba(255,120,20,0)');
g.fillStyle = rg;
g.beginPath();
for (let i = 0; i < 12; i++) {
const a = (i / 12) * Math.PI * 2;
const r = i % 2 ? 12 : 32;
g.lineTo(32 + Math.cos(a) * r, 32 + Math.sin(a) * r);
}
g.fill();
muzzleTex = new THREE.CanvasTexture(c);
muzzleTex.colorSpace = THREE.SRGBColorSpace;
return muzzleTex;
}

View File

@@ -13,6 +13,10 @@ interface Index {
/** 요원 몸 (리플레이 캐릭터 클래스 → glb), 무기 (equipKinds 이름 → glb). 옛 index 에는 없다 */
agents?: Record<string, { code: string; file: string; bytes: number }>;
weapons?: Record<string, { file: string; bytes: number }>;
/** 모든 요원 공용 애니메이션 (앉기 · 점프 · 무기별 자세 · 재장전 · 죽음 …). 옛 index 에는 없다 */
anims?: { file: string; bytes: number } | null;
/** 스킬 모델 · 파티클 · 텍스처 (abilities.json). 옛 index 에는 없다 */
abilities?: { file: string; bytes: number } | null;
}
let indexP: Promise<Index | null> | null = null;

View File

@@ -1,9 +1,12 @@
import type { KillData, MatchDetail } from '@gvr/shared';
/** tools/replay-extract (gvr-replay v1) 출력. t 는 리플레이 시작부터 ms, 좌표는 게임 월드 단위 */
/**
* tools/replay-extract (gvr-replay v1 · v2) 출력. t 는 리플레이 시작부터 ms, 좌표는 게임 월드 단위(cm).
* v2 는 v1 열을 그대로 두고 뒤에 열 · 필드를 더했다 (옛 JSON 은 없는 필드 → 빈 것으로 본다).
*/
export interface ReplayFile {
format: 'gvr-replay';
v: 1;
v: 1 | 2;
matchId: string | null;
map: string | null;
build: string | null;
@@ -11,21 +14,105 @@ export interface ReplayFile {
recordedAt: number;
durationMs: number;
sampleMs: number;
players: { puuid: string | null; character: string | null; track: { t: number[]; x: number[]; y: number[]; z: number[]; yaw: number[]; pitch: number[] } }[];
players: { puuid: string | null; character: string | null; track: { t: number[]; x: number[]; y: number[]; z: number[]; yaw: number[]; pitch: number[]; f?: number[] } }[];
rounds: { num: number; buy: number; combat: number; end: number }[];
phases: [number, number][];
/** [t, killer, victim] */
kills: [number, number, number][];
/** [t, killer, victim, deathAnim(v2, deathAnims 번호 · -1)] */
kills: [number, number, number, number?][];
/** 죽는 모션 이름 (TP_Core_Death_Head_Front_SM_Montage …) */
deathAnims?: string[];
/** [t, player, x, y, z, yaw, pitch] */
shots: [number, number, number, number, number, number, number][];
/** [t0, t1, kind, x, y, z, owner] */
objects: [number, number, number, number, number, number, number][];
/** [t0, t1, kind, x, y, z, owner, yaw(v2), pitch(v2)]. 날아가는 것은 t1 = 부딪힌 시각 (v2) */
objects: [number, number, number, number, number, number, number, number?, number?][];
objectKinds: string[];
/** 움직이는 스킬 경로 (투사체 비행 · 드론 · 분신), o = objects 번호 */
objectPaths?: ObjectPath[];
/** 무기 · 스킬 상태 [t, player, equipKind, stateKind] */
states?: [number, number, number, number][];
stateKinds?: string[];
/** 맞은 것 [t, attacker, victim, ox, oy, oz, ix, iy, iz, 부위(1 머리 2 몸 3 다리), 죽였으면 1] */
hits?: number[][];
/** 스파이크 설치 [t, player, x, y, z] */
plants?: number[][];
/** 이어지는 동작 [t0, t1, player, actionKind] (Plant · Defuse · Rope) */
actions?: [number, number, number, number][];
actionKinds?: string[];
/** 들고 있는 것이 바뀐 시각 [t, player, kind] (변환기 새 버전부터. 옛 리플레이 JSON 에는 없다) */
equips?: [number, number, number][];
equipKinds?: string[];
}
export interface ObjectPath {
o: number;
t: number[];
x: number[];
y: number[];
z: number[];
/** 드론 · 분신만 */
yaw: number[];
}
/** 움직임 상태 비트 (track.f) */
export const MOVE_CROUCH = 1;
export const MOVE_WALK = 2;
export const MOVE_AIR = 4;
export const MOVE_FLY = 8;
/** 표본 배열 t 에서 t 이하 마지막 번호 (없으면 -1) */
export function indexAt(T: ArrayLike<number>, t: number): number {
if (!T.length || t < T[0]) return -1;
let lo = 0;
let hi = T.length - 1;
while (lo < hi) {
const mid = (lo + hi + 1) >> 1;
if (T[mid] <= t) lo = mid;
else hi = mid - 1;
}
return lo;
}
/** t 시점 움직임 상태 비트 (옛 리플레이는 0) */
export function moveFlagsAt(tr: ReplayFile['players'][number]['track'], t: number): number {
if (!tr.f) return 0;
const i = indexAt(tr.t, t);
return i < 0 ? 0 : tr.f[i] ?? 0;
}
/** 경로 위 t 시점 위치 (앞뒤 표본을 Catmull-Rom 으로 부드럽게). 경로 밖이면 null */
export function samplePath(p: ObjectPath, t: number): { x: number; y: number; z: number; yaw: number | null; vx: number; vy: number; vz: number } | null {
const T = p.t;
if (T.length < 2 || t < T[0] || t > T[T.length - 1]) return null;
const i = Math.min(indexAt(T, t), T.length - 2);
const j = i + 1;
const h = i > 0 ? i - 1 : i;
const k2 = j < T.length - 1 ? j + 1 : j;
const span = T[j] - T[i] || 1;
const u = (t - T[i]) / span;
const cr = (a: number[]) => {
const p0 = a[h], p1 = a[i], p2 = a[j], p3 = a[k2];
const m1 = ((p2 - p0) / (T[j] - T[h] || 1)) * span;
const m2 = ((p3 - p1) / (T[k2] - T[i] || 1)) * span;
const u2 = u * u, u3 = u2 * u;
return (2 * u3 - 3 * u2 + 1) * p1 + (u3 - 2 * u2 + u) * m1 + (-2 * u3 + 3 * u2) * p2 + (u3 - u2) * m2;
};
let yaw: number | null = null;
if (p.yaw.length === T.length) {
let d = p.yaw[j] - p.yaw[i];
if (d > 180) d -= 360;
if (d < -180) d += 360;
yaw = p.yaw[i] + d * u;
}
return { x: cr(p.x), y: cr(p.y), z: cr(p.z), yaw, vx: (p.x[j] - p.x[i]) / span * 1000, vy: (p.y[j] - p.y[i]) / span * 1000, vz: (p.z[j] - p.z[i]) / span * 1000 };
}
/** 선수별 무기 · 스킬 상태 [t, equipKind, stateName] (시간 순) */
export function stateTracks(r: ReplayFile): [number, number, string][][] {
const out: [number, number, string][][] = r.players.map(() => []);
for (const [t, p, ek, sk] of r.states ?? []) out[p]?.push([t, ek, r.stateKinds?.[sk] ?? '']);
return out;
}
const WEAPON_KO: Record<string, string> = {
Classic: '클래식', Shorty: '쇼티', Frenzy: '프렌지', Ghost: '고스트', Sheriff: '셰리프', 'Compact Pistol': '밴딧',
Stinger: '스팅어', Spectre: '스펙터', Bucky: '버키', Judge: '저지', Bulldog: '불독', Guardian: '가디언', Phantom: '팬텀', Vandal: '밴달',

View File

@@ -0,0 +1,120 @@
import { deathClipName, weaponCat, type RigInput } from './agents3d';
import { equipAt, indexAt, MOVE_AIR, MOVE_CROUCH, MOVE_FLY, roundAt, type ReplayFile } from './replay';
/**
* 리플레이 기록 → 요원 몸 동작 (agents3d RigInput). 모두 t 하나로 정해지므로 되감기 · 멈춤 · 배속에도 같은 자세다.
* 공중 · 착지: track.f 공중 비트가 이어진 구간
* 위 몸 한 번 동작: 해체 · 설치(이어지는 동작) > 던지기(이 선수 투사체가 생김) > 재장전 · 칼 휘두르기(무기 상태) > 꺼내기(들고 있는 것이 바뀜)
* 죽음: 이 라운드에서 죽은 킬 (사망 모션 이름)
*/
export interface AnimIndex {
equips: [number, number][][];
/** 선수별 [t, equipKind, state] */
states: [number, number, string][][];
/** 선수별 던진 시각 (Projectile_* 생김) */
throws: number[][];
/** 선수별 이어지는 동작 [t0, t1, kind] */
actions: [number, number, string][][];
/** 선수별 사격 시각 */
shots: number[][];
/** states · equips 의 시각만 (찾기용) */
stateT: number[][];
equipT: number[][];
}
export function buildAnimIndex(r: ReplayFile, equips: [number, number][][]): AnimIndex {
const n = r.players.length;
const states: AnimIndex['states'] = Array.from({ length: n }, () => []);
for (const [t, p, ek, sk] of r.states ?? []) states[p]?.push([t, ek, r.stateKinds?.[sk] ?? '']);
const throws: number[][] = Array.from({ length: n }, () => []);
for (const o of r.objects) if (o[6] >= 0 && /^Projectile_/.test(r.objectKinds[o[2]] ?? '')) throws[o[6]]?.push(o[0]);
for (const a of throws) a.sort((x, y) => x - y);
const actions: AnimIndex['actions'] = Array.from({ length: n }, () => []);
for (const [t0, t1, p, k] of r.actions ?? []) actions[p]?.push([t0, t1 < 0 ? t0 + 7000 : t1, r.actionKinds?.[k] ?? '']);
const shots: number[][] = Array.from({ length: n }, () => []);
for (const s of r.shots) if (s[1] >= 0) shots[s[1]]?.push(s[0]);
return { equips, states, throws, actions, shots, stateT: states.map((a) => a.map((x) => x[0])), equipT: equips.map((a) => a.map((x) => x[0])) };
}
function lastBefore(a: number[], t: number): number | null {
const i = indexAt(a, t);
return i < 0 ? null : a[i];
}
/** 공중에 뜬 지 · 내려앉은 지 (ms) */
export function airState(tr: ReplayFile['players'][number]['track'], t: number): { airMs: number | null; landMs: number | null; crouch: boolean } {
const f = tr.f;
if (!f) return { airMs: null, landMs: null, crouch: false };
const i = indexAt(tr.t, t);
if (i < 0) return { airMs: null, landMs: null, crouch: false };
const air = (k: number) => (f[k] & (MOVE_AIR | MOVE_FLY)) !== 0;
const crouch = (f[i] & MOVE_CROUCH) !== 0;
if (air(i)) {
let k = i;
while (k > 0 && air(k - 1) && tr.t[k] - tr.t[k - 1] < 400) k--;
return { airMs: t - tr.t[k], landMs: null, crouch };
}
// 바로 전에 공중이었으면 착지
let k = i;
while (k > 0 && !air(k - 1) && tr.t[i] - tr.t[k - 1] < 600) k--;
if (k > 0 && air(k - 1)) return { airMs: null, landMs: t - tr.t[k], crouch };
return { airMs: null, landMs: null, crouch };
}
export function rigInput(
r: ReplayFile,
ix: AnimIndex,
p: number,
t: number,
base: { dt: number; fwd: number; right: number; pitch: number },
): RigInput & { shotMs: number | null } {
const tr = r.players[p].track;
const air = airState(tr, t);
const ek = equipAt(ix.equips[p], t);
const kind = r.equipKinds?.[ek];
const cat = weaponCat(kind);
let crouch = air.crouch;
let overlay: RigInput['overlay'] = null;
// 이어지는 동작 (해체 · 설치): 앉아서 손
for (const [a0, a1, k] of ix.actions[p]) {
if (a0 <= t && t <= a1 && (k === 'Defuse' || k === 'Plant')) {
crouch = true;
overlay = { clip: 'ub_defuse', ms: t - a0, loop: true };
}
}
if (!overlay) {
const th = lastBefore(ix.throws[p], t + 300);
// 던지는 동작은 손을 놓는 때(투사체가 생긴 때)보다 0.3초 먼저 시작한다
if (th != null && t - (th - 300) < 1500) overlay = { clip: 'ub_throw', ms: t - (th - 300) };
}
if (!overlay) {
const st = ix.states[p];
const i = indexAt(ix.stateT[p], t);
if (i >= 0) {
const [ts, sek, name] = st[i];
if (sek === ek && name === 'ReloadState') overlay = { clip: cat === 'pistol' ? 'ub_reloadPistol' : cat === 'sniper' ? 'ub_reloadSniper' : 'ub_reloadRifle', ms: t - ts };
else if (sek === ek && /^AnimTriggeredState/.test(name) && t - ts < 1500) overlay = { clip: /Alt/.test(name) ? 'ub_knifeAlt' : name.endsWith('2') ? 'ub_knifeAttack2' : 'ub_knifeAttack', ms: t - ts };
}
}
if (!overlay) {
const eq = ix.equips[p];
const i = indexAt(ix.equipT[p], t);
if (i >= 0 && t - eq[i][0] < 1500) {
const clip = cat === 'ability' ? 'ub_equipAbility' : cat === 'knife' ? 'ub_equipKnife' : cat === 'pistol' ? 'ub_equipPistol' : cat === 'sniper' ? 'ub_equipSniper' : 'ub_equipRifle';
overlay = { clip, ms: t - eq[i][0] };
}
}
// 죽음: 이 라운드에서 죽은 킬
let death: RigInput['death'] = null;
const rd = roundAt(r, t);
if (rd) {
for (const k of r.kills) {
if (k[2] !== p || k[0] < rd.buy || k[0] > t) continue;
death = { clip: deathClipName(k[3] != null && k[3] >= 0 ? r.deathAnims?.[k[3]] : null), ms: t - k[0] };
}
}
const sh = lastBefore(ix.shots[p], t);
return { ...base, crouch, airMs: air.airMs, landMs: air.landMs, cat, overlay, death, shotMs: sh == null ? null : t - sh };
}

View File

@@ -1,7 +1,8 @@
#!/usr/bin/env python3
"""gvr-map-extract 결과(<코드>.glb + <코드>.json)를 사이트용으로 압축한다.
pack.py <추출 폴더> <출력 폴더> <버전(예: VALORANT_13.08)>
(agents.json 이 있으면 요원 agent_*.glb · 무기 weapon_*.glb 도 같은 폴더에, index.json agents · weapons)
(agents.json 이 있으면 요원 agent_*.glb · 무기 weapon_*.glb 도 같은 폴더에, index.json agents · weapons.
anims.glb 가 있으면 공용 애니메이션 index.json anims)
출력: <출력>/<dir>/<코드>.glb.gz (gltfpack -cc 로 meshopt 압축 · 위치 양자화 → gzip) + <출력>/index.json
-ke: 재질 extras(두 층 섞기 B 층) 유지, -vt 14: 반복 UV 가 뭉개지지 않게
사이트 서버 data/maps3d 에 그대로 올리면 된다 (site/server/src/maps3d.ts)."""
@@ -30,19 +31,19 @@ for name in sorted(os.listdir(src)):
print(f"{code}: {info['triangles']} 삼각형 → {size / 1e6:.1f}MB")
# 요원 · 무기 (agents 명령 결과 agents.json 이 있으면): 뼈대 · 애니메이션 · 노드 이름을 지킨다 (-kn)
agents, weapons = {}, {}
def pack_one(file):
glb = os.path.join(src, file)
if not os.path.exists(glb):
return None
packed = os.path.join(out, d, file)
subprocess.run(['npx', '-y', 'gltfpack@1.3.0', '-i', glb, '-o', packed, '-cc', '-kn', '-ke'], check=True, stdout=subprocess.DEVNULL)
with open(packed, 'rb') as f, gzip.open(packed + '.gz', 'wb', 9) as g:
shutil.copyfileobj(f, g)
os.remove(packed)
return os.path.getsize(packed + '.gz')
aj = os.path.join(src, 'agents.json')
if os.path.exists(aj):
a = json.load(open(aj))
def pack_one(file):
glb = os.path.join(src, file)
if not os.path.exists(glb):
return None
packed = os.path.join(out, d, file)
subprocess.run(['npx', '-y', 'gltfpack@1.3.0', '-i', glb, '-o', packed, '-cc', '-kn', '-ke'], check=True, stdout=subprocess.DEVNULL)
with open(packed, 'rb') as f, gzip.open(packed + '.gz', 'wb', 9) as g:
shutil.copyfileobj(f, g)
os.remove(packed)
return os.path.getsize(packed + '.gz')
for cls, v in a.get('agents', {}).items():
size = pack_one(v['file'])
if size:
@@ -52,7 +53,13 @@ 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)}')
idx = {'version': version, 'dir': d, 'updatedAt': datetime.datetime.now(datetime.timezone.utc).isoformat(), 'maps': maps, 'agents': agents, 'weapons': weapons}
# 공용 애니메이션 (anims 명령 결과 anims.glb): 뼈 이름으로 요원 몸에 붙인다 (-kn)
anims = None
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}
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

@@ -125,6 +125,7 @@ GVR_USMAP="$usmap" GVR_MANIFEST="$manifest" "$BIN" extract "$raw"
# 요원 3D 몸 · 애니메이션 · 무기. 하나라도 실패하면 맵과 같이 올리지 않는다 (사이트의 이전 맵 · 요원 · 무기 유지, 재시도)
stage="요원 추출"
GVR_USMAP="$usmap" GVR_MANIFEST="$manifest" "$BIN" agents "$raw"
GVR_USMAP="$usmap" GVR_MANIFEST="$manifest" "$BIN" anims "$raw"
stage="압축"
python3 "$GVR_MAPS_HOME/scripts/pack.py" "$raw" "$out" "$version"
dir="$(jq -r .dir "$out/index.json")"

View File

@@ -224,7 +224,7 @@ public static class Agents
return new Result(tris, bones.Length, animations.Count, tex.Count, tex.Bytes);
}
private static HashSet<int> Subtree(MeshBoneDto[] bones, string rootName)
internal static HashSet<int> Subtree(MeshBoneDto[] bones, string rootName)
{
var set = new HashSet<int>();
var root = Array.FindIndex(bones, b => b.Name.Equals(rootName, StringComparison.OrdinalIgnoreCase));
@@ -236,7 +236,7 @@ public static class Agents
}
/// <summary>한 애니메이션을 glTF 애니메이션으로: 고른 뼈만, 프레임마다 회전(+움직이면 이동)</summary>
private static JsonObject? Clip(Glb glb, CUE4Parse_Conversion.Writers.ActorX.Structs.Animations.CAnimSequence seq, USkeleton skel, Dictionary<string, int> nameToBone, HashSet<int> only, int[] boneNode, MeshBoneDto[] bones, string name, HashSet<int> noTranslate)
internal static JsonObject? Clip(Glb glb, CUE4Parse_Conversion.Writers.ActorX.Structs.Animations.CAnimSequence seq, USkeleton skel, Dictionary<string, int> nameToBone, HashSet<int> only, int[] boneNode, MeshBoneDto[] bones, string name, HashSet<int> noTranslate)
{
var frames = Math.Max(1, seq.NumFrames);
var fps = seq.FramesPerSecond > 0 ? seq.FramesPerSecond : 30;

View File

@@ -0,0 +1,160 @@
using System.Text.Json.Nodes;
using CUE4Parse.FileProvider;
using CUE4Parse.UE4.Assets.Exports.Animation;
using CUE4Parse_Conversion.Animations;
using CUE4Parse_Conversion.Dto;
namespace GvrMapExtract;
/// <summary>
/// 모든 요원이 같이 쓰는 3인칭 애니메이션 (Core_Skeleton, 뼈 이름이 모든 요원과 같다) → anims.glb 하나.
/// 메시 없이 뼈 노드(Core_Skeleton 참조 자세)와 애니메이션만 들어 있다. 사이트는 뼈 이름으로 요원 몸에 붙이고,
/// 이동 트랙은 (요원 참조 자세 − 이 파일 참조 자세)만큼 옮겨 쓴다.
/// 이름: lb_* 아래 몸(Pelvis 아래 + Splitter, Skeleton · Root 는 회전만), ub_* 위 몸(Spine1 · MasterWeaponAim 아래), fb_* 온몸.
/// 게임의 더하기(additive) 애니메이션(조준 각 · 사격 반동)은 CUE4Parse 가 기준 자세(RefPoseSeq)에 더해 온 자세로 풀어 준다.
/// 그래서 조준 위 · 아래(*Up · *Down)와 사격(*Fire)도 온 자세다: 사이트가 보는 각 · 사격 순간에 따라 비율로 섞는다.
/// </summary>
public static class CoreAnims
{
private const string A = "/Game/Characters/_Core/3P/Anims/";
private const string D = "/Game/Characters/_Core/Death/3P/Anims/";
private const string Ak = "/Game/Equippables/Guns/Rifles/AK/S0/3P/Anims/TP_Core_AK_S0_";
private const string Pistol = "/Game/Equippables/Guns/Sidearms/BasePistol/S0/3P/Anims/TP_Core_BasePistol_S0_";
private const string Sniper = "/Game/Equippables/Guns/SniperRifles/Boltsniper/S0/3P/Anims/TP_Core_Boltsniper_S0_";
private const string Knife = "/Game/Equippables/Melee/S0/3P/Anims/TP_Core_Melee_S0_";
private const string Core = "/Game/Characters/_Core/3P/Models/Core_Skeleton";
private static readonly (string Name, string Path, char Part)[] Clips =
[
// 아래 몸: 앉기 · 점프
("lb_crouch", A + "TP_Core_CrouchIdle_LB", 'L'),
("lb_crouchN", A + "TP_Core_CrouchWalkN_LB", 'L'),
("lb_crouchS", A + "TP_Core_CrouchWalkS_LB", 'L'),
("lb_crouchE", A + "TP_Core_CrouchWalkE_LB", 'L'),
("lb_crouchW", A + "TP_Core_CrouchWalkW_LB", 'L'),
("lb_jump", A + "TP_Core_Jump_LB", 'L'),
("lb_fall", A + "TP_Core_Falling_LB", 'L'),
("lb_land", A + "TP_Core_JumpLand_LB", 'L'),
// 위 몸: 무기 종류별 자세 (서기 / 앉기) + 조준 위(Up, AimN) · 아래(Down, AimS)
("ub_rifle", Ak + "IdlePose_UB", 'U'),
("ub_rifleUp", Ak + "AimN_UB", 'U'),
("ub_rifleDown", Ak + "AimS_UB", 'U'),
("ub_rifleCrouch", Ak + "CrouchPose_UB", 'U'),
("ub_rifleCrouchUp", Ak + "CrouchAimN_UB", 'U'),
("ub_rifleCrouchDown", Ak + "CrouchAimS_UB", 'U'),
("ub_rifleFire", Ak + "FireAdd", 'U'),
("ub_pistol", Pistol + "AimC", 'U'),
("ub_pistolUp", Pistol + "AimN_UB", 'U'),
("ub_pistolDown", Pistol + "AimS_UB", 'U'),
("ub_pistolCrouch", Pistol + "CrouchPose_UB", 'U'),
("ub_pistolCrouchUp", Pistol + "Crouch_AimN_UB", 'U'),
("ub_pistolCrouchDown", Pistol + "Crouch_AimS_UB", 'U'),
("ub_pistolFire", Pistol + "FireAdd_UB", 'U'),
("ub_sniper", Sniper + "IdlePose_UB", 'U'),
("ub_sniperUp", Sniper + "AimN_UB", 'U'),
("ub_sniperDown", Sniper + "AimS_UB", 'U'),
("ub_sniperCrouch", Sniper + "CrouchPose_UB", 'U'),
("ub_sniperCrouchUp", Sniper + "CrouchAimN_UB", 'U'),
("ub_sniperCrouchDown", Sniper + "CrouchAimS_UB", 'U'),
("ub_sniperFire", Sniper + "Fire_UB", 'U'),
("ub_knife", Knife + "Aggressive_Idle_UB", 'U'),
("ub_knifeCrouch", Knife + "Aggressive_CrouchIdle_UB", 'U'),
("ub_ability", A + "Grenade/TP_Core_Grenade_Idle_UB", 'U'),
("ub_abilityCrouch", A + "Grenade/TP_Core_Grenade_CrouchIdle_UB", 'U'),
// 위 몸: 동작
("ub_throw", A + "TP_Core_Grenade_ThrowPrimary_UB", 'U'),
("ub_equipAbility", A + "TP_Core_Grenade_Equip_UB", 'U'),
("ub_reloadRifle", Ak + "Reload_UB", 'U'),
("ub_reloadPistol", Pistol + "Reload_UB", 'U'),
("ub_reloadSniper", Sniper + "Reload_UB", 'U'),
("ub_equipRifle", Ak + "Equip_UB", 'U'),
("ub_equipPistol", Pistol + "Equip_UB", 'U'),
("ub_equipSniper", Sniper + "Equip_UB", 'U'),
("ub_equipKnife", Knife + "Aggressive_Equip_UB", 'U'),
("ub_knifeAttack", Knife + "Aggressive_Attack01_UB", 'U'),
("ub_knifeAttack2", Knife + "Aggressive_Attack02_UB", 'U'),
("ub_knifeAlt", Knife + "Aggressive_Attack_Alt_UB", 'U'),
("ub_defuse", A + "Bomb/Core_Bomb_Spike_Defuse", 'U'),
];
/// <summary>죽는 모션 (온몸): 경기 기록의 TP_Core_Death_X_Montage → fb_X</summary>
private static readonly string[] Deaths =
[
"Belly_Front_LG", "Belly_Front_SM", "BigN", "BodyN_Small",
"Body_Back_LG", "Body_Back_SM", "Body_Front_LG", "Body_Front_SM", "Body_Left_LG", "Body_Left_SM", "Body_Right_LG", "Body_Right_SM",
"Head_Back_LG", "Head_Back_SM", "Head_Front_LG", "Head_Front_SM", "Head_Left_LG", "Head_Left_SM", "Head_Right_LG", "Head_Right_SM", "Headshot01",
"Leg_Back_LG", "Leg_Front_LG", "Leg_Left_LG", "Leg_Right_LG",
"Lumbar_Back_LG", "Lumbar_Back_SM",
];
public sealed record Result(int Clips, int Failed, List<string> Missing);
public static Result Export(IFileProvider provider, string file)
{
var skel = provider.LoadPackageObject<USkeleton>(Core + "." + Core[(Core.LastIndexOf('/') + 1)..]);
var info = skel.ReferenceSkeleton.FinalRefBoneInfo;
var pose = skel.ReferenceSkeleton.FinalRefBonePose;
var bones = info.Select((b, i) => new MeshBoneDto(b, pose[i])).ToArray();
var glb = new Glb();
var boneNode = 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"] = Arr(t.Translation.X, t.Translation.Y, t.Translation.Z),
["rotation"] = Arr(t.Rotation.X, t.Rotation.Y, t.Rotation.Z, t.Rotation.W),
["scale"] = Arr(t.Scale3D.X, t.Scale3D.Y, t.Scale3D.Z),
});
boneNode[i] = glb.Nodes.Count - 1;
}
for (var i = 0; i < bones.Length; i++)
{
var p = bones[i].ParentIndex;
if (p < 0) { glb.Roots.Add(boneNode[i]); continue; }
var parent = glb.Nodes[boneNode[p]]!.AsObject();
if (parent["children"] is not JsonArray ch) parent["children"] = ch = new JsonArray();
ch.Add(boneNode[i]);
}
var nameToBone = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
for (var i = 0; i < bones.Length; i++) nameToBone.TryAdd(bones[i].Name, i);
var upper = Agents.Subtree(bones, "Spine1");
upper.UnionWith(Agents.Subtree(bones, "MasterWeaponAim"));
var lower = Agents.Subtree(bones, "Pelvis");
if (nameToBone.TryGetValue("Splitter", out var spl)) lower.Add(spl);
var rootOnlyRot = new HashSet<int>();
foreach (var n in new[] { "Skeleton", "Root" })
if (nameToBone.TryGetValue(n, out var ri)) { lower.Add(ri); rootOnlyRot.Add(ri); }
var all = Enumerable.Range(0, bones.Length).ToHashSet();
var list = Clips.Concat(Deaths.Select(d => ("fb_" + d, D + "TP_Core_Death_" + d, 'A'))).ToList();
var animations = new JsonArray();
var missing = new List<string>();
var failed = 0;
foreach (var (name, path, part) in list)
{
try
{
var a = provider.LoadPackageObject<UAnimSequence>(path + "." + path[(path.LastIndexOf('/') + 1)..]);
var set = a.ConvertAnims();
var seq = set.Sequences[0];
var only = part switch { 'U' => upper, 'L' => lower, _ => all };
var anim = Agents.Clip(glb, seq, set.Skeleton, nameToBone, only, boneNode, bones, name, rootOnlyRot);
if (anim != null) animations.Add(anim);
else missing.Add(name);
}
catch (Exception e)
{
failed++;
missing.Add(name);
Console.Error.WriteLine($" 애니메이션 {name} 실패: {e.GetType().Name} {e.Message}");
}
}
glb.Write(file, new JsonObject { ["animations"] = animations });
return new Result(animations.Count, failed, missing);
}
private static JsonArray Arr(params float[] v) => new(v.Select(x => (JsonNode)x).ToArray());
}

View File

@@ -15,6 +15,8 @@ using GvrMapExtract;
// gvr-map-extract ls <정규식> [개수] 파일 목록
// gvr-map-extract maps 맵 목록 (코드 이름 · 레벨 수)
// 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_USMAP 매핑 파일 (.usmap, 필수: 13.08 부터 패키지에 형 정보가 없다). uedb.dev 에서 받는다
@@ -168,6 +170,14 @@ switch (args[0])
Console.WriteLine($"끝: 요원 {list.Count} · 무기 {weapons.Count} · 실패 {failedAgents} · 받은 양 {store.DownloadedBytes >> 20}MB · {sw.Elapsed.TotalMinutes:F1}분");
return failedAgents == 0 ? 0 : 1;
}
case "anims":
{
// 모든 요원 공용 애니메이션 anims.glb (앉기 · 점프 · 무기별 자세 · 재장전 · 던지기 · 죽음)
Directory.CreateDirectory(args[1]);
var r = CoreAnims.Export(provider, Path.Combine(args[1], "anims.glb"));
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 "anim":
foreach (var a in args.Skip(1)) ProbeAnim.Anim(provider, a);
break;

View File

@@ -1,4 +1,5 @@
using System.Text.RegularExpressions;
using Replay.Models.Descriptors;
using Replay.Models.Events;
using Replay.Models.Unreal;
using Replay.Valorant.Combat;
@@ -6,6 +7,7 @@ using Replay.Valorant.Descriptors;
using Replay.Valorant.Descriptors.Agents;
using Replay.Valorant.Events.Combat;
using Replay.Valorant.Events.Movement;
using Replay.Valorant.Flashes.Descriptors;
using Replay.Valorant.GameState;
namespace GvrReplay;
@@ -26,9 +28,23 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink
private readonly List<(int T, int NewRoundIndex)> _roundEnds = [];
private readonly List<(int T, uint Killer, uint Victim)> _kills = [];
private readonly List<(int T, uint State, int X, int Y, int Z, int Yaw, int Pitch)> _shots = [];
private readonly List<(int T0, uint Actor, string Kind, int X, int Y, int Z)> _objects = [];
private readonly List<(int T0, uint Actor, string Kind, int X, int Y, int Z, int Yaw, int Pitch)> _objects = [];
private readonly Dictionary<uint, int> _closedAt = [];
private readonly Dictionary<uint, uint> _objectOwner = [];
// 액터의 Instigator / Owner (진단 필드). 스킬 → 요원 몸 (또는 장비 · 드론 → 요원 몸)
private readonly Dictionary<uint, uint> _instigator = [];
private readonly Dictionary<uint, uint> _ownerRef = [];
private readonly Dictionary<uint, string> _pathByGuid = [];
// 투사체 비행: ReplicatedMovement [t, x, y, z] · 부딪힌 시각 (MulticastStopProjectile) · 피닉스 섬광 미리 계산된 경로
private readonly Dictionary<uint, List<int[]>> _flight = [];
private readonly Dictionary<uint, (double X, double Y, double Z)> _spawnLoc = [];
private readonly Dictionary<uint, int> _stopAt = [];
private readonly Dictionary<uint, List<int[]>> _presetPath = [];
// 무기 · 스킬 상태 머신 (장비 액터, 상태 이름)
private readonly List<(int T, uint Equip, string State)> _esm = [];
private readonly List<(int T, uint Victim, uint Attacker, int[] Origin, int[] Impact, int Region, bool Killed, string? Montage)> _hits = [];
private readonly List<(int T, uint Planter, int X, int Y, int Z)> _plants = [];
private readonly Dictionary<ulong, (int T, uint Actor, string Kind)> _fxOpen = [];
private readonly List<(int T0, int T1, uint Actor, string Kind)> _actions = [];
private readonly Dictionary<string, int> _stats = [];
// 들고 있는 것: 장비 액터 → 이름 (총은 파서 목록 이름, 나머지는 클래스 이름), 캐릭터별 바뀐 시각
private readonly Dictionary<uint, string> _equipName = [];
@@ -52,6 +68,7 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink
{
case NetGuidExported g:
if (_map is null && MapPath().IsMatch(g.Path)) _map = g.Path;
_pathByGuid[g.NetGuid] = g.Path;
break;
case ActorSpawned s:
if (s.ArchetypePath is { } arch)
@@ -61,7 +78,11 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink
_equipName[s.ActorNetGuid] = en;
Count("spawn " + Simplify(arch));
if (s.Location is { } loc && ObjectClass().IsMatch(arch) && !arch.EndsWith("_PC_C"))
_objects.Add((Ms(s.TimeSeconds), s.ActorNetGuid, Simplify(arch), R(loc.X), R(loc.Y), R(loc.Z)));
{
var rot = s.Rotation;
_objects.Add((Ms(s.TimeSeconds), s.ActorNetGuid, Simplify(arch), R(loc.X), R(loc.Y), R(loc.Z), R(rot?.Yaw ?? 0), R(rot?.Pitch ?? 0)));
_spawnLoc[s.ActorNetGuid] = (loc.X, loc.Y, loc.Z);
}
}
break;
case ActorClosed c:
@@ -84,6 +105,7 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink
private void OnExport(ExportGroupReceived x)
{
OnFields(x);
switch (x.Payload)
{
case BombGameStateDescriptor gs when gs.HasDecoded(nameof(BombGameStateDescriptor.MatchID)) && !string.IsNullOrEmpty(gs.MatchID):
@@ -109,21 +131,89 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink
case GenericAgentDescriptor agent:
if (agent.HasDecoded(nameof(GenericAgentDescriptor.PlayerState)) && agent.PlayerState.NetGuid != 0)
_stateByCharacter.TryAdd(x.ActorNetGuid, agent.PlayerState.NetGuid);
if (agent.HasDecoded(nameof(GenericAgentDescriptor.Owner)) && agent.Owner.NetGuid != 0)
_objectOwner.TryAdd(x.ActorNetGuid, agent.Owner.NetGuid);
if (agent.HasDecoded(nameof(GenericAgentDescriptor.Instigator)) && agent.Instigator.NetGuid != 0)
_objectOwner[x.ActorNetGuid] = agent.Instigator.NetGuid;
break;
}
}
// 진단 필드 (모든 페이로드 공통): Instigator · Owner · ReplicatedMovement · 상태 머신 CurrentState
private void OnFields(ExportGroupReceived x)
{
var a = x.ActorNetGuid;
foreach (var f in x.DiagnosticFields)
{
var v = f.Value;
switch (v.Kind)
{
case DecodedFieldValueKind.ObjectReference when v.ObjectReferenceValue.NetGuid != 0:
if (f.Name == "Instigator" && x.IsActor) _instigator.TryAdd(a, v.ObjectReferenceValue.NetGuid);
else if (f.Name == "Owner" && x.IsActor) _ownerRef.TryAdd(a, v.ObjectReferenceValue.NetGuid);
else if (f.Name == "CurrentState" && x.ExportGroupPath is { } gp && gp.EndsWith("EquippableStateMachineComponent"))
{
var st = Leaf(v.ObjectReferenceValue.Path ?? _pathByGuid.GetValueOrDefault(v.ObjectReferenceValue.NetGuid));
if (st != null) _esm.Add((Ms(x.TimeSeconds), a, st));
}
break;
case DecodedFieldValueKind.RepMovement when x.IsActor && v.RepMovementValue.Location is { } l && _spawnLoc.TryGetValue(a, out var sp)
&& _archetypeByActor.TryGetValue(a, out var arch) && arch.StartsWith("Default__Projectile_"):
{
// 파서가 위치를 1/100 로 읽는다 (VectorNetQuantize100 로 보지만 발로란트는 정수 cm). 생긴 위치에 더 가까운 쪽을 쓴다
double D(double k) => Math.Abs(l.X * k - sp.X) + Math.Abs(l.Y * k - sp.Y) + Math.Abs(l.Z * k - sp.Z);
if (!_flight.TryGetValue(a, out var list)) _flight[a] = list = [];
var k = list.Count > 0 ? list[0][4] : D(100) < D(1) ? 100 : 1;
list.Add([Ms(x.TimeSeconds), R(l.X * k), R(l.Y * k), R(l.Z * k), k]);
break;
}
}
}
}
private static string? Leaf(string? path)
{
if (string.IsNullOrEmpty(path)) return null;
var i = path.LastIndexOfAny(['.', '/']);
return i >= 0 ? path[(i + 1)..] : path;
}
private void OnRpc(RpcReceived r)
{
var t = Ms(r.TimeSeconds);
if (ValorantEquippableResolver.TryResolveClassNetCachePath(r.ClassPath, r.ActorNetGuid, out var eq) && eq.Name is { } en)
_equipName.TryAdd(r.ActorNetGuid, en);
if (r.FunctionName == "MulticastStopProjectile") _stopAt.TryAdd(r.ActorNetGuid, t);
switch (r.Payload)
{
case PrecalculatedProjectileSetPathParameters sp when sp.NetworkedProjectilePath is { } pts:
_presetPath[r.ActorNetGuid] = pts.Where(q => q?.Location is not null)
.Select(q => new[] { t + Ms(q!.ElapsedSeconds ?? 0), R(q.Location!.Value.X), R(q.Location.Value.Y), R(q.Location.Value.Z) }).ToList();
break;
case MulticastNotifyDamagePointParameters d:
{
int[] V(Replay.Models.Unreal.FVector? q) => q is { } w ? [R(w.X), R(w.Y), R(w.Z)] : [0, 0, 0];
var bone = d.DamagedBone ?? "";
var region = bone.Length == 0 ? 0 : bone.Contains("Head", StringComparison.OrdinalIgnoreCase) || bone.Contains("Neck", StringComparison.OrdinalIgnoreCase) ? 1
: bone.Contains("Leg", StringComparison.OrdinalIgnoreCase) || bone.Contains("Foot", StringComparison.OrdinalIgnoreCase) || bone.Contains("Thigh", StringComparison.OrdinalIgnoreCase) || bone.Contains("Calf", StringComparison.OrdinalIgnoreCase) ? 3 : 2;
var montage = d.DamageKilledTarget && d.DeathAnimMontage.NetGuid != 0 ? Leaf(d.DeathAnimMontage.Path ?? _pathByGuid.GetValueOrDefault(d.DeathAnimMontage.NetGuid)) : null;
_hits.Add((t, r.ActorNetGuid, d.EventInstigatorPawn.NetGuid, V(d.DamageOrigin), V(d.DamageImpactLocation), region, d.DamageKilledTarget, montage));
break;
}
case BombPlantedRpcParameters bp:
_plants.Add((t, bp.BombPlanter.NetGuid, R(bp.PlantLocation.X), R(bp.PlantLocation.Y), R(bp.PlantLocation.Z)));
break;
case EffectManagerPlayContinuousParameters fx when fx.EffectId is { } id:
{
var kind = Leaf(fx.EffectContainerPath ?? (fx.EffectContainer is { } ec ? ec.Path ?? _pathByGuid.GetValueOrDefault(ec.NetGuid) : null)) switch
{
"FXC_Bomb_Plant_C" => "Plant",
"FXC_DefuseBomb_Defuser_C" => "Defuse",
"FXC_Ascender_OnRope_C" => "Rope",
_ => null,
};
if (kind != null) _fxOpen[id] = (t, r.ActorNetGuid, kind);
break;
}
case EffectManagerStopContinuousParameters fs when fs.EffectId is { } id && _fxOpen.Remove(id, out var open):
_actions.Add((open.T, t, open.Actor, open.Kind));
break;
case ClientGamePhaseBeginParameters p:
// 같은 시각에 같은 단계가 여러 컨트롤러로 올 수 있다
if (_phases.Count == 0 || _phases[^1][1] != p.NewPhase || _phases[^1][0] != t)
@@ -148,7 +238,10 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink
_lastMoveT[ch] = t;
var p = m.Move.Position;
if (!_moves.TryGetValue(ch, out var list)) _moves[ch] = list = [];
list.Add([t, R(p.X), R(p.Y), R(p.Z), R(m.Move.Yaw), R(m.Move.Pitch)]);
// RotationYawMultiplier 는 실제로 움직임 비트 (0x02 앉음 · 0x10 걷기), UnusedByte 는 이동 모드 (1 땅 · 3 공중 · 5 날기)
var bits = (byte)m.Move.RotationYawMultiplier;
var flags = ((bits & 0x02) != 0 ? 1 : 0) | ((bits & 0x10) != 0 ? 2 : 0) | (m.Move.UnusedByte == 3 ? 4 : 0) | (m.Move.UnusedByte == 5 ? 8 : 0);
list.Add([t, R(p.X), R(p.Y), R(p.Z), R(m.Move.Yaw), R(m.Move.Pitch), flags]);
}
private void OnShot(ValorantShotReceived s)
@@ -228,7 +321,7 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink
{
if (mv[0] - lastT < sampleMs) continue;
lastT = mv[0];
tr.T.Add(mv[0]); tr.X.Add(mv[1]); tr.Y.Add(mv[2]); tr.Z.Add(mv[3]); tr.Yaw.Add(mv[4]); tr.Pitch.Add(mv[5]);
tr.T.Add(mv[0]); tr.X.Add(mv[1]); tr.Y.Add(mv[2]); tr.Z.Add(mv[3]); tr.Yaw.Add(mv[4]); tr.Pitch.Add(mv[5]); tr.F.Add(mv[6]);
}
}
@@ -245,26 +338,95 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink
rounds.Add(new ReplayRound { Num = starts[r].Num, Buy = buy >= 0 ? buy : from, Combat = Phase(4), End = Phase(5) });
}
// 액터 → 선수: Instigator(없으면 Owner)를 따라 올라가 요원 몸 · 선수 상태를 만날 때까지 (스킬 → 장비/드론 → 요원)
int OwnerOf(uint actor)
{
var cur = actor;
for (var d = 0; d < 6; d++)
{
if (indexByCharacter.TryGetValue(cur, out var pi)) return pi;
if (_subjectByState.ContainsKey(cur)) return PlayerOfState(cur);
if (!_instigator.TryGetValue(cur, out var up) && !_ownerRef.TryGetValue(cur, out up)) return -1;
if (up == cur) return -1;
cur = up;
}
return -1;
}
var kinds = new List<string>();
var kindIndex = new Dictionary<string, int>();
var objects = new List<int[]>();
var paths = new List<ObjectPath>();
// 맵 자체 연출(예: GameObject_Infinity_Rain_*)은 뺀다
var mapName = _map?.Split('/')[^1];
foreach (var o in _objects)
{
if (mapName is not null && o.Kind.Contains("_" + mapName + "_")) continue;
if (!kindIndex.TryGetValue(o.Kind, out var k)) { k = kinds.Count; kinds.Add(o.Kind); kindIndex[o.Kind] = k; }
var owner = -1;
var cur = o.Actor;
for (var d = 0; d < 6 && _objectOwner.TryGetValue(cur, out var up); d++)
var owner = OwnerOf(o.Actor);
// 스파이크는 심은 사람 (같은 자리 설치 기록)
if (owner < 0 && o.Kind == "TimedBomb_C")
{
if (indexByCharacter.TryGetValue(up, out owner)) break;
owner = -1;
if (_stateByCharacter.ContainsKey(up)) break;
if (_subjectByState.ContainsKey(up)) { owner = PlayerOfState(up); break; }
cur = up;
var pl = _plants.Where(q => Math.Abs(q.T - o.T0) < 3000).OrderBy(q => Math.Abs(q.T - o.T0)).FirstOrDefault();
if (pl.Planter != 0) owner = OwnerOf(pl.Planter);
}
objects.Add([o.T0, _closedAt.TryGetValue(o.Actor, out var t1) && t1 >= o.T0 ? t1 : -1, k, o.X, o.Y, o.Z, owner]);
// 요루 분신 생성기는 참조가 없다: 생성기가 사라질 때 같은 자리에 나온 분신의 주인
if (owner < 0 && o.Kind.StartsWith("GameObject_Stealth_DecoySpawner") && _closedAt.TryGetValue(o.Actor, out var sc))
{
var dec = _objects.Where(q => q.Kind.StartsWith("Pawn_Stealth_4_Decoy") && Math.Abs(q.T0 - sc) < 1000 && Math.Abs(q.X - o.X) + Math.Abs(q.Y - o.Y) < 600).Select(q => q.Actor).FirstOrDefault();
if (dec != 0) owner = OwnerOf(dec);
}
var t1 = _closedAt.TryGetValue(o.Actor, out var tc) && tc >= o.T0 ? tc : -1;
// 날아가는 것은 부딪힌 시각에 끝 (닫힘은 1~2초 늦을 수 있다)
if (_stopAt.TryGetValue(o.Actor, out var ts) && ts >= o.T0 && (t1 < 0 || ts < t1)) t1 = ts;
var oi = objects.Count;
objects.Add([o.T0, t1, k, o.X, o.Y, o.Z, owner, o.Yaw, o.Pitch]);
// 경로: 미리 계산된 경로(피닉스 섬광) > ReplicatedMovement (투사체) > 캐릭터 이동 (드론 · 분신 · 가짜 순간이동)
var path = new ObjectPath { O = oi };
if (_presetPath.TryGetValue(o.Actor, out var pre) && pre.Count > 1)
{
foreach (var q in pre) { path.T.Add(q[0]); path.X.Add(q[1]); path.Y.Add(q[2]); path.Z.Add(q[3]); }
}
else if (_flight.TryGetValue(o.Actor, out var fl) && fl.Count > 0)
{
path.T.Add(o.T0); path.X.Add(o.X); path.Y.Add(o.Y); path.Z.Add(o.Z);
foreach (var q in fl)
{
if (q[0] <= path.T[^1] || (t1 >= 0 && q[0] > t1)) continue;
path.T.Add(q[0]); path.X.Add(q[1]); path.Y.Add(q[2]); path.Z.Add(q[3]);
}
}
else if (o.Kind.StartsWith("Pawn_") && _moves.TryGetValue(o.Actor, out var mv) && mv.Count > 1)
{
foreach (var q in mv.OrderBy(q => q[0]))
{
if (path.T.Count > 0 && q[0] - path.T[^1] < sampleMs) continue;
path.T.Add(q[0]); path.X.Add(q[1]); path.Y.Add(q[2]); path.Z.Add(q[3]); path.Yaw.Add(q[4]);
}
}
if (path.T.Count > 1) paths.Add(path);
}
var hits = _hits.Select(h => new[] { h.T, OwnerOf(h.Attacker), OwnerOf(h.Victim), h.Origin[0], h.Origin[1], h.Origin[2], h.Impact[0], h.Impact[1], h.Impact[2], h.Region, h.Killed ? 1 : 0 }).ToList();
var deathAnims = new List<string>();
int DeathAnim(int t, uint victim)
{
var h = _hits.Where(q => q.Killed && q.Montage != null && q.Victim == victim && Math.Abs(q.T - t) < 500).OrderBy(q => Math.Abs(q.T - t)).FirstOrDefault();
if (h.Montage is null) return -1;
var i = deathAnims.IndexOf(h.Montage);
if (i < 0) { i = deathAnims.Count; deathAnims.Add(h.Montage); }
return i;
}
var actionKinds = new List<string>();
var actions = new List<int[]>();
foreach (var a in _actions.Concat(_fxOpen.Values.Select(o => (T0: o.T, T1: -1, o.Actor, o.Kind))).OrderBy(a => a.T0))
{
var pi = OwnerOf(a.Actor);
if (pi < 0) continue;
var ak = actionKinds.IndexOf(a.Kind);
if (ak < 0) { ak = actionKinds.Count; actionKinds.Add(a.Kind); }
actions.Add([a.T0, a.T1, pi, ak]);
}
// 들고 있는 것: [t, 선수, 종류]. 같은 선수가 같은 것을 다시 들면 뺀다
@@ -298,6 +460,28 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink
equips.Add([e.T, e.P, EquipKind(e.Name)]);
}
// 무기 · 스킬 상태: 장비 액터 → 선수 (인벤토리 기록, 없으면 Instigator)
var equipOwner = new Dictionary<uint, int>();
foreach (var (_, ch, eq) in _equips)
if (indexByCharacter.TryGetValue(ch, out var pi)) equipOwner[eq] = pi;
var stateKinds = new List<string>();
var stateKindIndex = new Dictionary<string, int>();
var states = new List<int[]>();
var lastState = new Dictionary<uint, string>();
// 들고 있지 않은 장비의 상태(Inactive · 줌 꺼짐)는 쓸모가 없다
foreach (var (t, eq, st) in _esm)
{
if (st is "InactiveState" or "ZoomStateDisabled") continue;
if (lastState.TryGetValue(eq, out var ls) && ls == st) continue;
lastState[eq] = st;
if (!equipOwner.TryGetValue(eq, out var pi)) { pi = OwnerOf(eq); if (pi < 0) continue; equipOwner[eq] = pi; }
var name = _equipName.TryGetValue(eq, out var en) ? en : _archetypeByActor.TryGetValue(eq, out var ea) ? Simplify(ea) : null;
if (name is null) continue;
if (!stateKindIndex.TryGetValue(st, out var sk)) { sk = stateKinds.Count; stateKinds.Add(st); stateKindIndex[st] = sk; }
states.Add([t, pi, EquipKind(name), sk]);
}
return new ReplayFile
{
Equips = equips,
@@ -311,7 +495,15 @@ public sealed partial class Collector(int sampleMs) : IReplayEventSink
Players = players,
Rounds = rounds,
Phases = _phases,
Kills = _kills.Select(k => new[] { k.T, indexByCharacter.GetValueOrDefault(k.Killer, -1), indexByCharacter.GetValueOrDefault(k.Victim, -1) }).ToList(),
Kills = _kills.Select(k => new[] { k.T, indexByCharacter.GetValueOrDefault(k.Killer, -1), indexByCharacter.GetValueOrDefault(k.Victim, -1), DeathAnim(k.T, k.Victim) }).ToList(),
DeathAnims = deathAnims,
ObjectPaths = paths,
States = states,
StateKinds = stateKinds,
Hits = hits,
Plants = _plants.Select(p => new[] { p.T, OwnerOf(p.Planter), p.X, p.Y, p.Z }).ToList(),
Actions = actions,
ActionKinds = actionKinds,
Shots = _shots.Select(s => new[] { s.T, PlayerOfState(s.State), s.X, s.Y, s.Z, s.Yaw, s.Pitch }).ToList(),
Objects = objects,
ObjectKinds = kinds,

View File

@@ -7,7 +7,8 @@ namespace GvrReplay;
public sealed class ReplayFile
{
public string Format { get; set; } = "gvr-replay";
public int V { get; set; } = 1;
/// 2: objects 에 yaw · pitch, objectPaths · track.f · states · hits · plants · actions · kills 4번째 열 추가 (v1 열은 그대로)
public int V { get; set; } = 2;
public string? MatchId { get; set; }
public string? Map { get; set; }
public string? Build { get; set; }
@@ -19,13 +20,27 @@ public sealed class ReplayFile
public List<ReplayRound> Rounds { get; set; } = [];
/// [t, phase] 게임 단계 바뀜 (원본 값)
public List<int[]> Phases { get; set; } = [];
/// [t, killer, victim] (선수 번호, 모르면 -1)
/// [t, killer, victim, deathAnim] (선수 번호, 모르면 -1. deathAnim = deathAnims 번호, 모르면 -1)
public List<int[]> Kills { get; set; } = [];
/// 죽는 모션 이름 (예: TP_Core_Death_Head_Front_SM_Montage)
public List<string> DeathAnims { get; set; } = [];
/// [t, player, x, y, z, yaw, pitch] 사격 위치와 방향
public List<int[]> Shots { get; set; } = [];
/// 스킬 · 설치물 [t0, t1, kind 번호, x, y, z, player] (t1 = 사라진 시각, 모르면 -1)
/// 스킬 · 설치물 [t0, t1, kind 번호, x, y, z, player, yaw, pitch] (t1 = 사라진 시각, 날아가는 것은 부딪힌 시각, 모르면 -1. yaw · pitch 는 생길 때 방향(도))
public List<int[]> Objects { get; set; } = [];
public List<string> ObjectKinds { get; set; } = [];
/// 움직이는 스킬의 경로 (투사체 비행 · 드론 · 분신). o = objects 번호
public List<ObjectPath> ObjectPaths { get; set; } = [];
/// 무기 · 스킬 상태 바뀜 [t, player, equipKind, stateKind] (FiringState · ReloadState · ZoomStateLevel1 · EquipState …)
public List<int[]> States { get; set; } = [];
public List<string> StateKinds { get; set; } = [];
/// 맞은 것 [t, attacker, victim, 쏜 x, y, z, 맞은 x, y, z, 부위(1 머리 · 2 몸 · 3 다리 · 0 모름), 죽였으면 1]
public List<int[]> Hits { get; set; } = [];
/// 스파이크 설치 [t, player, x, y, z]
public List<int[]> Plants { get; set; } = [];
/// 이어지는 동작 [t0, t1, player, actionKind] (Plant 설치 중 · Defuse 해체 중 · Rope 줄 타기), t1 모르면 -1
public List<int[]> Actions { get; set; } = [];
public List<string> ActionKinds { get; set; } = [];
/// 들고 있는 것이 바뀐 시각 [t, player, kind 번호]. 총은 영어 이름(Vandal 등), 칼은 Melee, 스파이크는 Spike, 스킬은 클래스 이름
public List<int[]> Equips { get; set; } = [];
public List<string> EquipKinds { get; set; } = [];
@@ -48,6 +63,19 @@ public sealed class PlayerTrack
public List<int> Z { get; set; } = [];
public List<int> Yaw { get; set; } = [];
public List<int> Pitch { get; set; } = [];
/// 움직임 상태 비트: 1 앉음 · 2 걷기(Shift) · 4 공중(점프 · 떨어짐) · 8 날기(제트 대시 등)
public List<int> F { get; set; } = [];
}
public sealed class ObjectPath
{
public int O { get; set; }
public List<int> T { get; set; } = [];
public List<int> X { get; set; } = [];
public List<int> Y { get; set; } = [];
public List<int> Z { get; set; } = [];
/// 드론 · 분신만 (보는 방향, 도). 투사체는 빈 배열
public List<int> Yaw { get; set; } = [];
}
public sealed class ReplayRound

View File

@@ -1,4 +1,4 @@
// gvr-replay: 발로란트 리플레이(.vrf) → 사이트 재생기용 JSON (형식 gvr-replay v1)
// gvr-replay: 발로란트 리플레이(.vrf) → 사이트 재생기용 JSON (형식 gvr-replay v2)
// gvr-replay <file.vrf> <out.json> [--hz 10]
// gvr-replay <file.vrf> --stats (디버그: 액터 종류별 개수)
// 성공하면 종료 코드 0 과 함께 stdout 마지막 줄에 {"ok":true,...} 요약을 쓴다. 실패는 1 과 {"ok":false,"error":...}
@@ -32,7 +32,9 @@ public static class Program
using var file = File.OpenRead(input);
using var archive = new FBinaryArchive(file);
var enricher = new ValorantEventEnricher(collector);
var result = ValorantReplayReader.CreateDefault(null, enricher, ParseProfile.Default).Read(archive);
// 진단 필드: 스킬 주인(Instigator) · 투사체 비행(ReplicatedMovement) · 무기 상태(CurrentState)를 페이로드 종류와 상관없이 읽는다
var profile = new ParseProfile { EnabledCategories = ExportCategory.All, CaptureDiagnosticFields = true };
var result = ValorantReplayReader.CreateDefault(null, enricher, profile).Read(archive);
enricher.Complete();
var info = result.Metadata.ReplayInfo;
if (stats)