First-person VR mode, calendar system, agent fixes, player character
Browse files- First-person mode (WASD+mouse) with PointerLockControls
- WebXR VR support for headsets
- Player can join city as playable character with HUD
- NPCs face the player when nearby in FP mode
- Calendar system starting 1 April 2026 with seasons
- Weather: 75% sunny, snow only in winter, rain other seasons
- Aging tied to calendar (1 year = 365 days, not tick-based)
- Moon phases (full/half/quarter/new, 28-day cycle)
- Agents always visible (no indoor hiding)
- Windows semi-transparent in interior view
- Dead agents show death date/age, no needs bars
- Agent movement speed 4x faster
- Sleeping agents lie along beds (not perpendicular)
- Furniture marked isFurniture for interior view
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
105 unmodified lines10610710810911011141 unmodified lines1531541551561571588 unmodified lines167168169170171172487 unmodified lines66066166266366466566666766866967067167267367467567667767867968068168268368435 unmodified lines720721722723724725726727728729730731732733653 unmodified lines13871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424216 unmodified lines16411642164316441645164616471648164916501651165216531 unmodified line165516561657165816591660180 unmodified lines18411842184318441845184618471848433 unmodified lines22822283228422852286228722882289229022912292229322942295229622972298229923002301136 unmodified lines2438243924402441244224432444244524462447244824492450245124522453245424552456245724589 unmodified lines246824692470247124722473247424752476120 unmodified lines25972598259926002601260226032604260526062607260826092 unmodified lines261226132614261526162617261856 unmodified lines267526762677267826792680268126822683268426857 unmodified lines269326942695269626972698269927002701270227032704270584 unmodified lines279027912792279327942795279610 unmodified lines28072808280928102811281228132814281528162817281828192820282127 unmodified lines284928502851285228532854285584 unmodified lines294029412942294329442945294629472948294929502951295229532954295513 unmodified lines29692970297129722973297429752976297729782979298029812982298329842985298629872988298971 unmodified lines3061306230633064306530663067306818 unmodified lines30873088308930903091309230933 unmodified lines3097309830993100310131023103310431053106310731083109105 unmodified lines.ctrl-btn:hover { background: rgba(30,30,50,0.85); color: #fff; }.ctrl-btn.active { background: rgba(78,204,163,0.3); border-color: #4ecca3; color: #4ecca3; }#loading {position: fixed; inset: 0;display: flex; flex-direction: column;41 unmodified lines<button class="ctrl-btn" onclick="toggleTopDown()" title="Top-down view">▲</button><button class="ctrl-btn" onclick="zoomIn()" title="Zoom in">+</button><button class="ctrl-btn" onclick="zoomOut()" title="Zoom out">−</button></div><script type="importmap">8 unmodified lines<script type="module">import * as THREE from 'three';import { OrbitControls } from 'three/addons/controls/OrbitControls.js';// ============================================================// CONSTANTS487 unmodified linesgroup.add(win);}// Bed (visible when house is transparent at night)const bed = new THREE.Mesh(new THREE.BoxGeometry(1.2, 0.15, 0.7),mat(0x8b6040));bed.position.set(0.6, 0.08, 0);group.add(bed);const mattress = new THREE.Mesh(new THREE.BoxGeometry(1.1, 0.1, 0.6),mat(0xe8e0d0));mattress.position.set(0.6, 0.18, 0);group.add(mattress);const pillow = new THREE.Mesh(new THREE.BoxGeometry(0.25, 0.08, 0.35),mat(0xf0f0f0));pillow.position.set(1.1, 0.24, 0);group.add(pillow);const label = createLabel(locData.label, group, wallH + roofH + 1);const badge = createOccupantBadge(group, wallH + roofH);35 unmodified lines}}// Beds inside (visible at night through transparent walls)for (let bx = -1; bx <= 1; bx += 2) {const bed = new THREE.Mesh(new THREE.BoxGeometry(1.0, 0.12, 0.5), mat(0x8b6040));bed.position.set(bx * 1.2, 0.06, 0);group.add(bed);const matt = new THREE.Mesh(new THREE.BoxGeometry(0.9, 0.08, 0.45), mat(0xe0d8c8));matt.position.set(bx * 1.2, 0.14, 0);group.add(matt);}const label = createLabel(locData.label, group, wallH + 2);653 unmodified linesconst chairMat = mat(0x6a5030);const deskMat = mat(0xa09080);if (FOOD_LOCS.has(id)) {for (let i = -1; i <= 1; i++) {const table = new THREE.Mesh(new THREE.BoxGeometry(0.7, 0.4, 0.7), tableMat);table.position.set(i * 1.2, 0.2, 0);group.add(table);for (let s of [-0.5, 0.5]) {const chair = new THREE.Mesh(new THREE.BoxGeometry(0.3, 0.25, 0.3), chairMat);chair.position.set(i * 1.2 + s, 0.125, 0.5);group.add(chair);const back = new THREE.Mesh(new THREE.BoxGeometry(0.3, 0.3, 0.05), chairMat);back.position.set(i * 1.2 + s, 0.35, 0.65);group.add(back);}}} else if (DESK_LOCS.has(id)) {for (let i = -1; i <= 1; i += 2) {const desk = new THREE.Mesh(new THREE.BoxGeometry(1.2, 0.45, 0.6), deskMat);desk.position.set(i * 1.3, 0.225, 0);group.add(desk);const ch = new THREE.Mesh(new THREE.BoxGeometry(0.3, 0.25, 0.3), chairMat);ch.position.set(i * 1.3, 0.125, 0.5);group.add(ch);}} else if (SEAT_LOCS.has(id)) {for (let row = 0; row < 2; row++) {for (let col = -1; col <= 1; col++) {const seat = new THREE.Mesh(new THREE.BoxGeometry(0.4, 0.25, 0.35), chairMat);seat.position.set(col * 0.7, 0.125, -0.5 + row * 0.8);group.add(seat);const sb = new THREE.Mesh(new THREE.BoxGeometry(0.4, 0.35, 0.05), chairMat);sb.position.set(col * 0.7, 0.35, -0.5 + row * 0.8 + 0.18);group.add(sb);}}}216 unmodified linessunSprite.renderOrder = -1;scene.add(sunSprite);// Moonconst moonGeo = new THREE.SphereGeometry(4, 32, 32);const moonMat = new THREE.MeshBasicMaterial({ color: 0xeeeeff, transparent: true, opacity: 0.95 });const moonMesh = new THREE.Mesh(moonGeo, moonMat);moonMesh.renderOrder = -1;moonMesh.visible = false;scene.add(moonMesh);const moonGlow = new THREE.Sprite(new THREE.SpriteMaterial({ map: celestialTex(0xaabbee), transparent: true, depthTest: false }));1 unmodified linemoonGlow.renderOrder = -2;moonGlow.visible = false;scene.add(moonGlow);// Starsconst starCount = 500;180 unmodified linesmoonMesh.visible = true;moonGlow.position.set(mx, my, mz - 1);moonGlow.visible = true;} else {moonMesh.visible = false;moonGlow.visible = false;}starPoints.visible = hour >= 18 || hour <= 5;433 unmodified linesconst bldg = buildingMeshes.get(buildingId);if (!bldg) return;bldg.traverse(child => {if (child.isMesh && !child.userData?.isWindow && !child.userData?.isDoor) {child.userData._savedOpacity = child.material.opacity;child.userData._savedTransparent = child.material.transparent;child.userData._savedDepthWrite = child.material.depthWrite;child.material.transparent = true;child.material.opacity = 0.12;child.material.depthWrite = false;}if (child.isMesh && child.userData?.isWindow) {child.userData._savedOpacity = child.material.opacity;child.userData._savedTransparent = child.material.transparent;child.material.transparent = true;child.material.opacity = 0.15;}});smoothZoomTo(bldg.position, 8);}136 unmodified lineshtml += `<div class="info-section">`;html += `<h4>Status</h4>`;html += `<div class="info-row"><span class="label">Location</span><span class="value">${data.location_name || data.location || '?'}</span></div>`;html += `<div class="info-row"><span class="label">State</span><span class="value">${data.state || '?'}</span></div>`;html += `<div class="info-row"><span class="label">Action</span><span class="value">${data.current_action || data.action || data.state || '?'}</span></div>`;if (data.mood !== undefined) {html += `<div class="info-row"><span class="label">Mood</span><span class="value">${typeof data.mood === 'number' ? (data.mood * 100).toFixed(0) + '%' : data.mood}</span></div>`;}if (data.age !== undefined) {html += `<div class="info-row"><span class="label">Age</span><span class="value">${data.age}</span></div>`;}if (data.gender) {html += `<div class="info-row"><span class="label">Gender</span><span class="value">${data.gender}</span></div>`;}if (data.occupation) {html += `<div class="info-row"><span class="label">Occupation</span><span class="value">${data.occupation}</span></div>`;}if (data.lifePhase) {html += `<div class="info-row"><span class="label">Life Phase</span><span class="value">${data.lifePhase}</span></div>`;}html += `</div>`;9 unmodified lineshtml += `</div>`;}// Needsconst needs = data.needs || {};if (Object.keys(needs).length > 0) {html += `<div class="info-section"><h4>Needs</h4>`;for (const [need, val] of Object.entries(needs)) {const pct = typeof val === 'number' ? val * 100 : parseFloat(val) * 100;120 unmodified linesconst clock = new THREE.Clock();let frameCount = 0;function animate() {requestAnimationFrame(animate);const dt = clock.getDelta();frameCount++;controls.update();updateCameraAnimation();// Smooth agent movementfor (const [agentId, mesh] of agentMeshes) {2 unmodified linesconst dx = target.x - mesh.position.x;const dz = target.z - mesh.position.z;const dist0 = Math.sqrt(dx * dx + dz * dz);const speed = 0.03;if (dist0 > speed) {let mx = (dx / dist0) * speed;56 unmodified lines}}// Agent visibility: hide inside buildings unless interior view is activeconst agentLoc2 = mesh.userData.data?.location || '';const locInfo2 = LOCATION_POSITIONS[agentLoc2] || dynamicLocations[agentLoc2];const isOutdoorLoc = OUTDOOR_LOCS.has(agentLoc2) || locInfo2?.type === 'park' || locInfo2?.type === 'square' || locInfo2?.type === 'sports';mesh.visible = isOutdoorLoc || agentLoc2 === interiorBuildingId;// Sleeping, sitting, walking, or idle animationconst agentState = mesh.userData.data?.state || '';7 unmodified linesconst isSitting = !moving && atLocation && SITTING_LOCS.has(agentLoc);if (isSleeping) {mesh.rotation.x = Math.PI / 2;mesh.rotation.z = 0;mesh.position.y = 0.35;if (mesh.userData.leftLeg) mesh.userData.leftLeg.rotation.x = 0.15;if (mesh.userData.rightLeg) mesh.userData.rightLeg.rotation.x = -0.08;if (mesh.userData.leftArm) mesh.userData.leftArm.rotation.x = 0.6;if (mesh.userData.rightArm) mesh.userData.rightArm.rotation.x = 0.4;} else if (isSitting) {mesh.rotation.x = 0;mesh.position.y = 0.0;84 unmodified linesif (cloud.position.x > 70) cloud.position.x = -70;}renderer.render(scene, camera);}// ============================================================10 unmodified linesrenderer.setSize(w, h);});// ============================================================// KEYBOARD// ============================================================document.addEventListener('keydown', (e) => {if (e.key === 'Escape') closeInfoPanel();if (e.key === 'r' || e.key === 'R') resetCamera();if (e.key === '+' || e.key === '=') zoomIn();if (e.key === '-') zoomOut();});// ============================================================// FALLBACK: REST polling if WebSocket isn't available27 unmodified lines}connectWebSocket();setInterval(pollFallback, 3000);animate();updateDetailLevel();let demoSpeedMultiplier = 1.0;84 unmodified lineslet demoDay = 1;let demoMinute = 630;const DEMO_WEATHER_CYCLE = ['sunny','sunny','sunny','cloudy','cloudy','rainy','stormy','rainy','cloudy','sunny','sunny','snowy','cloudy','sunny','foggy','sunny'];let demoWIdx = 0;let tickCount = 0;const deadAgents = [];function demoTimeStr() {const hh = Math.floor(demoMinute / 60);const mm = demoMinute % 60;const phase = hh >= 5 && hh < 7 ? 'dawn' : hh >= 7 && hh < 12 ? 'morning' : hh >= 12 && hh < 17 ? 'afternoon' : hh >= 17 && hh < 20 ? 'evening' : 'night';return `Day ${demoDay}, ${String(hh).padStart(2,'0')}:${String(mm).padStart(2,'0')} (${phase})`;}function getLifePlan(id) {13 unmodified linesconst aliveIds = allIds.filter(id => agentLife[id]?.alive);tickCount++;// Age all agents every 72 ticks (~1 sim-day ≈ 72 ticks of 20min → 1 year per ~3 real-min cycles)if (tickCount % 6 === 0) {for (const id of aliveIds) {agentLife[id].age++;demoAgents[id].age = agentLife[id].age;const a = agentLife[id].age;if (a === 3) { agentLife[id].lifePhase = 'kindergarten'; agentLife[id].occupation = 'Child'; }if (a === 6) { agentLife[id].lifePhase = 'school'; agentLife[id].occupation = 'Student'; agentMemories[id].push('Started school'); }if (a === 18) { agentLife[id].lifePhase = 'university'; agentLife[id].occupation = 'Student'; agentMemories[id].push('Graduated high school'); }if (a === 23) { agentLife[id].lifePhase = 'working'; agentLife[id].occupation = OCCUPATIONS[hash(id) % OCCUPATIONS.length]; agentMemories[id].push(`Started career as ${agentLife[id].occupation}`); }if (a === 65) { agentLife[id].lifePhase = 'retired'; agentMemories[id].push('Retired'); }demoAgents[id].occupation = agentLife[id].occupation;demoAgents[id].lifePhase = agentLife[id].lifePhase;}}// Marriage: every 4 ticks, try to match single adultsif (tickCount % 4 === 0) {71 unmodified linesagentLife[id].alive = false;demoAgents[id].location = 'cemetery';demoAgents[id].state = 'deceased';deadAgents.push({ id, name: demoAgents[id].name, age: a, day: demoDay });agentMemories[id].push(`Passed away at age ${a} (Day ${demoDay})`);if (agentLife[id].partner) {const p = agentLife[id].partner;agentLife[p].partner = null;18 unmodified lineshandleStateUpdate({type: 'tick', time: demoTimeStr(),state: { agents: demoAgents, locations: {}, weather: DEMO_WEATHER_CYCLE[0] }});document.getElementById('sim-agents').textContent = `${Object.keys(demoAgents).length} agents (demo)`;3 unmodified linesif (wsConnected || demoPaused) return;demoMinute += 20;if (demoMinute >= 1440) { demoMinute -= 1440; demoDay++; }const hh = Math.floor(demoMinute / 60);if (demoMinute % 60 === 0 && hh % 3 === 0) {demoWIdx = (demoWIdx + 1) % DEMO_WEATHER_CYCLE.length;}const w = DEMO_WEATHER_CYCLE[demoWIdx];const badW = w === 'rainy' || w === 'stormy' || w === 'snowy';const isNightTime = hh >= 22 || hh < 6;const isLateEvening = hh >= 20 && hh < 22;105 unmodified lines10610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914041 unmodified lines1821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132148 unmodified lines223224225226227228229487 unmodified lines71771871972072172272372472572672772872935 unmodified lines765766767768769770771772773774775776653 unmodified lines1430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469216 unmodified lines16861687168816891690169116921693169416951696169716981699170017011702170317041 unmodified line1706170717081709171017111712171317141715171617171718171917201721172217231724180 unmodified lines1905190619071908190919101911191219131914433 unmodified lines234823492350235123522353235423552356235723582359236023612362236323642365136 unmodified lines25022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825299 unmodified lines253925402541254225432544254525462547120 unmodified lines26682669267026712672267326742675267626772678267926802681268226832684268526862 unmodified lines268926902691269226932694269556 unmodified lines27522753275427552756275727587 unmodified lines276627672768276927702771277227732774277527762777277884 unmodified lines286328642865286628672868286910 unmodified lines28802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310727 unmodified lines31353136313731383139314084 unmodified lines322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329113 unmodified lines330533063307330833093310331171 unmodified lines3383338433853386338733883389339033913392339318 unmodified lines34123413341434153416341734183 unmodified lines3422342334243425342634273428342934303431343234333434105 unmodified lines.ctrl-btn:hover { background: rgba(30,30,50,0.85); color: #fff; }.ctrl-btn.active { background: rgba(78,204,163,0.3); border-color: #4ecca3; color: #4ecca3; }#player-login {position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%);background: rgba(10,10,18,0.95); border: 1px solid rgba(78,204,163,0.4);border-radius: 12px; padding: 24px 32px; z-index: 300; display: none;backdrop-filter: blur(16px); min-width: 280px; text-align: center;}#player-login h2 { color: #4ecca3; margin: 0 0 16px; font-size: 18px; font-weight: 400; letter-spacing: 2px; }#player-login input {width: 100%; padding: 8px 12px; margin: 6px 0; border: 1px solid rgba(255,255,255,0.15);border-radius: 6px; background: rgba(255,255,255,0.06); color: #e0e0e8; font-size: 14px;box-sizing: border-box;}#player-login select {width: 100%; padding: 8px 12px; margin: 6px 0; border: 1px solid rgba(255,255,255,0.15);border-radius: 6px; background: rgba(20,20,35,0.9); color: #e0e0e8; font-size: 14px;}#player-login button {margin-top: 12px; padding: 8px 24px; border: none; border-radius: 6px;background: #4ecca3; color: #0a0a12; font-size: 14px; cursor: pointer; font-weight: 600;}#player-login button:hover { background: #6be0b8; }#player-hud {position: fixed; top: 50px; left: 12px; background: rgba(10,10,18,0.8);border: 1px solid rgba(78,204,163,0.3); border-radius: 8px; padding: 10px 14px;z-index: 60; display: none; font-size: 12px; color: #ccc; min-width: 160px;backdrop-filter: blur(8px);}#player-hud .phud-name { color: #4ecca3; font-size: 14px; font-weight: 500; margin-bottom: 6px; }#loading {position: fixed; inset: 0;display: flex; flex-direction: column;41 unmodified lines<button class="ctrl-btn" onclick="toggleTopDown()" title="Top-down view">▲</button><button class="ctrl-btn" onclick="zoomIn()" title="Zoom in">+</button><button class="ctrl-btn" onclick="zoomOut()" title="Zoom out">−</button><button class="ctrl-btn" id="btn-fp" onclick="window._toggleFP()" title="First-person view">👁</button><button class="ctrl-btn" id="btn-vr" style="display:none" title="Enter VR">VR</button><button class="ctrl-btn" id="btn-join" onclick="window._showJoin()" title="Join as player">JOIN</button></div><div id="fp-crosshair" style="display:none;position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);pointer-events:none;z-index:50"><svg width="24" height="24"><circle cx="12" cy="12" r="3" fill="none" stroke="rgba(255,255,255,0.6)" stroke-width="1"/><line x1="12" y1="4" x2="12" y2="8" stroke="rgba(255,255,255,0.4)" stroke-width="1"/><line x1="12" y1="16" x2="12" y2="20" stroke="rgba(255,255,255,0.4)" stroke-width="1"/><line x1="4" y1="12" x2="8" y2="12" stroke="rgba(255,255,255,0.4)" stroke-width="1"/><line x1="16" y1="12" x2="20" y2="12" stroke="rgba(255,255,255,0.4)" stroke-width="1"/></svg></div><div id="fp-hint" style="display:none;position:fixed;bottom:60px;left:50%;transform:translateX(-50%);background:rgba(0,0,0,0.7);color:#fff;padding:8px 16px;border-radius:8px;font-size:13px;z-index:50;text-align:center">WASD — move · Mouse — look · ESC — exit · E — interact</div><div id="player-login"><h2>JOIN SOCI CITY</h2><input id="player-name" type="text" placeholder="Your name..." maxlength="20"><select id="player-gender"><option value="male">Male</option><option value="female">Female</option></select><select id="player-age"><option value="20">20</option><option value="25">25</option><option value="30">30</option><option value="35">35</option><option value="40">40</option></select><br><button onclick="window._joinCity()">Enter City</button><button onclick="document.getElementById('player-login').style.display='none'" style="background:transparent;color:#888;border:1px solid rgba(255,255,255,0.15);margin-left:8px">Cancel</button></div><div id="player-hud"><div class="phud-name" id="phud-name"></div><div id="phud-stats"></div></div><script type="importmap">8 unmodified lines<script type="module">import * as THREE from 'three';import { OrbitControls } from 'three/addons/controls/OrbitControls.js';import { PointerLockControls } from 'three/addons/controls/PointerLockControls.js';// ============================================================// CONSTANTS487 unmodified linesgroup.add(win);}// Bedconst bed = new THREE.Mesh(new THREE.BoxGeometry(1.2, 0.15, 0.7), mat(0x8b6040));bed.position.set(0.6, 0.08, 0); bed.userData.isFurniture = true; group.add(bed);const mattress = new THREE.Mesh(new THREE.BoxGeometry(1.1, 0.1, 0.6), mat(0xe8e0d0));mattress.position.set(0.6, 0.18, 0); mattress.userData.isFurniture = true; group.add(mattress);const pillow = new THREE.Mesh(new THREE.BoxGeometry(0.25, 0.08, 0.35), mat(0xf0f0f0));pillow.position.set(1.1, 0.24, 0); pillow.userData.isFurniture = true; group.add(pillow);const label = createLabel(locData.label, group, wallH + roofH + 1);const badge = createOccupantBadge(group, wallH + roofH);35 unmodified lines}}// Beds insidefor (let bx = -1; bx <= 1; bx += 2) {const bed = new THREE.Mesh(new THREE.BoxGeometry(1.0, 0.12, 0.5), mat(0x8b6040));bed.position.set(bx * 1.2, 0.06, 0); bed.userData.isFurniture = true; group.add(bed);const matt = new THREE.Mesh(new THREE.BoxGeometry(0.9, 0.08, 0.45), mat(0xe0d8c8));matt.position.set(bx * 1.2, 0.14, 0); matt.userData.isFurniture = true; group.add(matt);}const label = createLabel(locData.label, group, wallH + 2);653 unmodified linesconst chairMat = mat(0x6a5030);const deskMat = mat(0xa09080);function addF(mesh) { mesh.userData.isFurniture = true; group.add(mesh); }if (FOOD_LOCS.has(id)) {for (let i = -1; i <= 1; i++) {const table = new THREE.Mesh(new THREE.BoxGeometry(0.7, 0.4, 0.7), tableMat);table.position.set(i * 1.2, 0.2, 0);addF(table);for (let s of [-0.5, 0.5]) {const chair = new THREE.Mesh(new THREE.BoxGeometry(0.3, 0.25, 0.3), chairMat);chair.position.set(i * 1.2 + s, 0.125, 0.5);addF(chair);const back = new THREE.Mesh(new THREE.BoxGeometry(0.3, 0.3, 0.05), chairMat);back.position.set(i * 1.2 + s, 0.35, 0.65);addF(back);}}} else if (DESK_LOCS.has(id)) {for (let i = -1; i <= 1; i += 2) {const desk = new THREE.Mesh(new THREE.BoxGeometry(1.2, 0.45, 0.6), deskMat);desk.position.set(i * 1.3, 0.225, 0);addF(desk);const ch = new THREE.Mesh(new THREE.BoxGeometry(0.3, 0.25, 0.3), chairMat);ch.position.set(i * 1.3, 0.125, 0.5);addF(ch);}} else if (SEAT_LOCS.has(id)) {for (let row = 0; row < 2; row++) {for (let col = -1; col <= 1; col++) {const seat = new THREE.Mesh(new THREE.BoxGeometry(0.4, 0.25, 0.35), chairMat);seat.position.set(col * 0.7, 0.125, -0.5 + row * 0.8);addF(seat);const sb = new THREE.Mesh(new THREE.BoxGeometry(0.4, 0.35, 0.05), chairMat);sb.position.set(col * 0.7, 0.35, -0.5 + row * 0.8 + 0.18);addF(sb);}}}216 unmodified linessunSprite.renderOrder = -1;scene.add(sunSprite);// Moon with phasesconst moonGeo = new THREE.SphereGeometry(4, 32, 32);const moonMat = new THREE.MeshBasicMaterial({ color: 0xeeeeff, transparent: true, opacity: 0.95 });const moonMesh = new THREE.Mesh(moonGeo, moonMat);moonMesh.renderOrder = -1;moonMesh.visible = false;scene.add(moonMesh);const moonShadowGeo = new THREE.SphereGeometry(4.05, 32, 32);const moonShadowMat = new THREE.MeshBasicMaterial({ color: 0x0e1530, transparent: true, opacity: 0.92 });const moonShadow = new THREE.Mesh(moonShadowGeo, moonShadowMat);moonShadow.renderOrder = -0.5;moonShadow.visible = false;scene.add(moonShadow);const moonGlow = new THREE.Sprite(new THREE.SpriteMaterial({ map: celestialTex(0xaabbee), transparent: true, depthTest: false }));1 unmodified linemoonGlow.renderOrder = -2;moonGlow.visible = false;scene.add(moonGlow);let moonPhaseDay = 0;function getMoonPhase(day) {const phase = (day % 28) / 28;return phase;}function updateMoonPhase(day) {const phase = getMoonPhase(day);const offset = Math.cos(phase * Math.PI * 2) * 4.5;moonShadow.position.copy(moonMesh.position);moonShadow.position.x += offset;moonShadow.visible = moonMesh.visible;moonGlow.material.opacity = moonMesh.visible ? (0.15 + 0.45 * (0.5 + 0.5 * Math.cos(phase * Math.PI * 2))) : 0;}// Starsconst starCount = 500;180 unmodified linesmoonMesh.visible = true;moonGlow.position.set(mx, my, mz - 1);moonGlow.visible = true;updateMoonPhase(moonPhaseDay);} else {moonMesh.visible = false;moonShadow.visible = false;moonGlow.visible = false;}starPoints.visible = hour >= 18 || hour <= 5;433 unmodified linesconst bldg = buildingMeshes.get(buildingId);if (!bldg) return;bldg.traverse(child => {if (!child.isMesh) return;if (child.userData?.isFurniture || child.userData?.isDoor) return;child.userData._savedOpacity = child.material.opacity;child.userData._savedTransparent = child.material.transparent;child.userData._savedDepthWrite = child.material.depthWrite;child.material.transparent = true;if (child.userData?.isWindow) {child.material.opacity = 0.25;} else {child.material.opacity = 0.08;child.material.depthWrite = false;}});smoothZoomTo(bldg.position, 8);}136 unmodified lineshtml += `<div class="info-section">`;html += `<h4>Status</h4>`;html += `<div class="info-row"><span class="label">Location</span><span class="value">${data.location_name || data.location || '?'}</span></div>`;const isDead = data.state === 'deceased';if (isDead) {html += `<div class="info-row"><span class="label">State</span><span class="value" style="color:#e94560">Deceased</span></div>`;if (data.deathDate) html += `<div class="info-row"><span class="label">Death</span><span class="value">${data.deathDate}</span></div>`;if (data.deathAge) html += `<div class="info-row"><span class="label">Age at death</span><span class="value">${data.deathAge}</span></div>`;} else {html += `<div class="info-row"><span class="label">State</span><span class="value">${data.state || '?'}</span></div>`;html += `<div class="info-row"><span class="label">Action</span><span class="value">${data.current_action || data.action || data.state || '?'}</span></div>`;if (data.mood !== undefined) {html += `<div class="info-row"><span class="label">Mood</span><span class="value">${typeof data.mood === 'number' ? (data.mood * 100).toFixed(0) + '%' : data.mood}</span></div>`;}}if (data.age !== undefined && !isDead) {html += `<div class="info-row"><span class="label">Age</span><span class="value">${data.age}</span></div>`;}if (data.gender) {html += `<div class="info-row"><span class="label">Gender</span><span class="value">${data.gender}</span></div>`;}if (data.occupation && !isDead) {html += `<div class="info-row"><span class="label">Occupation</span><span class="value">${data.occupation}</span></div>`;}if (data.lifePhase && !isDead) {html += `<div class="info-row"><span class="label">Life Phase</span><span class="value">${data.lifePhase}</span></div>`;}html += `</div>`;9 unmodified lineshtml += `</div>`;}// Needs (hide for deceased)const needs = data.needs || {};if (!isDead && Object.keys(needs).length > 0) {html += `<div class="info-section"><h4>Needs</h4>`;for (const [need, val] of Object.entries(needs)) {const pct = typeof val === 'number' ? val * 100 : parseFloat(val) * 100;120 unmodified linesconst clock = new THREE.Clock();let frameCount = 0;renderer.setAnimationLoop(animate);function animate() {const dt = clock.getDelta();frameCount++;if (fpMode) {updateFPMovement();updateNPCFacing();updatePlayerPosition();} else {controls.update();updateCameraAnimation();}// Smooth agent movementfor (const [agentId, mesh] of agentMeshes) {2 unmodified linesconst dx = target.x - mesh.position.x;const dz = target.z - mesh.position.z;const dist0 = Math.sqrt(dx * dx + dz * dz);const speed = 0.12;if (dist0 > speed) {let mx = (dx / dist0) * speed;56 unmodified lines}}mesh.visible = true;// Sleeping, sitting, walking, or idle animationconst agentState = mesh.userData.data?.state || '';7 unmodified linesconst isSitting = !moving && atLocation && SITTING_LOCS.has(agentLoc);if (isSleeping) {mesh.rotation.x = 0;mesh.rotation.z = Math.PI / 2;mesh.position.y = 0.30;if (mesh.userData.leftLeg) mesh.userData.leftLeg.rotation.x = 0.1;if (mesh.userData.rightLeg) mesh.userData.rightLeg.rotation.x = -0.1;if (mesh.userData.leftArm) mesh.userData.leftArm.rotation.x = 0.3;if (mesh.userData.rightArm) mesh.userData.rightArm.rotation.x = 0.3;} else if (isSitting) {mesh.rotation.x = 0;mesh.position.y = 0.0;84 unmodified linesif (cloud.position.x > 70) cloud.position.x = -70;}renderer.render(scene, fpMode ? fpCamera : camera);}// ============================================================10 unmodified linesrenderer.setSize(w, h);});// ============================================================// FIRST-PERSON / VR MODE// ============================================================let fpMode = false;const fpCamera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 500);fpCamera.position.set(0, 1.8, 10);const fpControls = new PointerLockControls(fpCamera, renderer.domElement);const fpMoveState = { forward: false, backward: false, left: false, right: false };const fpVelocity = new THREE.Vector3();const fpDirection = new THREE.Vector3();const FP_SPEED = 12;const FP_HEIGHT = 1.8;let fpClock = new THREE.Clock();fpControls.addEventListener('lock', () => {document.getElementById('fp-crosshair').style.display = 'block';document.getElementById('fp-hint').style.display = 'block';setTimeout(() => { document.getElementById('fp-hint').style.display = 'none'; }, 5000);});fpControls.addEventListener('unlock', () => {document.getElementById('fp-crosshair').style.display = 'none';if (fpMode) {setTimeout(() => { if (fpMode) fpControls.lock(); }, 200);}});function enterFPMode() {fpMode = true;fpCamera.position.set(0, FP_HEIGHT, 10);fpCamera.aspect = window.innerWidth / window.innerHeight;fpCamera.updateProjectionMatrix();controls.enabled = false;fpControls.lock();fpClock.start();document.getElementById('btn-fp').classList.add('active');document.getElementById('btn-fp').title = 'Exit first-person';}function exitFPMode() {fpMode = false;fpControls.unlock();controls.enabled = true;fpClock.stop();document.getElementById('fp-crosshair').style.display = 'none';document.getElementById('fp-hint').style.display = 'none';document.getElementById('btn-fp').classList.remove('active');document.getElementById('btn-fp').title = 'First-person view';}window._toggleFP = () => {if (fpMode) exitFPMode(); else enterFPMode();};function updateFPMovement() {if (!fpMode) return;const delta = Math.min(fpClock.getDelta(), 0.1);fpDirection.z = Number(fpMoveState.forward) - Number(fpMoveState.backward);fpDirection.x = Number(fpMoveState.right) - Number(fpMoveState.left);fpDirection.normalize();fpVelocity.x = fpDirection.x * FP_SPEED * delta;fpVelocity.z = fpDirection.z * FP_SPEED * delta;fpControls.moveRight(fpVelocity.x);fpControls.moveForward(fpVelocity.z);fpCamera.position.y = FP_HEIGHT;// Keep within world boundsfpCamera.position.x = Math.max(-HALF, Math.min(HALF, fpCamera.position.x));fpCamera.position.z = Math.max(-HALF, Math.min(HALF, fpCamera.position.z));}// FP interaction: E key to interact with nearest agent/buildingfunction fpInteract() {if (!fpMode) return;const ray = new THREE.Raycaster();ray.setFromCamera(new THREE.Vector2(0, 0), fpCamera);ray.far = 10;const agentObjs = [];for (const [, m] of agentMeshes) agentObjs.push(m);const hits = ray.intersectObjects(agentObjs, true);if (hits.length > 0) {let p = hits[0].object;while (p.parent && !p.userData?.id) p = p.parent;if (p.userData?.id && p.userData.type === 'agent') {selectAgent(p.userData.id);return;}}const bldgObjs = [];for (const [, m] of buildingMeshes) bldgObjs.push(m);const bHits = ray.intersectObjects(bldgObjs, true);if (bHits.length > 0) {let p = bHits[0].object;while (p.parent && !p.userData?.id) p = p.parent;if (p.userData?.id) {selectBuilding(p.userData.id);enterInterior(p.userData.id);}}}// WebXR supportif (navigator.xr) {navigator.xr.isSessionSupported('immersive-vr').then(supported => {if (supported) {const vrBtn = document.getElementById('btn-vr');vrBtn.style.display = '';vrBtn.onclick = () => {navigator.xr.requestSession('immersive-vr', { optionalFeatures: ['local-floor', 'hand-tracking'] }).then(session => {renderer.xr.enabled = true;renderer.xr.setSession(session);fpCamera.position.set(0, FP_HEIGHT, 10);session.addEventListener('end', () => { renderer.xr.enabled = false; });});};}});}// NPC facing: make nearby agents turn toward the player in FP modefunction updateNPCFacing() {if (!fpMode) return;const pp = fpCamera.position;for (const [, mesh] of agentMeshes) {const dx = pp.x - mesh.position.x;const dz = pp.z - mesh.position.z;const dist = Math.sqrt(dx * dx + dz * dz);if (dist < 8 && dist > 0.3) {mesh.rotation.y = Math.atan2(dx, dz);}}}// Resize handler for FP camerawindow.addEventListener('resize', () => {fpCamera.aspect = window.innerWidth / window.innerHeight;fpCamera.updateProjectionMatrix();});// ============================================================// PLAYER CHARACTER// ============================================================let playerData = null;let playerMesh = null;window._showJoin = () => {document.getElementById('player-login').style.display = 'block';};window._joinCity = () => {const name = document.getElementById('player-name').value.trim() || 'Player';const gender = document.getElementById('player-gender').value;const age = parseInt(document.getElementById('player-age').value) || 25;document.getElementById('player-login').style.display = 'none';playerData = { name, gender, age, location: 'town_square', state: 'exploring', needs: { hunger: 0.8, energy: 0.9, social: 0.6, fun: 0.7 } };const playerAgentData = { ...playerData, occupation: 'Explorer', lifePhase: 'playing' };playerMesh = createAgentMesh('player', playerAgentData);const sq = LOCATION_POSITIONS['town_square'];const pos = toWorld(sq.x, sq.y);playerMesh.position.set(pos.x, 0, pos.z);document.getElementById('player-hud').style.display = 'block';document.getElementById('phud-name').textContent = name;updatePlayerHUD();document.getElementById('btn-join').textContent = 'PLAYING';document.getElementById('btn-join').classList.add('active');enterFPMode();fpCamera.position.set(pos.x, FP_HEIGHT, pos.z + 2);};function updatePlayerHUD() {if (!playerData) return;const n = playerData.needs;let html = '';for (const [k, v] of Object.entries(n)) {const pct = (v * 100).toFixed(0);const color = v > 0.6 ? '#4ecca3' : v > 0.3 ? '#f0c040' : '#e94560';html += `<div style="display:flex;align-items:center;gap:4px;margin:2px 0">`;html += `<span style="width:50px;color:#aaa">${k}</span>`;html += `<div style="flex:1;height:6px;background:rgba(255,255,255,0.1);border-radius:3px"><div style="width:${pct}%;height:100%;background:${color};border-radius:3px"></div></div>`;html += `<span style="width:28px;text-align:right;color:#888">${pct}%</span></div>`;}document.getElementById('phud-stats').innerHTML = html;}function updatePlayerPosition() {if (!playerData || !playerMesh || !fpMode) return;playerMesh.position.set(fpCamera.position.x, 0, fpCamera.position.z);playerMesh.rotation.y = fpCamera.rotation.y;playerMesh.visible = false;}// ============================================================// KEYBOARD// ============================================================document.addEventListener('keydown', (e) => {if (e.key === 'Escape') { if (fpMode) { exitFPMode(); return; } closeInfoPanel(); }if (fpMode) {if (e.key === 'w' || e.key === 'W' || e.key === 'ArrowUp') fpMoveState.forward = true;if (e.key === 's' || e.key === 'S' || e.key === 'ArrowDown') fpMoveState.backward = true;if (e.key === 'a' || e.key === 'A' || e.key === 'ArrowLeft') fpMoveState.left = true;if (e.key === 'd' || e.key === 'D' || e.key === 'ArrowRight') fpMoveState.right = true;if (e.key === 'e' || e.key === 'E') fpInteract();return;}if (e.key === 'r' || e.key === 'R') resetCamera();if (e.key === '+' || e.key === '=') zoomIn();if (e.key === '-') zoomOut();});document.addEventListener('keyup', (e) => {if (e.key === 'w' || e.key === 'W' || e.key === 'ArrowUp') fpMoveState.forward = false;if (e.key === 's' || e.key === 'S' || e.key === 'ArrowDown') fpMoveState.backward = false;if (e.key === 'a' || e.key === 'A' || e.key === 'ArrowLeft') fpMoveState.left = false;if (e.key === 'd' || e.key === 'D' || e.key === 'ArrowRight') fpMoveState.right = false;});// ============================================================// FALLBACK: REST polling if WebSocket isn't available27 unmodified lines}connectWebSocket();setInterval(pollFallback, 3000);updateDetailLevel();let demoSpeedMultiplier = 1.0;84 unmodified lineslet demoDay = 1;let demoMinute = 630;let demoMonth = 4; // Start April 1stlet demoDayOfMonth = 1;let demoYear = 2026;function getSeason() {if (demoMonth >= 3 && demoMonth <= 5) return 'spring';if (demoMonth >= 6 && demoMonth <= 8) return 'summer';if (demoMonth >= 9 && demoMonth <= 11) return 'autumn';return 'winter';}const DAYS_IN_MONTH = [0,31,28,31,30,31,30,31,31,30,31,30,31];function advanceCalendar() {demoDayOfMonth++;if (demoDayOfMonth > DAYS_IN_MONTH[demoMonth]) {demoDayOfMonth = 1;demoMonth++;if (demoMonth > 12) { demoMonth = 1; demoYear++; ageAllAgents(); }}}function ageAllAgents() {for (const id of allIds) {if (!agentLife[id]?.alive) continue;agentLife[id].age++;demoAgents[id].age = agentLife[id].age;const a = agentLife[id].age;if (a === 3) { agentLife[id].lifePhase = 'kindergarten'; agentLife[id].occupation = 'Child'; }if (a === 6) { agentLife[id].lifePhase = 'school'; agentLife[id].occupation = 'Student'; agentMemories[id].push('Started school'); }if (a === 18) { agentLife[id].lifePhase = 'university'; agentLife[id].occupation = 'Student'; agentMemories[id].push('Graduated high school'); }if (a === 23) { agentLife[id].lifePhase = 'working'; agentLife[id].occupation = OCCUPATIONS[hash(id) % OCCUPATIONS.length]; agentMemories[id].push(`Started career as ${agentLife[id].occupation}`); }if (a === 65) { agentLife[id].lifePhase = 'retired'; agentMemories[id].push('Retired'); }demoAgents[id].occupation = agentLife[id].occupation;demoAgents[id].lifePhase = agentLife[id].lifePhase;}}let currentDemoWeather = 'sunny';function pickWeather() {const season = getSeason();const r = Math.random();if (r < 0.75) return 'sunny';if (season === 'winter') {if (r < 0.82) return 'cloudy';if (r < 0.92) return 'snowy';if (r < 0.97) return 'foggy';return 'stormy';}if (r < 0.84) return 'cloudy';if (r < 0.94) return 'rainy';if (r < 0.97) return 'foggy';return 'stormy';}let tickCount = 0;const deadAgents = [];const MONTH_NAMES = ['','Яну','Фев','Мар','Апр','Май','Юни','Юли','Авг','Сеп','Окт','Ное','Дек'];function demoTimeStr() {const hh = Math.floor(demoMinute / 60);const mm = demoMinute % 60;const phase = hh >= 5 && hh < 7 ? 'dawn' : hh >= 7 && hh < 12 ? 'morning' : hh >= 12 && hh < 17 ? 'afternoon' : hh >= 17 && hh < 20 ? 'evening' : 'night';return `Day ${demoDay} (${demoDayOfMonth} ${MONTH_NAMES[demoMonth]} ${demoYear}), ${String(hh).padStart(2,'0')}:${String(mm).padStart(2,'0')} (${phase})`;}function getLifePlan(id) {13 unmodified linesconst aliveIds = allIds.filter(id => agentLife[id]?.alive);tickCount++;// Aging is now handled by calendar (ageAllAgents on Jan 1)// Marriage: every 4 ticks, try to match single adultsif (tickCount % 4 === 0) {71 unmodified linesagentLife[id].alive = false;demoAgents[id].location = 'cemetery';demoAgents[id].state = 'deceased';demoAgents[id].deathDate = `${demoDayOfMonth} ${MONTH_NAMES[demoMonth]} ${demoYear}`;demoAgents[id].deathAge = a;demoAgents[id].needs = null;deadAgents.push({ id, name: demoAgents[id].name, age: a, day: demoDay });agentMemories[id].push(`Passed away at age ${a} (${demoDayOfMonth} ${MONTH_NAMES[demoMonth]} ${demoYear})`);if (agentLife[id].partner) {const p = agentLife[id].partner;agentLife[p].partner = null;18 unmodified lineshandleStateUpdate({type: 'tick', time: demoTimeStr(),state: { agents: demoAgents, locations: {}, weather: currentDemoWeather }});document.getElementById('sim-agents').textContent = `${Object.keys(demoAgents).length} agents (demo)`;3 unmodified linesif (wsConnected || demoPaused) return;demoMinute += 20;if (demoMinute >= 1440) { demoMinute -= 1440; demoDay++; moonPhaseDay++; advanceCalendar(); }const hh = Math.floor(demoMinute / 60);if (demoMinute % 60 === 0 && hh === 6) {currentDemoWeather = pickWeather();}const w = currentDemoWeather;const badW = w === 'rainy' || w === 'stormy' || w === 'snowy';const isNightTime = hh >= 22 || hh < 6;const isLateEvening = hh >= 20 && hh < 22;
web/3d.html+421-96