awacke1 commited on
Commit
a375863
·
verified ·
1 Parent(s): 36738a6

Update index.html

Browse files
Files changed (1) hide show
  1. index.html +538 -808
index.html CHANGED
@@ -1,818 +1,548 @@
1
- import * as THREE from 'three';
2
- import * as CANNON from 'cannon-es';
3
- // import CannonDebugger from 'cannon-es-debugger'; // Keep commented for now
4
-
5
- // --- DOM Elements ---
6
- const sceneContainer = document.getElementById('scene-container');
7
- const statsElement = document.getElementById('stats-display');
8
- const inventoryElement = document.getElementById('inventory-display');
9
- const logElement = document.getElementById('log-display');
10
-
11
- // --- Config ---
12
- const ROOM_SIZE = 10;
13
- const WALL_HEIGHT = 3; // Slightly shorter walls
14
- const WALL_THICKNESS = 0.5;
15
- const CAMERA_Y_OFFSET = 25; // Higher camera
16
- const PLAYER_SPEED = 6;
17
- const PLAYER_RADIUS = 0.5;
18
- const PLAYER_HEIGHT = 1.8; // Visual height
19
- const PLAYER_JUMP_IMPULSE = 7; // Impulse force for jump
20
- const PROJECTILE_SPEED = 15;
21
- const PROJECTILE_RADIUS = 0.2;
22
- const PICKUP_RADIUS = 1.5;
23
- const PICKUP_RADIUS_SQ = PICKUP_RADIUS * PICKUP_RADIUS; // Use squared distance
24
-
25
- // --- Three.js Setup ---
26
- let scene, camera, renderer;
27
- let playerMesh;
28
- const meshesToSync = []; // Holds { mesh: THREE.Mesh, body: CANNON.Body }
29
- const projectiles = []; // Holds { mesh, body, lifetime }
30
- let axesHelper;
31
-
32
- // --- Physics Setup ---
33
- let world;
34
- let playerBody;
35
- const physicsBodies = new Map(); // Use Map<id, CANNON.Body> for easier removal
36
- let groundMaterial, playerMaterial, wallMaterial, monsterMaterial, itemMaterial; // Physics materials
37
- let cannonDebugger = null;
38
-
39
- // --- Game State ---
40
- let gameState = {};
41
- const keysPressed = {};
42
- let gameLoopActive = false;
43
- let animationFrameId = null;
44
- let selectedTool = null; // For building tools later
45
-
46
- // --- Game Data (Ensure starting point 0,0 exists!) ---
47
- const gameData = {
48
- // Structure: "x,y": { type, features?, items?, monsters?, name? }
49
- "0,0": { type: 'city', features: ['door_north', 'item_Key'], name: "City Square"},
50
- "0,1": { type: 'forest', features: ['path_north', 'door_south', 'item_Healing_Potion'], name: "Forest Entrance" },
51
- "0,2": { type: 'forest', features: ['path_south', 'monster_goblin'], name: "Deep Forest"},
52
- "1,1": { type: 'forest', features: ['river', 'path_west'], name: "River Bend" },
53
- "-1,1": { type: 'ruins', features: ['path_east'], name: "Old Ruins"},
54
- "1,0": { type: 'plains', features: ['door_west'], name: "East Plains"},
55
- "-1,0": { type: 'plains', features: ['door_east'], name: "West Plains"},
56
- };
57
-
58
- const itemsData = { // Add 'name' for consistency
59
- "Healing Potion": { name: "Healing Potion", type: "consumable", description: "Restores 10 HP.", hpRestore: 10, model: 'sphere_red' },
60
- "Key": { name: "Key", type: "quest", description: "A rusty key.", model: 'box_gold'},
61
- };
62
-
63
- const monstersData = { // Add 'name'
64
- "goblin": { name: "Goblin", hp: 15, attack: 4, defense: 1, speed: 2.5, model: 'capsule_green', xp: 5 },
65
- };
66
-
67
- // --- Materials and Geometries (Defined once) ---
68
- // Using basic wireframe materials for initial debugging
69
- const debugMaterials = {
70
- player: new THREE.MeshBasicMaterial({ color: 0x0077ff, wireframe: true }),
71
- wall: new THREE.MeshBasicMaterial({ color: 0xff0000, wireframe: true }),
72
- item: new THREE.MeshBasicMaterial({ color: 0x00ff00, wireframe: true }),
73
- monster: new THREE.MeshBasicMaterial({ color: 0xff00ff, wireframe: true }),
74
- projectile: new THREE.MeshBasicMaterial({ color: 0xffff00 }), // Keep projectiles solid
75
- floor_default: new THREE.MeshBasicMaterial({ color: 0x555555, wireframe: true }), // Wireframe floor
76
- };
77
- // Normal Materials (Use after debugging)
78
- // const normalMaterials = {
79
- // player: new THREE.MeshLambertMaterial({ color: 0x0077ff }),
80
- // wall: new THREE.MeshLambertMaterial({ color: 0x888888 }),
81
- // item_consumable: new THREE.MeshStandardMaterial({ color: 0xff0000, roughness: 0.6 }),
82
- // item_quest: new THREE.MeshStandardMaterial({ color: 0xffd700, roughness: 0.4 }),
83
- // monster_goblin: new THREE.MeshLambertMaterial({ color: 0x00ff00 }),
84
- // floor_city: new THREE.MeshLambertMaterial({ color: 0xdeb887 }),
85
- // floor_forest: new THREE.MeshLambertMaterial({ color: 0x228B22 }),
86
- // // ... add all floor types
87
- // floor_default: new THREE.MeshLambertMaterial({ color: 0xaaaaaa })
88
- // };
89
- const activeMaterials = debugMaterials; // Switch to normalMaterials when ready
90
-
91
- const geometries = { // Keep geometries simple
92
- floor: new THREE.PlaneGeometry(ROOM_SIZE, ROOM_SIZE),
93
- wallNS: new THREE.BoxGeometry(ROOM_SIZE, WALL_HEIGHT, WALL_THICKNESS),
94
- wallEW: new THREE.BoxGeometry(WALL_THICKNESS, WALL_HEIGHT, ROOM_SIZE),
95
- playerCylinder: new THREE.CylinderGeometry(PLAYER_RADIUS, PLAYER_RADIUS, PLAYER_HEIGHT - (PLAYER_RADIUS * 2), 8),
96
- playerSphere: new THREE.SphereGeometry(PLAYER_RADIUS, 8, 8),
97
- playerNose: new THREE.ConeGeometry(PLAYER_RADIUS * 0.3, PLAYER_RADIUS * 0.5, 4),
98
- monsterCapsuleBody: new THREE.CylinderGeometry(0.4, 0.4, 1.0, 8),
99
- monsterCapsuleHead: new THREE.SphereGeometry(0.4, 8, 8),
100
- itemSphere: new THREE.SphereGeometry(0.3, 8, 8),
101
- itemBox: new THREE.BoxGeometry(0.4, 0.4, 0.4),
102
- projectile: new THREE.SphereGeometry(PROJECTILE_RADIUS, 6, 6),
103
- };
104
-
105
-
106
- // --- Initialization ---
107
-
108
- function init() {
109
- console.log("--- Initializing Game ---");
110
- // Reset state and clear arrays/maps
111
- gameState = { inventory: [], stats: { hp: 30, maxHp: 30, strength: 7, wisdom: 5, courage: 6 }, monsters: [], items: [] };
112
- keysPressed = {};
113
- meshesToSync.length = 0;
114
- projectiles.length = 0;
115
- physicsBodies.clear(); // Clear the map
116
-
117
- // Clear previous scene if restarting
118
- if (scene) {
119
- while (scene.children.length > 0) scene.remove(scene.children[0]);
120
- } else {
121
- scene = new THREE.Scene(); // Create scene only if it doesn't exist
122
- }
123
- scene.background = new THREE.Color(0x1a1a1a);
124
-
125
- // Clear previous renderer if restarting
126
- if (renderer) {
127
- renderer.dispose();
128
- if (renderer.domElement.parentNode) {
129
- renderer.domElement.parentNode.removeChild(renderer.domElement);
130
  }
131
- }
132
-
133
- initThreeJS(); // Setup camera, renderer, lights
134
- initPhysics(); // Setup world, materials
135
- initPlayer(); // Setup player mesh + body
136
- generateMap(); // Setup static map meshes + bodies
137
- setupInputListeners();
138
- updateUI();
139
- addLog("Welcome! Move: QWEASDZXC, Jump: X, Attack: Space, Pickup: F", "info");
140
- console.log("--- Initialization Complete ---");
141
-
142
- if (animationFrameId) cancelAnimationFrame(animationFrameId);
143
- gameLoopActive = true;
144
- animate();
145
- }
146
-
147
- function initThreeJS() {
148
- console.log("Initializing Three.js...");
149
- const aspect = sceneContainer.clientWidth / sceneContainer.clientHeight;
150
- camera = new THREE.PerspectiveCamera(60, aspect, 0.1, 1000);
151
- // Set camera directly overhead looking down
152
- camera.position.set(0, CAMERA_Y_OFFSET, 0);
153
- camera.lookAt(0, 0, 0); // Look straight down at origin initially
154
- camera.rotation.x = -Math.PI / 2; // Explicitly set rotation if lookAt isn't enough
155
-
156
- renderer = new THREE.WebGLRenderer({ antialias: true });
157
- renderer.setSize(sceneContainer.clientWidth, sceneContainer.clientHeight);
158
- renderer.shadowMap.enabled = true;
159
- renderer.shadowMap.type = THREE.PCFSoftShadowMap;
160
- sceneContainer.appendChild(renderer.domElement);
161
-
162
- // Lighting
163
- scene.add(new THREE.AmbientLight(0xffffff, 0.7)); // Brighter ambient for debug
164
- const dirLight = new THREE.DirectionalLight(0xffffff, 1.0);
165
- dirLight.position.set(10, 30, 20); // Angled light
166
- dirLight.castShadow = true;
167
- dirLight.shadow.mapSize.width = 1024;
168
- dirLight.shadow.mapSize.height = 1024;
169
- scene.add(dirLight);
170
-
171
- // Axes Helper
172
- axesHelper = new THREE.AxesHelper(ROOM_SIZE * 0.5);
173
- axesHelper.position.set(0, 0.01, 0);
174
- scene.add(axesHelper);
175
- console.log("Three.js Initialized. Camera at:", camera.position);
176
-
177
- window.addEventListener('resize', onWindowResize, false);
178
- }
179
-
180
- function initPhysics() {
181
- console.log("Initializing Cannon-es...");
182
- world = new CANNON.World({ gravity: new CANNON.Vec3(0, -15, 0) });
183
- world.broadphase = new CANNON.SAPBroadphase(world);
184
- world.allowSleep = true;
185
-
186
- // Define materials
187
- groundMaterial = new CANNON.Material("ground");
188
- playerMaterial = new CANNON.Material("player");
189
- wallMaterial = new CANNON.Material("wall");
190
- monsterMaterial = new CANNON.Material("monster");
191
- itemMaterial = new CANNON.Material("item"); // Not used for physics bodies anymore
192
-
193
- // Ground physics body
194
- const groundShape = new CANNON.Plane();
195
- const groundBody = new CANNON.Body({ mass: 0, material: groundMaterial });
196
- groundBody.addShape(groundShape);
197
- groundBody.quaternion.setFromEuler(-Math.PI / 2, 0, 0);
198
- world.addBody(groundBody);
199
- physicsBodies.set(groundBody.id, groundBody); // Track it
200
-
201
- // Contact Materials
202
- const playerGround = new CANNON.ContactMaterial(playerMaterial, groundMaterial, { friction: 0.1, restitution: 0.1 }); // Low friction
203
- const playerWall = new CANNON.ContactMaterial(playerMaterial, wallMaterial, { friction: 0.01, restitution: 0.1 }); // Very low friction vs walls
204
- const monsterGround = new CANNON.ContactMaterial(monsterMaterial, groundMaterial, { friction: 0.4, restitution: 0.1 });
205
- const monsterWall = new CANNON.ContactMaterial(monsterMaterial, wallMaterial, { friction: 0.1, restitution: 0.2 });
206
-
207
- world.addContactMaterial(playerGround);
208
- world.addContactMaterial(playerWall);
209
- world.addContactMaterial(monsterGround);
210
- world.addContactMaterial(monsterWall);
211
- console.log("Physics World Initialized.");
212
-
213
- // Optional: Physics Debugger Init
214
- // try { cannonDebugger = new CannonDebugger(scene, world, { color: 0x00ff00 }); console.log("Debugger Init."); }
215
- // catch (e) { console.error("Failed CannonDebugger.", e); }
216
- }
217
-
218
- // --- Primitive Assembly Functions ---
219
- function createPlayerMesh() {
220
- const group = new THREE.Group();
221
- const bodyMat = activeMaterials.player; // Use active material set
222
- const body = new THREE.Mesh(geometries.playerCylinder, bodyMat);
223
- body.position.y = PLAYER_RADIUS; body.castShadow = true;
224
- const head = new THREE.Mesh(geometries.playerSphere, bodyMat);
225
- head.position.y = PLAYER_HEIGHT - PLAYER_RADIUS; head.castShadow = true;
226
- group.add(body); group.add(head);
227
- const nose = new THREE.Mesh(geometries.playerNose, new THREE.MeshBasicMaterial({ color: 0xffff00 })); // Nose always bright yellow
228
- nose.position.set(0, PLAYER_HEIGHT * 0.6, PLAYER_RADIUS); // Point forward +Z
229
- // No rotation needed if pointing +Z
230
- group.add(nose);
231
- // Important: Set group's origin to the intended base/center of the physics body
232
- group.position.set(0, 0, 0); // Position will be controlled by sync
233
- return group;
234
- }
235
- function createSimpleMonsterMesh(modelType = 'capsule_green') {
236
- const group = new THREE.Group();
237
- const mat = activeMaterials.monster; // Use active debug/normal material
238
- if (modelType === 'capsule_green') {
239
- const body = new THREE.Mesh(geometries.monsterCapsuleBody, mat);
240
- const head = new THREE.Mesh(geometries.monsterCapsuleHead, mat);
241
- body.position.y = 0.5; head.position.y = 1.0 + 0.4;
242
- group.add(body); group.add(head);
243
- } else { /* Add other monster types if needed */ }
244
- group.traverse(child => { if (child.isMesh) child.castShadow = true; });
245
- group.position.set(0, 0, 0); // Position set by sync
246
- return group;
247
- }
248
- function createSimpleItemMesh(modelType = 'sphere_red') {
249
- let geom;
250
- const mat = activeMaterials.item; // Use active debug/normal material
251
- if(modelType === 'sphere_red') geom = geometries.itemSphere;
252
- else if (modelType === 'box_gold') geom = geometries.itemBox;
253
- else geom = geometries.itemSphere; // Default
254
- const mesh = new THREE.Mesh(geom, mat);
255
- mesh.position.y = PLAYER_RADIUS; // Default height
256
- mesh.castShadow = true;
257
- return mesh;
258
- }
259
- function createProjectileMesh() {
260
- const mat = activeMaterials.projectile; // Use active material
261
- const mesh = new THREE.Mesh(geometries.projectile, mat);
262
- return mesh;
263
- }
264
-
265
- // --- Player Setup ---
266
- function initPlayer() {
267
- console.log("Initializing Player...");
268
- // Visual Mesh
269
- playerMesh = createPlayerMesh();
270
- // Set initial position high to avoid spawning inside floor
271
- playerMesh.position.set(0, PLAYER_HEIGHT + 1, 0);
272
- scene.add(playerMesh);
273
- console.log("Player mesh added to scene at initial pos:", playerMesh.position);
274
-
275
- // Physics Body - Start at center of 0,0 cell, slightly above ground
276
- const startX = 0;
277
- const startZ = 0;
278
- const startY = PLAYER_HEIGHT * 1.5; // Start higher
279
- const playerShape = new CANNON.Sphere(PLAYER_RADIUS);
280
- playerBody = new CANNON.Body({
281
- mass: 70,
282
- shape: playerShape,
283
- position: new CANNON.Vec3(startX, startY, startZ),
284
- linearDamping: 0.95,
285
- angularDamping: 1.0, // Completely prevent angular rotation from physics
286
- material: playerMaterial // Use defined material
287
- });
288
- playerBody.allowSleep = false;
289
- playerBody.addEventListener("collide", handlePlayerCollision);
290
- world.addBody(playerBody);
291
- physicsBodies.set(playerBody.id, playerBody); // Track body using Map
292
- console.log(`Player physics body added at ${startX}, ${startY}, ${startZ}`);
293
-
294
- // Add to sync list
295
- meshesToSync.push({ mesh: playerMesh, body: playerBody });
296
- console.log("Player added to sync list.");
297
- }
298
-
299
- // --- Map Generation ---
300
- function generateMap() {
301
- console.log("Generating Map...");
302
- const wallPhysicsMaterial = world.materials.find(m => m.name === "wall");
303
- const groundPhysicsMaterial = world.materials.find(m => m.name === "ground");
304
-
305
- // DEBUG: Only generate the starting cell "0,0"
306
- const startCoord = "0,0";
307
- const data = gameData[startCoord];
308
- if (!data) {
309
- console.error("CRITICAL: No gameData found for starting cell '0,0'!");
310
- return;
311
- }
312
-
313
- const x = 0;
314
- const z = 0;
315
- const type = data.type || 'default';
316
- console.log(`Generating START cell: ${startCoord} (Type: ${type})`);
317
-
318
- // Create Floor Mesh
319
- const floorMat = activeMaterials[`floor_${type}`] || activeMaterials.floor_default; // Use debug mats
320
- const floorMesh = new THREE.Mesh(geometries.floor, floorMat);
321
- floorMesh.rotation.x = -Math.PI / 2;
322
- floorMesh.position.set(x * ROOM_SIZE, 0, z * ROOM_SIZE);
323
- floorMesh.receiveShadow = true; // Floors should receive shadows
324
- scene.add(floorMesh);
325
- console.log(`Added floor at ${x},${z}`);
326
-
327
- // Create Walls (Visual + Physics) for the single cell
328
- const features = data.features || [];
329
- const wallDefs = [
330
- ['north', geometries.wallNS, 0, -0.5], ['south', geometries.wallNS, 0, 0.5],
331
- ['east', geometries.wallEW, 0.5, 0], ['west', geometries.wallEW, -0.5, 0],
332
- ];
333
-
334
- wallDefs.forEach(([dir, geom, xOff, zOff]) => {
335
- const doorFeature = `door_${dir}`; const pathFeature = `path_${dir}`;
336
- if (!features.includes(doorFeature) && !features.includes(pathFeature)) {
337
- const wallX = x * ROOM_SIZE + xOff * ROOM_SIZE;
338
- const wallZ = z * ROOM_SIZE + zOff * ROOM_SIZE;
339
- const wallY = WALL_HEIGHT / 2;
340
-
341
- // Visual Wall (DEBUG)
342
- const wallMesh = new THREE.Mesh(geom, activeMaterials.wall); // Use debug wall mat
343
- wallMesh.position.set(wallX, wallY, wallZ);
344
- wallMesh.castShadow = true; wallMesh.receiveShadow = true;
345
- scene.add(wallMesh);
346
-
347
- // Physics Wall
348
- const wallShape = new CANNON.Box(new CANNON.Vec3(geom.parameters.width / 2, geom.parameters.height / 2, geom.parameters.depth / 2));
349
- const wallBody = new CANNON.Body({ mass: 0, shape: wallShape, position: new CANNON.Vec3(wallX, wallY, wallZ), material: wallPhysicsMaterial });
350
- world.addBody(wallBody);
351
- physicsBodies.set(wallBody.id, wallBody); // Track it
352
- // console.log(`Added ${dir} wall for cell ${x},${z}`);
353
- } else {
354
- console.log(`Skipping ${dir} wall for cell ${x},${z} due to feature.`);
355
  }
356
- });
357
-
358
- // Spawn Items & Monsters based on features for the single cell
359
- features.forEach(feature => {
360
- if (feature.startsWith('item_')) {
361
- const itemName = feature.substring(5).replace(/_/g, ' ');
362
- if (itemsData[itemName]) spawnItem(itemName, x, z);
363
- else console.warn(`Item feature found but no data for: ${itemName}`);
364
- } else if (feature.startsWith('monster_')) {
365
- const monsterType = feature.substring(8);
366
- if (monstersData[monsterType]) spawnMonster(monsterType, x, z);
367
- else console.warn(`Monster feature found but no data for: ${monsterType}`);
368
- }
369
- });
370
-
371
- console.log("Map Generation Complete (Debug Mode - Single Cell).");
372
- }
373
-
374
- // --- Item/Monster Spawning (Simplified for Pickup 'F') ---
375
- function spawnItem(itemName, gridX, gridZ) {
376
- const itemData = itemsData[itemName];
377
- if (!itemData) return;
378
- const x = gridX * ROOM_SIZE + (Math.random() - 0.5) * (ROOM_SIZE * 0.4);
379
- const z = gridZ * ROOM_SIZE + (Math.random() - 0.5) * (ROOM_SIZE * 0.4);
380
- const y = PLAYER_RADIUS; // Item height
381
-
382
- // Use DEBUG material
383
- const mesh = createSimpleItemMesh(itemData.model); // Use debug mat via create func
384
- if (!mesh) return; // Safety check
385
- mesh.position.set(x, y, z);
386
- mesh.userData = { type: 'item', name: itemName }; // Store data on mesh
387
- mesh.castShadow = true;
388
- scene.add(mesh);
389
-
390
- // Store item in game state WITHOUT physics body
391
- gameState.items.push({
392
- id: mesh.uuid, // Use mesh UUID as item ID
393
- name: itemName,
394
- mesh: mesh,
395
- position: mesh.position // Store position for proximity check
396
- });
397
- console.log(`Spawned item ${itemName} at ${x.toFixed(1)}, ${y.toFixed(1)}, ${z.toFixed(1)} (visual only)`);
398
- }
399
-
400
- function spawnMonster(monsterType, gridX, gridZ) {
401
- const monsterData = monstersData[monsterType];
402
- if (!monsterData) return;
403
- const x = gridX * ROOM_SIZE + (Math.random() - 0.5) * (ROOM_SIZE * 0.4);
404
- const z = gridZ * ROOM_SIZE + (Math.random() - 0.5) * (ROOM_SIZE * 0.4);
405
- const y = PLAYER_HEIGHT; // Start higher
406
-
407
- // Use DEBUG material
408
- const mesh = createSimpleMonsterMesh(monsterData.model); // Uses debug mat via create func
409
- if (!mesh) return; // Safety check
410
- mesh.position.set(x, y, z); // Initial visual position
411
- mesh.userData = { type: 'monster', monsterType: monsterType };
412
- scene.add(mesh);
413
-
414
- // Physics Body
415
- const shape = new CANNON.Sphere(PLAYER_RADIUS * 0.8);
416
- const body = new CANNON.Body({
417
- mass: 10, shape: shape, position: new CANNON.Vec3(x, y, z),
418
- linearDamping: 0.8, angularDamping: 0.9,
419
- material: world.materials.find(m => m.name === "monster") || new CANNON.Material("monster")
420
- });
421
- body.allowSleep = true;
422
- // Store reference to mesh and HP on body's userData
423
- body.userData = { type: 'monster', monsterType: monsterType, mesh: mesh, hp: monsterData.hp };
424
- world.addBody(body);
425
-
426
- gameState.monsters.push({ id: body.id, type: monsterType, hp: monsterData.hp, body: body, mesh: mesh });
427
- meshesToSync.push({ mesh: mesh, body: body });
428
- physicsBodies.set(body.id, body); // Use map for tracking
429
- console.log(`Spawned monster ${monsterType} at ${x.toFixed(1)}, ${y.toFixed(1)}, ${z.toFixed(1)}`);
430
- }
431
-
432
-
433
- // --- Input Handling (QWEASDZXC + Jump 'X' + F + Space) ---
434
- function setupInputListeners() { /* ... same ... */
435
- console.log("Setting up input listeners.");
436
- window.addEventListener('keydown', (event) => { keysPressed[event.key.toLowerCase()] = true; keysPressed[event.code] = true; if (['space', 'arrowup', 'arrowdown', 'arrowleft', 'arrowright', 'keyx', 'keyf'].includes(event.code.toLowerCase())) { event.preventDefault(); }});
437
- window.addEventListener('keyup', (event) => { keysPressed[event.key.toLowerCase()] = false; keysPressed[event.code] = false; });
438
- }
439
-
440
- function handleInput(deltaTime) {
441
- if (!playerBody) return;
442
-
443
- const moveSpeed = PLAYER_SPEED;
444
- // Correct forward/backward/strafe directions relative to world axes
445
- // Assume +Z is SOUTH, -Z is NORTH
446
- // Assume +X is EAST, -X is WEST
447
- let forceX = 0;
448
- let forceZ = 0;
449
-
450
- // Forward (-Z) / Backward (+Z)
451
- if (keysPressed['w']) forceZ -= 1; // W = North = -Z
452
- if (keysPressed['s']) forceZ += 1; // S = South = +Z
453
-
454
- // Strafe Left (-X) / Right (+X)
455
- if (keysPressed['a']) forceX -= 1; // A = West = -X
456
- if (keysPressed['d']) forceX += 1; // D = East = +X
457
-
458
- // Diagonals - combine basic directions
459
- if (keysPressed['q']) { forceZ -= 0.707; forceX -= 0.707; } // Q = NW
460
- if (keysPressed['e']) { forceZ -= 0.707; forceX += 0.707; } // E = NE
461
- if (keysPressed['z']) { forceZ += 0.707; forceX -= 0.707; } // Z = SW
462
- if (keysPressed['c']) { forceZ += 0.707; forceX += 0.707; } // C = SE
463
-
464
- // --- Calculate final velocity vector ---
465
- // We set velocity directly for more responsive control than forces
466
- const targetVelocity = new CANNON.Vec3(0, playerBody.velocity.y, 0); // Preserve Y velocity
467
-
468
- if (forceX !== 0 || forceZ !== 0) {
469
- const moveVec = new THREE.Vector2(forceX, forceZ);
470
- if (moveVec.lengthSq() > 1.0) { // Normalize only if combined magnitude > 1
471
- moveVec.normalize();
472
- }
473
- targetVelocity.x = moveVec.x * moveSpeed;
474
- targetVelocity.z = moveVec.y * moveSpeed;
475
-
476
- // --- Rotation ---
477
- // Rotate player mesh to face movement direction
478
- // Calculate angle from positive Z axis (adjust if your model faces differently)
479
- const angle = Math.atan2(targetVelocity.x, targetVelocity.z);
480
- const targetQuaternion = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), angle);
481
- // Slerp for smooth rotation
482
- playerMesh.quaternion.slerp(targetQuaternion, 0.15); // Adjust 0.15 for responsiveness
483
-
484
- } else {
485
- // No movement keys pressed - rely on linear damping to stop
486
- // Or force stop X/Z velocity:
487
- targetVelocity.x = 0;
488
- targetVelocity.z = 0;
489
- }
490
-
491
- playerBody.velocity.x = targetVelocity.x;
492
- playerBody.velocity.z = targetVelocity.z;
493
- // Y velocity is controlled by gravity + jump impulse
494
-
495
- // --- Jump (X) ---
496
- if (keysPressed['x'] || keysPressed['keyx']) { // Check code too
497
- // !! Basic jump - Needs ground check via raycast or contact materials !!
498
- // Add a simple cooldown or only allow if Y velocity is low
499
- if (Math.abs(playerBody.velocity.y) < 0.5) { // Crude check if mostly grounded
500
- console.log("JUMP!");
501
- addLog("Jump!", "info");
502
- // Apply impulse upwards
503
- playerBody.applyImpulse(new CANNON.Vec3(0, PLAYER_JUMP_IMPULSE, 0), playerBody.position);
504
  }
505
- keysPressed['x'] = false; keysPressed['keyx'] = false; // Consume jump input
506
- }
507
-
508
- // --- Pickup (F) ---
509
- if (keysPressed['f'] || keysPressed['keyf']) {
510
- pickupNearbyItem();
511
- keysPressed['f'] = false; keysPressed['keyf'] = false; // Consume pickup input
512
- }
513
-
514
- // --- Fire (Space) ---
515
- if (keysPressed['space']) {
516
- fireProjectile();
517
- keysPressed['space'] = false; // Consume fire input
518
- }
519
- }
520
-
521
- // --- Interaction Logic ---
522
- function pickupNearbyItem() {
523
- if (!playerBody) return;
524
- const playerPos = playerBody.position;
525
- let pickedUp = false;
526
- let closestItemIndex = -1;
527
- let minDistanceSq = PICKUP_RADIUS_SQ; // Use squared distance
528
-
529
- // Find the closest item within radius
530
- for (let i = 0; i < gameState.items.length; i++) {
531
- const item = gameState.items[i];
532
- const distanceSq = playerPos.distanceSquared(item.position);
533
- if (distanceSq < minDistanceSq) {
534
- minDistanceSq = distanceSq;
535
- closestItemIndex = i;
536
  }
537
- }
538
-
539
- // Pick up the closest item if found
540
- if (closestItemIndex > -1) {
541
- const item = gameState.items[closestItemIndex];
542
- if (!gameState.inventory.includes(item.name)) {
543
- gameState.inventory.push(item.name);
544
- addLog(`Picked up ${item.name}!`, "pickup");
545
- updateInventoryDisplay();
546
-
547
- // Remove item visually and from state
548
- if(item.mesh.parent) scene.remove(item.mesh);
549
- gameState.items.splice(closestItemIndex, 1);
550
- pickedUp = true;
551
- } else {
552
- addLog(`Already have ${item.name}.`, "info");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
553
  }
554
- }
555
-
556
- if (!pickedUp) {
557
- addLog("Nothing nearby to pick up.", "info");
558
- }
559
- }
560
-
561
-
562
- // --- Combat (Projectile logic remains similar) ---
563
- function fireProjectile() {
564
- if (!playerBody || !playerMesh) return;
565
- addLog("Pew!", "combat");
566
- const projectileMesh = createProjectileMesh();
567
- const projectileShape = new CANNON.Sphere(PROJECTILE_RADIUS);
568
- const projectileBody = new CANNON.Body({ mass: 0.1, shape: projectileShape, linearDamping: 0.01, angularDamping: 0.01 });
569
- projectileBody.addEventListener("collide", handleProjectileCollision);
570
-
571
- // Calculate start position and velocity based on player's *current* rotation
572
- const offsetDistance = PLAYER_RADIUS + PROJECTILE_RADIUS + 0.1;
573
- const direction = new THREE.Vector3(0, 0, 1); // Base direction +Z
574
- direction.applyQuaternion(playerMesh.quaternion); // Rotate based on player mesh
575
-
576
- const startPos = new CANNON.Vec3().copy(playerBody.position).vadd(
577
- new CANNON.Vec3(direction.x, 0, direction.z).scale(offsetDistance) // Offset horizontally
578
- );
579
- // Adjust start Y based on player body center + visual model height
580
- startPos.y = playerBody.position.y; // Fire from player center height
581
-
582
- projectileBody.position.copy(startPos);
583
- projectileMesh.position.copy(startPos);
584
-
585
- // Velocity in player facing direction
586
- projectileBody.velocity = new CANNON.Vec3(direction.x, 0, direction.z).scale(PROJECTILE_SPEED);
587
-
588
- scene.add(projectileMesh);
589
- world.addBody(projectileBody);
590
- const projectileData = { mesh: projectileMesh, body: projectileBody, lifetime: 2.0 }; // Shorter lifetime
591
- meshesToSync.push(projectileData);
592
- projectiles.push(projectileData);
593
- physicsBodies.set(projectileBody.id, projectileBody); // Track
594
- projectileBody.userData = { type: 'projectile', data: projectileData };
595
- projectileMesh.userData = { type: 'projectile', data: projectileData }; // No body ref needed on mesh
596
- }
597
-
598
- // --- Collision Handling ---
599
- function handlePlayerCollision(event) {
600
- const otherBody = event.body;
601
- if (!otherBody || !otherBody.userData || !playerBody) return;
602
-
603
- // Player <-> Monster (Example: Simple damage, could add knockback)
604
- if (otherBody.userData.type === 'monster') {
605
- // Check for cooldown before applying damage again?
606
- console.log("Player collided with monster", otherBody.id);
607
- // gameState.stats.hp -= 1;
608
- // addLog(`Hit by ${otherBody.userData.monsterType || 'monster'}! HP: ${gameState.stats.hp}`, "combat");
609
- // updateStatsDisplay();
610
- // if (gameState.stats.hp <= 0) { gameOver("Defeated by a monster!"); }
611
- // Apply small impulse away from monster
612
- const impulse = playerBody.position.vsub(otherBody.position).unit().scale(20); // Knockback force
613
- playerBody.applyImpulse(impulse, playerBody.position);
614
- }
615
- // Player <-> Wall (Handled by physics engine)
616
- // Player <-> Item (Handled by 'F' key)
617
- }
618
-
619
- function handleProjectileCollision(event) {
620
- const projectileBody = event.target;
621
- const otherBody = event.body;
622
- if (!projectileBody?.userData || !otherBody?.userData) return; // Null checks
623
-
624
- const projectileData = projectileBody.userData.data;
625
- let shouldRemoveProjectile = true; // Assume removal unless hitting player
626
-
627
- if (otherBody.userData.type === 'monster') {
628
- const monsterId = otherBody.id;
629
- const monsterIndex = gameState.monsters.findIndex(m => m.id === monsterId);
630
- if (monsterIndex > -1) {
631
- const monster = gameState.monsters[monsterIndex];
632
- const damage = gameState.stats.strength + Math.floor(Math.random() * 3); // Add randomness
633
- monster.hp -= damage;
634
- otherBody.userData.hp = monster.hp;
635
- addLog(`Hit ${otherBody.userData.monsterType} for ${damage} damage! (HP: ${monster.hp})`, "combat");
636
-
637
- // Apply impulse to monster
638
- const impulseDir = projectileBody.velocity.unit();
639
- otherBody.applyImpulse(impulseDir.scale(damage * 5), projectileBody.position); // Knockback scales with damage
640
-
641
-
642
- if (monster.hp <= 0) {
643
- addLog(`Defeated ${otherBody.userData.monsterType}!`, "info");
644
- // Safely remove monster after physics step using setTimeout
645
- setTimeout(() => {
646
- if(monster.mesh.parent) scene.remove(monster.mesh);
647
- if(world.bodies.includes(monster.body)) world.removeBody(monster.body);
648
- meshesToSync = meshesToSync.filter(sync => sync.body.id !== monster.body.id);
649
- physicsBodies.delete(monster.body.id);
650
- gameState.monsters = gameState.monsters.filter(m => m.id !== monsterId);
651
- }, 0);
652
  }
 
 
653
  }
654
- } else if (otherBody === playerBody) {
655
- shouldRemoveProjectile = false; // Don't destroy projectile if it hits the player who fired it
656
- console.log("Projectile hit player - ignored");
657
- } else if (otherBody.mass === 0) {
658
- // Hit a static object like a wall
659
- console.log("Projectile hit wall/static");
660
- // Optional: Add impact effect
661
- }
662
-
663
-
664
- if (shouldRemoveProjectile) {
665
- // Schedule removal might be safer than immediate
666
- setTimeout(() => removeProjectile(projectileData), 0);
667
- }
668
- }
669
-
670
- function removeProjectile(projectileData) {
671
- if (!projectileData) return;
672
- const index = projectiles.indexOf(projectileData);
673
- if (index === -1) return;
674
-
675
- if (projectileData.mesh?.parent) scene.remove(projectileData.mesh);
676
- if (projectileData.body && world.bodies.includes(projectileData.body)) world.removeBody(projectileData.body);
677
-
678
- meshesToSync = meshesToSync.filter(sync => sync.body?.id !== projectileData.body?.id);
679
- if (projectileData.body) physicsBodies.delete(projectileData.body.id);
680
- projectiles.splice(index, 1);
681
- }
682
-
683
-
684
- // --- Monster AI ---
685
- function updateMonsters(deltaTime) {
686
- const agroRangeSq = (ROOM_SIZE * 2) ** 2; // Increased range
687
- if(!playerBody) return;
688
-
689
- gameState.monsters.forEach(monster => {
690
- if (!monster || !monster.body || monster.hp <= 0) return; // Skip dead or removed monsters
691
-
692
- const monsterPos = monster.body.position;
693
- const playerPos = playerBody.position;
694
- const distanceSq = playerPos.distanceSquared(monsterPos);
695
-
696
- if (distanceSq < agroRangeSq) { // If player is close
697
- const direction = playerPos.vsub(monsterPos);
698
- direction.y = 0; // Ignore height difference for movement plan
699
- if (distanceSq > (PLAYER_RADIUS * 2)**2 && direction.lengthSquared() > 0.1) { // If not too close and direction is valid
700
- direction.normalize();
701
- const monsterData = monstersData[monster.type];
702
- const speed = monsterData?.speed || 1;
703
-
704
- // Apply velocity for chasing
705
- monster.body.velocity.x = direction.x * speed;
706
- monster.body.velocity.z = direction.z * speed;
707
-
708
- // Rotation
709
- const angle = Math.atan2(direction.x, direction.z);
710
- const targetQuaternion = new THREE.Quaternion().setFromAxisAngle(new THREE.Vector3(0, 1, 0), angle);
711
- monster.mesh.quaternion.slerp(targetQuaternion, 0.1);
712
- } else { // Too close or direction invalid, stop horizontal movement
713
- monster.body.velocity.x = 0;
714
- monster.body.velocity.z = 0;
715
- // TODO: Add attack logic here if close enough
716
  }
717
- } else { // Player too far, stop moving
718
- monster.body.velocity.x = 0;
719
- monster.body.velocity.z = 0;
 
 
 
 
 
 
 
720
  }
721
- // Wake up body if needed (should be awake if chasing)
722
- if(monster.body.sleepState === CANNON.Body.SLEEPING) monster.body.wakeUp();
723
- });
724
- }
725
-
726
- // --- UI Update Functions ---
727
- function updateUI() { updateStatsDisplay(); updateInventoryDisplay(); }
728
- function updateStatsDisplay() { /* ... same ... */
729
- let statsHTML = ''; statsHTML += `<span>HP: ${gameState.stats.hp}/${gameState.stats.maxHp}</span>`; statsHTML += `<span>Str: ${gameState.stats.strength}</span>`; statsHTML += `<span>Wis: ${gameState.stats.wisdom}</span>`; statsHTML += `<span>Cor: ${gameState.stats.courage}</span>`; statsElement.innerHTML = statsHTML;
730
- }
731
- function updateInventoryDisplay() { /* ... same ... */
732
- let inventoryHTML = ''; if (gameState.inventory.length === 0) { inventoryHTML += '<em>Empty</em>'; } else { gameState.inventory.forEach(item => { const itemInfo = itemsData[item] || { type: 'unknown', description: '???' }; const itemClass = `item-${itemInfo.type || 'unknown'}`; inventoryHTML += `<span class="${itemClass}" title="${itemInfo.description}">${item}</span>`; }); } inventoryElement.innerHTML = inventoryHTML;
733
- }
734
- function addLog(message, type = "info") { /* ... same ... */
735
- const p = document.createElement('p'); p.classList.add(type); p.textContent = `[${new Date().toLocaleTimeString([], { hour12: false, hour: '2-digit', minute: '2-digit', second: '2-digit' })}] ${message}`; logElement.appendChild(p); logElement.scrollTop = logElement.scrollHeight;
736
- }
737
-
738
- // --- Game Over ---
739
- function gameOver(reason) { /* ... same ... */
740
- addLog(`GAME OVER: ${reason}`, "error"); console.log("Game Over:", reason);
741
- gameLoopActive = false; // Stop the game loop
742
- const restartButton = document.createElement('button'); restartButton.textContent = "RESTART GAME"; restartButton.style.cssText = `position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); padding: 20px 40px; font-size: 2em; cursor: pointer; z-index: 1000; background-color: #ffc107; border: none; border-radius: 5px; color: #333; font-family: 'Courier New', monospace;`;
743
- restartButton.onclick = () => { if (restartButton.parentNode) restartButton.parentNode.removeChild(restartButton); init(); }; // Re-initialize
744
- sceneContainer.appendChild(restartButton);
745
- }
746
-
747
- // --- Main Game Loop ---
748
- let lastTimestamp = 0;
749
- function animate(timestamp) {
750
- if (!gameLoopActive) return;
751
- animationFrameId = requestAnimationFrame(animate);
752
-
753
- const deltaTime = (timestamp - lastTimestamp) * 0.001;
754
- lastTimestamp = timestamp;
755
- const dtClamped = Math.min(deltaTime, 1 / 20); // Clamp delta time (max 20 FPS step)
756
-
757
- if (!world || !playerBody || !scene || !camera || !renderer) {
758
- console.error("Core component missing, stopping loop.");
759
- gameLoopActive = false;
760
- return;
761
- }
762
-
763
- // 1. Input
764
- handleInput(dtClamped);
765
-
766
- // 2. AI
767
- updateMonsters(dtClamped);
768
-
769
- // 3. Physics Step
770
- try { world.step(dtClamped); }
771
- catch (e) { console.error("Physics step error:", e); gameLoopActive = false; return; } // Stop loop on error
772
-
773
- // 4. Projectiles Update
774
- for (let i = projectiles.length - 1; i >= 0; i--) {
775
- const p = projectiles[i];
776
- if (p) { p.lifetime -= dtClamped; if (p.lifetime <= 0) removeProjectile(p); }
777
- }
778
-
779
- // 5. Sync Visuals
780
- meshesToSync.forEach(item => {
781
- if (item?.body && item?.mesh && item.mesh.parent) { // Check existence
782
- item.mesh.position.copy(item.body.position);
783
- item.mesh.quaternion.copy(item.body.quaternion);
784
  }
785
- });
786
-
787
- // 6. Update Camera
788
- if (playerBody && camera) {
789
- const targetCameraPos = new THREE.Vector3(
790
- playerBody.position.x,
791
- CAMERA_Y_OFFSET,
792
- playerBody.position.z // Look straight down from above player
793
- );
794
- camera.position.lerp(targetCameraPos, 0.1); // Smooth follow
795
- // Camera already looking down due to initial setup / rotation
796
- // camera.lookAt(playerBody.position.x, 0, playerBody.position.z); // Keep looking at player's feet
797
- }
798
-
799
- // 7. Physics Debugger (Optional)
800
- // if (cannonDebugger) cannonDebugger.update();
801
-
802
- // 8. Render
803
- renderer.render(scene, camera);
804
- }
805
-
806
- // --- Window Resize ---
807
- function onWindowResize() {
808
- if (!renderer || !camera) return;
809
- const width = sceneContainer.clientWidth;
810
- const height = sceneContainer.clientHeight;
811
- camera.aspect = width / height;
812
- camera.updateProjectionMatrix();
813
- renderer.setSize(width, height);
814
- console.log("Resized");
815
- }
816
-
817
- // --- Start Game ---
818
- init();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html>
3
+ <head>
4
+ <title>Shared World Builder</title>
5
+ <style>
6
+ body { margin: 0; overflow: hidden; }
7
+ canvas { display: block; }
8
+ </style>
9
+ </head>
10
+ <body>
11
+ <script type="importmap">
12
+ {
13
+ "imports": {
14
+ "three": "https://unpkg.com/three@0.163.0/build/three.module.js",
15
+ "three/addons/": "https://unpkg.com/[email protected]/examples/jsm/"
16
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  }
18
+ </script>
19
+
20
+ <script type="module">
21
+ import * as THREE from 'three';
22
+
23
+ let scene, camera, renderer, playerMesh;
24
+ let raycaster, mouse;
25
+ const keysPressed = {};
26
+ const playerSpeed = 0.15;
27
+
28
+ // --- World State (Managed by Server via WebSocket) ---
29
+ const worldObjects = new Map(); // Map<obj_id, THREE.Object3D>
30
+ const groundMeshes = {}; // Map<gridKey, THREE.Mesh>
31
+
32
+ // --- WebSocket ---
33
+ let socket = null;
34
+ let connectionRetries = 0;
35
+ const MAX_RETRIES = 5;
36
+
37
+ // --- Access State from Streamlit (Injected) ---
38
+ const myUsername = window.USERNAME || `User_${Math.random().toString(36).substring(2, 6)}`;
39
+ const websocketUrl = window.WEBSOCKET_URL || "ws://localhost:8765";
40
+ let selectedObjectType = window.SELECTED_OBJECT_TYPE || "None"; // Can be updated
41
+ const plotWidth = window.PLOT_WIDTH || 50.0;
42
+ const plotDepth = window.PLOT_DEPTH || 50.0;
43
+
44
+ // --- Materials ---
45
+ const groundMaterial = new THREE.MeshStandardMaterial({ color: 0x55aa55, roughness: 0.9, metalness: 0.1, side: THREE.DoubleSide });
46
+ const placeholderGroundMaterial = new THREE.MeshStandardMaterial({ color: 0x448844, roughness: 0.95, metalness: 0.1, side: THREE.DoubleSide });
47
+ // Basic material cache/reuse
48
+ const objectMaterials = {
49
+ 'wood': new THREE.MeshStandardMaterial({ color: 0x8B4513, roughness: 0.9 }),
50
+ 'leaf': new THREE.MeshStandardMaterial({ color: 0x228B22, roughness: 0.8 }),
51
+ 'stone': new THREE.MeshStandardMaterial({ color: 0xaaaaaa, roughness: 0.8, metalness: 0.1 }),
52
+ 'house_wall': new THREE.MeshStandardMaterial({ color: 0xffccaa, roughness: 0.8 }),
53
+ 'house_roof': new THREE.MeshStandardMaterial({ color: 0xaa5533, roughness: 0.7 }),
54
+ 'brick': new THREE.MeshStandardMaterial({ color: 0x9B4C43, roughness: 0.85 }),
55
+ 'metal': new THREE.MeshStandardMaterial({ color: 0xcccccc, roughness: 0.4, metalness: 0.8 }),
56
+ 'gem': new THREE.MeshStandardMaterial({ color: 0x4FFFFF, roughness: 0.1, metalness: 0.2, transparent: true, opacity: 0.8 }),
57
+ 'light': new THREE.MeshBasicMaterial({ color: 0xFFFF88 }), // For light sources
58
+ // Add more reusable materials
59
+ };
60
+
61
+
62
+ function init() {
63
+ scene = new THREE.Scene();
64
+ scene.background = new THREE.Color(0xabcdef);
65
+
66
+ const aspect = window.innerWidth / window.innerHeight;
67
+ camera = new THREE.PerspectiveCamera(60, aspect, 0.1, 5000); // Increased far plane
68
+ camera.position.set(plotWidth / 2, 15, plotDepth / 2 + 20);
69
+ camera.lookAt(plotWidth/2, 0, plotDepth/2);
70
+ scene.add(camera);
71
+
72
+ setupLighting();
73
+ // Don't setup initial ground here, wait for WebSocket initial state? Or create base?
74
+ createGroundPlane(0, 0, false); // Create the origin ground at least
75
+ setupPlayer();
76
+
77
+ raycaster = new THREE.Raycaster();
78
+ mouse = new THREE.Vector2();
79
+
80
+ renderer = new THREE.WebGLRenderer({ antialias: true });
81
+ renderer.setSize(window.innerWidth, window.innerHeight);
82
+ renderer.shadowMap.enabled = true;
83
+ renderer.shadowMap.type = THREE.PCFSoftShadowMap;
84
+ document.body.appendChild(renderer.domElement);
85
+
86
+ // --- Initialize WebSocket Connection ---
87
+ connectWebSocket();
88
+
89
+ // Event Listeners
90
+ document.addEventListener('mousemove', onMouseMove, false);
91
+ document.addEventListener('click', onDocumentClick, false); // Place object
92
+ window.addEventListener('resize', onWindowResize, false);
93
+ document.addEventListener('keydown', onKeyDown);
94
+ document.addEventListener('keyup', onKeyUp);
95
+
96
+ // --- Define global functions needed by Python ---
97
+ window.teleportPlayer = teleportPlayer;
98
+ // Removed getSaveDataAndPosition - saving now server-side via WS
99
+ // Removed resetNewlyPlacedObjects - no longer needed
100
+ window.updateSelectedObjectType = updateSelectedObjectType; // Still needed
101
+
102
+ console.log(`Three.js Initialized for user: ${myUsername}. Connecting to ${websocketUrl}...`);
103
+ animate();
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
  }
105
+
106
+ // --- WebSocket Logic ---
107
+ function connectWebSocket() {
108
+ console.log("Attempting WebSocket connection...");
109
+ socket = new WebSocket(websocketUrl);
110
+
111
+ socket.onopen = () => {
112
+ console.log("WebSocket connection established.");
113
+ connectionRetries = 0;
114
+ // Request initial state? Server sends it automatically now.
115
+ // socket.send(JSON.stringify({ type: "request_initial_state" }));
116
+ };
117
+
118
+ socket.onmessage = (event) => {
119
+ try {
120
+ const data = JSON.parse(event.data);
121
+ // console.log("WebSocket message received:", data); // Debugging
122
+ handleWebSocketMessage(data);
123
+ } catch (e) {
124
+ console.error("Failed to parse WebSocket message:", event.data, e);
125
+ }
126
+ };
127
+
128
+ socket.onerror = (error) => {
129
+ console.error("WebSocket error:", error);
130
+ // Consider showing an error message to the user in Streamlit?
131
+ };
132
+
133
+ socket.onclose = (event) => {
134
+ console.warn(`WebSocket connection closed. Code: ${event.code}, Reason: ${event.reason}. Clean: ${event.wasClean}`);
135
+ socket = null;
136
+ // Implement reconnection strategy
137
+ if (connectionRetries < MAX_RETRIES) {
138
+ connectionRetries++;
139
+ const delay = Math.pow(2, connectionRetries) * 1000; // Exponential backoff
140
+ console.log(`Attempting reconnection in ${delay / 1000}s...`);
141
+ setTimeout(connectWebSocket, delay);
142
+ } else {
143
+ console.error("WebSocket reconnection failed after max retries.");
144
+ // Inform user connection lost - maybe via Streamlit call?
145
+ }
146
+ };
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
  }
148
+
149
+ function sendWebSocketMessage(type, payload) {
150
+ if (socket && socket.readyState === WebSocket.OPEN) {
151
+ const message = JSON.stringify({ type, payload });
152
+ socket.send(message);
153
+ } else {
154
+ console.warn("WebSocket not open. Message not sent:", type, payload);
155
+ // Optionally queue messages to send on reconnect?
156
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
  }
158
+
159
+ function handleWebSocketMessage(data) {
160
+ const { type, payload } = data;
161
+
162
+ switch (type) {
163
+ case "initial_state":
164
+ console.log(`Received initial world state with ${Object.keys(payload).length} objects.`);
165
+ // Clear existing objects (except player?) before loading initial state
166
+ clearWorldObjects();
167
+ for (const obj_id in payload) {
168
+ createAndPlaceObject(payload[obj_id], false); // false = not newly placed
169
+ }
170
+ // Setup ground based on loaded objects' positions? Or separate metadata needed?
171
+ // For now, rely on dynamic ground expansion.
172
+ break;
173
+ case "object_placed":
174
+ console.log(`Object placed by ${payload.username}:`, payload.object_data);
175
+ // Add or update the object in the scene
176
+ createAndPlaceObject(payload.object_data, false); // false = not newly placed by *this* client
177
+ break;
178
+ case "object_deleted":
179
+ console.log(`Object deleted by ${payload.username}:`, payload.obj_id);
180
+ removeObjectById(payload.obj_id);
181
+ break;
182
+ case "user_join":
183
+ console.log(`User joined: ${payload.username} (${payload.id})`);
184
+ // Optionally display user join message in chat tab or 3D world?
185
+ break;
186
+ case "user_leave":
187
+ console.log(`User left: ${payload.username} (${payload.id})`);
188
+ // Optionally display user leave message
189
+ break;
190
+ case "user_rename":
191
+ console.log(`User ${payload.old_username} is now ${payload.new_username}`);
192
+ break;
193
+ case "chat_message":
194
+ console.log(`Chat from ${payload.username}: ${payload.message}`);
195
+ // Handle displaying chat in the Streamlit Chat tab (Python side handles this)
196
+ break;
197
+ // Add handlers for other message types
198
+ default:
199
+ console.warn("Received unknown WebSocket message type:", type);
200
+ }
201
  }
202
+
203
+ function clearWorldObjects() {
204
+ console.log("Clearing existing world objects...");
205
+ for (const [obj_id, mesh] of worldObjects.entries()) {
206
+ scene.remove(mesh);
207
+ // Optional: Dispose geometry/material for memory management
208
+ // disposeObject3D(mesh);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
209
  }
210
+ worldObjects.clear();
211
+ // Also clear ground meshes? Or keep them? Keep for now.
212
  }
213
+
214
+ function removeObjectById(obj_id) {
215
+ if (worldObjects.has(obj_id)) {
216
+ const mesh = worldObjects.get(obj_id);
217
+ scene.remove(mesh);
218
+ // disposeObject3D(mesh); // Optional cleanup
219
+ worldObjects.delete(obj_id);
220
+ console.log(`Removed object ${obj_id} from scene.`);
221
+ } else {
222
+ console.warn(`Attempted to remove non-existent object ID: ${obj_id}`);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
  }
224
+ }
225
+
226
+ // --- Standard Setup Functions ---
227
+ function setupLighting() { /* ... (Keep as before) ... */
228
+ const ambientLight = new THREE.AmbientLight(0xffffff, 0.6); scene.add(ambientLight);
229
+ const directionalLight = new THREE.DirectionalLight(0xffffff, 1.2); directionalLight.position.set(75, 150, 100); directionalLight.castShadow = true; directionalLight.shadow.mapSize.width = 2048; directionalLight.shadow.mapSize.height = 2048; directionalLight.shadow.camera.near = 10; directionalLight.shadow.camera.far = 400; directionalLight.shadow.camera.left = -150; directionalLight.shadow.camera.right = 150; directionalLight.shadow.camera.top = 150; directionalLight.shadow.camera.bottom = -150; directionalLight.shadow.bias = -0.002; scene.add(directionalLight);
230
+ const hemiLight = new THREE.HemisphereLight( 0xabcdef, 0x55aa55, 0.5 ); scene.add( hemiLight );
231
+ }
232
+ function setupPlayer() { /* ... (Keep as before) ... */
233
+ const playerGeo = new THREE.CapsuleGeometry(0.4, 0.8, 4, 8); const playerMat = new THREE.MeshStandardMaterial({ color: 0x0055ff, roughness: 0.6 }); playerMesh = new THREE.Mesh(playerGeo, playerMat); playerMesh.position.set(plotWidth / 2, 0.8, plotDepth / 2); playerMesh.castShadow = true; playerMesh.receiveShadow = false; scene.add(playerMesh);
234
  }
235
+ function createGroundPlane(gridX, gridZ, isPlaceholder) { /* ... (Keep as before) ... */
236
+ const gridKey = `${gridX}_${gridZ}`; if (groundMeshes[gridKey]) return groundMeshes[gridKey];
237
+ const groundGeometry = new THREE.PlaneGeometry(plotWidth, plotDepth); const material = isPlaceholder ? placeholderGroundMaterial : groundMaterial; const groundMesh = new THREE.Mesh(groundGeometry, material); groundMesh.rotation.x = -Math.PI / 2; groundMesh.position.y = -0.05; groundMesh.position.x = gridX * plotWidth + plotWidth / 2.0; groundMesh.position.z = gridZ * plotDepth + plotDepth / 2.0; groundMesh.receiveShadow = true; groundMesh.userData.gridKey = gridKey; groundMesh.userData.isPlaceholder = isPlaceholder; scene.add(groundMesh); groundMeshes[gridKey] = groundMesh; return groundMesh;
238
+ }
239
+
240
+ // --- Object Creation & Placement (Modified for WebSocket & New Primitives) ---
241
+
242
+ // Central function to add/update objects based on data
243
+ function createAndPlaceObject(objData, isNewlyPlacedLocally) { // isNewlyPlacedLocally not really used now
244
+ if (!objData || !objData.obj_id || !objData.type) {
245
+ console.warn("Invalid object data:", objData);
246
+ return null;
247
+ }
248
+
249
+ // Check if object already exists (update vs create)
250
+ let mesh = worldObjects.get(objData.obj_id);
251
+ let isNew = false;
252
+
253
+ if (mesh) {
254
+ // Update existing mesh position/rotation if different
255
+ if (mesh.position.distanceToSquared(objData.position) > 0.001) {
256
+ mesh.position.set(objData.position.x, objData.position.y, objData.position.z);
257
+ }
258
+ if (objData.rotation && (
259
+ Math.abs(mesh.rotation.x - objData.rotation._x) > 0.01 ||
260
+ Math.abs(mesh.rotation.y - objData.rotation._y) > 0.01 ||
261
+ Math.abs(mesh.rotation.z - objData.rotation._z) > 0.01 )) {
262
+ mesh.rotation.set(objData.rotation._x, objData.rotation._y, objData.rotation._z, objData.rotation._order || 'XYZ');
263
+ }
264
+ // Could add logic here to update geometry/material if type changes? Unlikely.
265
+ // console.log(`Updated object ${objData.obj_id}`);
266
+ } else {
267
+ // Create new mesh
268
+ mesh = createPrimitiveMesh(objData.type); // Use the new factory function
269
+ if (!mesh) return null; // Failed to create mesh type
270
+
271
+ isNew = true;
272
+ mesh.userData.obj_id = objData.obj_id; // Assign ID from data
273
+ mesh.userData.type = objData.type;
274
+ mesh.position.set(objData.position.x, objData.position.y, objData.position.z);
275
+ if (objData.rotation) {
276
+ mesh.rotation.set(objData.rotation._x, objData.rotation._y, objData.rotation._z, objData.rotation._order || 'XYZ');
277
+ }
278
+
279
+ scene.add(mesh);
280
+ worldObjects.set(objData.obj_id, mesh); // Add to our map
281
+ // console.log(`Created new object ${objData.obj_id} (${objData.type})`);
282
+ }
283
+ return mesh;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
284
  }
285
+
286
+ // Factory function for creating meshes based on type name
287
+ function createPrimitiveMesh(type) {
288
+ let mesh = null;
289
+ let geometry, material, material2; // Declare vars
290
+
291
+ // Use reusable materials where possible
292
+ const wood = objectMaterials.wood;
293
+ const leaf = objectMaterials.leaf;
294
+ const stone = objectMaterials.stone;
295
+ const house_wall = objectMaterials.house_wall;
296
+ const house_roof = objectMaterials.house_roof;
297
+ const brick = objectMaterials.brick;
298
+ const metal = objectMaterials.metal;
299
+ const gem = objectMaterials.gem;
300
+ const lightMat = objectMaterials.light;
301
+
302
+ try { // Wrap in try-catch for safety if geometry fails
303
+ switch(type) {
304
+ // --- Original Primitives ---
305
+ case "Tree":
306
+ mesh = new THREE.Group();
307
+ geometry = new THREE.CylinderGeometry(0.3, 0.4, 2, 8); material = wood;
308
+ const trunk = new THREE.Mesh(geometry, material); trunk.position.y = 1; trunk.castShadow=true; trunk.receiveShadow=true; mesh.add(trunk);
309
+ geometry = new THREE.IcosahedronGeometry(1.2, 0); material = leaf;
310
+ const canopy = new THREE.Mesh(geometry, material); canopy.position.y = 2.8; canopy.castShadow=true; canopy.receiveShadow=false; mesh.add(canopy);
311
+ break;
312
+ case "Rock":
313
+ geometry = new THREE.IcosahedronGeometry(0.7, 1); material = stone;
314
+ // Optional: Deform geometry slightly (can be slow if done often)
315
+ mesh = new THREE.Mesh(geometry, material); mesh.castShadow = true; mesh.receiveShadow = true;
316
+ mesh.scale.set(1, Math.random()*0.4 + 0.8, 1); // Vary shape slightly
317
+ break;
318
+ case "Simple House":
319
+ mesh = new THREE.Group();
320
+ geometry = new THREE.BoxGeometry(2, 1.5, 2.5); material = house_wall;
321
+ const body = new THREE.Mesh(geometry, material); body.position.y = 0.75; body.castShadow = true; body.receiveShadow = true; mesh.add(body);
322
+ geometry = new THREE.ConeGeometry(1.8, 1, 4); material = house_roof;
323
+ const roof = new THREE.Mesh(geometry, material); roof.position.y = 1.5 + 0.5; roof.rotation.y = Math.PI / 4; roof.castShadow = true; roof.receiveShadow = false; mesh.add(roof);
324
+ break;
325
+ case "Fence Post": // Keep original simple fence post
326
+ geometry = new THREE.BoxGeometry(0.2, 1.5, 0.2); material = wood;
327
+ mesh = new THREE.Mesh(geometry, material); mesh.position.y = 0.75; mesh.castShadow = true; mesh.receiveShadow = true;
328
+ break;
329
+
330
+ // --- New Primitives ---
331
+ case "Pine Tree": // Example: Cone for canopy
332
+ mesh = new THREE.Group();
333
+ geometry = new THREE.CylinderGeometry(0.2, 0.3, 2.5, 8); material = wood;
334
+ const pineTrunk = new THREE.Mesh(geometry, material); pineTrunk.position.y = 1.25; pineTrunk.castShadow=true; pineTrunk.receiveShadow=true; mesh.add(pineTrunk);
335
+ geometry = new THREE.ConeGeometry(1, 2.5, 8); material = leaf;
336
+ const pineCanopy = new THREE.Mesh(geometry, material); pineCanopy.position.y = 2.5 + (2.5/2) - 0.5; pineCanopy.castShadow=true; pineCanopy.receiveShadow=false; mesh.add(pineCanopy);
337
+ break;
338
+ case "Brick Wall": // Simple box with brick color
339
+ geometry = new THREE.BoxGeometry(3, 2, 0.3); material = brick;
340
+ mesh = new THREE.Mesh(geometry, material); mesh.position.y = 1; mesh.castShadow = true; mesh.receiveShadow = true;
341
+ break;
342
+ case "Sphere":
343
+ geometry = new THREE.SphereGeometry(0.8, 16, 12); material = metal;
344
+ mesh = new THREE.Mesh(geometry, material); mesh.position.y = 0.8; mesh.castShadow = true; mesh.receiveShadow = true;
345
+ break;
346
+ case "Cube": // Simple cube
347
+ geometry = new THREE.BoxGeometry(1, 1, 1); material = stone; // Re-use stone
348
+ mesh = new THREE.Mesh(geometry, material); mesh.position.y = 0.5; mesh.castShadow = true; mesh.receiveShadow = true;
349
+ break;
350
+ case "Cylinder":
351
+ geometry = new THREE.CylinderGeometry(0.5, 0.5, 1.5, 16); material = metal;
352
+ mesh = new THREE.Mesh(geometry, material); mesh.position.y = 0.75; mesh.castShadow = true; mesh.receiveShadow = true;
353
+ break;
354
+ case "Cone":
355
+ geometry = new THREE.ConeGeometry(0.6, 1.2, 16); material = house_roof; // Re-use roof
356
+ mesh = new THREE.Mesh(geometry, material); mesh.position.y = 0.6; mesh.castShadow = true; mesh.receiveShadow = true;
357
+ break;
358
+ case "Torus": // Donut shape
359
+ geometry = new THREE.TorusGeometry(0.6, 0.2, 8, 24); material = gem; // Use gem material
360
+ mesh = new THREE.Mesh(geometry, material); mesh.position.y = 0.7; mesh.castShadow = true; mesh.receiveShadow = true;
361
+ mesh.rotation.x = Math.PI / 2; // Stand it up
362
+ break;
363
+ case "Mushroom":
364
+ mesh = new THREE.Group();
365
+ geometry = new THREE.CylinderGeometry(0.15, 0.1, 0.6, 8); material = house_wall; // Cream stem
366
+ const stem = new THREE.Mesh(geometry, material); stem.position.y = 0.3; stem.castShadow = true; stem.receiveShadow = true; mesh.add(stem);
367
+ geometry = new THREE.SphereGeometry(0.4, 16, 8, 0, Math.PI * 2, 0, Math.PI / 2); material = house_roof; // Red cap
368
+ const cap = new THREE.Mesh(geometry, material); cap.position.y = 0.6; cap.castShadow = true; cap.receiveShadow = false; mesh.add(cap);
369
+ break;
370
+ case "Cactus": // Simple segmented cactus
371
+ mesh = new THREE.Group(); material = leaf; // Green material
372
+ geometry = new THREE.CylinderGeometry(0.3, 0.3, 1.5, 8);
373
+ const main = new THREE.Mesh(geometry, material); main.position.y = 0.75; main.castShadow = true; main.receiveShadow = true; mesh.add(main);
374
+ geometry = new THREE.CylinderGeometry(0.2, 0.2, 0.8, 8);
375
+ const arm1 = new THREE.Mesh(geometry, material); arm1.position.set(0.3, 1, 0); arm1.rotation.z = Math.PI / 4; arm1.castShadow = true; arm1.receiveShadow = true; mesh.add(arm1);
376
+ const arm2 = new THREE.Mesh(geometry, material); arm2.position.set(-0.3, 0.8, 0); arm2.rotation.z = -Math.PI / 4; arm2.castShadow = true; arm2.receiveShadow = true; mesh.add(arm2);
377
+ break;
378
+ case "Campfire":
379
+ mesh = new THREE.Group();
380
+ material = wood; geometry = new THREE.CylinderGeometry(0.1, 0.1, 0.8, 5);
381
+ const log1 = new THREE.Mesh(geometry, material); log1.rotation.x = Math.PI/2; log1.position.set(0, 0.1, 0.2); mesh.add(log1);
382
+ const log2 = new THREE.Mesh(geometry, material); log2.rotation.set(Math.PI/2, 0, Math.PI/3); log2.position.set(0.2*Math.cos(Math.PI/6), 0.1, -0.2*Math.sin(Math.PI/6)); mesh.add(log2);
383
+ const log3 = new THREE.Mesh(geometry, material); log3.rotation.set(Math.PI/2, 0, -Math.PI/3); log3.position.set(-0.2*Math.cos(Math.PI/6), 0.1, -0.2*Math.sin(Math.PI/6)); mesh.add(log3);
384
+ material2 = lightMat; geometry = new THREE.ConeGeometry(0.2, 0.5, 8); // Simple flame
385
+ const flame = new THREE.Mesh(geometry, material2); flame.position.y = 0.35; mesh.add(flame);
386
+ // Add shadows later if needed
387
+ break;
388
+ case "Star":
389
+ geometry = new THREE.SphereGeometry(0.5, 4, 2); // Low poly sphere looks star-like
390
+ material = lightMat;
391
+ mesh = new THREE.Mesh(geometry, material); mesh.position.y = 1;
392
+ break;
393
+ case "Gem":
394
+ geometry = new THREE.OctahedronGeometry(0.6, 0); material = gem;
395
+ mesh = new THREE.Mesh(geometry, material); mesh.position.y = 0.6; mesh.castShadow = true; mesh.receiveShadow = true;
396
+ break;
397
+ case "Tower": // Simple cylinder tower
398
+ geometry = new THREE.CylinderGeometry(1, 1.2, 5, 8); material = stone;
399
+ mesh = new THREE.Mesh(geometry, material); mesh.position.y = 2.5; mesh.castShadow = true; mesh.receiveShadow = true;
400
+ break;
401
+ case "Barrier": // Simple box barrier
402
+ geometry = new THREE.BoxGeometry(2, 0.5, 0.5); material = metal;
403
+ mesh = new THREE.Mesh(geometry, material); mesh.position.y = 0.25; mesh.castShadow = true; mesh.receiveShadow = true;
404
+ break;
405
+ case "Fountain": // Placeholder: Tiered cylinders
406
+ mesh = new THREE.Group(); material = stone;
407
+ geometry = new THREE.CylinderGeometry(1.5, 1.5, 0.3, 16);
408
+ const baseF = new THREE.Mesh(geometry, material); baseF.position.y = 0.15; mesh.add(baseF);
409
+ geometry = new THREE.CylinderGeometry(0.8, 0.8, 0.5, 16);
410
+ const midF = new THREE.Mesh(geometry, material); midF.position.y = 0.3+0.25; mesh.add(midF);
411
+ geometry = new THREE.CylinderGeometry(0.4, 0.4, 0.7, 16);
412
+ const topF = new THREE.Mesh(geometry, material); topF.position.y = 0.8+0.35; mesh.add(topF);
413
+ mesh.castShadow = true; mesh.receiveShadow = true; // Apply to group?
414
+ break;
415
+ case "Lantern":
416
+ mesh = new THREE.Group(); material = metal;
417
+ geometry = new THREE.BoxGeometry(0.4, 0.6, 0.4);
418
+ const bodyL = new THREE.Mesh(geometry, material); bodyL.position.y = 0.3; mesh.add(bodyL);
419
+ geometry = new THREE.SphereGeometry(0.15); material2 = lightMat;
420
+ const lightL = new THREE.Mesh(geometry, material2); lightL.position.y = 0.3; mesh.add(lightL);
421
+ mesh.castShadow = true; // Group casts shadow?
422
+ break;
423
+ case "Sign Post":
424
+ mesh = new THREE.Group(); material = wood;
425
+ geometry = new THREE.CylinderGeometry(0.05, 0.05, 1.8, 8);
426
+ const postS = new THREE.Mesh(geometry, material); postS.position.y = 0.9; mesh.add(postS);
427
+ geometry = new THREE.BoxGeometry(0.8, 0.4, 0.05);
428
+ const signS = new THREE.Mesh(geometry, material); signS.position.y = 1.5; mesh.add(signS);
429
+ mesh.castShadow = true; mesh.receiveShadow = true;
430
+ break;
431
+
432
+
433
+ default:
434
+ console.warn("Unknown primitive type for mesh creation:", type);
435
+ return null; // Return null if type not found
436
+ }
437
+ } catch (e) {
438
+ console.error(`Error creating geometry/mesh for type ${type}:`, e);
439
+ return null;
440
+ }
441
+
442
+ // Common post-creation steps (if mesh created)
443
+ if (mesh) {
444
+ // Set default userData structure (will be overwritten by createAndPlaceObject)
445
+ mesh.userData = { type: type };
446
+ // Ensure position is defaulted reasonably if created standalone
447
+ if (!mesh.position.y && mesh.geometry) {
448
+ mesh.geometry.computeBoundingBox();
449
+ mesh.position.y = (mesh.geometry.boundingBox.max.y - mesh.geometry.boundingBox.min.y) / 2;
450
+ }
451
+ }
452
+ return mesh;
453
+ }
454
+
455
+
456
+ // --- Event Handlers ---
457
+ function onMouseMove(event) { /* ... (Keep as before) ... */
458
+ mouse.x = (event.clientX / window.innerWidth) * 2 - 1; mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;
459
+ }
460
+
461
+ function onDocumentClick(event) {
462
+ if (selectedObjectType === "None" || !selectedObjectType) return;
463
+
464
+ const groundCandidates = Object.values(groundMeshes);
465
+ if (groundCandidates.length === 0) return;
466
+
467
+ raycaster.setFromCamera(mouse, camera);
468
+ const intersects = raycaster.intersectObjects(groundCandidates);
469
+
470
+ if (intersects.length > 0) {
471
+ const intersectPoint = intersects[0].point;
472
+
473
+ // Prepare object data for the server
474
+ const newObjData = {
475
+ obj_id: THREE.MathUtils.generateUUID(), // Generate unique ID client-side
476
+ type: selectedObjectType,
477
+ position: { x: intersectPoint.x, y: 0, z: intersectPoint.z }, // Base position on ground
478
+ rotation: { _x: 0, _y: Math.random() * Math.PI * 2, _z: 0, _order: 'XYZ' } // Random Y rotation
479
+ };
480
+
481
+ // Adjust Y position based on object type AFTER getting the type
482
+ // This should ideally use the geometry's bounding box, but hardcoding for now
483
+ const tempMesh = createPrimitiveMesh(selectedObjectType); // Create temporarily to get height? Costly.
484
+ if (tempMesh && tempMesh.geometry) {
485
+ tempMesh.geometry.computeBoundingBox();
486
+ const height = tempMesh.geometry.boundingBox.max.y - tempMesh.geometry.boundingBox.min.y;
487
+ // Assume origin is at the center Y for most default geometries
488
+ newObjData.position.y = (height / 2) + intersectPoint.y + 0.01; // Place base slightly above ground
489
+ } else {
490
+ // Fallback if mesh creation failed or no geometry
491
+ newObjData.position.y = 0.5 + intersectPoint.y; // Default lift
492
+ }
493
+
494
+ console.log(`Placing ${selectedObjectType} (${newObjData.obj_id}) at`, newObjData.position);
495
+
496
+ // 1. Add object visually immediately (Optimistic Update)
497
+ createAndPlaceObject(newObjData, true); // Mark as locally placed initially? Not needed now.
498
+
499
+ // 2. Send placement message to server via WebSocket
500
+ sendWebSocketMessage("place_object", {
501
+ username: myUsername,
502
+ object_data: newObjData
503
+ });
504
+
505
+ // 3. No need for local saving (sessionStorage) anymore
506
+ }
507
+ }
508
+
509
+ function onKeyDown(event) { /* ... (Keep as before) ... */ keysPressed[event.code] = true; }
510
+ function onKeyUp(event) { /* ... (Keep as before) ... */ keysPressed[event.code] = false; }
511
+ function onWindowResize() { /* ... (Keep as before) ... */ camera.aspect = window.innerWidth / window.innerHeight; camera.updateProjectionMatrix(); renderer.setSize(window.innerWidth, window.innerHeight); }
512
+
513
+ // --- Functions called by Python ---
514
+ function teleportPlayer(targetX, targetZ) { /* ... (Keep as before) ... */
515
+ console.log(`JS teleportPlayer called: x=${targetX}, z=${targetZ}`); if (playerMesh) { playerMesh.position.x = targetX; playerMesh.position.z = targetZ; const offset = new THREE.Vector3(0, 15, 20); const targetPosition = playerMesh.position.clone().add(offset); camera.position.copy(targetPosition); camera.lookAt(playerMesh.position); console.log("Player teleported to:", playerMesh.position); } else { console.error("Player mesh not found for teleport."); }
516
+ }
517
+ function updateSelectedObjectType(newType) { // Renamed from previous attempt
518
+ console.log("JS updateSelectedObjectType received:", newType);
519
+ selectedObjectType = newType;
520
+ // Optionally provide visual feedback (e.g., change cursor)
521
+ }
522
+
523
+ // --- Animation Loop & Helpers ---
524
+ function updatePlayerMovement() { /* ... (Keep as before, includes checkAndExpandGroundVisuals) ... */
525
+ if (!playerMesh) return; const moveDirection = new THREE.Vector3(0, 0, 0); if (keysPressed['KeyW'] || keysPressed['ArrowUp']) moveDirection.z -= 1; if (keysPressed['KeyS'] || keysPressed['ArrowDown']) moveDirection.z += 1; if (keysPressed['KeyA'] || keysPressed['ArrowLeft']) moveDirection.x -= 1; if (keysPressed['KeyD'] || keysPressed['ArrowRight']) moveDirection.x += 1;
526
+ if (moveDirection.lengthSq() > 0) { const forward = new THREE.Vector3(); camera.getWorldDirection(forward); forward.y = 0; forward.normalize(); const right = new THREE.Vector3().crossVectors(camera.up, forward).normalize(); const worldMove = new THREE.Vector3(); worldMove.add(forward.multiplyScalar(-moveDirection.z)); worldMove.add(right.multiplyScalar(-moveDirection.x)); worldMove.normalize().multiplyScalar(playerSpeed); playerMesh.position.add(worldMove); playerMesh.position.y = Math.max(playerMesh.position.y, 0.8); checkAndExpandGroundVisuals(); }
527
+ }
528
+ function checkAndExpandGroundVisuals() { /* ... (Keep as before) ... */
529
+ if (!playerMesh) return; const currentGridX = Math.floor(playerMesh.position.x / plotWidth); const currentGridZ = Math.floor(playerMesh.position.z / plotDepth); const viewDistanceGrids = 3; // Expand further?
530
+ for (let dx = -viewDistanceGrids; dx <= viewDistanceGrids; dx++) { for (let dz = -viewDistanceGrids; dz <= viewDistanceGrids; dz++) { const checkX = currentGridX + dx; const checkZ = currentGridZ + dz; const gridKey = `${checkX}_${checkZ}`; if (!groundMeshes[gridKey]) { createGroundPlane(checkX, checkZ, true); } } }
531
+ }
532
+ function updateCamera() { /* ... (Keep as before) ... */
533
+ if (!playerMesh) return; const offset = new THREE.Vector3(0, 12, 18); const targetPosition = playerMesh.position.clone().add(offset); camera.position.lerp(targetPosition, 0.08); const lookAtTarget = playerMesh.position.clone().add(new THREE.Vector3(0, 0.5, 0)); camera.lookAt(lookAtTarget);
534
+ }
535
+
536
+ function animate() {
537
+ requestAnimationFrame(animate);
538
+ updatePlayerMovement();
539
+ updateCamera();
540
+ renderer.render(scene, camera);
541
+ }
542
+
543
+ // --- Start ---
544
+ init();
545
+
546
+ </script>
547
+ </body>
548
+ </html>