Đang kiến tạo hồ cá Koi 3D...

Nishikigoi 3D — Hồ Cá Koi Nhật Bản

Chạm mặt nước 3D để thả mồi • Chuột phải hoặc lăn chuột để xoay & thu phóng

hemiSky: new THREE.Color(0xcff6f0), hemiGround: new THREE.Color(0x183834), hemiIntensity: 0.92, causticStrength: 0.42, lanternIntensity: 0.0, rainAmount: 0.0 }, sunset: { skyTop: new THREE.Color(0x281b18), skyHorizon: new THREE.Color(0x5c3624), fogColor: new THREE.Color(0x291c18), waterDeep: new THREE.Color(0x241d17), waterShallow: new THREE.Color(0x523928), skyReflect: new THREE.Color(0xffb570), sunColor: new THREE.Color(0xff9d47), sunIntensity: 1.45, sunPos: new THREE.Vector3(-14, 7.5, -10), hemiSky: new THREE.Color(0xffcfa0), hemiGround: new THREE.Color(0x261a14), hemiIntensity: 0.78, causticStrength: 0.30, lanternIntensity: 2.8, rainAmount: 0.0 }, moonlight: { skyTop: new THREE.Color(0x050b16), skyHorizon: new THREE.Color(0x0d1f38), fogColor: new THREE.Color(0x060e1c), waterDeep: new THREE.Color(0x061426), waterShallow: new THREE.Color(0x122d4f), skyReflect: new THREE.Color(0x7ab2f5), sunColor: new THREE.Color(0xa6ccff), sunIntensity: 0.85, sunPos: new THREE.Vector3(7, 15, -8), hemiSky: new THREE.Color(0x6d99d6), hemiGround: new THREE.Color(0x081322), hemiIntensity: 0.62, causticStrength: 0.18, lanternIntensity: 3.4, rainAmount: 0.0 }, drizzle: { skyTop: new THREE.Color(0x132226), skyHorizon: new THREE.Color(0x243b40), fogColor: new THREE.Color(0x15262a), waterDeep: new THREE.Color(0x0e2529), waterShallow: new THREE.Color(0x1f4347), skyReflect: new THREE.Color(0x88aab0), sunColor: new THREE.Color(0xc8dfe3), sunIntensity: 0.82, sunPos: new THREE.Vector3(0, 18, 0), hemiSky: new THREE.Color(0x9ec0c7), hemiGround: new THREE.Color(0x132629), hemiIntensity: 0.88, causticStrength: 0.07, lanternIntensity: 1.9, rainAmount: 1.0 } }; const state = { mode: 'feed', // 'feed' | 'clap' | 'touch' | 'orbit' themeKey: 'morning', targetFishCount: 10, audioEnabled: false, zenMode: false, time: 0 }; const rand = (min, max) => min + Math.random() * (max - min); const clamp = (v, min, max) => Math.max(min, Math.min(max, v)); const lerp = (a, b, t) => a + (b - a) * t; const normalizeAngle = (a) => { while (a > Math.PI) a -= Math.PI * 2; while (a < -Math.PI) a += Math.PI * 2; return a; }; // ========================================================================= // 2. HỆ THỐNG ÂM THANH THIÊN NHIÊN (WEB AUDIO API) // ========================================================================= class GardenAudio3D { constructor() { this.ctx = null; this.isRunning = false; this.streamGain = null; this.rainGain = null; this.noiseBuffer = null; this.nodes = []; } init() { if (this.ctx) return; const AudioCtx = window.AudioContext || window.webkitAudioContext; if (!AudioCtx) return; this.ctx = new AudioCtx(); const len = this.ctx.sampleRate * 4; this.noiseBuffer = this.ctx.createBuffer(1, len, this.ctx.sampleRate); const out = this.noiseBuffer.getChannelData(0); let b0 = 0, b1 = 0, b2 = 0, b3 = 0, b4 = 0, b5 = 0, b6 = 0; for (let i = 0; i < len; i++) { const white = Math.random() * 2 - 1; b0 = 0.99886 * b0 + white * 0.0555179; b1 = 0.99332 * b1 + white * 0.0750759; b2 = 0.96900 * b2 + white * 0.1538520; b3 = 0.86650 * b3 + white * 0.3104856; b4 = 0.55000 * b4 + white * 0.5329522; b5 = -0.7616 * b5 - white * 0.0168980; out[i] = (b0 + b1 + b2 + b3 + b4 + b5 + b6 + white * 0.5362) * 0.032; b6 = white * 0.115926; } } toggle(enable) { if (enable) { this.init(); if (!this.ctx) return false; if (this.ctx.state === 'suspended') this.ctx.resume(); this.startLoops(); this.isRunning = true; return true; } else { this.stopLoops(); this.isRunning = false; return false; } } startLoops() { if (!this.ctx || this.nodes.length > 0) return; const streamSrc = this.ctx.createBufferSource(); streamSrc.buffer = this.noiseBuffer; streamSrc.loop = true; const streamFilter = this.ctx.createBiquadFilter(); streamFilter.type = 'bandpass'; streamFilter.frequency.value = 650; streamFilter.Q.value = 1.1; const lfo = this.ctx.createOscillator(); lfo.frequency.value = 0.32; const lfoGain = this.ctx.createGain(); lfoGain.gain.value = 170; lfo.connect(lfoGain); lfoGain.connect(streamFilter.frequency); lfo.start(); this.streamGain = this.ctx.createGain(); this.streamGain.gain.setValueAtTime(0.001, this.ctx.currentTime); this.streamGain.gain.exponentialRampToValueAtTime(0.24, this.ctx.currentTime + 1.0); streamSrc.connect(streamFilter); streamFilter.connect(this.streamGain); this.streamGain.connect(this.ctx.destination); streamSrc.start(); const rainSrc = this.ctx.createBufferSource(); rainSrc.buffer = this.noiseBuffer; rainSrc.loop = true; const rainFilter = this.ctx.createBiquadFilter(); rainFilter.type = 'highpass'; rainFilter.frequency.value = 1400; this.rainGain = this.ctx.createGain(); this.rainGain.gain.value = state.themeKey === 'drizzle' ? 0.22 : 0.0001; rainSrc.connect(rainFilter); rainFilter.connect(this.rainGain); this.rainGain.connect(this.ctx.destination); rainSrc.start(); this.nodes = [streamSrc, lfo, rainSrc]; } updateWeatherMix(rainIntensity) { if (!this.isRunning || !this.rainGain || !this.ctx) return; const targetGain = Math.max(0.0001, rainIntensity * 0.24); this.rainGain.gain.setTargetAtTime(targetGain, this.ctx.currentTime, 0.35); } stopLoops() { if (!this.ctx || this.nodes.length === 0) return; const now = this.ctx.currentTime; if (this.streamGain) this.streamGain.gain.setTargetAtTime(0.0001, now, 0.15); if (this.rainGain) this.rainGain.gain.setTargetAtTime(0.0001, now, 0.15); const oldNodes = [...this.nodes]; setTimeout(() => { oldNodes.forEach(n => { try { n.stop(); } catch (e) {} }); }, 400); this.nodes = []; } playWaterDrop(baseFreq = 540, vol = 0.10) { if (!this.isRunning || !this.ctx) return; try { const now = this.ctx.currentTime; const osc = this.ctx.createOscillator(); const gain = this.ctx.createGain(); const f0 = baseFreq + rand(-70, 70); osc.type = 'sine'; osc.frequency.setValueAtTime(f0, now); osc.frequency.exponentialRampToValueAtTime(f0 * 2.05, now + 0.08); gain.gain.setValueAtTime(0.001, now); gain.gain.linearRampToValueAtTime(vol, now + 0.01); gain.gain.exponentialRampToValueAtTime(0.0001, now + 0.16); osc.connect(gain); gain.connect(this.ctx.destination); osc.start(now); osc.stop(now + 0.18); } catch (e) {} } playClapCall() { if (!this.isRunning || !this.ctx) return; try { const now = this.ctx.currentTime; [0, 0.11].forEach((offset, idx) => { const t = now + offset; const src = this.ctx.createBufferSource(); src.buffer = this.noiseBuffer; const filter = this.ctx.createBiquadFilter(); filter.type = 'bandpass'; filter.frequency.value = idx === 0 ? 1150 : 1280; filter.Q.value = 2.4; const gain = this.ctx.createGain(); gain.gain.setValueAtTime(0.001, t); gain.gain.linearRampToValueAtTime(idx === 0 ? 0.24 : 0.28, t + 0.006); gain.gain.exponentialRampToValueAtTime(0.0001, t + 0.09); src.connect(filter); filter.connect(gain); gain.connect(this.ctx.destination); src.start(t); src.stop(t + 0.11); }); } catch (e) {} } } const audioEngine = new GardenAudio3D(); // ========================================================================= // 3. TRÌNH SINH TEXTURE PBR THỦ TỤC (VẢY CÁ 3D, HOA VĂN NISHIKIGOI, SỎI & SEN) // ========================================================================= // Sinh Normal Map lớp vảy cá xếp chồng 3D giúp ánh sáng lấp lánh trên từng chiếc vảy function createKoiScaleNormalTexture() { const size = 256; const canvas = document.createElement('canvas'); canvas.width = size; canvas.height = size; const ctx = canvas.getContext('2d'); ctx.fillStyle = 'rgb(128, 128, 255)'; ctx.fillRect(0, 0, size, size); const cols = 16; const rows = 14; const cw = size / cols; const ch = size / rows; for (let row = -1; row <= rows; row++) { for (let col = -1; col <= cols; col++) { const cx = (col + (row % 2 === 0 ? 0.5 : 0)) * cw; const cy = row * ch; const r = cw * 0.68; const grad = ctx.createRadialGradient(cx - r * 0.15, cy - r * 0.15, r * 0.05, cx, cy, r); grad.addColorStop(0, 'rgb(142, 118, 255)'); grad.addColorStop(0.72, 'rgb(122, 134, 248)'); grad.addColorStop(0.92, 'rgb(92, 156, 222)'); grad.addColorStop(1, 'rgb(128, 128, 255)'); ctx.fillStyle = grad; ctx.beginPath(); ctx.arc(cx, cy, r, 0, Math.PI * 2); ctx.fill(); ctx.strokeStyle = 'rgba(85, 165, 210, 0.55)'; ctx.lineWidth = 1.2; ctx.beginPath(); ctx.arc(cx, cy, r * 0.94, -Math.PI * 0.45, Math.PI * 0.45); ctx.stroke(); } } const tex = new THREE.CanvasTexture(canvas); tex.wrapS = THREE.RepeatWrapping; tex.wrapT = THREE.RepeatWrapping; tex.repeat.set(2.2, 1.4); return tex; } // Sinh Texture vây cá bán trong suốt có các nan tia vây tinh xảo function createFinRayTexture() { const size = 256; const canvas = document.createElement('canvas'); canvas.width = size; canvas.height = size; const ctx = canvas.getContext('2d'); ctx.clearRect(0, 0, size, size); // Gốc vây đục dần ra viền ngoài trong suốt const baseGrad = ctx.createLinearGradient(0, 0, size, 0); baseGrad.addColorStop(0, 'rgba(255, 252, 246, 0.88)'); baseGrad.addColorStop(0.45, 'rgba(255, 250, 242, 0.56)'); baseGrad.addColorStop(0.85, 'rgba(255, 248, 240, 0.24)'); baseGrad.addColorStop(1, 'rgba(255, 248, 240, 0.02)'); ctx.fillStyle = baseGrad; ctx.fillRect(0, 0, size, size); // Vẽ các nan xương vây (Fin Rays) phân nhánh nhẹ const rays = 24; for (let i = 0; i < rays; i++) { const yStart = (i / (rays - 1)) * size; const yEnd = size * 0.5 + (yStart - size * 0.5) * 1.12; const rayGrad = ctx.createLinearGradient(0, yStart, size, yEnd); rayGrad.addColorStop(0, 'rgba(255, 255, 255, 0.72)'); rayGrad.addColorStop(0.7, 'rgba(255, 255, 255, 0.32)'); rayGrad.addColorStop(1, 'rgba(255, 255, 255, 0.0)'); ctx.strokeStyle = rayGrad; ctx.lineWidth = i % 2 === 0 ? 1.8 : 1.1; ctx.beginPath(); ctx.moveTo(0, yStart); ctx.quadraticCurveTo(size * 0.5, (yStart + yEnd) * 0.5 + Math.sin(i) * 3, size * 0.96, yEnd); ctx.stroke(); } const tex = new THREE.CanvasTexture(canvas); return tex; } // Sinh hoa văn riêng biệt (Albedo UV Texture) cho từng giống cá Koi Nishikigoi // UV.x: 0 (chóp mõm) -> 1 (cuống đuôi); UV.y: 0.5 (sống lưng), 0 & 1 (bụng dưới) function createKoiPatternTexture(breed) { const w = 512; const h = 256; const canvas = document.createElement('canvas'); canvas.width = w; canvas.height = h; const ctx = canvas.getContext('2d'); // Màu nền thân cá ctx.fillStyle = breed.base; ctx.fillRect(0, 0, w, h); // Chuyển sắc nhẹ từ sống lưng (y = h/2) xuống bụng sáng hơn const bellyGrad = ctx.createLinearGradient(0, 0, 0, h); bellyGrad.addColorStop(0, breed.bellyColor); bellyGrad.addColorStop(0.28, 'rgba(255,255,255,0)'); bellyGrad.addColorStop(0.72, 'rgba(255,255,255,0)'); bellyGrad.addColorStop(1, breed.bellyColor); ctx.fillStyle = bellyGrad; ctx.fillRect(0, 0, w, h); const drawOrganicPatch = (cx, cy, rx, ry, color) => { ctx.save(); ctx.translate(cx, cy); ctx.fillStyle = color; ctx.beginPath(); const pts = 16; for (let i = 0; i <= pts; i++) { const a = (i / pts) * Math.PI * 2; const wobble = 0.82 + Math.sin(i * 3.1 + cx) * 0.14 + Math.cos(i * 2.3 + cy) * 0.1; const px = Math.cos(a) * rx * wobble; const py = Math.sin(a) * ry * wobble; if (i === 0) ctx.moveTo(px, py); else ctx.lineTo(px, py); } ctx.closePath(); ctx.fill(); ctx.restore(); }; if (breed.pattern === 'tancho') { // Đốm đỏ tròn hoàn hảo trên đỉnh đầu (giữa mũi u=0.05 và vai u=0.22) drawOrganicPatch(w * 0.13, h * 0.5, w * 0.048, h * 0.13, breed.hiColor); } else if (breed.pattern === 'kohaku' || breed.pattern === 'sanke' || breed.pattern === 'showa') { const count = Math.floor(rand(3, 6)); for (let i = 0; i < count; i++) { const ux = rand(0.10, 0.82); const uy = 0.5 + rand(-0.18, 0.18); drawOrganicPatch(w * ux, h * uy, w * rand(0.06, 0.14), h * rand(0.16, 0.30), breed.hiColor); } if (breed.pattern === 'sanke') { const sumiCount = Math.floor(rand(5, 9)); for (let i = 0; i < sumiCount; i++) { drawOrganicPatch(w * rand(0.20, 0.85), h * (0.5 + rand(-0.24, 0.24)), w * rand(0.022, 0.045), h * rand(0.06, 0.12), breed.sumiColor); } } else if (breed.pattern === 'showa') { const shiroCount = Math.floor(rand(3, 6)); for (let i = 0; i < shiroCount; i++) { drawOrganicPatch(w * rand(0.08, 0.82), h * (0.5 + rand(-0.22, 0.22)), w * rand(0.05, 0.12), h * rand(0.14, 0.26), breed.sumiColor); } } } else if (breed.pattern === 'asagi') { // Lưới vảy xanh chàm (Fukurin) trên lưng và má/bụng đỏ cam rực rỡ ctx.strokeStyle = 'rgba(20, 35, 52, 0.52)'; ctx.lineWidth = 1.6; const cols = 28; const rows = 14; const cw = w / cols; const ch = h / rows; for (let r = 2; r < rows - 2; r++) { for (let c = 4; c < cols - 1; c++) { const cx = (c + (r % 2 === 0 ? 0.5 : 0)) * cw; const cy = r * ch; ctx.beginPath(); ctx.arc(cx, cy, cw * 0.58, -Math.PI * 0.45, Math.PI * 0.45); ctx.stroke(); } } // Má & sườn bụng đỏ Hi drawOrganicPatch(w * 0.22, h * 0.22, w * 0.14, h * 0.12, breed.hiColor); drawOrganicPatch(w * 0.22, h * 0.78, w * 0.14, h * 0.12, breed.hiColor); } // Đường rãnh nắp mang (Operculum) tinh tế ở u = 0.21 ctx.strokeStyle = breed.pattern === 'showa' ? 'rgba(255,255,255,0.22)' : 'rgba(65, 42, 32, 0.32)'; ctx.lineWidth = 2.6; ctx.beginPath(); ctx.arc(w * 0.20, h * 0.34, h * 0.14, -0.6, 1.3); ctx.stroke(); ctx.beginPath(); ctx.arc(w * 0.20, h * 0.66, h * 0.14, -1.3, 0.6); ctx.stroke(); const tex = new THREE.CanvasTexture(canvas); tex.encoding = THREE.sRGBEncoding; return tex; } // Sinh Texture đáy hồ sỏi cuội & rêu thủy sinh 1024x1024 function createPondBedTextures() { const size = 1024; const albedoCanvas = document.createElement('canvas'); albedoCanvas.width = size; albedoCanvas.height = size; const ctx = albedoCanvas.getContext('2d'); const bumpCanvas = document.createElement('canvas'); bumpCanvas.width = size; bumpCanvas.height = size; const bCtx = bumpCanvas.getContext('2d'); // Nền cát sỏi trầm tích dưới đáy ao ctx.fillStyle = '#1b2c2a'; ctx.fillRect(0, 0, size, size); bCtx.fillStyle = '#303030'; bCtx.fillRect(0, 0, size, size); // Các mảng rêu thủy sinh mềm mại for (let i = 0; i < 45; i++) { const mx = rand(0, size); const my = rand(0, size); const mr = rand(45, 130); const grad = ctx.createRadialGradient(mx, my, 4, mx, my, mr); grad.addColorStop(0, 'rgba(34, 66, 44, 0.45)'); grad.addColorStop(0.65, 'rgba(24, 48, 35, 0.25)'); grad.addColorStop(1, 'rgba(20, 40, 30, 0)'); ctx.fillStyle = grad; ctx.beginPath(); ctx.arc(mx, my, mr, 0, Math.PI * 2); ctx.fill(); } // Hàng trăm viên sỏi cuội đa sắc xếp dày đặc dưới đáy hồ const stonePalettes = [ ['#5a6661', '#3b4541', '#222826'], ['#6b6458', '#4a453c', '#2b2823'], ['#4a5c5b', '#303e3d', '#1c2424'], ['#556352', '#384236', '#20261f'] ]; for (let i = 0; i < 950; i++) { const px = rand(0, size); const py = rand(0, size); const rx = rand(6, 22); const ry = rx * rand(0.65, 0.92); const rot = rand(0, Math.PI); const pal = stonePalettes[i % stonePalettes.length]; // Vẽ lặp qua biên để texture liền mạch for (const ox of [-size, 0, size]) { for (const oy of [-size, 0, size]) { const x = px + ox; const y = py + oy; if (x < -40 || x > size + 40 || y < -40 || y > size + 40) continue; ctx.save(); ctx.translate(x, y); ctx.rotate(rot); const g = ctx.createRadialGradient(-rx * 0.25, -ry * 0.25, 1, 0, 0, rx); g.addColorStop(0, pal[0]); g.addColorStop(0.7, pal[1]); g.addColorStop(1, pal[2]); ctx.fillStyle = g; ctx.beginPath(); ctx.ellipse(0, 0, rx, ry, 0, 0, Math.PI * 2); ctx.fill(); ctx.restore(); bCtx.save(); bCtx.translate(x, y); bCtx.rotate(rot); const bg = bCtx.createRadialGradient(0, 0, 1, 0, 0, rx); bg.addColorStop(0, '#d8d8d8'); bg.addColorStop(0.8, '#808080'); bg.addColorStop(1, '#252525'); bCtx.fillStyle = bg; bCtx.beginPath(); bCtx.ellipse(0, 0, rx, ry, 0, 0, Math.PI * 2); bCtx.fill(); bCtx.restore(); } } } const map = new THREE.CanvasTexture(albedoCanvas); map.wrapS = THREE.RepeatWrapping; map.wrapT = THREE.RepeatWrapping; map.repeat.set(2.5, 2.5); map.encoding = THREE.sRGBEncoding; const bumpMap = new THREE.CanvasTexture(bumpCanvas); bumpMap.wrapS = THREE.RepeatWrapping; bumpMap.wrapT = THREE.RepeatWrapping; bumpMap.repeat.set(2.5, 2.5); return { map, bumpMap }; } // Sinh Texture lá sen có gân tỏa tia tự nhiên function createLilyPadTexture() { const size = 256; const canvas = document.createElement('canvas'); canvas.width = size; canvas.height = size; const ctx = canvas.getContext('2d'); const c = size / 2; const grad = ctx.createRadialGradient(c * 0.9, c * 0.9, 6, c, c, c); grad.addColorStop(0, '#448250'); grad.addColorStop(0.68, '#2d5e38'); grad.addColorStop(0.92, '#21472b'); grad.addColorStop(1, '#436339'); ctx.fillStyle = grad; ctx.fillRect(0, 0, size, size); ctx.strokeStyle = 'rgba(165, 225, 155, 0.28)'; ctx.lineWidth = 1.4; for (let i = 0; i < 16; i++) { const a = (i / 16) * Math.PI * 2; ctx.beginPath(); ctx.moveTo(c, c); ctx.quadraticCurveTo( c + Math.cos(a + 0.05) * c * 0.52, c + Math.sin(a + 0.05) * c * 0.52, c + Math.cos(a) * c * 0.94, c + Math.sin(a) * c * 0.94 ); ctx.stroke(); } const tex = new THREE.CanvasTexture(canvas); tex.encoding = THREE.sRGBEncoding; return tex; } // ========================================================================= // 4. KHỞI TẠO CẢNH 3D THREE.JS, ÁNH SÁNG & BỘ ĐỆM KHÚC XẠ NƯỚC // ========================================================================= // Tự động nhận diện cấu hình thiết bị & độ phân giải để giữ 60 FPS ổn định function getDeviceProfile() { const w = window.innerWidth; const h = window.innerHeight; const aspect = w / Math.max(h, 1); const isTouchDevice = ('ontouchstart' in window) || (navigator.maxTouchPoints > 0); const isMobile = w < 640; const isTablet = w >= 640 && w < 1024; const cores = navigator.hardwareConcurrency || 4; const rawDpr = window.devicePixelRatio || 1; // Giới hạn DPR hợp lý trên thiết bị di động mật độ điểm ảnh cao để tránh nóng máy const maxDpr = isMobile ? 1.75 : (cores <= 4 ? 1.75 : 2.0); const pixelRatio = Math.min(rawDpr, maxDpr); const refractionScale = isMobile ? 0.60 : (isTablet ? 0.68 : 0.75); const waterSegX = isMobile ? 105 : 150; const waterSegZ = isMobile ? 85 : 120; return { w, h, aspect, isTouchDevice, isMobile, isTablet, pixelRatio, refractionScale, waterSegX, waterSegZ }; } let deviceProfile = getDeviceProfile(); const container = document.getElementById('webgl-container'); const scene = new THREE.Scene(); scene.background = SCENE_THEMES.morning.skyTop.clone(); scene.fog = new THREE.FogExp2(SCENE_THEMES.morning.fogColor.getHex(), 0.019); const initialFov = deviceProfile.aspect < 0.85 ? 48 : (deviceProfile.aspect < 1.15 ? 45 : 42); const camera = new THREE.PerspectiveCamera(initialFov, deviceProfile.aspect, 0.1, 140); const renderer = new THREE.WebGLRenderer({ antialias: true, powerPreference: 'high-performance' }); renderer.setSize(deviceProfile.w, deviceProfile.h); renderer.setPixelRatio(deviceProfile.pixelRatio); renderer.toneMapping = THREE.ACESFilmicToneMapping; renderer.toneMappingExposure = 1.12; container.appendChild(renderer.domElement); // RenderTarget chụp hình ảnh thế giới dưới mặt nước để tính khúc xạ (Refraction) const refractionTarget = new THREE.WebGLRenderTarget( Math.floor(deviceProfile.w * deviceProfile.refractionScale), Math.floor(deviceProfile.h * deviceProfile.refractionScale), { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBAFormat } ); // Hệ thống ánh sáng 3D const hemiLight = new THREE.HemisphereLight( SCENE_THEMES.morning.hemiSky.getHex(), SCENE_THEMES.morning.hemiGround.getHex(), SCENE_THEMES.morning.hemiIntensity ); scene.add(hemiLight); const sunLight = new THREE.DirectionalLight(SCENE_THEMES.morning.sunColor.getHex(), SCENE_THEMES.morning.sunIntensity); sunLight.position.copy(SCENE_THEMES.morning.sunPos); scene.add(sunLight); // Đèn điểm ấm áp bên trong Đèn đá Nhật Bản Yukimi-dōrō const lanternLight = new THREE.PointLight(0xffaa44, 0, 14, 1.6); lanternLight.position.set(7.8, 1.35, -5.6); scene.add(lanternLight); // Shared PBR Textures const scaleNormalTex = createKoiScaleNormalTexture(); const finRayTex = createFinRayTexture(); const pondBedTex = createPondBedTextures(); const lilyPadTex = createLilyPadTexture(); // ========================================================================= // 5. ĐÁY HỒ 3D, VỆT NẮNG CAUSTICS GLSL & SỎI ĐÁ CHÌM // ========================================================================= const POND_RADIUS_X = 12.5; const POND_RADIUS_Z = 9.5; const POND_DEPTH = -1.75; const pondBedGeo = new THREE.PlaneGeometry(34, 28, 48, 48); pondBedGeo.rotateX(-Math.PI / 2); // Tạo độ trũng tự nhiên ở lòng hồ và nâng nhẹ ở rìa bờ const bedPosAttr = pondBedGeo.attributes.position; for (let i = 0; i < bedPosAttr.count; i++) { const vx = bedPosAttr.getX(i); const vz = bedPosAttr.getZ(i); const normDist = Math.hypot(vx / POND_RADIUS_X, vz / POND_RADIUS_Z); const bowlY = POND_DEPTH + Math.pow(clamp(normDist, 0, 1.4), 2.4) * 1.65 + Math.sin(vx * 0.7) * Math.cos(vz * 0.7) * 0.08; bedPosAttr.setY(i, bowlY); } pondBedGeo.computeVertexNormals(); const pondBedMat = new THREE.MeshStandardMaterial({ map: pondBedTex.map, bumpMap: pondBedTex.bumpMap, bumpScale: 0.08, roughness: 0.88, metalness: 0.05 }); // Tiêm mã GLSL Caustics (vệt nắng khúc xạ lung linh) trực tiếp vào vật liệu đáy hồ const causticUniforms = { uTime: { value: 0 }, uCausticStrength: { value: SCENE_THEMES.morning.causticStrength }, uCausticColor: { value: new THREE.Color(0xd8fff5) } }; pondBedMat.onBeforeCompile = (shader) => { shader.uniforms.uTime = causticUniforms.uTime; shader.uniforms.uCausticStrength = causticUniforms.uCausticStrength; shader.uniforms.uCausticColor = causticUniforms.uCausticColor; shader.vertexShader = shader.vertexShader.replace( '#include ', `#include varying vec3 vWorldPosBed;` ).replace( '#include ', `#include vWorldPosBed = (modelMatrix * vec4(transformed, 1.0)).xyz;` ); shader.fragmentShader = shader.fragmentShader.replace( '#include ', `#include uniform float uTime; uniform float uCausticStrength; uniform vec3 uCausticColor; varying vec3 vWorldPosBed; float causticPattern(vec2 uv, float t) { vec2 p = mod(uv * 6.2831853, 6.2831853) - 250.0; vec2 i = p; float c = 1.0; float inten = 0.005; for (int n = 0; n < 4; n++) { float time = t * (1.0 - (3.5 / float(n + 1))); i = p + vec2(cos(time - i.x) + sin(time + i.y), sin(time - i.y) + cos(time + i.x)); c += 1.0 / length(vec2(p.x / (sin(i.x + time) / inten), p.y / (cos(i.y + time) / inten))); } c /= 4.0; c = 1.17 - pow(c, 1.4); return pow(abs(c), 7.0); }` ).replace( '#include ', `float c1 = causticPattern(vWorldPosBed.xz * 0.14, uTime * 0.55); float c2 = causticPattern(vWorldPosBed.xz * 0.19 + vec2(0.35, -0.22), -uTime * 0.42); float cMask = smoothstep(-0.1, -0.6, vWorldPosBed.y); gl_FragColor.rgb += uCausticColor * (c1 + c2 * 0.75) * uCausticStrength * cMask; #include ` ); }; const pondBedMesh = new THREE.Mesh(pondBedGeo, pondBedMat); scene.add(pondBedMesh); // Rải thêm các tảng đá cuội 3D nổi khối dưới đáy hồ const pebbleGeo = new THREE.IcosahedronGeometry(0.28, 1); const pebblePos = pebbleGeo.attributes.position; for (let i = 0; i < pebblePos.count; i++) { pebblePos.setY(i, pebblePos.getY(i) * 0.52); } pebbleGeo.computeVertexNormals(); const pebbleMat = new THREE.MeshStandardMaterial({ color: 0x3b4846, roughness: 0.78 }); const pebbleInst = new THREE.InstancedMesh(pebbleGeo, pebbleMat, 95); const dummy = new THREE.Object3D(); for (let i = 0; i < 95; i++) { const a = rand(0, Math.PI * 2); const r = Math.sqrt(Math.random()) * 0.88; const px = Math.cos(a) * POND_RADIUS_X * r; const pz = Math.sin(a) * POND_RADIUS_Z * r; const py = POND_DEPTH + Math.pow(r, 2.4) * 1.65 + 0.04; dummy.position.set(px, py, pz); dummy.rotation.set(rand(-0.2, 0.2), rand(0, Math.PI), rand(-0.2, 0.2)); const s = rand(0.55, 1.85); dummy.scale.set(s * rand(0.9, 1.3), s * 0.75, s); dummy.updateMatrix(); pebbleInst.setMatrixAt(i, dummy.matrix); } scene.add(pebbleInst); // ========================================================================= // 6. MẶT NƯỚC 3D VỚI GLSL SHADER KHÚC XẠ, PHẢN CHIẾU FRESNEL & 16 SÓNG ĐỘNG // ========================================================================= const MAX_RIPPLES = 16; const rippleData = []; for (let i = 0; i < MAX_RIPPLES; i++) { rippleData.push(new THREE.Vector4(0, 0, -100, 0)); // x, z, birthTime, amplitude } let rippleCursor = 0; function spawnWaterRipple3D(x, z, amplitude = 1.0) { rippleData[rippleCursor].set(x, z, state.time, amplitude); rippleCursor = (rippleCursor + 1) % MAX_RIPPLES; } const waterUniforms = { uTime: { value: 0 }, uRefractionMap: { value: refractionTarget.texture }, uResolution: { value: new THREE.Vector2(window.innerWidth, window.innerHeight) }, uRipples: { value: rippleData }, uDeepColor: { value: SCENE_THEMES.morning.waterDeep.clone() }, uShallowColor: { value: SCENE_THEMES.morning.waterShallow.clone() }, uSkyReflectColor: { value: SCENE_THEMES.morning.skyReflect.clone() }, uSunDir: { value: SCENE_THEMES.morning.sunPos.clone().normalize() }, uSunColor: { value: SCENE_THEMES.morning.sunColor.clone() }, uLanternPos: { value: lanternLight.position.clone() }, uLanternIntensity: { value: 0 } }; const waterShaderMat = new THREE.ShaderMaterial({ uniforms: waterUniforms, transparent: true, vertexShader: ` uniform float uTime; uniform vec4 uRipples[${MAX_RIPPLES}]; varying vec3 vWorldPos; varying vec4 vClipPos; void main() { vec4 worldPos = modelMatrix * vec4(position, 1.0); float h = sin(worldPos.x * 1.15 + uTime * 1.4) * 0.012 + cos(worldPos.z * 1.35 - uTime * 1.2) * 0.012; for (int i = 0; i < ${MAX_RIPPLES}; i++) { vec4 rp = uRipples[i]; float age = uTime - rp.z; if (age > 0.0 && age < 4.5 && rp.w > 0.001) { float dist = distance(worldPos.xz, rp.xy); float waveRadius = age * 2.85; float band = exp(-pow(dist - waveRadius, 2.0) * 3.8); float decay = exp(-age * 0.95) * rp.w; h += sin((dist - waveRadius) * 16.0) * band * decay * 0.055; } } worldPos.y += h; vWorldPos = worldPos.xyz; vClipPos = projectionMatrix * viewMatrix * worldPos; gl_Position = vClipPos; } `, fragmentShader: ` uniform float uTime; uniform sampler2D uRefractionMap; uniform vec4 uRipples[${MAX_RIPPLES}]; uniform vec3 uDeepColor; uniform vec3 uShallowColor; uniform vec3 uSkyReflectColor; uniform vec3 uSunDir; uniform vec3 uSunColor; uniform vec3 uLanternPos; uniform float uLanternIntensity; varying vec3 vWorldPos; varying vec4 vClipPos; // Tính độ cao mặt nước tại điểm xz để suy ra vector pháp tuyến 3D chính xác float getWaveHeight(vec2 p) { float h = sin(p.x * 1.15 + uTime * 1.4) * 0.012 + cos(p.y * 1.35 - uTime * 1.2) * 0.012; h += sin(p.x * 3.8 - uTime * 2.1 + p.y * 2.2) * 0.0045; h += cos(p.y * 4.4 + uTime * 1.8 - p.x * 1.9) * 0.004; for (int i = 0; i < ${MAX_RIPPLES}; i++) { vec4 rp = uRipples[i]; float age = uTime - rp.z; if (age > 0.0 && age < 4.5 && rp.w > 0.001) { float dist = distance(p, rp.xy); float waveRadius = age * 2.85; float band = exp(-pow(dist - waveRadius, 2.0) * 3.8); float decay = exp(-age * 0.95) * rp.w; h += sin((dist - waveRadius) * 16.0) * band * decay * 0.055; } } return h; } void main() { float eps = 0.04; float hC = getWaveHeight(vWorldPos.xz); float hX = getWaveHeight(vWorldPos.xz + vec2(eps, 0.0)); float hZ = getWaveHeight(vWorldPos.xz + vec2(0.0, eps)); vec3 normal = normalize(vec3(hC - hX, eps * 1.35, hC - hZ)); // Tọa độ UV màn hình cho ảnh khúc xạ đáy hồ & cá Koi bên dưới vec2 ndc = (vClipPos.xy / vClipPos.w) * 0.5 + 0.5; vec2 refractUV = clamp(ndc + normal.xz * 0.065, 0.002, 0.998); vec3 refractedScene = texture2D(uRefractionMap, refractUV).rgb; // Sắc độ nước theo độ sâu từ tâm ra bờ float radial = length(vec2(vWorldPos.x / 12.5, vWorldPos.z / 9.5)); vec3 waterTint = mix(uDeepColor, uShallowColor, clamp(radial, 0.0, 1.0)); vec3 underWaterColor = mix(refractedScene, refractedScene * (waterTint * 2.4 + 0.35), 0.34); // Hiệu ứng Fresnel phản chiếu bầu trời ở góc nhìn nghiêng vec3 viewDir = normalize(cameraPosition - vWorldPos); float fresnel = 0.03 + 0.97 * pow(1.0 - max(dot(normal, viewDir), 0.0), 4.2); vec3 color = mix(underWaterColor, uSkyReflectColor, clamp(fresnel * 0.68, 0.0, 0.78)); // Ánh nắng / ánh trăng lấp lánh trên đỉnh sóng vec3 halfVec = normalize(uSunDir + viewDir); float spec = pow(max(dot(normal, halfVec), 0.0), 140.0); color += uSunColor * spec * 1.35; // Phản chiếu ánh nến ấm từ đèn đá Yukimi-dōrō lên sóng nước if (uLanternIntensity > 0.01) { vec3 toLantern = normalize(uLanternPos - vWorldPos); float distL = distance(uLanternPos.xz, vWorldPos.xz); vec3 lHalf = normalize(toLantern + viewDir); float lSpec = pow(max(dot(normal, lHalf), 0.0), 48.0); float atten = exp(-distL * 0.24); color += vec3(1.0, 0.68, 0.24) * (lSpec * 1.6 + 0.16) * atten * uLanternIntensity; } // Bọt sáng li ti trên đỉnh gợn sóng mạnh float crestFoam = smoothstep(0.018, 0.055, hC); color += vec3(0.85, 0.96, 0.98) * crestFoam * 0.28; gl_FragColor = vec4(color, 0.96); } ` }); const waterGeo = new THREE.PlaneGeometry(32, 26, deviceProfile.waterSegX, deviceProfile.waterSegZ); waterGeo.rotateX(-Math.PI / 2); const waterMesh = new THREE.Mesh(waterGeo, waterShaderMat); waterMesh.position.y = 0; scene.add(waterMesh); // ========================================================================= // 7. MÔ HÌNH CÁ KOI NISHIKIGOI 3D KHỐI TRÒN UỐN LƯỢN 24 ĐỐT XƯƠNG SỐNG // ========================================================================= const KOI_BREEDS_3D = [ { name: 'Kohaku', base: '#faf7f0', bellyColor: 'rgba(235,228,215,0.5)', pattern: 'kohaku', hiColor: '#e23217', sumiColor: null, metalness: 0.08, finColor: 0xfbf8f2 }, { name: 'Taisho Sanke', base: '#f8f5ed', bellyColor: 'rgba(235,228,215,0.5)', pattern: 'sanke', hiColor: '#df2f15', sumiColor: '#17191e', metalness: 0.08, finColor: 0xf8f5ee }, { name: 'Showa Sanshoku', base: '#1a1c21', bellyColor: 'rgba(42,46,54,0.6)', pattern: 'showa', hiColor: '#e83e1a', sumiColor: '#f7f4ec', metalness: 0.10, finColor: 0xeae8e3 }, { name: 'Tancho', base: '#fcfaf5', bellyColor: 'rgba(238,232,222,0.45)', pattern: 'tancho', hiColor: '#dc2419', sumiColor: null, metalness: 0.10, finColor: 0xfcfaf5 }, { name: 'Yamabuki Ogon', base: '#f0b629', bellyColor: 'rgba(255,236,155,0.65)', pattern: 'ogon', hiColor: '#ffd966', sumiColor: null, metalness: 0.72, finColor: 0xfce08b }, { name: 'Asagi', base: '#6b8699', bellyColor: 'rgba(224,62,32,0.85)', pattern: 'asagi', hiColor: '#e03c1e', sumiColor: null, metalness: 0.42, finColor: 0xe8643c } ]; // Hồ sơ giải phẫu 3D chiều rộng (W) và chiều cao (H) dọc theo 24 đốt xương sống (0=mõm -> 23=gốc đuôi) const KOI_SPINE_COUNT = 24; const KOI_PROFILE_W = [ 0.04, 0.34, 0.62, 0.80, 0.92, 0.99, 1.00, 0.97, 0.92, 0.85, 0.78, 0.70, 0.62, 0.54, 0.46, 0.39, 0.32, 0.26, 0.21, 0.17, 0.13, 0.10, 0.08, 0.07 ]; const KOI_PROFILE_H = [ 0.04, 0.28, 0.50, 0.68, 0.82, 0.93, 0.98, 0.96, 0.91, 0.84, 0.76, 0.68, 0.60, 0.52, 0.44, 0.37, 0.31, 0.25, 0.21, 0.18, 0.16, 0.15, 0.16, 0.18 ]; // Tạo hình học 3D rỗng có sẵn tọa độ cục bộ chuẩn để biến dạng theo xương sống mỗi khung hình function buildArticulatedKoiBodyGeometry(scale) { const radialSegs = 26; const rings = KOI_SPINE_COUNT; const positions = []; const uvs = []; const indices = []; const baseMeta = []; // Lưu { ringIdx, localY, localZ } cho từng đỉnh const maxW = 0.23 * scale; const maxH = 0.24 * scale; for (let r = 0; r < rings; r++) { const u = r / (rings - 1); const w = KOI_PROFILE_W[r] * maxW; const h = KOI_PROFILE_H[r] * maxH; for (let s = 0; s <= radialSegs; s++) { const v = s / radialSegs; const theta = v * Math.PI * 2; // 0 = sống lưng (+Y), PI = bụng (-Y) // Tạo dáng thân cá Koi thật: lưng tròn đầy, má đầy đặn, bụng hơi phẳng nhẹ let ly = Math.cos(theta) * h; if (ly < 0) ly *= 0.82; // Nâng nhẹ gù sống lưng vùng vai (u ~ 0.25) const dorsalArch = Math.sin(Math.pow(u, 0.75) * Math.PI) * 0.055 * scale; ly += dorsalArch; const lz = Math.sin(theta) * w; positions.push(0, ly, lz); uvs.push(u, v); baseMeta.push({ ring: r, ly, lz }); } } const stride = radialSegs + 1; for (let r = 0; r < rings - 1; r++) { for (let s = 0; s < radialSegs; s++) { const a = r * stride + s; const b = (r + 1) * stride + s; const c = (r + 1) * stride + (s + 1); const d = r * stride + (s + 1); indices.push(a, b, d); indices.push(b, c, d); } } const geo = new THREE.BufferGeometry(); geo.setAttribute('position', new THREE.Float32BufferAttribute(positions, 3)); geo.setAttribute('uv', new THREE.Float32BufferAttribute(uvs, 2)); geo.setIndex(indices); geo.userData.baseMeta = baseMeta; return geo; } // Tạo hình học 3D vây đuôi (Caudal Fin) xòe hình quạt uốn lượn function buildCaudalFinGeometry(scale) { const segX = 12; const segY = 16; const geo = new THREE.PlaneGeometry(0.46 * scale, 0.42 * scale, segX, segY); const pos = geo.attributes.position; for (let i = 0; i < pos.count; i++) { const x = pos.getX(i); // -half -> +half const y = pos.getY(i); const u = clamp((x / (0.46 * scale)) + 0.5, 0, 1); // 0 (gốc đuôi) -> 1 (mép đuôi) const v = clamp(y / (0.21 * scale), -1, 1); // -1 -> +1 // Tụ nhỏ ở gốc đuôi và xòe rộng về phía sau, chẻ nhẹ ở chính giữa mép đuôi const spread = 0.14 + Math.pow(u, 0.85) * 0.86; const fork = 1.0 - Math.pow(u, 2.2) * (1.0 - Math.abs(v)) * 0.24; pos.setX(i, -u * 0.46 * scale * fork); pos.setY(i, y * spread); } geo.computeVertexNormals(); return geo; } // Tạo hình học 3D vây ngực (Pectoral Fin) function buildPectoralFinGeometry(scale, side) { const geo = new THREE.PlaneGeometry(0.36 * scale, 0.22 * scale, 8, 6); const pos = geo.attributes.position; for (let i = 0; i < pos.count; i++) { const x = pos.getX(i); const y = pos.getY(i); const u = clamp((x / (0.36 * scale)) + 0.5, 0, 1); // 0 (nách vây) -> 1 (chóp vây) const v = clamp(y / (0.11 * scale), -1, 1); // -1 -> +1 const taper = Math.sin(Math.pow(u, 0.65) * Math.PI) * 0.92 + (1 - u) * 0.25; pos.setX(i, -u * 0.26 * scale); pos.setY(i, (v * 0.11 * scale * taper) - u * 0.04 * scale); pos.setZ(i, side * u * 0.34 * scale); } geo.computeVertexNormals(); return geo; } // Tạo hình học 3D vây lưng (Dorsal Fin) function buildDorsalFinGeometry(scale) { const segX = 14; const segY = 5; const geo = new THREE.PlaneGeometry(0.62 * scale, 0.16 * scale, segX, segY); const pos = geo.attributes.position; for (let i = 0; i < pos.count; i++) { const x = pos.getX(i); const y = pos.getY(i); const u = clamp((x / (0.62 * scale)) + 0.5, 0, 1); // 0 -> 1 const v = clamp((y / (0.16 * scale)) + 0.5, 0, 1); // 0 (chân vây) -> 1 (ngọn vây) const crest = Math.sin(Math.pow(u, 0.72) * Math.PI); pos.setX(i, -u * 0.62 * scale - v * 0.06 * scale); pos.setY(i, v * 0.16 * scale * crest); pos.setZ(i, 0); } geo.computeVertexNormals(); return geo; } // Bóng đổ mềm dưới đáy hồ cho mỗi con cá Koi function createShadowBlobTexture() { const size = 128; const canvas = document.createElement('canvas'); canvas.width = size; canvas.height = size; const ctx = canvas.getContext('2d'); const grad = ctx.createRadialGradient(size / 2, size / 2, 4, size / 2, size / 2, size / 2); grad.addColorStop(0, 'rgba(2, 10, 12, 0.62)'); grad.addColorStop(0.55, 'rgba(2, 10, 12, 0.28)'); grad.addColorStop(1, 'rgba(2, 10, 12, 0)'); ctx.fillStyle = grad; ctx.fillRect(0, 0, size, size); return new THREE.CanvasTexture(canvas); } const shadowBlobTex = createShadowBlobTexture(); class KoiFish3D { constructor(scene, x, y, z, breedIndex = null) { const idx = breedIndex !== null ? breedIndex : Math.floor(Math.random() * KOI_BREEDS_3D.length); this.breed = KOI_BREEDS_3D[idx]; this.scale = rand(0.84, 1.18); this.segLen = 0.066 * this.scale; this.yaw = rand(0, Math.PI * 2); this.pitch = 0; this.baseSpeed = rand(1.45, 2.05); this.speed = this.baseSpeed; this.vx = Math.cos(this.yaw) * this.speed; this.vz = Math.sin(this.yaw) * this.speed; this.vy = 0; this.preferredDepth = rand(-0.78, -0.34); // 24 đốt xương sống 3D (x, y, z, yaw, pitch) this.spine = []; for (let i = 0; i < KOI_SPINE_COUNT; i++) { this.spine.push({ x: x - Math.cos(this.yaw) * i * this.segLen, y: y, z: z - Math.sin(this.yaw) * i * this.segLen, yaw: this.yaw, pitch: 0 }); } this.swimPhase = rand(0, Math.PI * 2); this.wanderAngle = rand(0, Math.PI * 2); this.startleTimer = 0; this.turnRate = 0; this.group = new THREE.Group(); // 1. Thân cá 3D với vật liệu PBR bóng ướt (Clearcoat + Scale Normal Map) this.bodyGeo = buildArticulatedKoiBodyGeometry(this.scale); this.bodyMat = new THREE.MeshPhysicalMaterial({ map: createKoiPatternTexture(this.breed), normalMap: scaleNormalTex, normalScale: new THREE.Vector2(0.55, 0.55), roughness: this.breed.metalness > 0.5 ? 0.22 : 0.32, metalness: this.breed.metalness, clearcoat: 1.0, clearcoatRoughness: 0.12, reflectivity: 0.9 }); this.bodyMesh = new THREE.Mesh(this.bodyGeo, this.bodyMat); this.bodyMesh.frustumCulled = false; this.group.add(this.bodyMesh); // Vật liệu vây bán trong suốt có nan tia vây this.finMat = new THREE.MeshPhysicalMaterial({ color: this.breed.finColor, alphaMap: finRayTex, transparent: true, opacity: 0.85, roughness: 0.35, clearcoat: 0.8, side: THREE.DoubleSide, depthWrite: false }); // 2. Vây đuôi 3D this.caudalGeo = buildCaudalFinGeometry(this.scale); this.caudalMesh = new THREE.Mesh(this.caudalGeo, this.finMat); this.group.add(this.caudalMesh); // 3. Vây lưng 3D this.dorsalGeo = buildDorsalFinGeometry(this.scale); this.dorsalMesh = new THREE.Mesh(this.dorsalGeo, this.finMat); this.group.add(this.dorsalMesh); // 4. Vây ngực trái & phải 3D this.leftPecMesh = new THREE.Mesh(buildPectoralFinGeometry(this.scale, -1), this.finMat); this.rightPecMesh = new THREE.Mesh(buildPectoralFinGeometry(this.scale, 1), this.finMat); this.group.add(this.leftPecMesh, this.rightPecMesh); // 5. Đôi mắt 3D & 2 cặp râu cảm giác 3D this.headGroup = new THREE.Group(); const eyeGeo = new THREE.SphereGeometry(0.024 * this.scale, 10, 10); const irisMat = new THREE.MeshStandardMaterial({ color: 0xd9a836, roughness: 0.2, metalness: 0.3 }); const pupilGeo = new THREE.SphereGeometry(0.015 * this.scale, 8, 8); const pupilMat = new THREE.MeshBasicMaterial({ color: 0x090a0d }); [-1, 1].forEach(side => { const eye = new THREE.Mesh(eyeGeo, irisMat); eye.position.set(-0.14 * this.scale, 0.05 * this.scale, side * 0.135 * this.scale); const pupil = new THREE.Mesh(pupilGeo, pupilMat); pupil.position.set(0.004 * this.scale, 0.004 * this.scale, side * 0.012 * this.scale); eye.add(pupil); this.headGroup.add(eye); // Râu cảm giác 3D cong mềm mại const curve = new THREE.CatmullRomCurve3([ new THREE.Vector3(-0.04 * this.scale, -0.01 * this.scale, side * 0.06 * this.scale), new THREE.Vector3(-0.06 * this.scale, -0.03 * this.scale, side * 0.14 * this.scale), new THREE.Vector3(-0.13 * this.scale, -0.045 * this.scale, side * 0.21 * this.scale) ]); const barbelGeo = new THREE.TubeGeometry(curve, 6, 0.005 * this.scale, 5, false); const barbelMat = new THREE.MeshStandardMaterial({ color: 0xdba874, roughness: 0.5 }); this.headGroup.add(new THREE.Mesh(barbelGeo, barbelMat)); }); this.group.add(this.headGroup); // 6. Bóng đổ mềm in xuống đáy hồ bên dưới cá const shadowGeo = new THREE.PlaneGeometry(1.75 * this.scale, 0.68 * this.scale); shadowGeo.rotateX(-Math.PI / 2); this.shadowMat = new THREE.MeshBasicMaterial({ map: shadowBlobTex, transparent: true, opacity: 0.55, depthWrite: false }); this.shadowMesh = new THREE.Mesh(shadowGeo, this.shadowMat); scene.add(this.group); scene.add(this.shadowMesh); } startleFrom(px, pz, strength = 1.0) { const head = this.spine[0]; const dx = head.x - px; const dz = head.z - pz; const dist = Math.hypot(dx, dz); if (dist < 4.2 * strength && dist > 0.05) { const fleeYaw = Math.atan2(dz, dx); const intensity = (1 - dist / (4.2 * strength)) * strength; this.vx += Math.cos(fleeYaw) * 3.5 * intensity; this.vz += Math.sin(fleeYaw) * 3.5 * intensity; this.vy -= 0.65 * intensity; // Lặn sâu xuống khi giật mình this.startleTimer = Math.max(this.startleTimer, 0.85 + intensity * 0.6); } } update(dt, kois, pellets3D, acousticCalls3D) { const step = dt * 60; const head = this.spine[0]; let steerX = 0; let steerZ = 0; let targetY = this.preferredDepth + Math.sin(state.time * 0.7 + this.swimPhase * 0.1) * 0.12; // 1. Thuật toán đàn cá Boids 3D let sepX = 0, sepZ = 0, sepCount = 0; let aliX = 0, aliZ = 0, aliCount = 0; let cohX = 0, cohZ = 0, cohCount = 0; for (let i = 0; i < kois.length; i++) { const other = kois[i]; if (other === this) continue; const oh = other.spine[0]; const dx = head.x - oh.x; const dz = head.z - oh.z; const dSq = dx * dx + dz * dz; if (dSq > 0.001 && dSq < 1.35 * 1.35) { const d = Math.sqrt(dSq); sepX += (dx / d) / d; sepZ += (dz / d) / d; sepCount++; } if (dSq < 3.4 * 3.4) { aliX += other.vx; aliZ += other.vz; aliCount++; cohX += oh.x; cohZ += oh.z; cohCount++; } } if (sepCount > 0) { steerX += (sepX / sepCount) * 0.16; steerZ += (sepZ / sepCount) * 0.16; } if (aliCount > 0) { steerX += ((aliX / aliCount) - this.vx) * 0.015; steerZ += ((aliZ / aliCount) - this.vz) * 0.015; } if (cohCount > 0) { steerX += ((cohX / cohCount) - head.x) * 0.006; steerZ += ((cohZ / cohCount) - head.z) * 0.006; } // 2. Bơi ngoi lên đớp hạt mồi 3D trên mặt nước let activeTarget = false; if (pellets3D.length > 0 && this.startleTimer <= 0) { let nearest = null; let minDist = 7.5; for (let i = 0; i < pellets3D.length; i++) { const p = pellets3D[i]; if (p.eaten) continue; const d = Math.hypot(p.mesh.position.x - head.x, p.mesh.position.z - head.z); if (d < minDist) { minDist = d; nearest = p; } } if (nearest) { activeTarget = true; const ang = Math.atan2(nearest.mesh.position.z - head.z, nearest.mesh.position.x - head.x); steerX += Math.cos(ang) * 0.24; steerZ += Math.sin(ang) * 0.24; // Ngoi dần lên sát mặt nước (y = -0.14) khi tới gần hạt mồi targetY = lerp(this.preferredDepth, -0.14, clamp(1 - minDist / 4.5, 0, 1)); if (minDist < 0.34 * this.scale && Math.abs(head.y - nearest.mesh.position.y) < 0.35) { nearest.eaten = true; spawnWaterRipple3D(nearest.mesh.position.x, nearest.mesh.position.z, 1.15); audioEngine.playWaterDrop(630, 0.10); this.swimPhase += 1.2; } } } // 3. Tụ lại khi nghe tiếng vỗ tay gọi cá if (!activeTarget && acousticCalls3D.length > 0 && this.startleTimer <= 0) { const call = acousticCalls3D[acousticCalls3D.length - 1]; const dx = call.x - head.x; const dz = call.z - head.z; const dist = Math.hypot(dx, dz); if (dist > 0.7 && dist < 9.5) { activeTarget = true; const ang = Math.atan2(dz, dx) + (dist < 2.1 ? 0.65 : 0); steerX += Math.cos(ang) * 0.15; steerZ += Math.sin(ang) * 0.15; targetY = -0.26; } } // 4. Bơi lượn tự nhiên & giữ trong lòng hồ elip if (!activeTarget) { this.wanderAngle += rand(-0.14, 0.14) * step; const wYaw = this.yaw + Math.sin(this.wanderAngle) * 0.65; steerX += Math.cos(wYaw) * 0.032; steerZ += Math.sin(wYaw) * 0.032; } const boundRx = POND_RADIUS_X - 2.3; const boundRz = POND_RADIUS_Z - 2.0; const normR = Math.hypot(head.x / boundRx, head.z / boundRz); if (normR > 0.85) { const toCenter = Math.atan2(-head.z, -head.x); const push = (normR - 0.85) * 0.85; steerX += Math.cos(toCenter) * push; steerZ += Math.sin(toCenter) * push; } // 5. Cập nhật vận tốc ngang & độ sâu thẳng đứng 3D this.vx += steerX * step; this.vz += steerZ * step; let targetSpeed = this.baseSpeed; if (this.startleTimer > 0) { this.startleTimer -= dt; targetSpeed = this.baseSpeed * 2.25; } else if (activeTarget) { targetSpeed = this.baseSpeed * 1.55; } const curSpeed = Math.hypot(this.vx, this.vz) || 0.001; this.speed = lerp(curSpeed, targetSpeed, 0.06 * step); const desiredYaw = Math.atan2(this.vz, this.vx); const yawDiff = normalizeAngle(desiredYaw - this.yaw); const maxTurn = (this.startleTimer > 0 ? 0.095 : 0.05) * step; const appliedTurn = clamp(yawDiff, -maxTurn, maxTurn); this.yaw += appliedTurn; this.turnRate = lerp(this.turnRate, appliedTurn, 0.16); this.vx = Math.cos(this.yaw) * this.speed; this.vz = Math.sin(this.yaw) * this.speed; // Chuyển động lên xuống theo trục Y (Pitch) const nextY = lerp(head.y, clamp(targetY, -1.15, -0.13), 0.045 * step); const dy = nextY - head.y; this.pitch = lerp(this.pitch, clamp(Math.atan2(dy, this.speed * dt + 0.001), -0.35, 0.35), 0.14); // 6. Nhịp vẫy đuôi & cập nhật đốt đầu tiên this.swimPhase += (0.085 + this.speed * 0.048) * step; const headSway = Math.sin(this.swimPhase) * 0.036; const moveYaw = this.yaw + headSway; head.x += Math.cos(moveYaw) * this.speed * dt; head.z += Math.sin(moveYaw) * this.speed * dt; head.y = nextY; head.yaw = moveYaw; head.pitch = this.pitch; // Tạo gợn sóng nhẹ nếu cá bơi sát mặt nước if (head.y > -0.22 && Math.random() < 0.16) { spawnWaterRipple3D(head.x, head.z, 0.24); } // 7. Động học xương sống 24 đốt trong không gian 3D for (let i = 1; i < KOI_SPINE_COUNT; i++) { const prev = this.spine[i - 1]; const curr = this.spine[i]; const dx = prev.x - curr.x; const dz = prev.z - curr.z; let segYaw = Math.atan2(dz, dx); const tailRatio = i / (KOI_SPINE_COUNT - 1); segYaw += Math.sin(this.swimPhase - i * 0.28) * 0.025 * Math.pow(tailRatio, 1.15); const relDiff = normalizeAngle(segYaw - prev.yaw); if (Math.abs(relDiff) > 0.22) { segYaw = prev.yaw + Math.sign(relDiff) * 0.22; } curr.yaw = segYaw; curr.pitch = lerp(curr.pitch, prev.pitch, 0.35); curr.x = prev.x - Math.cos(segYaw) * this.segLen; curr.z = prev.z - Math.sin(segYaw) * this.segLen; curr.y = lerp(curr.y, prev.y - Math.sin(prev.pitch) * this.segLen, 0.45); } this.update3DMeshGeometry(); } // Cập nhật toàn bộ 900 đỉnh lưới thân cá & các vây 3D theo xương sống update3DMeshGeometry() { const posAttr = this.bodyGeo.attributes.position; const meta = this.bodyGeo.userData.baseMeta; for (let i = 0; i < meta.length; i++) { const m = meta[i]; const joint = this.spine[m.ring]; // Xoay tiết diện ngang của đốt xương theo góc yaw & nghiêng nhẹ khi rẽ const bankAngle = -this.turnRate * 4.5; const cosB = Math.cos(bankAngle); const sinB = Math.sin(bankAngle); const by = m.ly * cosB - m.lz * sinB; const bz = m.ly * sinB + m.lz * cosB; // Vector ngang vuông góc với hướng bơi trong mặt phẳng XZ const rightX = -Math.sin(joint.yaw); const rightZ = Math.cos(joint.yaw); const wx = joint.x + rightX * bz; const wy = joint.y + by; const wz = joint.z + rightZ * bz; posAttr.setXYZ(i, wx, wy, wz); } posAttr.needsUpdate = true; this.bodyGeo.computeVertexNormals(); // Gắn đầu, mắt & râu vào đốt xương số 0 const head = this.spine[0]; this.headGroup.position.set(head.x, head.y, head.z); this.headGroup.rotation.set(0, -head.yaw, head.pitch); // Gắn vây ngực trái & phải vào đốt xương số 5 (nách mang) const pecJoint = this.spine[5]; const rx = -Math.sin(pecJoint.yaw); const rz = Math.cos(pecJoint.yaw); const pecWidthOffset = 0.20 * this.scale; const rowWave = Math.sin(this.swimPhase - 0.6) * 0.16; const turnFlare = clamp(Math.abs(this.turnRate) * 14, 0, 0.45); this.leftPecMesh.position.set(pecJoint.x - rx * pecWidthOffset, pecJoint.y - 0.04 * this.scale, pecJoint.z - rz * pecWidthOffset); this.leftPecMesh.rotation.set(0.25, -pecJoint.yaw + rowWave + turnFlare, -0.22); this.rightPecMesh.position.set(pecJoint.x + rx * pecWidthOffset, pecJoint.y - 0.04 * this.scale, pecJoint.z + rz * pecWidthOffset); this.rightPecMesh.rotation.set(-0.25, -pecJoint.yaw - rowWave - turnFlare, -0.22); // Gắn vây lưng vào đốt số 8 const dorsalJoint = this.spine[8]; this.dorsalMesh.position.set(dorsalJoint.x, dorsalJoint.y + 0.21 * this.scale, dorsalJoint.z); this.dorsalMesh.rotation.set(0, -dorsalJoint.yaw + Math.sin(this.swimPhase - 1.5) * 0.08, 0); // Gắn & uốn lượn vây đuôi 3D tại đốt cuối cùng const tailJoint = this.spine[KOI_SPINE_COUNT - 1]; this.caudalMesh.position.set(tailJoint.x, tailJoint.y + 0.02 * this.scale, tailJoint.z); this.caudalMesh.rotation.set(0, -tailJoint.yaw + Math.sin(this.swimPhase - 2.9) * 0.24, 0); // Cập nhật bóng đổ mềm trên đáy hồ bên dưới thân cá const midJoint = this.spine[9]; const normDist = Math.hypot(midJoint.x / POND_RADIUS_X, midJoint.z / POND_RADIUS_Z); const bedY = POND_DEPTH + Math.pow(clamp(normDist, 0, 1.3), 2.4) * 1.65 + 0.02; const heightAboveBed = Math.max(0.05, midJoint.y - bedY); this.shadowMesh.position.set(midJoint.x + 0.18, bedY, midJoint.z + 0.24); this.shadowMesh.rotation.y = -midJoint.yaw; const shadowSpread = 1.0 + heightAboveBed * 0.35; this.shadowMesh.scale.set(shadowSpread, 1, shadowSpread); this.shadowMat.opacity = clamp(0.62 - heightAboveBed * 0.22, 0.20, 0.58); } dispose(scene) { scene.remove(this.group); scene.remove(this.shadowMesh); this.bodyGeo.dispose(); this.bodyMat.map.dispose(); this.bodyMat.dispose(); this.caudalGeo.dispose(); this.dorsalGeo.dispose(); this.finMat.dispose(); } } // ========================================================================= // 8. KIẾN TRÚC VƯỜN NHẬT 3D (BỜ ĐÁ RÊU, ỐNG TRE KAKEI, ĐÈN ĐÁ YUKIMI, SEN & TRÚC) // ========================================================================= const gardenGroup = new THREE.Group(); scene.add(gardenGroup); // Tạo đá tự nhiên 3D có bề mặt lồi lõm & đỉnh phủ rêu xanh function createMossyBoulder3D(rx, ry, rz, hasMoss = true) { const geo = new THREE.IcosahedronGeometry(1, 2); const pos = geo.attributes.position; const colors = []; const stoneCol = new THREE.Color(0x4b534f); const wetCol = new THREE.Color(0x212725); const mossCol = new THREE.Color(0x3a6b2c); for (let i = 0; i < pos.count; i++) { let vx = pos.getX(i); let vy = pos.getY(i); let vz = pos.getZ(i); const noise = 0.84 + Math.sin(vx * 4.2 + vy * 3.1) * 0.11 + Math.cos(vz * 4.7 - vx * 2.3) * 0.09; vx *= rx * noise; vy *= ry * noise; vz *= rz * noise; pos.setXYZ(i, vx, vy, vz); const c = stoneCol.clone(); if (vy < 0.05) c.lerp(wetCol, 0.65); else if (hasMoss && vy > ry * 0.35) c.lerp(mossCol, clamp((vy / ry - 0.35) * 1.4, 0, 0.85)); colors.push(c.r, c.g, c.b); } geo.setAttribute('color', new THREE.Float32BufferAttribute(colors, 3)); geo.computeVertexNormals(); const mat = new THREE.MeshStandardMaterial({ vertexColors: true, roughness: 0.86, metalness: 0.05 }); return new THREE.Mesh(geo, mat); } // Xếp vòng bờ đá rêu tự nhiên quanh hồ elip const shoreCount = 34; for (let i = 0; i < shoreCount; i++) { const a = (i / shoreCount) * Math.PI * 2 + rand(-0.04, 0.04); const rx = rand(1.1, 2.2); const ry = rand(0.55, 1.15); const rz = rand(1.0, 1.9); const rock = createMossyBoulder3D(rx, ry, rz, Math.random() < 0.82); rock.position.set( Math.cos(a) * (POND_RADIUS_X + rand(-0.2, 0.8)), ry * 0.25 - 0.1, Math.sin(a) * (POND_RADIUS_Z + rand(-0.2, 0.8)) ); rock.rotation.y = rand(0, Math.PI * 2); gardenGroup.add(rock); } // Kiến trúc 1: Ống tre dẫn nước Kakei ở góc trên bên trái (-8.2, z=-6.2) const kakeiGroup = new THREE.Group(); kakeiGroup.position.set(-8.6, 0.15, -6.2); kakeiGroup.rotation.y = -0.62; const bambooMat = new THREE.MeshStandardMaterial({ color: 0x5c8238, roughness: 0.48, metalness: 0.05 }); const bambooNodeMat = new THREE.MeshStandardMaterial({ color: 0x2f451c, roughness: 0.7 }); const ropeMat = new THREE.MeshStandardMaterial({ color: 0x1c1917, roughness: 0.95 }); // Cọc đứng & ống ngang const vPost = new THREE.Mesh(new THREE.CylinderGeometry(0.11, 0.12, 1.5, 14), bambooMat); vPost.position.set(0.9, 0.55, 0); kakeiGroup.add(vPost); const hPipe = new THREE.Mesh(new THREE.CylinderGeometry(0.10, 0.10, 2.3, 14), bambooMat); hPipe.rotation.z = Math.PI / 2 - 0.12; hPipe.position.set(1.0, 1.15, 0); kakeiGroup.add(hPipe); // Các đốt tre & dây thừng đen buộc chéo [0.35, 1.45].forEach(nx => { const ring = new THREE.Mesh(new THREE.TorusGeometry(0.105, 0.015, 8, 16), bambooNodeMat); ring.rotation.y = Math.PI / 2; ring.position.set(nx, 1.15 + (nx - 1.0) * 0.12, 0); kakeiGroup.add(ring); }); const knot = new THREE.Mesh(new THREE.TorusGeometry(0.15, 0.025, 8, 14), ropeMat); knot.position.set(0.9, 1.14, 0); knot.rotation.set(0.5, 0.4, 0.3); kakeiGroup.add(knot); // Dòng nước 3D chảy từ miệng ống tre xuống mặt hồ const streamCurve = new THREE.CatmullRomCurve3([ new THREE.Vector3(2.1, 1.0, 0), new THREE.Vector3(2.38, 0.55, 0), new THREE.Vector3(2.55, -0.18, 0) ]); const streamGeo = new THREE.TubeGeometry(streamCurve, 12, 0.032, 8, false); const streamMat = new THREE.MeshPhysicalMaterial({ color: 0xe6fbff, transparent: true, opacity: 0.72, roughness: 0.1, clearcoat: 1.0 }); const streamMesh = new THREE.Mesh(streamGeo, streamMat); kakeiGroup.add(streamMesh); gardenGroup.add(kakeiGroup); // Tọa độ điểm nước rơi từ ống tre trong không gian thế giới const kakeiSplashWorld = new THREE.Vector3(2.55, 0, 0).applyMatrix4(kakeiGroup.matrixWorld); // Kiến trúc 2: Đèn đá Nhật Bản Yukimi-dōrō 3D ở góc trên bên phải (7.8, z=-5.6) const lanternGroup = new THREE.Group(); lanternGroup.position.set(7.8, 0.15, -5.6); const graniteMat = new THREE.MeshStandardMaterial({ color: 0x6c716e, roughness: 0.88, metalness: 0.04 }); // 3 chân trụ cong for (let i = 0; i < 3; i++) { const a = (i / 3) * Math.PI * 2 + 0.3; const legCurve = new THREE.CatmullRomCurve3([ new THREE.Vector3(Math.cos(a) * 0.42, 0, Math.sin(a) * 0.42), new THREE.Vector3(Math.cos(a) * 0.36, 0.38, Math.sin(a) * 0.36), new THREE.Vector3(Math.cos(a) * 0.18, 0.72, Math.sin(a) * 0.18) ]); const leg = new THREE.Mesh(new THREE.TubeGeometry(legCurve, 8, 0.075, 8, false), graniteMat); lanternGroup.add(leg); } // Bệ đỡ lục giác const baseDisc = new THREE.Mesh(new THREE.CylinderGeometry(0.48, 0.52, 0.14, 6), graniteMat); baseDisc.position.y = 0.76; lanternGroup.add(baseDisc); // Lồng đèn phát sáng (Washi paper core) const fireBoxMat = new THREE.MeshStandardMaterial({ color: 0xffe4a0, emissive: 0xff9922, emissiveIntensity: 0.0, roughness: 0.6 }); const fireBox = new THREE.Mesh(new THREE.CylinderGeometry(0.28, 0.28, 0.44, 6), fireBoxMat); fireBox.position.y = 1.05; lanternGroup.add(fireBox); // 6 cột khung đá quanh lồng đèn for (let i = 0; i < 6; i++) { const a = (i / 6) * Math.PI * 2; const pillar = new THREE.Mesh(new THREE.CylinderGeometry(0.035, 0.035, 0.46, 6), graniteMat); pillar.position.set(Math.cos(a) * 0.31, 1.05, Math.sin(a) * 0.31); lanternGroup.add(pillar); } // Mái chóp lục giác Yukimi (ngắm tuyết) & viên ngọc Hōju trên đỉnh const roof = new THREE.Mesh(new THREE.ConeGeometry(0.82, 0.42, 6), graniteMat); roof.position.y = 1.48; lanternGroup.add(roof); const finial = new THREE.Mesh(new THREE.SphereGeometry(0.11, 10, 10), graniteMat); finial.position.y = 1.74; lanternGroup.add(finial); gardenGroup.add(lanternGroup); // Kiến trúc 3: Lá sen 3D nổi & Hoa sen nhiều tầng cánh const lilyPadObjects = []; function createLilyPadAndLotus3D(x, z, radius, hasFlower = false) { const group = new THREE.Group(); group.position.set(x, 0.018, z); group.rotation.y = rand(0, Math.PI * 2); // Lá sen có vết khuyết chữ V đặc trưng const padGeo = new THREE.CircleGeometry(radius, 28, 0.22, Math.PI * 2 - 0.44); padGeo.rotateX(-Math.PI / 2); const padMat = new THREE.MeshStandardMaterial({ map: lilyPadTex, roughness: 0.65, side: THREE.DoubleSide }); const padMesh = new THREE.Mesh(padGeo, padMat); group.add(padMesh); if (hasFlower) { const flowerGroup = new THREE.Group(); flowerGroup.position.set(radius * 0.15, 0.03, 0); const isPink = Math.random() > 0.35; const petalMat = new THREE.MeshStandardMaterial({ color: isPink ? 0xf7a8c4 : 0xffffff, roughness: 0.45, side: THREE.DoubleSide }); // 3 tầng cánh hoa sen 3D xòe tự nhiên const tiers = [ { count: 10, len: 0.28, wid: 0.10, tilt: 0.42 }, { count: 8, len: 0.23, wid: 0.085, tilt: 0.78 }, { count: 6, len: 0.17, wid: 0.07, tilt: 1.12 } ]; tiers.forEach((t, ti) => { for (let i = 0; i < t.count; i++) { const pGeo = new THREE.SphereGeometry(t.len, 8, 6, 0, Math.PI * 0.4, 0, Math.PI * 0.5); pGeo.scale(1, 0.35, t.wid / t.len); const petal = new THREE.Mesh(pGeo, petalMat); const a = (i / t.count) * Math.PI * 2 + ti * 0.3; petal.rotation.set(0, a, t.tilt); flowerGroup.add(petal); } }); // Nhụy vàng ở tâm hoa const centerPod = new THREE.Mesh( new THREE.CylinderGeometry(0.065, 0.04, 0.07, 10), new THREE.MeshStandardMaterial({ color: 0xe6b83a, roughness: 0.6 }) ); centerPod.position.y = 0.04; flowerGroup.add(centerPod); group.add(flowerGroup); } gardenGroup.add(group); lilyPadObjects.push({ group, baseX: x, baseZ: z, phase: rand(0, Math.PI * 2), bobAmp: 0 }); } // Bố trí 3 cụm lá sen & hoa sen quanh hồ createLilyPadAndLotus3D(6.8, 4.8, 0.72, true); createLilyPadAndLotus3D(7.9, 4.1, 0.55, false); createLilyPadAndLotus3D(6.1, 5.8, 0.48, false); createLilyPadAndLotus3D(-7.2, 5.1, 0.75, true); createLilyPadAndLotus3D(-8.3, 4.2, 0.52, false); createLilyPadAndLotus3D(1.4, -6.5, 0.62, false); // Kiến trúc 4: Khóm trúc Nhật xanh mướt ven bờ đá tạo chiều sâu vườn thiền const bambooGrovePositions = [ [-11.8, -6.8], [-12.3, -5.9], [-11.4, -7.6], [-12.6, -4.8], [11.6, -6.4], [12.2, -5.5], [11.2, -7.3] ]; bambooGrovePositions.forEach(([bx, bz], idx) => { const h = rand(3.6, 5.4); const stalkGroup = new THREE.Group(); stalkGroup.position.set(bx, 0.2, bz); stalkGroup.rotation.set(rand(-0.06, 0.06), rand(0, Math.PI), rand(-0.07, 0.07)); const stalk = new THREE.Mesh( new THREE.CylinderGeometry(0.065, 0.085, h, 10), idx % 2 === 0 ? bambooMat : bambooNodeMat ); stalk.position.y = h * 0.5; stalkGroup.add(stalk); const nodes = Math.floor(h / 0.85); for (let n = 1; n < nodes; n++) { const ring = new THREE.Mesh(new THREE.TorusGeometry(0.08, 0.012, 6, 12), bambooNodeMat); ring.rotation.x = Math.PI / 2; ring.position.y = n * 0.85; stalkGroup.add(ring); } gardenGroup.add(stalkGroup); }); // Kiến trúc 5: Cánh hoa anh đào Sakura & lá phong đỏ trôi lững lờ trên mặt nước const floatingPetals = []; const petalShapeGeo = new THREE.CircleGeometry(0.075, 6); petalShapeGeo.scale(1.35, 0.75, 1); petalShapeGeo.rotateX(-Math.PI / 2); const sakuraPetalMat = new THREE.MeshStandardMaterial({ color: 0xffc8da, roughness: 0.5, side: THREE.DoubleSide }); const mapleLeafMat = new THREE.MeshStandardMaterial({ color: 0xd94826, roughness: 0.6, side: THREE.DoubleSide }); for (let i = 0; i < 24; i++) { const isSakura = i < 16; const mesh = new THREE.Mesh(petalShapeGeo, isSakura ? sakuraPetalMat : mapleLeafMat); const a = rand(0, Math.PI * 2); const r = Math.sqrt(Math.random()) * 0.86; mesh.position.set( Math.cos(a) * POND_RADIUS_X * r, 0.014, Math.sin(a) * POND_RADIUS_Z * r ); mesh.rotation.y = rand(0, Math.PI * 2); const s = isSakura ? rand(0.75, 1.15) : rand(1.15, 1.65); mesh.scale.set(s, 1, s); scene.add(mesh); floatingPetals.push({ mesh, angle: rand(0, Math.PI * 2), speed: rand(0.08, 0.22), spin: rand(-0.4, 0.4), phase: rand(0, Math.PI * 2) }); } // ========================================================================= // 9. HẠT MỒI 3D (FOOD PELLETS) & HẠT MƯA PHÙN 3D // ========================================================================= const pellets3D = []; const acousticCalls3D = []; const pelletGeo = new THREE.SphereGeometry(0.068, 10, 8); const pelletMat = new THREE.MeshStandardMaterial({ color: 0xd6903e, roughness: 0.65 }); function spawnFoodPellet3D(x, z) { if (pellets3D.length >= 40) { const oldest = pellets3D.shift(); scene.remove(oldest.mesh); } const mesh = new THREE.Mesh(pelletGeo, pelletMat); mesh.position.set(x, 0.02, z); scene.add(mesh); pellets3D.push({ mesh, vx: rand(-0.15, 0.15), vz: rand(-0.15, 0.15), phase: rand(0, Math.PI * 2), eaten: false }); } // Hệ thống hạt mưa phùn 3D const rainCount = 350; const rainPositions = new Float32Array(rainCount * 6); for (let i = 0; i < rainCount; i++) { const rx = rand(-15, 15); const ry = rand(0, 14); const rz = rand(-12, 12); rainPositions[i * 6] = rx; rainPositions[i * 6 + 1] = ry; rainPositions[i * 6 + 2] = rz; rainPositions[i * 6 + 3] = rx - 0.06; rainPositions[i * 6 + 4] = ry - 0.42; rainPositions[i * 6 + 5] = rz; } const rainGeo = new THREE.BufferGeometry(); rainGeo.setAttribute('position', new THREE.BufferAttribute(rainPositions, 3)); const rainMat = new THREE.LineBasicMaterial({ color: 0xcbe8f0, transparent: true, opacity: 0.0 }); const rainLines = new THREE.LineSegments(rainGeo, rainMat); scene.add(rainLines); // ========================================================================= // 10. QUẢN LÝ ĐÀN CÁ KOI 3D & ĐIỀU KHIỂN CAMERA QUỸ ĐẠO (ORBIT + RAYCAST) // ========================================================================= let kois3D = []; function syncFishCount3D() { while (kois3D.length < state.targetFishCount) { const breedIdx = kois3D.length < KOI_BREEDS_3D.length ? kois3D.length : null; const a = rand(0, Math.PI * 2); const r = rand(1.0, 6.5); kois3D.push(new KoiFish3D( scene, Math.cos(a) * r, rand(-0.75, -0.35), // Trạng thái Camera 3D mượt mà (Tự động cân chỉnh khoảng cách theo tỉ lệ khung hình) let currentCamPreset = 'angled'; function getAspectDistanceMultiplier() { const aspect = window.innerWidth / Math.max(window.innerHeight, 1); if (aspect >= 1.2) return 1.0; // Trên màn hình dọc (điện thoại), lùi camera ra hợp lý để thấy trọn chiều ngang hồ return clamp(1.18 / Math.max(aspect, 0.45), 1.0, 1.52); } const camState = { theta: 0.0, phi: 0.72, radius: 17.5 * getAspectDistanceMultiplier(), targetTheta: 0.0, targetPhi: 0.72, targetRadius: 17.5 * getAspectDistanceMultiplier(), lookAt: new THREE.Vector3(0, -0.2, 0.3), targetLookAt: new THREE.Vector3(0, -0.2, 0.3) }; function setCameraPreset(preset) { currentCamPreset = preset; const mult = getAspectDistanceMultiplier(); if (preset === 'angled') { camState.targetTheta = 0.0; camState.targetPhi = 0.72; camState.targetRadius = 17.5 * mult; camState.targetLookAt.set(0, -0.2, 0.3); } else if (preset === 'top') { camState.targetTheta = 0.0; camState.targetPhi = 0.14; camState.targetRadius = 18.8 * mult; camState.targetLookAt.set(0, -0.2, 0); } else if (preset === 'lantern') { camState.targetTheta = -0.58; camState.targetPhi = 0.96; camState.targetRadius = 13.5 * Math.min(mult, 1.28); camState.targetLookAt.set(2.2, 0.1, -1.8); } } // Raycaster xác định tọa độ chạm chính xác trên mặt nước 3D (y = 0) const raycaster = new THREE.Raycaster(); const pointerNDC = new THREE.Vector2(); const waterPlane = new THREE.Plane(new THREE.Vector3(0, 1, 0), 0); const hitPoint3D = new THREE.Vector3(); function getWaterHitPoint(clientX, clientY) { pointerNDC.x = (clientX / window.innerWidth) * 2 - 1; pointerNDC.y = -(clientY / window.innerHeight) * 2 + 1; raycaster.setFromCamera(pointerNDC, camera); const hit = raycaster.ray.intersectPlane(waterPlane, hitPoint3D); if (!hit) return null; // Giới hạn trong phạm vi mặt hồ if (Math.hypot(hit.x / POND_RADIUS_X, hit.z / POND_RADIUS_Z) > 1.02) return null; return hit; } let isPointerDown = false; let isRightMouseOrbit = false; let prevX = 0; let prevY = 0; let dragDist = 0; let moveCooldown = 0; let zenHideTimer = null; const btnExitZen = document.getElementById('btnExitZen'); function revealExitZenButton() { if (!state.zenMode) return; btnExitZen.classList.remove('opacity-0', 'pointer-events-none'); btnExitZen.classList.add('opacity-95'); clearTimeout(zenHideTimer); zenHideTimer = setTimeout(() => { if (state.zenMode) { btnExitZen.classList.add('opacity-0', 'pointer-events-none'); btnExitZen.classList.remove('opacity-95'); } }, 2800); } function handleWaterAction(pt) { if (!pt) return; if (state.mode === 'feed') { const count = Math.floor(rand(2, 4)); for (let i = 0; i < count; i++) { spawnFoodPellet3D(pt.x + rand(-0.35, 0.35), pt.z + rand(-0.35, 0.35)); } spawnWaterRipple3D(pt.x, pt.z, 1.1); audioEngine.playWaterDrop(510, 0.11); } else if (state.mode === 'clap') { acousticCalls3D.push({ x: pt.x, z: pt.z, life: 4.5 }); if (acousticCalls3D.length > 2) acousticCalls3D.shift(); spawnWaterRipple3D(pt.x, pt.z, 1.8); audioEngine.playClapCall(); } else if (state.mode === 'touch') { spawnWaterRipple3D(pt.x, pt.z, 1.65); kois3D.forEach(k => k.startleFrom(pt.x, pt.z, 1.15)); lilyPadObjects.forEach(lp => { if (Math.hypot(lp.baseX - pt.x, lp.baseZ - pt.z) < 3.5) lp.bobAmp = 0.045; }); audioEngine.playWaterDrop(340, 0.08); } } container.addEventListener('contextmenu', (e) => e.preventDefault()); container.addEventListener('mousedown', (e) => { revealExitZenButton(); isPointerDown = true; isRightMouseOrbit = (e.button === 2 || e.shiftKey || state.mode === 'orbit'); prevX = e.clientX; prevY = e.clientY; dragDist = 0; if (!isRightMouseOrbit) { const pt = getWaterHitPoint(e.clientX, e.clientY); handleWaterAction(pt); } }); window.addEventListener('mousemove', (e) => { revealExitZenButton(); const dx = e.clientX - prevX; const dy = e.clientY - prevY; prevX = e.clientX; prevY = e.clientY; if (isPointerDown) { dragDist += Math.hypot(dx, dy); if (isRightMouseOrbit) { camState.targetTheta -= dx * 0.0065; camState.targetPhi = clamp(camState.targetPhi - dy * 0.0055, 0.12, 1.18); return; } } if (moveCooldown <= 0 && Math.hypot(dx, dy) > 4) { const pt = getWaterHitPoint(e.clientX, e.clientY); if (pt) { moveCooldown = 0.055; const amp = (state.mode === 'touch' && isPointerDown) ? 1.35 : 0.48; spawnWaterRipple3D(pt.x, pt.z, amp); if (state.mode === 'touch' && isPointerDown) { kois3D.forEach(k => k.startleFrom(pt.x, pt.z, 0.85)); } } } }); window.addEventListener('mouseup', () => { isPointerDown = false; isRightMouseOrbit = false; }); container.addEventListener('wheel', (e) => { e.preventDefault(); const maxZoom = 26.0 * getAspectDistanceMultiplier(); camState.targetRadius = clamp(camState.targetRadius + e.deltaY * 0.012, 8.0, maxZoom); }, { passive: false }); // Hỗ trợ cảm ứng đa điểm (1 ngón tương tác/xoay, 2 ngón thu phóng 3D) let lastPinchDist = 0; container.addEventListener('touchstart', (e) => { revealExitZenButton(); if (e.touches.length === 1) { isPointerDown = true; const t = e.touches[0]; prevX = t.clientX; prevY = t.clientY; if (state.mode !== 'orbit') { handleWaterAction(getWaterHitPoint(t.clientX, t.clientY)); } } else if (e.touches.length === 2) { lastPinchDist = Math.hypot( e.touches[0].clientX - e.touches[1].clientX, e.touches[0].clientY - e.touches[1].clientY ); } }, { passive: true }); container.addEventListener('touchmove', (e) => { if (e.touches.length === 1 && isPointerDown) { const t = e.touches[0]; const dx = t.clientX - prevX; const dy = t.clientY - prevY; prevX = t.clientX; prevY = t.clientY; if (state.mode === 'orbit') { camState.targetTheta -= dx * 0.0075; camState.targetPhi = clamp(camState.targetPhi - dy * 0.0065, 0.12, 1.18); } else if (moveCooldown <= 0) { const pt = getWaterHitPoint(t.clientX, t.clientY); if (pt) { moveCooldown = 0.06; spawnWaterRipple3D(pt.x, pt.z, state.mode === 'touch' ? 1.35 : 0.55); if (state.mode === 'touch') kois3D.forEach(k => k.startleFrom(pt.x, pt.z, 0.85)); } } } else if (e.touches.length === 2) { const d = Math.hypot( e.touches[0].clientX - e.touches[1].clientX, e.touches[0].clientY - e.touches[1].clientY ); if (lastPinchDist > 0) { const maxZoom = 26.0 * getAspectDistanceMultiplier(); camState.targetRadius = clamp(camState.targetRadius - (d - lastPinchDist) * 0.04, 8.0, maxZoom); } lastPinchDist = d; } }, { passive: true }); container.addEventListener('touchend', () => { isPointerDown = false; lastPinchDist = 0; }); // ========================================================================= // 11. KẾT NỐI BẢNG ĐIỀU KHIỂN GIAO DIỆN TIẾNG VIỆT // ========================================================================= const modeBtns = { feed: document.getElementById('btnModeFeed'), clap: document.getElementById('btnModeClap'), touch: document.getElementById('btnModeTouch'), orbit: document.getElementById('btnModeOrbit') }; const modeHint = document.getElementById('modeHint'); const statusBadge = document.getElementById('statusBadge'); function updateModeUI() { const inactive = 'zen-btn flex flex-col sm:flex-row items-center justify-center gap-1 py-2 px-1.5 rounded-lg text-[11px] sm:text-xs font-medium text-stone-300/85 hover:text-white hover:bg-white/5 border border-transparent'; const activeStyles = { feed: 'bg-amber-500/25 text-amber-200 border-amber-400/35 shadow-sm', clap: 'bg-rose-500/25 text-rose-200 border-rose-400/35 shadow-sm', touch: 'bg-sky-500/25 text-sky-200 border-sky-400/35 shadow-sm', orbit: 'bg-emerald-500/25 text-emerald-200 border-emerald-400/35 shadow-sm' }; Object.keys(modeBtns).forEach(k => { modeBtns[k].className = k === state.mode ? `zen-btn flex flex-col sm:flex-row items-center justify-center gap-1 py-2 px-1.5 rounded-lg text-[11px] sm:text-xs font-medium border ${activeStyles[k]}` : inactive; }); container.classList.toggle('orbit-cursor', state.mode === 'orbit'); const isTouch = deviceProfile.isTouchDevice; if (state.mode === 'feed') { modeHint.textContent = isTouch ? 'Chạm mặt nước để thả mồi • Chụm 2 ngón để thu phóng 3D' : 'Chạm mặt nước 3D để thả mồi • Chuột phải xoay 360° & lăn chuột thu phóng'; } else if (state.mode === 'clap') { modeHint.textContent = 'Chạm mặt nước để vỗ tay tạo sóng âm gọi đàn cá tụ lại'; } else if (state.mode === 'touch') { modeHint.textContent = 'Chạm hoặc rê trên mặt nước để tạo sóng khúc xạ thực tế'; } else { modeHint.textContent = isTouch ? 'Kéo 1 ngón xoay 360° quanh hồ • Chụm 2 ngón để thu phóng' : 'Kéo chuột để xoay góc nhìn 360° quanh hồ • Lăn chuột để thu phóng'; } } // Nút thu gọn/mở rộng bảng điều khiển trên màn hình điện thoại nhỏ const btnToggleMobilePanel = document.getElementById('btnToggleMobilePanel'); const controlPanelBody = document.getElementById('controlPanelBody'); let isMobilePanelCollapsed = false; if (btnToggleMobilePanel && controlPanelBody) { btnToggleMobilePanel.addEventListener('click', () => { isMobilePanelCollapsed = !isMobilePanelCollapsed; controlPanelBody.classList.toggle('hidden', isMobilePanelCollapsed); btnToggleMobilePanel.textContent = isMobilePanelCollapsed ? 'Mở rộng' : 'Thu gọn'; }); } Object.keys(modeBtns).forEach(k => { modeBtns[k].addEventListener('click', () => { state.mode = k; updateModeUI(); }); }); document.querySelectorAll('.cam-btn').forEach(btn => { btn.addEventListener('click', () => { setCameraPreset(btn.dataset.cam); document.querySelectorAll('.cam-btn').forEach(b => { b.className = b === btn ? 'cam-btn zen-btn px-2.5 py-1.5 rounded-lg text-xs font-medium bg-amber-500/25 text-amber-100 border border-amber-400/35' : 'cam-btn zen-btn px-2.5 py-1.5 rounded-lg text-xs font-medium text-stone-300 hover:text-white hover:bg-white/5 border border-transparent'; }); }); }); document.querySelectorAll('.theme-btn').forEach(btn => { btn.addEventListener('click', () => { state.themeKey = btn.dataset.theme; document.querySelectorAll('.theme-btn').forEach(b => { const active = b.dataset.theme === state.themeKey; const styles = { morning: 'bg-teal-500/25 text-teal-100 border-teal-400/35', sunset: 'bg-amber-500/25 text-amber-100 border-amber-400/35', moonlight: 'bg-indigo-500/30 text-indigo-100 border-indigo-400/35', drizzle: 'bg-cyan-500/25 text-cyan-100 border-cyan-400/35' }; b.className = active ? `theme-btn zen-btn py-1.5 px-1.5 rounded-lg text-[11px] sm:text-xs font-medium border ${styles[state.themeKey]}` : 'theme-btn zen-btn py-1.5 px-1.5 rounded-lg text-[11px] sm:text-xs font-medium text-stone-300/85 hover:text-white hover:bg-white/5 border border-transparent'; }); audioEngine.updateWeatherMix(SCENE_THEMES[state.themeKey].rainAmount); }); }); const fishSlider = document.getElementById('fishSlider'); const fishCountLabel = document.getElementById('fishCountLabel'); function setFishCount(val) { const count = clamp(parseInt(val, 10) || 10, 4, 16); state.targetFishCount = count; fishSlider.value = count; fishCountLabel.textContent = `${count} con`; syncFishCount3D(); } fishSlider.addEventListener('input', (e) => setFishCount(e.target.value)); document.getElementById('btnFishMinus').addEventListener('click', () => setFishCount(state.targetFishCount - 1)); document.getElementById('btnFishPlus').addEventListener('click', () => setFishCount(state.targetFishCount + 1)); const btnAudio = document.getElementById('btnAudio'); const audioLabel = document.getElementById('audioLabel'); const iconAudioOff = document.getElementById('iconAudioOff'); const iconAudioOn = document.getElementById('iconAudioOn'); btnAudio.addEventListener('click', () => { state.audioEnabled = audioEngine.toggle(!state.audioEnabled); if (state.audioEnabled) { audioLabel.textContent = 'Âm thanh: Bật'; iconAudioOff.classList.add('hidden'); iconAudioOn.classList.remove('hidden'); btnAudio.classList.add('border-emerald-400/35', 'bg-emerald-500/15', 'text-emerald-100'); } else { audioLabel.textContent = 'Âm thanh: Tắt'; iconAudioOff.classList.remove('hidden'); iconAudioOn.classList.add('hidden'); btnAudio.classList.remove('border-emerald-400/35', 'bg-emerald-500/15', 'text-emerald-100'); } }); const controlPanel = document.getElementById('controlPanel'); const headerOverlay = document.getElementById('headerOverlay'); const cameraBar = document.getElementById('cameraBar'); function setZenMode(enable) { state.zenMode = enable; if (enable) { controlPanel.classList.add('ui-hidden'); headerOverlay.classList.add('ui-hidden'); cameraBar.classList.add('ui-hidden'); revealExitZenButton(); } else { controlPanel.classList.remove('ui-hidden'); headerOverlay.classList.remove('ui-hidden'); cameraBar.classList.remove('ui-hidden'); btnExitZen.classList.add('opacity-0', 'pointer-events-none'); btnExitZen.classList.remove('opacity-95'); clearTimeout(zenHideTimer); } } document.getElementById('btnZenMode').addEventListener('click', () => setZenMode(true)); btnExitZen.addEventListener('click', () => setZenMode(false)); // ========================================================================= // 12. VÒNG LẶP KẾT XUẤT 3D HAI LƯỢT (REFRACTION PASS + MAIN WATER PASS) // ========================================================================= function handleViewportResize() { deviceProfile = getDeviceProfile(); const { w, h, aspect, pixelRatio, refractionScale } = deviceProfile; camera.fov = aspect < 0.85 ? 48 : (aspect < 1.15 ? 45 : 42); camera.aspect = aspect; camera.updateProjectionMatrix(); renderer.setPixelRatio(pixelRatio); renderer.setSize(w, h); refractionTarget.setSize(Math.floor(w * refractionScale), Math.floor(h * refractionScale)); waterUniforms.uResolution.value.set(w, h); setCameraPreset(currentCamPreset); updateModeUI(); } window.addEventListener('resize', handleViewportResize); window.addEventListener('orientationchange', () => setTimeout(handleViewportResize, 120)); let lastTime = performance.now(); let kakeiTimer = 0; function animate(now) { requestAnimationFrame(animate); const dt = Math.min((now - lastTime) / 1000, 0.05); lastTime = now; state.time += dt; if (moveCooldown > 0) moveCooldown -= dt; // 1. Nội suy mượt mà ánh sáng & màu sắc theo bối cảnh thời tiết const targetTheme = SCENE_THEMES[state.themeKey]; const blend = Math.min(dt * 3.0, 1); scene.background.lerp(targetTheme.skyTop, blend); scene.fog.color.lerp(targetTheme.fogColor, blend); waterUniforms.uDeepColor.value.lerp(targetTheme.waterDeep, blend); waterUniforms.uShallowColor.value.lerp(targetTheme.waterShallow, blend); waterUniforms.uSkyReflectColor.value.lerp(targetTheme.skyReflect, blend); waterUniforms.uSunColor.value.lerp(targetTheme.sunColor, blend); waterUniforms.uSunDir.value.lerp(targetTheme.sunPos.clone().normalize(), blend); sunLight.color.lerp(targetTheme.sunColor, blend); sunLight.intensity = lerp(sunLight.intensity, targetTheme.sunIntensity, blend); sunLight.position.lerp(targetTheme.sunPos, blend); hemiLight.color.lerp(targetTheme.hemiSky, blend); hemiLight.groundColor.lerp(targetTheme.hemiGround, blend); hemiLight.intensity = lerp(hemiLight.intensity, targetTheme.hemiIntensity, blend); causticUniforms.uTime.value = state.time; causticUniforms.uCausticStrength.value = lerp(causticUniforms.uCausticStrength.value, targetTheme.causticStrength, blend); waterUniforms.uTime.value = state.time; const flicker = 0.9 + Math.sin(state.time * 10) * 0.06 + Math.cos(state.time * 16) * 0.04; const currentLantern = lerp(lanternLight.intensity, targetTheme.lanternIntensity * flicker, blend); lanternLight.intensity = currentLantern; fireBoxMat.emissiveIntensity = currentLantern * 0.55; waterUniforms.uLanternIntensity.value = currentLantern * 0.35; // 2. Cập nhật vị trí Camera 3D mượt mà camState.theta = lerp(camState.theta, camState.targetTheta, 0.08); camState.phi = lerp(camState.phi, camState.targetPhi, 0.08); camState.radius = lerp(camState.radius, camState.targetRadius, 0.08); camState.lookAt.lerp(camState.targetLookAt, 0.08); camera.position.x = camState.lookAt.x + camState.radius * Math.sin(camState.phi) * Math.sin(camState.theta); camera.position.y = camState.lookAt.y + camState.radius * Math.cos(camState.phi); camera.position.z = camState.lookAt.z + camState.radius * Math.sin(camState.phi) * Math.cos(camState.theta); camera.lookAt(camState.lookAt); // 3. Sóng tự nhiên từ ống tre Kakei & mưa phùn kakeiTimer -= dt; if (kakeiTimer <= 0) { kakeiTimer = 0.52; spawnWaterRipple3D(kakeiSplashWorld.x, kakeiSplashWorld.z, 0.72); } if (targetTheme.rainAmount > 0.05) { rainMat.opacity = lerp(rainMat.opacity, 0.36, blend); const rPos = rainGeo.attributes.position.array; for (let i = 0; i < rainCount; i++) { rPos[i * 6 + 1] -= 18 * dt; rPos[i * 6 + 4] -= 18 * dt; if (rPos[i * 6 + 1] <= 0) { if (Math.random() < 0.06) { spawnWaterRipple3D(rPos[i * 6], rPos[i * 6 + 2], 0.32); } const ny = rand(10, 15); rPos[i * 6 + 1] = ny; rPos[i * 6 + 4] = ny - 0.42; } } rainGeo.attributes.position.needsUpdate = true; } else { rainMat.opacity = lerp(rainMat.opacity, 0.0, blend); } // 4. Cập nhật hạt mồi 3D, lá sen bồng bềnh & đàn cá Koi 3D for (let i = acousticCalls3D.length - 1; i >= 0; i--) { acousticCalls3D[i].life -= dt; if (acousticCalls3D[i].life <= 0) acousticCalls3D.splice(i, 1); } for (let i = pellets3D.length - 1; i >= 0; i--) { const p = pellets3D[i]; if (p.eaten) { scene.remove(p.mesh); pellets3D.splice(i, 1); continue; } p.phase += dt * 3.5; p.mesh.position.x += p.vx * dt; p.mesh.position.z += p.vz * dt; p.mesh.position.y = 0.015 + Math.sin(p.phase) * 0.008; p.vx *= 0.96; p.vz *= 0.96; } statusBadge.textContent = acousticCalls3D.length > 0 ? 'Đang gọi đàn cá...' : `${pellets3D.length} hạt mồi`; lilyPadObjects.forEach(lp => { lp.bobAmp = lerp(lp.bobAmp, 0.006, 0.05); lp.group.position.y = 0.018 + Math.sin(state.time * 1.8 + lp.phase) * lp.bobAmp; lp.group.rotation.z = Math.sin(state.time * 1.4 + lp.phase) * lp.bobAmp * 1.2; }); floatingPetals.forEach(fp => { fp.angle += Math.sin(state.time * 0.4 + fp.phase) * 0.18 * dt; fp.mesh.position.x += Math.cos(fp.angle) * fp.speed * dt; fp.mesh.position.z += Math.sin(fp.angle) * fp.speed * dt; fp.mesh.position.y = 0.014 + Math.sin(state.time * 2.2 + fp.phase) * 0.004; fp.mesh.rotation.y += fp.spin * dt; // Giữ cánh hoa trôi nhẹ nhàng bên trong mặt hồ if (Math.hypot(fp.mesh.position.x / (POND_RADIUS_X - 1.2), fp.mesh.position.z / (POND_RADIUS_Z - 1.0)) > 0.95) { fp.angle = Math.atan2(-fp.mesh.position.z, -fp.mesh.position.x) + rand(-0.5, 0.5); } }); for (let i = 0; i < kois3D.length; i++) { kois3D[i].update(dt, kois3D, pellets3D, acousticCalls3D); } // 5. LƯỢT KẾT XUẤT 1 (Refraction Pass): Chụp thế giới dưới mặt nước vào RenderTarget waterMesh.visible = false; renderer.setRenderTarget(refractionTarget); renderer.clear(); renderer.render(scene, camera); // 6. LƯỢT KẾT XUẤT 2 (Main Pass): Hiển thị mặt nước 3D khúc xạ & phản chiếu hoàn chỉnh waterMesh.visible = true; renderer.setRenderTarget(null); renderer.render(scene, camera); } window.onload = () => { updateModeUI(); syncFishCount3D(); spawnWaterRipple3D(0, 0, 1.1); const loader = document.getElementById('loadingOverlay'); loader.style.opacity = '0'; setTimeout(() => loader.remove(), 700); lastTime = performance.now(); requestAnimationFrame(animate); }; })();