보고서: 텀블링 몽키 3D 물리 간이 실험 스크립트·결과, 설계 문서 근거 연결

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
EJClaw
2026-10-11 23:21:00 +09:00
parent 2fe43952d3
commit bd179c7a43
2 changed files with 156 additions and 2 deletions

View File

@@ -1,6 +1,6 @@
# 텀블링 몽키 (`tumblin-monkeys`)
> 마일스톤: 미정(새 게임 후보 52번, 사용자 확인 후 시작) · 인원: 최소 2 ~ 최대 4명 · 예상 시간: 약 5~10분 · 난이도: 쉬움
> 마일스톤: 미정(사용자 확인 후 시작) · 인원: 최소 2 ~ 최대 4명 · 예상 시간: 약 5~10분 · 난이도: 쉬움
## 1. 개요
- 나무 기둥 구멍에 색 막대를 꽂고 위에서 원숭이를 쏟아 걸어 둔다. 차례마다 주사위 색에 맞는 막대를 하나 뽑고, 그때 떨어진 원숭이는 뽑은 사람이 가진다. 끝났을 때 원숭이가 가장 적은 사람이 이긴다.
@@ -44,7 +44,7 @@
### 8.1 물리 엔진과 결정성
- **Rapier 결정적 빌드**(`@dimforge/rapier3d-deterministic-compat`, WASM)를 서버에서만 쓴다. 같은 입력이면 어느 컴퓨터에서든 같은 결과가 나오도록 만든 빌드다.
- 고정 시간 간격(1/60초), 한 번 뽑을 때 최대 6초(360걸음)까지 계산. 모든 원숭이가 멈추면 일찍 끝낸다.
- 시험(2026-10-11, 이 서버, 원숭이 30·막대 24): 한 걸음 약 0.2ms, 막대 하나 뽑을 때 수십 ms. 같은 시드로 두 번 돌리면 모든 원숭이 위치가 비트 단위로 같았다. 스냅숏 저장 → 복원 후 계산도 같았다.
- 간이 실험(2026-10-11, 대충 만든 모양, 원숭이 30·막대 24, `docs/reports/tumblin-monkeys-physics-20261011.md`): 한 걸음 약 0.2ms, 막대 하나 평균 약 11~14ms(상한 600걸음 ≈ 120ms). 같은 시드로 두 번 돌린 최종 위치 해시가 같았고, 스냅숏 저장 → 복원 후 계산도 같았다. 실제 모양으로 바꾸면 다시 잰다.
- 상태에는 물리 세계를 통째로 넣지 않고(스냅숏 약 130KB), **멈춘 원숭이 위치·회전과 남은 막대**만 넣는다. 매 차례 그것으로 세계를 다시 만들어 계산한다. 결과는 이 값에만 달려 있으니 다시 보기·재시작에도 똑같다.
- 물리 모듈은 `packages/games`의 서버 전용 파일로 둔다. 웹 번들에 Rapier(약 4MB)가 들어가지 않게 웹은 이 파일을 가져오지 않는다.

View File

