/** * MuJoCo WebAssembly Physics Player & Three.js 3D WebGL Renderer * 100% Client-Side Physics Execution powered by Google DeepMind @mujoco/mujoco * Zero Backend Server Dependency · Zero Prerecorded GIFs · 60 FPS Real-time WebGL * Built with love by HWIHWA LAB */ // Lazy, auth-aware loading (HF private Space): carry this module's query string // (which includes `__sign`) over to mujoco.js and mujoco.wasm requests. const __SELF_QUERY = (() => { try { return new URL(import.meta.url).search; } catch (e) { return ''; } })(); function __signedSibling(path) { const u = new URL(path, import.meta.url); const sign = new URLSearchParams(__SELF_QUERY).get('__sign'); if (sign) u.searchParams.set('__sign', sign); return u.href; } export class MujocoWasmPlayer { constructor(canvasContainer) { this.container = canvasContainer; this.canvas = null; this.renderer = null; this.scene = null; this.camera = null; this.geomMeshes = []; this.mujoco = null; this.model = null; this.data = null; this.currentId = 7; this.cameraName = 'cam_front'; this.gameState = 'ready'; // 'ready', 'playing', 'gameover', 'victory' this.controlMode = 'manual'; // 'manual', 'ai' this.survivalTime = 0.0; this.bestScore = 0.0; this.victoryBanner = null; // Game Specific States this.beansDropped = 4; this.beansLanded = 0; this.flipperL = 0.0; this.flipperR = 0.0; this.pinballScore = 0; this.dominoCleared = false; this.swingLoops = 0; this.swingPrevAngle = 0.0; this.swingPumpTimer = 0.0; this.somersaultCount = 0; this.raceWinner = null; this.raceGateOpen = false; this.raceLeaderText = "Sliding down!"; this.pinkStartQpos = [-0.9, 0.2, 1.68, 1.0, 0.0, 0.0, 0.0]; this.mintStartQpos = [-0.9, -0.2, 1.68, 1.0, 0.0, 0.0, 0.0]; this.userAction = 0.0; this.carCtrl = [0.0, 0.0]; this.coinsCollected = 0; this.coinBids = []; this.coinFlags = [false, false, false, false, false]; this.aiStuckTimer = 0.0; this.aiReverseTimer = 0.0; this.robotTarget = [0.0, 0.0]; this.clawMagnetOn = false; this.plushieGrabbed = false; this.cannonPower = 1.0; this.demolitionRate = 0.0; this.towerInitialZ = []; this.aiCannonFired = false; this.aiLastActionTime = 0.0; this.aiModeT0 = 0.0; this.onTelemetryUpdate = null; this.onCoinCollected = null; this.onStateChange = null; this.isRunning = false; this.isReady = false; this.pendingGameId = null; this.initPromise = null; this.lastFrameTime = performance.now(); } async init() { if (this.initPromise) return this.initPromise; this.initPromise = (async () => { const { default: loadMujoco } = await import(__signedSibling('./mujoco.js')); this.mujoco = await loadMujoco({ locateFile: (path) => __signedSibling(path) }); // Three.js Setup (에셋 원본과 100% 동일한 산뜻하고 화사한 파스텔 카니발 스카이) this.scene = new THREE.Scene(); // MuJoCo gradient skybox 1:1 완벽 재현: 상단 솜사탕 라일락(#ebd8ed) -> 하단 청량한 파스텔 하늘색(#c0daf4) const skyCanvas = document.createElement('canvas'); skyCanvas.width = 2; skyCanvas.height = 256; const skyCtx = skyCanvas.getContext('2d'); const skyGrad = skyCtx.createLinearGradient(0, 0, 0, 256); skyGrad.addColorStop(0.0, '#ebd8ed'); skyGrad.addColorStop(0.5, '#dfe5f6'); skyGrad.addColorStop(1.0, '#c0daf4'); skyCtx.fillStyle = skyGrad; skyCtx.fillRect(0, 0, 2, 256); const skyTex = new THREE.CanvasTexture(skyCanvas); skyTex.colorSpace = THREE.SRGBColorSpace; this.scene.background = skyTex; // Canvas & Renderer this.canvas = document.createElement('canvas'); this.canvas.className = 'sim-screen wasm-canvas'; this.canvas.style.display = 'block'; this.canvas.style.width = '100%'; this.canvas.style.height = '100%'; this.canvas.style.objectFit = 'contain'; this.container.appendChild(this.canvas); this.renderer = new THREE.WebGLRenderer({ canvas: this.canvas, antialias: true, powerPreference: 'high-performance' }); this.renderer.setSize(this.container.clientWidth || 640, this.container.clientHeight || 480); this.renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2)); this.renderer.shadowMap.enabled = true; this.renderer.shadowMap.type = THREE.PCFSoftShadowMap; // ★ 에셋 원본의 산뜻하고 화사한 캔디 컬러 100% 재현 (sRGB 표준 모니터 감마 매핑) this.renderer.toneMapping = THREE.NoToneMapping; if (typeof THREE.SRGBColorSpace !== 'undefined') { this.renderer.outputColorSpace = THREE.SRGBColorSpace; } // Camera (Z-up coordinate space to match MuJoCo native physics, far 100 for infinite horizon) this.camera = new THREE.PerspectiveCamera(45, (this.canvas.width || 640) / (this.canvas.height || 480), 0.05, 100); this.camera.up.set(0, 0, 1); // ★ 5-Way High-Key Pastel Carnival Studio Lighting (에셋 원본 1:1 완벽 일치 파스텔 조도 1.85) // 1. 헤드라이트 앰비언트: 전체 최저 조도를 0.75로 높여 전 색상의 베이스 명도와 소프트 하이키 톤 확보 const ambientLight = new THREE.AmbientLight(0xfff8fd, 0.75); this.scene.add(ambientLight); // 2. 헤미스피어 라이트: 하늘빛 라일락 & 바닥 반사광 (0.35) const hemiLight = new THREE.HemisphereLight(0xfff0fe, 0xf0f6ff, 0.35); hemiLight.position.set(0, 0, 10); this.scene.add(hemiLight); // 3. 주광 (Key Light): 부드럽고 넓은 스튜디오 분산광으로 핫스팟 없이 화사한 하이키 광량 확보 (1.10) const keyLight = new THREE.DirectionalLight(0xffffff, 1.10); keyLight.position.set(1.5, -2.8, 4.5); keyLight.castShadow = true; keyLight.shadow.mapSize.width = 2048; keyLight.shadow.mapSize.height = 2048; keyLight.shadow.camera.near = 0.5; keyLight.shadow.camera.far = 16; keyLight.shadow.camera.left = -6.0; keyLight.shadow.camera.right = 6.0; keyLight.shadow.camera.top = 6.0; keyLight.shadow.camera.bottom = -6.0; keyLight.shadow.bias = -0.0003; keyLight.shadow.normalBias = 0.02; this.scene.add(keyLight); // 4. 후방 보조광 (Fill Light): 캐릭터 외곽 윤곽을 살려주는 부드러운 림라이트 (0.40) const fillLight = new THREE.DirectionalLight(0xffeefa, 0.40); fillLight.position.set(-2.0, 2.5, 4.0); this.scene.add(fillLight); // 5. 카메라 헤드라이트 (MuJoCo Headlight 1:1 완벽 고정): // 카메라 시선 벡터에 직접 묶여 모든 캔디 컬러(민트, 핑크, 옐로우, 블루)를 255 천장까지 화사하게 비추는 핵심 캔디 헤드라이트 (1.40) const headLight = new THREE.DirectionalLight(0xffffff, 1.40); headLight.position.set(0, 0, 0); const headLightTarget = new THREE.Object3D(); headLightTarget.position.set(0, 0, -1); this.camera.add(headLight); this.camera.add(headLightTarget); headLight.target = headLightTarget; this.scene.add(this.camera); window.addEventListener('resize', () => this.handleResize()); // Start Rendering Loop this.isRunning = true; this.isReady = true; // 대기 중이던 게임이 있으면 즉시 로드, 없으면 기본 게임(currentId=7) 즉시 로드! const pId = this.pendingGameId || this.currentId || 7; this.pendingGameId = null; this.loadGame(pId); requestAnimationFrame((t) => this.renderLoop(t)); return true; })(); return this.initPromise; } handleResize() { if (!this.container || !this.renderer || !this.camera) return; const w = this.container.clientWidth || 640; const h = this.container.clientHeight || 480; this.camera.aspect = w / h; this.camera.updateProjectionMatrix(); this.renderer.setSize(w, h); } loadGame(exampleId) { this.currentId = parseInt(exampleId); this.isGameLoaded = false; // 아직 WASM 물리 엔진이 준비되지 않았으면 큐에 저장 후 안전 리턴 (Cannot read properties of null 방어!) if (!this.mujoco || !this.isReady) { this.pendingGameId = this.currentId; return; } // Cleanup previous model meshes for (const mesh of this.geomMeshes) { if (mesh) { this.scene.remove(mesh); if (mesh.isGroup) { mesh.children.forEach(c => { if (c.geometry) c.geometry.dispose(); if (c.material) c.material.dispose(); }); } else { if (mesh.geometry) mesh.geometry.dispose(); if (mesh.material) mesh.material.dispose(); } } } this.geomMeshes = []; if (this.data) { this.data.delete(); this.data = null; } if (this.model) { this.model.delete(); this.model = null; } const xmlMap = window.PREMIUM_GAME_XMLS || {}; const xml = xmlMap[String(this.currentId)] || xmlMap[this.currentId]; if (!xml) { console.error(`XML for Game ${this.currentId} not found in window.PREMIUM_GAME_XMLS!`); return; } this.model = this.mujoco.MjModel.from_xml_string(xml); this.data = new this.mujoco.MjData(this.model); // Build Three.js meshes for all geoms this.buildThreeGeoms(); // Cache Coin Body IDs for Game 08 this.coinBids = []; if (this.currentId === 8) { for (let i = 1; i <= 5; i++) { const bid = this.mujoco.mj_name2id(this.model, this.mujoco.mjtObj.mjOBJ_BODY.value, `coin${i}`); if (bid >= 0) this.coinBids.push(bid); } } this.resetGame(); this.updateCameraView(); this.handleResize(); this.mujoco.mj_forward(this.model, this.data); this.updateMeshPositions(); if (this.renderer && this.scene && this.camera) { this.renderer.render(this.scene, this.camera); } this.isGameLoaded = true; this._sceneFullyRendered = false; this._renderedFrames = 0; } buildThreeGeoms() { const ngeom = this.model.ngeom; for (let g = 0; g < ngeom; g++) { const type = this.model.geom_type[g]; const size = [ this.model.geom_size[g * 3], this.model.geom_size[g * 3 + 1], this.model.geom_size[g * 3 + 2] ]; // Material Color Resolver const matId = this.model.geom_matid ? this.model.geom_matid[g] : -1; let r = 0.85, gc = 0.88, b = 0.92, a = 1.0; if (matId >= 0 && this.model.mat_rgba) { r = this.model.mat_rgba[matId * 4]; gc = this.model.mat_rgba[matId * 4 + 1]; b = this.model.mat_rgba[matId * 4 + 2]; a = this.model.mat_rgba[matId * 4 + 3]; } else if (this.model.geom_rgba) { r = this.model.geom_rgba[g * 4]; gc = this.model.geom_rgba[g * 4 + 1]; b = this.model.geom_rgba[g * 4 + 2]; a = this.model.geom_rgba[g * 4 + 3]; } // ★ 방안 B: 민트 바 및 민트 젤리빈의 Blue 채널 보정 (anim_07.gif 1:1 청량한 하늘빛 시안 민트 완벽 일치) // 초록(Green >= 0.80) 주도에 Blue가 0.65~0.78인 민트 계열의 Blue를 0.86으로 리프팅하여 // Three.js sRGB 파이프라인에서 에메랄드 초록으로 치우치지 않고 원본의 [90, 251, 244] 시안 민트로 정확히 발현! if (gc >= 0.80 && b >= 0.65 && b <= 0.78 && r <= 0.30) { b = 0.86; } const isFloor = (type === 0); if (isFloor) { // Floor Plane: 에셋 10개 전체에서 검증된 100% 영구 순백색 보장 하네스! // MeshBasicMaterial(0xffffff)로 바닥 베이스는 무조건 255 순백색으로 빛나며, // 그 위에 ShadowMaterial(opacity: 0.22)로 부드럽고 투명한 쿨 라일락 그림자만 깔끔하게 합성! const floorGroup = new THREE.Group(); const floorGeo = new THREE.PlaneGeometry(160, 160); const whiteMesh = new THREE.Mesh(floorGeo, new THREE.MeshBasicMaterial({ color: 0xffffff })); const shadowMesh = new THREE.Mesh(floorGeo, new THREE.ShadowMaterial({ opacity: 0.22, color: 0x3a3852 })); shadowMesh.position.set(0, 0, 0.001); shadowMesh.receiveShadow = true; floorGroup.add(whiteMesh); floorGroup.add(shadowMesh); floorGroup.matrixAutoUpdate = false; this.scene.add(floorGroup); this.geomMeshes.push(floorGroup); continue; } // ★ 에셋 원본의 산뜻하고 살짝 매트한 새틴 젤리빈 질감 (MuJoCo Blinn-Phong sRGB 1:1 일치) const color = new THREE.Color(r, gc, b).convertSRGBToLinear(); // 그늘진 면이 어둡게 푹 꺼지지 않도록 하는 미세한 보조 에미시브(0.04) const emissive = color.clone().multiplyScalar(0.04); // 살짝 매트하면서 컬러가 풍부하게 살아있는 에셋 원본의 소프트 새틴(Semi-Matte Satin) 질감! // 과도한 유리알 번쩍임을 원천 차단하기 위해 specular를 은은한 0.12, shininess를 20으로 설정 const mat = new THREE.MeshPhongMaterial({ color: color, emissive: emissive, specular: new THREE.Color(0.12, 0.12, 0.12), shininess: 20, transparent: a < 0.99, opacity: a }); let geom = null; if (type === 2) { // Sphere geom = new THREE.SphereGeometry(size[0], 24, 24); } else if (type === 3) { // Capsule (radius size[0], half-length size[1]) if (typeof THREE.CapsuleGeometry !== 'undefined') { geom = new THREE.CapsuleGeometry(size[0], size[1] * 2, 16, 24); } else { geom = new THREE.CylinderGeometry(size[0], size[0], size[1] * 2, 24); } geom.rotateX(Math.PI / 2); } else if (type === 4) { // Ellipsoid geom = new THREE.SphereGeometry(1, 24, 24); geom.scale(size[0], size[1], size[2]); } else if (type === 5) { // Cylinder (radius size[0], half-height size[1]) geom = new THREE.CylinderGeometry(size[0], size[0], size[1] * 2, 24); geom.rotateX(Math.PI / 2); } else if (type === 6) { // Box (half-extents) geom = new THREE.BoxGeometry(size[0] * 2, size[1] * 2, size[2] * 2); } if (geom) { const mesh = new THREE.Mesh(geom, mat); mesh.castShadow = (type !== 0); mesh.receiveShadow = true; mesh.matrixAutoUpdate = false; this.scene.add(mesh); this.geomMeshes.push(mesh); } else { this.geomMeshes.push(null); } } } setCamera(camName) { this.cameraName = camName; this.updateCameraView(); } setMode(mode) { this.controlMode = (mode === 'ai') ? 'ai' : 'manual'; if (this.controlMode === 'ai') { this.aiModeT0 = this.survivalTime; this.aiLastActionTime = this.survivalTime; if (this.gameState === 'ready') this.startGame(); } } start() { this.startGame(); } reset() { this.resetGame(); } updateCameraView() { if (!this.camera) return; if (this.currentId === 8) { if (this.cameraName === 'cam_quarter') { this.camera.position.set(-2.4, -2.4, 2.2); this.camera.lookAt(0, 0, 0.2); } else if (this.cameraName === 'cam_topdown') { this.camera.position.set(0, -0.01, 3.8); this.camera.lookAt(0, 0, 0); } else { // cam_front default this.camera.position.set(0, -3.0, 1.3); this.camera.lookAt(0, 0, 0.2); } } else if (this.currentId === 9) { // 🧸 Game 09: Toy Claw Machine & Plushie Bean (클로 머신 & 인형 전용 최적 확대 시점) if (this.cameraName === 'cam_quarter') { this.camera.position.set(-1.0, -1.25, 1.15); this.camera.lookAt(0.2, 0.05, 0.38); } else if (this.cameraName === 'cam_topdown') { this.camera.position.set(0.2, -0.01, 1.85); this.camera.lookAt(0.2, 0.05, 0.38); } else { // cam_front default: 정면 클로 머신과 인형이 다른 게임처럼 화면에 꽉 차도록 1.8배 줌인 this.camera.position.set(0.2, -1.55, 0.75); this.camera.lookAt(0.2, 0.05, 0.38); } } else { // General 3-way views for other games if (this.cameraName === 'cam_quarter') { this.camera.position.set(-2.5, -2.5, 2.4); this.camera.lookAt(0, 0, 0.5); } else if (this.cameraName === 'cam_topdown') { this.camera.position.set(0, -0.01, 4.0); this.camera.lookAt(0, 0, 0.5); } else { if (this.currentId === 7) { // anim_07.gif 1:1 일치: XML 정면 카메라 (pos: 0 -3.35 1.25, lookAt: 0 0.1 0.6) this.camera.position.set(0, -3.35, 1.25); this.camera.lookAt(0, 0.1, 0.6); } else { this.camera.position.set(0, -2.8, 1.3); this.camera.lookAt(0, 0, 0.5); } } } } resetGame() { if (!this.data || !this.model) return; this.mujoco.mj_resetData(this.model, this.data); this.gameState = 'ready'; this.controlMode = 'manual'; this.victoryBanner = null; this.survivalTime = 0.0; this.carCtrl = [0.0, 0.0]; this.userAction = 0.0; this.beansDropped = 0; this.beansLanded = 0; this.flipperL = 0.0; this.flipperR = 0.0; this.pinballScore = 0; this.dominoCleared = false; this.swingLoops = 0; this.swingPrevAngle = 0.0; this.swingPumpTimer = 0.0; this.somersaultCount = 0; this.raceWinner = null; this.coinsCollected = 0; this.coinFlags = [false, false, false, false, false]; this.aiStuckTimer = 0.0; this.aiReverseTimer = 0.0; this.robotTarget = [0.0, 0.0]; this.clawMagnetOn = false; this.plushieGrabbed = false; this.demolitionRate = 0.0; this.aiCannonFired = false; this.aiLastActionTime = 0.0; this.aiModeT0 = 0.0; this.raceGateOpen = false; this.raceWinner = null; this.raceLeaderText = "Sliding down!"; if (this.currentId === 1) { for (let b = 0; b < Math.min(4, Math.floor(this.model.nq / 7)); b++) { this.data.qpos[b * 7] = (b % 2 === 0 ? -0.4 : 0.4); this.data.qpos[b * 7 + 1] = (b < 2 ? -0.3 : 0.3); this.data.qpos[b * 7 + 2] = 2.4 + b * 0.4; for (let vi = 0; vi < 6; vi++) this.data.qvel[b * 6 + vi] = 0.0; } } else if (this.currentId === 4) { this.data.qpos[0] = 0.6; } else if (this.currentId === 5) { this.data.qpos[0] = 1.8; this.data.qpos[1] = 0.4; } else if (this.currentId === 6) { this.raceGateOpen = false; this.raceLeaderText = "Ready at Gate"; for (let i = 0; i < 7; i++) { this.data.qpos[i] = this.pinkStartQpos[i]; this.data.qpos[7 + i] = this.mintStartQpos[i]; } for (let vi = 0; vi < 12; vi++) this.data.qvel[vi] = 0.0; } else if (this.currentId === 7) { this.data.qpos[0] = 0.0; this.data.qpos[1] = 0.0; } else if (this.currentId === 8) { for (const bid of this.coinBids) { this.model.body_pos[bid * 3 + 2] = 0.1; } } this.mujoco.mj_forward(this.model, this.data); if (this.currentId === 10) { this.towerInitialZ = []; for (let b = 0; b < 9; b++) { this.towerInitialZ.push(this.data.xpos[(b + 1) * 3 + 2]); } } this.updateMeshPositions(); if (this.onStateChange) this.onStateChange(this.gameState, null); } startGame() { if (!this.data || !this.model) return; this.gameState = 'playing'; this.victoryBanner = null; this.survivalTime = 0.0; this.aiModeT0 = 0.0; this.aiLastActionTime = 0.0; this.aiCannonFired = false; if (this.currentId === 1) { this.beansDropped = 0; this.beansLanded = 0; for (let b = 0; b < Math.min(4, Math.floor(this.model.nq / 7)); b++) { this.data.qpos[b * 7] = (Math.random() - 0.5) * 0.8; this.data.qpos[b * 7 + 1] = (Math.random() - 0.5) * 0.8; this.data.qpos[b * 7 + 2] = 2.4 + b * 0.5; this.data.qvel[b * 6 + 2] = -0.6; this.data.qvel[b * 6 + 3] = (Math.random() - 0.5) * 1.5; } } else if (this.currentId === 7) { this.data.qpos[0] = 0.0; this.data.qpos[1] = 0.02; // Gentle 1.1° initial sway to bring balance physics to life immediately this.data.qvel[0] = 0.0; this.data.qvel[1] = 0.01; this.mujoco.mj_forward(this.model, this.data); this.updateMeshPositions(); } if (this.onStateChange) this.onStateChange(this.gameState, null); } applyAction(actionType, value = 0) { if (!this.data || !this.model) return; if (actionType === 'start') { this.startGame(); return; } if (actionType === 'reset') { this.resetGame(); return; } if (actionType === 'set_mode') { this.controlMode = (value === 1 || value === 'ai') ? 'ai' : 'manual'; if (this.controlMode === 'ai') { this.aiModeT0 = this.survivalTime; this.aiLastActionTime = this.survivalTime; if (this.gameState === 'ready') this.startGame(); } return; } if (this.controlMode === 'ai') this.controlMode = 'manual'; if (this.currentId === 1) { if (actionType === 'drop_bean') { if (this.gameState === 'ready') this.startGame(); this.dropExtraBean(); } else if (actionType === 'bounce_cushion') { if (this.gameState === 'ready') this.startGame(); const dir = (value < 0) ? -1.0 : 1.0; for (let b = 0; b < Math.min(4, Math.floor(this.model.nq / 7)); b++) { const z = this.data.qpos[b * 7 + 2]; if (z < 0.6) { this.data.qvel[b * 6 + 2] = 2.2 + Math.random() * 0.8; this.data.qvel[b * 6] += dir * 0.8; } } } } else if (this.currentId === 2) { if (['flip_left', 'flip_right', 'ball_rain'].includes(actionType)) { if (this.gameState === 'ready') this.startGame(); } if (actionType === 'flip_left') this.flipperL = 1.0; else if (actionType === 'flip_right') this.flipperR = 1.0; else if (actionType === 'flip_stop') { this.flipperL = 0; this.flipperR = 0; } else if (actionType === 'ball_rain') { for (let q = 0; q < Math.min(7, Math.floor(this.model.nq / 7)); q++) { this.data.qpos[q * 7 + 2] = 1.8 + Math.random() * 1.2; this.data.qvel[q * 6 + 2] = -1.5; } } } else if (this.currentId === 3) { if (actionType === 'push_domino') { if (this.gameState === 'ready') this.startGame(); if (this.model.nv >= 1) this.data.qvel[0] = 7.0; } } else if (this.currentId === 4) { if (actionType === 'swing_pump') { if (this.gameState === 'ready') this.startGame(); const vel = this.model.nv >= 1 ? this.data.qvel[0] : 1.0; const dir = vel >= 0 ? 1.0 : -1.0; if (this.model.nu >= 1) this.data.ctrl[0] = dir * 1.0; this.swingPumpTimer = 0.25; } } else if (this.currentId === 5) { if (this.gameState === 'ready') this.startGame(); if (actionType === 'acrobatic_flip') { if (this.model.nu >= 2) { this.data.ctrl[0] = Math.random() < 0.5 ? -1.0 : 1.0; this.data.ctrl[1] = Math.random() < 0.5 ? -1.0 : 1.0; } } else if (actionType === 'acrobatic_j1_up' && this.model.nu >= 1) this.data.ctrl[0] = 1.0; else if (actionType === 'acrobatic_j1_down' && this.model.nu >= 1) this.data.ctrl[0] = -1.0; else if (actionType === 'acrobatic_j2_up' && this.model.nu >= 2) this.data.ctrl[1] = 1.0; else if (actionType === 'acrobatic_j2_down' && this.model.nu >= 2) this.data.ctrl[1] = -1.0; else if (actionType === 'acrobatic_stop' && this.model.nu >= 2) { this.data.ctrl[0] = 0; this.data.ctrl[1] = 0; } } else if (this.currentId === 6) { if (actionType === 'start_race' || actionType === 'start') { if (this.gameState === 'ready') this.startGame(); this.raceGateOpen = true; if (this.model.nv >= 12) { this.data.qvel[0] = Math.max(this.data.qvel[0], 0.35) + (Math.random() - 0.5) * 0.04; this.data.qvel[6] = Math.max(this.data.qvel[6], 0.35) + (Math.random() - 0.5) * 0.04; } } else if (actionType === 'slide_boost_pink' && this.model.nv >= 12) { if (this.gameState === 'ready') this.startGame(); this.raceGateOpen = true; const boostP = 1.8; this.data.qvel[0] += boostP * 0.9063; this.data.qvel[2] -= boostP * 0.4226; } else if (actionType === 'slide_boost_mint' && this.model.nv >= 12) { if (this.gameState === 'ready') this.startGame(); this.raceGateOpen = true; const boostP = 1.8; this.data.qvel[6] += boostP * 0.9063; this.data.qvel[8] -= boostP * 0.4226; } } else if (this.currentId === 7) { if (this.gameState === 'ready') this.startGame(); if (actionType === 'cart_left') this.userAction = -1.0; else if (actionType === 'cart_right') this.userAction = 1.0; else if (actionType === 'cart_stop') this.userAction = 0.0; } else if (this.currentId === 8) { if (this.gameState === 'ready') this.startGame(); if (actionType === 'car_forward') this.carCtrl = [1.0, 1.0]; else if (actionType === 'car_backward') this.carCtrl = [-0.85, -0.85]; else if (actionType === 'car_left') this.carCtrl = [-0.8, 0.8]; else if (actionType === 'car_right') this.carCtrl = [0.8, -0.8]; else if (actionType === 'car_fwd_left') this.carCtrl = [0.35, 1.0]; else if (actionType === 'car_fwd_right') this.carCtrl = [1.0, 0.35]; else if (actionType === 'car_bwd_left') this.carCtrl = [-0.35, -0.85]; else if (actionType === 'car_bwd_right') this.carCtrl = [-0.85, -0.35]; else if (actionType === 'car_stop') this.carCtrl = [0.0, 0.0]; } else if (this.currentId === 9) { if (this.gameState === 'ready') this.startGame(); if (actionType === 'arm_shoulder_up') this.robotTarget[0] = Math.max(-1.5, Math.min(1.5, this.robotTarget[0] - 0.1)); else if (actionType === 'arm_shoulder_down') this.robotTarget[0] = Math.max(-1.5, Math.min(1.5, this.robotTarget[0] + 0.1)); else if (actionType === 'arm_elbow_up') this.robotTarget[1] = Math.max(-2.0, Math.min(2.0, this.robotTarget[1] + 0.1)); else if (actionType === 'arm_elbow_down') this.robotTarget[1] = Math.max(-2.0, Math.min(2.0, this.robotTarget[1] - 0.1)); else if (actionType === 'claw_magnet_toggle') this.clawMagnetOn = !this.clawMagnetOn; } else if (this.currentId === 10) { if (actionType === 'fire_cannon') { if (this.gameState === 'ready') this.startGame(); const nv = this.model.nv; if (nv >= 6) { const spd = -9.0 * this.cannonPower; this.data.qvel[nv - 6] = spd; this.data.qvel[nv - 4] = 1.6 * this.cannonPower; } } } } dropExtraBean() { if (!this.data || !this.model) return; this.beansDropped++; const b = (this.beansDropped - 1) % 4; if (this.model.nq >= (b + 1) * 7) { const q = b * 7; this.data.qpos[q] = (Math.random() - 0.5) * 1.0; this.data.qpos[q + 1] = (Math.random() - 0.5) * 1.0; this.data.qpos[q + 2] = 2.4 + Math.random() * 0.8; const v = b * 6; this.data.qvel[v] = (Math.random() - 0.5) * 0.8; this.data.qvel[v + 1] = (Math.random() - 0.5) * 0.8; this.data.qvel[v + 2] = -1.8; this.data.qvel[v + 3] = (Math.random() - 0.5) * 3.5; this.data.qvel[v + 4] = (Math.random() - 0.5) * 3.5; } // 8개 이상 드롭되었을 때 승리 축하 배너 (이후에도 계속 빈 투하 가능!) if (this.beansDropped >= 8 && !this.victoryBanner) { this.triggerVictory('PARTY PILE MASTER!', '🎈'); } } triggerVictory(title, icon) { this.gameState = 'victory'; this.victoryBanner = { title, icon }; if (this.onStateChange) this.onStateChange(this.gameState, this.victoryBanner); } triggerGameOver() { this.gameState = 'gameover'; if (this.survivalTime > this.bestScore) this.bestScore = parseFloat(this.survivalTime.toFixed(2)); if (this.onStateChange) this.onStateChange(this.gameState, { survival_time: this.survivalTime, rank: 'B' }); } updatePhysics(duration) { if (!this.data || !this.model || !this.isGameLoaded) return; if (this.gameState !== 'playing' && this.gameState !== 'victory') return; const dt = this.model.opt.timestep; const steps = Math.max(1, Math.round(duration / dt)); for (let s = 0; s < steps; s++) { this.survivalTime += dt; // 1. Skydiving if (this.currentId === 1) { // [스마트 AI 모드] 1.5초 간격으로 리듬감 있게 자동 릴레이 투하 시연! if (this.controlMode === 'ai' && this.gameState === 'playing') { if (this.survivalTime - this.aiLastActionTime >= 1.5 && this.beansDropped < 8) { this.dropExtraBean(); this.aiLastActionTime = this.survivalTime; } } let landed = 0; for (let b = 0; b < Math.min(4, Math.floor(this.model.nq / 7)); b++) { if (this.data.qpos[b * 7 + 2] < 0.42) landed++; } this.beansLanded = landed; // ★ 즉사 버그 완전 차단: // 유저가 스페이스바로 추가 빈을 최소 6회 이상 투하하고 충분히 즐겼을 때(survivalTime > 6.0)만 클리어 판정! if (this.beansLanded >= 4 && this.beansDropped >= 6 && !this.victoryBanner && this.survivalTime > 6.0) { this.triggerVictory('SKYDIVING SQUAD!', '🎈'); } } // 2. Pinball else if (this.currentId === 2) { if (this.controlMode === 'ai') { let dangerL = false, dangerR = false; for (let q = 0; q < Math.min(11, Math.floor(this.model.nq / 7)); q++) { const bx = this.data.qpos[q * 7]; const by = this.data.qpos[q * 7 + 1]; const bz = this.data.qpos[q * 7 + 2]; if (by > -0.98 && by < -0.40 && bz < 0.65) { if (bx <= 0.08) dangerL = true; if (bx >= -0.08) dangerR = true; } } this.flipperL = dangerL ? 1.0 : 0.0; this.flipperR = dangerR ? 1.0 : 0.0; if (this.survivalTime - this.aiLastActionTime >= 5.2) { for (let q = 0; q < Math.min(7, Math.floor(this.model.nq / 7)); q++) { this.data.qpos[q * 7 + 2] = 1.8 + Math.random() * 1.2; this.data.qvel[q * 6 + 2] = -1.5; } this.aiLastActionTime = this.survivalTime; } } if (this.model.nu >= 2) { this.data.ctrl[0] = this.flipperL; this.data.ctrl[1] = this.flipperR; } let velSum = 0; for (let v = 0; v < Math.min(14, this.model.nv); v++) velSum += Math.abs(this.data.qvel[v]); if (velSum > 6.0) this.pinballScore += Math.floor(velSum * 1.5); if ((velSum > 15.0 || this.pinballScore >= 1000) && !this.victoryBanner && this.survivalTime > 4.0) { this.triggerVictory('PINBALL POP MASTER!', '🍬'); } } // 3. Domino else if (this.currentId === 3) { if (this.controlMode === 'ai' && !this.dominoCleared) { const aiT = this.survivalTime - this.aiModeT0; if (aiT < 0.15 && this.model.nv >= 1) this.data.qvel[0] = 7.0; else if (aiT > 4.0 && !this.dominoCleared && this.model.nv >= 1) this.data.qvel[0] = 7.0; } const starBid = this.mujoco.mj_name2id(this.model, this.mujoco.mjtObj.mjOBJ_BODY.value, 'gold_star_target'); if (starBid >= 0) { const sx = this.data.xpos[starBid * 3]; const sy = this.data.xpos[starBid * 3 + 1]; const sz = this.data.xpos[starBid * 3 + 2]; const knocked = (Math.abs(sx - 1.55) > 0.08 || Math.abs(sy) > 0.10 || sz < 0.10); if (knocked && this.survivalTime > 0.45 && !this.dominoCleared) { this.dominoCleared = true; this.triggerVictory('DOMINO CLEARED!', '🌟'); } } } // 4. Swing else if (this.currentId === 4) { if (this.controlMode === 'ai' && this.model.nu >= 1) { const vel = this.model.nv >= 1 ? this.data.qvel[0] : 1.0; const dir = vel >= 0 ? 1.0 : -1.0; this.data.ctrl[0] = dir * 1.0; } else if (this.model.nu >= 1) { if (this.swingPumpTimer > 0) this.swingPumpTimer -= dt; else this.data.ctrl[0] = 0; } const curr = this.data.qpos[0]; if (Math.abs(curr) > 2 * Math.PI && !this.victoryBanner) { this.swingLoops++; this.triggerVictory('360° LOOP MASTER!', '🎡'); } } // 5. Acrobatic else if (this.currentId === 5) { if (this.controlMode === 'ai' && this.model.nu >= 2) { const t = this.survivalTime; this.data.ctrl[0] = Math.max(-1, Math.min(1, 1.2 * Math.sin(t * 3.8) + 0.4 * Math.sin(t * 9.1))); this.data.ctrl[1] = Math.max(-1, Math.min(1, 1.1 * Math.cos(t * 4.2))); } const curr = this.data.qpos[0]; if (Math.abs(curr) > 2 * Math.PI * (this.somersaultCount + 1)) { this.somersaultCount++; if (this.somersaultCount >= 3 && !this.victoryBanner) { this.triggerVictory('ACROBATIC COMBO 3X!', '🤸'); } } } // 6. Slide else if (this.currentId === 6) { const pinkBid = this.mujoco.mj_name2id(this.model, this.mujoco.mjtObj.mjOBJ_BODY.value, 'pink_racer'); const mintBid = this.mujoco.mj_name2id(this.model, this.mujoco.mjtObj.mjOBJ_BODY.value, 'mint_racer'); if (!this.raceGateOpen && pinkBid >= 0 && mintBid >= 0) { for (let vi = 0; vi < 12; vi++) this.data.qvel[vi] = 0.0; for (let i = 0; i < 7; i++) { this.data.qpos[i] = this.pinkStartQpos[i]; this.data.qpos[7 + i] = this.mintStartQpos[i]; } } if (pinkBid >= 0 && mintBid >= 0 && !this.raceWinner) { const px = this.data.xpos[pinkBid * 3]; const mx = this.data.xpos[mintBid * 3]; const pz = this.data.xpos[pinkBid * 3 + 2]; const mz = this.data.xpos[mintBid * 3 + 2]; const diff = px - mx; if (Math.abs(diff) < 0.05) { this.raceLeaderText = "Neck & Neck! (Tie)"; } else if (diff > 0) { this.raceLeaderText = `Pink Bean (+${diff.toFixed(2)}m) 🏆`; } else { this.raceLeaderText = `Mint Bean (+${Math.abs(diff).toFixed(2)}m) 🏆`; } if (this.controlMode === 'ai' && this.model.nv >= 12 && this.raceGateOpen) { if (px < mx) this.data.qvel[0] += 0.012; else if (mx < px) this.data.qvel[6] += 0.012; } if (this.survivalTime > 1.2 && this.raceGateOpen) { if (px >= 1.22 || pz < 0.35) { this.raceWinner = 'Pink Bean'; this.triggerVictory('PINK BEAN WINS!', '🥇'); } else if (mx >= 1.22 || mz < 0.35) { this.raceWinner = 'Mint Bean'; this.triggerVictory('MINT BEAN WINS!', '🥇'); } } } } // 7. Cartpole else if (this.currentId === 7) { const x = this.data.qpos[0]; const th = this.data.qpos[1]; const v = this.data.qvel[0]; const w = this.data.qvel[1]; const t = this.survivalTime; let breeze = 0; if (t > 2.5) { breeze = 0.22 * Math.sin((t - 2.5) * 3.5) + 0.08 * Math.sin(t * 7.2); if (t > 10.0) breeze += 0.12 * Math.sin(t * 5.2); } this.data.qfrc_applied[1] = breeze; if (this.controlMode === 'ai') { this.data.ctrl[0] = Math.max(-1, Math.min(1, 16.0 * th + 3.0 * w + 1.8 * x + 2.5 * v)); } else { this.data.ctrl[0] = Math.max(-1, Math.min(1, this.userAction * 1.0)); } if (this.survivalTime >= 15.0 && !this.victoryBanner) { this.triggerVictory('GOLDEN BALANCER!', '🍮'); } if (this.survivalTime > 2.5 && (Math.abs(th) > 0.70 || Math.abs(x) > 1.80)) { this.triggerGameOver(); break; } } // 8. Bumper Car else if (this.currentId === 8) { const carBid = this.mujoco.mj_name2id(this.model, this.mujoco.mjtObj.mjOBJ_BODY.value, 'car_root'); if (carBid >= 0) { const cx = this.data.xpos[carBid * 3]; const cy = this.data.xpos[carBid * 3 + 1]; for (let i = 0; i < this.coinBids.length; i++) { if (!this.coinFlags[i]) { const bid = this.coinBids[i]; const dist = Math.hypot(cx - this.model.body_pos[bid * 3], cy - this.model.body_pos[bid * 3 + 1]); if (dist < 0.48) { this.coinFlags[i] = true; this.coinsCollected++; this.model.body_pos[bid * 3 + 2] = -5.0; // Hide coin under arena if (this.onCoinCollected) this.onCoinCollected(this.coinsCollected); } } } if (this.coinsCollected === this.coinBids.length && !this.victoryBanner) { this.triggerVictory('ALL COINS COLLECTED!', '⭐'); } if (this.controlMode === 'ai' && !this.victoryBanner) { const speed = Math.hypot(this.data.qvel[0], this.data.qvel[1]); if (speed < 0.08 && this.survivalTime > 0.8) this.aiStuckTimer += dt; else this.aiStuckTimer = Math.max(0, this.aiStuckTimer - dt); if (this.aiStuckTimer > 0.35) { this.aiReverseTimer = 0.55; this.aiStuckTimer = 0; } if (this.aiReverseTimer > 0) { this.aiReverseTimer -= dt; this.carCtrl = [-0.85, -0.3]; } else { let targetIdx = -1; let minD = 999; for (let i = 0; i < this.coinBids.length; i++) { if (!this.coinFlags[i]) { const bid = this.coinBids[i]; const dist = Math.hypot(cx - this.model.body_pos[bid * 3], cy - this.model.body_pos[bid * 3 + 1]); if (dist < minD) { minD = dist; targetIdx = i; } } } if (targetIdx >= 0) { const bid = this.coinBids[targetIdx]; const targetAngle = Math.atan2(this.model.body_pos[bid * 3 + 1] - cy, this.model.body_pos[bid * 3] - cx); const r00 = this.data.xmat[carBid * 9]; const r10 = this.data.xmat[carBid * 9 + 3]; const carHeading = Math.atan2(r10, r00); const angleErr = (targetAngle - carHeading + Math.PI) % (2 * Math.PI) - Math.PI; const turn = Math.max(-1, Math.min(1, angleErr * 1.8)); if (Math.abs(angleErr) > 0.8) { this.carCtrl = [-turn * 0.8, turn * 0.8]; } else { const spd = 0.95; this.carCtrl = [ Math.max(-1, Math.min(1, spd - turn * 0.7)), Math.max(-1, Math.min(1, spd + turn * 0.7)) ]; } } } } if (this.model.nu >= 4) { this.data.ctrl[0] = this.carCtrl[0]; this.data.ctrl[1] = this.carCtrl[1]; this.data.ctrl[2] = this.carCtrl[0] * 0.7; this.data.ctrl[3] = this.carCtrl[1] * 0.7; } } } // 9. Claw else if (this.currentId === 9) { if (this.controlMode === 'ai') { const t = this.survivalTime - this.aiModeT0; if (t < 1.4) { this.data.ctrl[0] = 0.52; this.data.ctrl[1] = -0.55; this.clawMagnetOn = false; } else if (t < 2.8) { this.data.ctrl[0] = 0.82; this.data.ctrl[1] = -0.15; this.clawMagnetOn = true; } else { this.data.ctrl[0] = -0.3; this.data.ctrl[1] = -0.8; this.clawMagnetOn = true; } } else if (this.model.nu >= 2) { this.data.ctrl[0] = this.robotTarget[0]; this.data.ctrl[1] = this.robotTarget[1]; } const plushieBid = this.mujoco.mj_name2id(this.model, this.mujoco.mjtObj.mjOBJ_BODY.value, 'target_plushie'); if (plushieBid >= 0 && this.clawMagnetOn) { const pz = this.data.xpos[plushieBid * 3 + 2]; if (pz < 0.65) { this.data.qvel[2] = 1.4; if (pz > 0.38 && !this.victoryBanner) { this.plushieGrabbed = true; this.triggerVictory('PLUSHIE RESCUED!', '🧸'); } } } } // 10. Cannon else if (this.currentId === 10) { if (this.controlMode === 'ai' && !this.aiCannonFired) { if (this.survivalTime > 1.2) { this.cannonPower = 1.0; const nv = this.model.nv; if (nv >= 6) { this.data.qvel[nv - 6] = -9.0 * this.cannonPower; this.data.qvel[nv - 4] = 1.6 * this.cannonPower; } this.aiCannonFired = true; } } let fallen = 0; for (let b = 0; b < 9; b++) { const cz = this.data.xpos[(b + 1) * 3 + 2]; const cx = this.data.xpos[(b + 1) * 3]; const cy = this.data.xpos[(b + 1) * 3 + 1]; const initZ = this.towerInitialZ[b] || (0.05 + b * 0.10); if ((initZ - cz > 0.07) || Math.abs(cx) > 0.16 || Math.abs(cy) > 0.16) { fallen++; } } this.demolitionRate = Math.round((fallen / 9.0) * 1000) / 10; if (this.demolitionRate >= 70.0 && this.survivalTime > 1.2 && !this.victoryBanner) { this.triggerVictory('TOWER ANNIHILATED!', '💥'); } } this.mujoco.mj_step(this.model, this.data); } } updateMeshPositions() { if (!this.data || !this.model || !this.geomMeshes) return; const ngeom = this.model.ngeom; for (let g = 0; g < ngeom; g++) { const mesh = this.geomMeshes[g]; if (!mesh) continue; const px = this.data.geom_xpos[g * 3]; const py = this.data.geom_xpos[g * 3 + 1]; const pz = this.data.geom_xpos[g * 3 + 2]; const r = g * 9; mesh.matrix.set( this.data.geom_xmat[r], this.data.geom_xmat[r + 1], this.data.geom_xmat[r + 2], px, this.data.geom_xmat[r + 3], this.data.geom_xmat[r + 4], this.data.geom_xmat[r + 5], py, this.data.geom_xmat[r + 6], this.data.geom_xmat[r + 7], this.data.geom_xmat[r + 8], pz, 0, 0, 0, 1 ); } } renderLoop(time) { if (!this.isRunning) return; requestAnimationFrame((t) => this.renderLoop(t)); const dt = Math.min(0.05, (time - this.lastFrameTime) / 1000.0); this.lastFrameTime = time; // ★ 로딩 중 또는 데이터 미준비 상태에서는 안전하게 렌더링만 유지하고 물리/텔레메트리 연산 중단 if (!this.data || !this.model || !this.isGameLoaded) { if (this.renderer && this.scene && this.camera) { this.renderer.render(this.scene, this.camera); } return; } this.updatePhysics(dt); this.updateMeshPositions(); if (this.renderer && this.scene && this.camera) { this.renderer.render(this.scene, this.camera); this._renderedFrames = (this._renderedFrames || 0) + 1; } // ★ 실제 3D 게임 메쉬가 씬에 배치되고 최소 45프레임(약 0.75초) 이상 GPU 렌더링이 안정화된 순간에만 완료 신호 전달! if (!this._sceneFullyRendered && this._renderedFrames >= 45 && this.isGameLoaded && this.model && this.geomMeshes.length > 0) { this._sceneFullyRendered = true; this.handleResize(); if (typeof window !== "undefined" && window.__engineLoadingMgr && typeof window.__engineLoadingMgr.notifySceneStable === "function") { window.__engineLoadingMgr.notifySceneStable(); } else if (typeof window !== "undefined" && window.__engineLoadingMgr) { window.__engineLoadingMgr.complete(); } else if (typeof window !== "undefined" && typeof window.__dismissLoadingOverlay === "function") { window.__dismissLoadingOverlay(); } } if (this.onTelemetryUpdate) { const hasQpos = !!(this.data && this.data.qpos); const hasXpos = !!(this.data && this.data.xpos); this.onTelemetryUpdate({ example_id: this.currentId, game_state: this.gameState, survival_time: this.survivalTime, best_score: this.bestScore, pole_angle: (this.currentId === 7 && hasQpos) ? (this.data.qpos[1] * 180 / Math.PI) : 0, pole_angle_deg: (this.currentId === 7 && hasQpos) ? (this.data.qpos[1] * 180 / Math.PI).toFixed(1) : "0.0", coins_collected: this.coinsCollected, demolition_rate: this.demolitionRate, beans_landed: this.beansLanded, beans_dropped: this.beansDropped, pinball_score: this.pinballScore, domino_cleared: this.dominoCleared, swing_angle: (this.currentId === 4 && hasQpos) ? (this.data.qpos[0] * 180 / Math.PI) : 0, swing_angle_deg: (this.currentId === 4 && hasQpos) ? (this.data.qpos[0] * 180 / Math.PI).toFixed(1) : "0.0", swing_loops: this.swingLoops, somersault_count: this.somersaultCount, race_winner: this.raceWinner, race_leader: this.raceLeaderText, claw_height: (this.currentId === 9 && hasXpos) ? 0.35 : 0, victory_banner: this.victoryBanner, rank: this.survivalTime > 15 ? 'S+' : (this.survivalTime > 10 ? 'A' : 'B') }); } } } if (typeof window !== "undefined") { window.MujocoWasmPlayer = MujocoWasmPlayer; }