@@ -0,0 +1,154 @@
# 텀블링 몽키 3D 물리 간이 실험 (2026-10-11)
`docs/games/tumblin-monkeys.md` 8.1절 수치의 근거. 대충 만든 모양(기둥 20면, 막대 24개, 원숭이 30마리 = 캡슐 몸통 + 캡슐 팔 4개)으로 한 **간이 실험**이라, 실제 게임 모양으로 바꾸면 다시 잰다.
- 엔진: `@dimforge/rapier3d-deterministic-compat@0.21.0`, Bun 1.3.13, 이 서버(8코어).
- 저장소 의존성에는 넣지 않았다. 재현: 빈 폴더(`$HOME/.tmp/...`)에서 `bun init -y && bun add @dimforge/rapier3d-deterministic-compat@0.21.0` 뒤 아래 두 파일을 `bun spike.ts`, `bun snap.ts`로 실행.
## 결과
- 결정성: 같은 시드(1)로 두 번 → 최종 원숭이 위치·회전 해시 `dcc3de9cd4d3f318` 동일, 막대별 떨어진 수도 동일. 스냅숏 저장 → 복원 후 300걸음 계산도 계속 계산한 것과 해시 동일.
- 속도: 한 걸음 약 0.20~0.21ms. 막대 24개를 차례로 뽑는 데 1193~1634걸음, 255~342ms(막대 하나 평균 약 11~14ms, 한 번 상한 600걸음 ≈ 120ms).
- 스냅숏 크기: 134,076바이트(base64 178,768) → 상태에는 넣지 않고 멈춘 위치만 저장하기로 함.
- 모양 문제: 붓고 나서 시드 1은 30마리 중 21마리, 시드 2는 27마리가 바로 떨어짐. 모양 조정이 필요.
## 출력
```
1 {
initialFallen: 21,
pourSettleMs: "512",
steps: 723,
pullSteps: 1634,
pullMs: "342",
msPerStep: "0.209",
pullLog: "0,0,0,0,0,0,1,0,0,0,0,0,0,3,1,3,0,0,0,0,1,0,0,0",
hash: "dcc3de9cd4d3f318",
}
1 {
initialFallen: 21,
pourSettleMs: "395",
steps: 723,
pullSteps: 1634,
pullMs: "330",
msPerStep: "0.202",
pullLog: "0,0,0,0,0,0,1,0,0,0,0,0,0,3,1,3,0,0,0,0,1,0,0,0",
hash: "dcc3de9cd4d3f318",
}
2 {
initialFallen: 27,
pourSettleMs: "300",
steps: 563,
pullSteps: 1193,
pullMs: "255",
msPerStep: "0.214",
pullLog: "0,0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0",
hash: "9ff54a49db397749",
}
snapshot bytes 134076 base64 178768
continuous 3b5d355264528620 restored 3b5d355264528620
```
## spike.ts
```ts
import RAPIER from '@dimforge/rapier3d-deterministic-compat';
await RAPIER.init();
function lcg(seed: number) { let s = seed >>> 0; return () => ((s = (Math.imul(s, 1664525) + 1013904223) >>> 0) / 2 ** 32); }
const TRUNK_R = 1.0, TRUNK_H = 4.0, STICK_Y0 = 1.6, STICK_Y1 = 3.6;
type Pose = { p: [number,number,number]; q: [number,number,number,number] };
function buildWorld(rand: () => number, nSticks: number) {
const world = new RAPIER.World({ x: 0, y: -9.81, z: 0 });
// floor tray
world.createCollider(RAPIER.ColliderDesc.cuboid(3, 0.05, 3).setTranslation(0, -0.05, 0));
// trunk walls: 20 boxes forming tube from y=1.2 to TRUNK_H
const seg = 20;
for (let i = 0; i < seg; i++) {
const a = (i / seg) * Math.PI * 2;
const half = Math.sin(Math.PI / seg) * TRUNK_R + 0.02;
const d = RAPIER.ColliderDesc.cuboid(0.04, (TRUNK_H - 1.2) / 2, half)
.setTranslation(Math.cos(a) * TRUNK_R, 1.2 + (TRUNK_H - 1.2) / 2, Math.sin(a) * TRUNK_R)
.setRotation(quatY(-a));
world.createCollider(d);
}
const sticks: RAPIER.Collider[] = [];
for (let i = 0; i < nSticks; i++) {
const y = STICK_Y0 + (i / nSticks) * (STICK_Y1 - STICK_Y0);
const a = rand() * Math.PI;
// cylinder along x axis -> rotate. Rapier cylinder along Y; rotate 90 deg about Z then around Y
const q = mul(quatY(a), quatZ(Math.PI / 2));
const c = world.createCollider(RAPIER.ColliderDesc.cylinder(TRUNK_R * 1.05, 0.035).setTranslation(0, y, 0).setRotation(q));
sticks.push(c);
}
return { world, sticks };
}
function quatY(a: number) { return { x: 0, y: Math.sin(a / 2), z: 0, w: Math.cos(a / 2) }; }
function quatZ(a: number) { return { x: 0, y: 0, z: Math.sin(a / 2), w: Math.cos(a / 2) }; }
function mul(a: any, b: any) { return { w: a.w*b.w - a.x*b.x - a.y*b.y - a.z*b.z, x: a.w*b.x + a.x*b.w + a.y*b.z - a.z*b.y, y: a.w*b.y - a.x*b.z + a.y*b.w + a.z*b.x, z: a.w*b.z + a.x*b.y - a.y*b.x + a.z*b.w }; }
function addMonkey(world: RAPIER.World, x: number, y: number, z: number, rot: any) {
const rb = world.createRigidBody(RAPIER.RigidBodyDesc.dynamic().setTranslation(x, y, z).setRotation(rot).setCcdEnabled(true).setLinearDamping(0.3).setAngularDamping(0.5));
world.createCollider(RAPIER.ColliderDesc.capsule(0.06, 0.06).setDensity(1).setFriction(0.8), rb); // body
// arms: hooks raised, curved -> two capsules each at 45deg
for (const s of [-1, 1]) {
world.createCollider(RAPIER.ColliderDesc.capsule(0.07, 0.022).setTranslation(s * 0.1, 0.12, 0).setRotation(quatZ(s * -0.7)).setFriction(0.9), rb);
world.createCollider(RAPIER.ColliderDesc.capsule(0.04, 0.022).setTranslation(s * 0.12, 0.24, 0).setRotation(quatZ(s * 0.6)).setFriction(0.9), rb);
}
return rb;
}
function run(seed: number, nMonkeys: number, nSticks: number) {
const rand = lcg(seed);
const { world, sticks } = buildWorld(rand, nSticks);
const monkeys: RAPIER.RigidBody[] = [];
const t0 = performance.now();
let steps = 0;
for (let i = 0; i < nMonkeys; i++) {
const r = rand() * 0.6, a = rand() * Math.PI * 2;
const q = mul(quatY(rand() * 6.28), quatZ((rand() - 0.5) * 1.5));
monkeys.push(addMonkey(world, Math.cos(a) * r, TRUNK_H + 0.3 + (i % 3) * 0.25, Math.sin(a) * r, q));
if (i % 3 === 2) for (let k = 0; k < 30; k++) { world.step(); steps++; }
}
// settle
let settleSteps = 0;
while (settleSteps < 1200) { world.step(); steps++; settleSteps++; if (monkeys.every(m => m.isSleeping() || m.linvel().y ** 2 + m.linvel().x ** 2 + m.linvel().z ** 2 < 1e-4)) break; }
const t1 = performance.now();
const fallen = () => monkeys.filter(m => m.translation().y < 1.2).length;
const initialFallen = fallen();
const pullLog: number[] = [];
let pullSteps = 0;
// pull sticks one by one
for (let s = 0; s < sticks.length; s++) {
world.removeCollider(sticks[s], true);
for (const m of monkeys) m.wakeUp();
const before = fallen();
let k = 0;
for (; k < 600; k++) { world.step(); pullSteps++; if (k > 30 && monkeys.every(m => m.isSleeping() || (m.linvel().x**2 + m.linvel().y**2 + m.linvel().z**2) < 1e-4)) break; }
pullLog.push(fallen() - before);
}
const t2 = performance.now();
const hashArr = new Float64Array(monkeys.flatMap(m => { const t = m.translation(), r = m.rotation(); return [t.x, t.y, t.z, r.x, r.y, r.z, r.w]; }));
const h = Bun.hash(new Uint8Array(hashArr.buffer)).toString(16);
return { initialFallen, pourSettleMs: (t1 - t0).toFixed(0), steps, pullSteps, pullMs: (t2 - t1).toFixed(0), msPerStep: ((t2 - t1) / pullSteps).toFixed(3), pullLog: pullLog.join(','), hash: h };
}
for (const seed of [1, 1, 2]) console.log(seed, run(seed, 30, 24));
```
## snap.ts
```ts
import RAPIER from '@dimforge/rapier3d-deterministic-compat';
await RAPIER.init();
const w = new RAPIER.World({x:0,y:-9.81,z:0});
w.createCollider(RAPIER.ColliderDesc.cuboid(3,0.05,3));
const bs = [] as RAPIER.RigidBody[];
for (let i=0;i<30;i++){ const rb=w.createRigidBody(RAPIER.RigidBodyDesc.dynamic().setTranslation((i%5)*0.3-0.6, 0.5+i*0.2, Math.floor(i/5)*0.05)); w.createCollider(RAPIER.ColliderDesc.capsule(0.06,0.06),rb); for(const s of [-1,1]) w.createCollider(RAPIER.ColliderDesc.capsule(0.07,0.02).setTranslation(s*0.1,0.12,0),rb); bs.push(rb);}
for(let i=0;i<60;i++) w.step();
const snap = w.takeSnapshot();
console.log('snapshot bytes', snap.length, 'base64', Buffer.from(snap).toString('base64').length);
const h = (world: RAPIER.World) => { const a:number[]=[]; world.forEachRigidBody(b=>{const t=b.translation(),r=b.rotation(); a.push(t.x,t.y,t.z,r.x,r.y,r.z,r.w)}); return Bun.hash(new Uint8Array(new Float64Array(a).buffer)).toString(16); };
for(let i=0;i<300;i++) w.step();
const w2 = RAPIER.World.restoreSnapshot(snap)!;
for(let i=0;i<300;i++) w2.step();
console.log('continuous', h(w), 'restored', h(w2));
```