Spaces:
Sleeping
Sleeping
<html> | |
<head> | |
<title>Three.js Shared World</title> | |
<style> | |
body { margin: 0; overflow: hidden; } | |
canvas { display: block; } | |
/* No Save button needed here anymore */ | |
</style> | |
</head> | |
<body> | |
<script type="importmap"> | |
{ | |
"imports": { | |
"three": "https://unpkg.com/[email protected]/build/three.module.js", | |
"three/addons/": "https://unpkg.com/[email protected]/examples/jsm/" | |
} | |
} | |
</script> | |
<script type="module"> | |
import * as THREE from 'three'; | |
let scene, camera, renderer, groundMesh = null, playerMesh; | |
let raycaster, mouse; | |
const keysPressed = {}; | |
const playerSpeed = 0.15; | |
let newlyPlacedObjects = []; // Track objects added THIS session for saving | |
// --- Session Storage Key --- | |
const SESSION_STORAGE_KEY = 'unsavedWorldBuilderState'; | |
// --- Access State from Streamlit --- | |
const allInitialObjects = window.ALL_INITIAL_OBJECTS || []; | |
const selectedObjectType = window.SELECTED_OBJECT_TYPE || "None"; | |
const plotWidth = window.PLOT_WIDTH || 50.0; | |
const nextPlotXOffset = window.NEXT_PLOT_X_OFFSET || 0.0; // Where the next plot starts | |
function init() { | |
scene = new THREE.Scene(); | |
scene.background = new THREE.Color(0xabcdef); | |
const aspect = window.innerWidth / window.innerHeight; | |
camera = new THREE.PerspectiveCamera(60, aspect, 0.1, 2000); // Increase far plane | |
camera.position.set(0, 15, 20); | |
camera.lookAt(0, 0, 0); | |
scene.add(camera); | |
setupLighting(); | |
setupGround(); // Ground needs to be potentially very wide now | |
setupPlayer(); | |
raycaster = new THREE.Raycaster(); | |
mouse = new THREE.Vector2(); | |
renderer = new THREE.WebGLRenderer({ antialias: true }); | |
renderer.setSize(window.innerWidth, window.innerHeight); | |
renderer.shadowMap.enabled = true; | |
renderer.shadowMap.type = THREE.PCFSoftShadowMap; | |
document.body.appendChild(renderer.domElement); | |
loadInitialObjects(); // Load ALL objects passed from Python | |
// *** ADDED: Restore unsaved state from sessionStorage *** | |
restoreUnsavedState(); | |
// Event Listeners | |
document.addEventListener('mousemove', onMouseMove, false); | |
document.addEventListener('click', onDocumentClick, false); | |
window.addEventListener('resize', onWindowResize, false); | |
document.addEventListener('keydown', onKeyDown); | |
document.addEventListener('keyup', onKeyUp); | |
// No save button listener needed here | |
// Define global functions needed by Python/streamlit-js-eval | |
window.teleportPlayer = teleportPlayer; | |
window.getSaveData = getSaveData; | |
window.resetNewlyPlacedObjects = resetNewlyPlacedObjects; | |
console.log("Three.js Initialized. Ready for commands."); | |
animate(); | |
} | |
function setupLighting() { /* ... unchanged ... */ | |
const ambientLight = new THREE.AmbientLight(0xffffff, 0.5); | |
scene.add(ambientLight); | |
const directionalLight = new THREE.DirectionalLight(0xffffff, 1.0); | |
directionalLight.position.set(50, 100, 75); // Adjust light position for wider world | |
directionalLight.castShadow = true; | |
directionalLight.shadow.mapSize.width = 2048*2; // Larger shadow map maybe needed | |
directionalLight.shadow.mapSize.height = 2048*2; | |
directionalLight.shadow.camera.near = 0.5; | |
directionalLight.shadow.camera.far = 500; // Increase shadow distance | |
// Adjust shadow camera frustum dynamically later if needed, make it wide for now | |
directionalLight.shadow.camera.left = -100; | |
directionalLight.shadow.camera.right = 100; | |
directionalLight.shadow.camera.top = 100; | |
directionalLight.shadow.camera.bottom = -100; | |
directionalLight.shadow.bias = -0.001; | |
scene.add(directionalLight); | |
} | |
function setupGround() { /* ... unchanged ... */ | |
const groundWidth = Math.max(plotWidth, nextPlotXOffset + plotWidth); | |
const groundDepth = 50; | |
const groundGeometry = new THREE.PlaneGeometry(groundWidth, groundDepth); | |
const groundMaterial = new THREE.MeshStandardMaterial({ color: 0x55aa55, roughness: 0.9, metalness: 0.1 }); | |
groundMesh = new THREE.Mesh(groundGeometry, groundMaterial); | |
groundMesh.rotation.x = -Math.PI / 2; | |
groundMesh.position.y = -0.05; | |
groundMesh.position.x = (groundWidth / 2.0) - (plotWidth / 2.0) ; | |
groundMesh.receiveShadow = true; | |
scene.add(groundMesh); | |
console.log(`Ground setup with width: ${groundWidth} centered near x=0`); | |
} | |
function setupPlayer() { /* ... unchanged ... */ | |
const playerGeo = new THREE.CapsuleGeometry(0.4, 0.8, 4, 8); | |
const playerMat = new THREE.MeshStandardMaterial({ color: 0x0000ff, roughness: 0.6 }); | |
playerMesh = new THREE.Mesh(playerGeo, playerMat); | |
playerMesh.position.set(2, 0.4 + 0.8/2, 5); // Start near origin (x=2 to be slightly in first plot) | |
playerMesh.castShadow = true; | |
playerMesh.receiveShadow = true; | |
scene.add(playerMesh); | |
} | |
function loadInitialObjects() { | |
console.log(`Loading ${allInitialObjects.length} initial objects from Python.`); | |
allInitialObjects.forEach(objData => { | |
createAndPlaceObject(objData, false); // Use helper, false=don't add to newlyPlaced | |
}); | |
console.log("Finished loading initial objects."); | |
} | |
// --- NEW: Helper to create/place objects from data --- | |
function createAndPlaceObject(objData, isNewObject) { | |
let loadedObject = null; | |
// Need to deserialize object based on 'type' field from CSV/Storage | |
switch (objData.type) { | |
case "Simple House": loadedObject = createSimpleHouse(); break; | |
case "Tree": loadedObject = createTree(); break; | |
case "Rock": loadedObject = createRock(); break; | |
case "Fence Post": loadedObject = createFencePost(); break; | |
default: console.warn("Unknown object type in data:", objData.type); break; | |
} | |
if (loadedObject) { | |
// Position depends on whether it's from initial load (world) or storage (world) | |
// or potentially relative if storage format changes (keep world for now) | |
if (objData.position && objData.position.x !== undefined) { | |
loadedObject.position.set(objData.position.x, objData.position.y, objData.position.z); | |
} else if (objData.pos_x !== undefined) { // Handle CSV loaded format too | |
loadedObject.position.set(objData.pos_x, objData.pos_y, objData.pos_z); | |
} | |
// Apply rotation | |
if (objData.rotation) { // Format from storage/newlyPlaced | |
loadedObject.rotation.set(objData.rotation._x, objData.rotation._y, objData.rotation._z, objData.rotation._order || 'XYZ'); | |
} else if (objData.rot_x !== undefined) { // Format from CSV | |
loadedObject.rotation.set(objData.rot_x, objData.rot_y, objData.rot_z, objData.rot_order || 'XYZ'); | |
} | |
// Assign unique ID if it has one, else use the one generated by createObjectBase | |
loadedObject.userData.obj_id = objData.obj_id || loadedObject.userData.obj_id; | |
scene.add(loadedObject); | |
if (isNewObject) { | |
// Only add to this array if it's being placed now or restored from session | |
newlyPlacedObjects.push(loadedObject); | |
} | |
return loadedObject; // Return the mesh/group | |
} | |
return null; | |
} | |
// --- NEW: Save/Load/Clear Unsaved State using sessionStorage --- | |
function saveUnsavedState() { | |
try { | |
const stateToSave = newlyPlacedObjects.map(obj => ({ | |
obj_id: obj.userData.obj_id, | |
type: obj.userData.type, | |
position: { x: obj.position.x, y: obj.position.y, z: obj.position.z }, | |
rotation: { _x: obj.rotation.x, _y: obj.rotation.y, _z: obj.rotation.z, _order: obj.rotation.order } | |
})); | |
sessionStorage.setItem(SESSION_STORAGE_KEY, JSON.stringify(stateToSave)); | |
console.log(`Saved ${stateToSave.length} unsaved objects to sessionStorage.`); | |
} catch (e) { | |
console.error("Error saving state to sessionStorage:", e); | |
} | |
} | |
function restoreUnsavedState() { | |
try { | |
const savedState = sessionStorage.getItem(SESSION_STORAGE_KEY); | |
if (savedState) { | |
console.log("Found unsaved state in sessionStorage. Restoring..."); | |
const objectsToRestore = JSON.parse(savedState); | |
if (Array.isArray(objectsToRestore)) { | |
// Clear existing newlyPlaced array before restoring | |
newlyPlacedObjects = []; | |
let count = 0; | |
objectsToRestore.forEach(objData => { | |
// Create object, add to scene, AND add to newlyPlacedObjects array | |
if(createAndPlaceObject(objData, true)) { | |
count++; | |
} | |
}); | |
console.log(`Restored ${count} objects.`); | |
} | |
} else { | |
console.log("No unsaved state found in sessionStorage."); | |
} | |
} catch (e) { | |
console.error("Error restoring state from sessionStorage:", e); | |
// Clear potentially corrupted storage | |
sessionStorage.removeItem(SESSION_STORAGE_KEY); | |
} | |
} | |
function clearUnsavedState() { | |
sessionStorage.removeItem(SESSION_STORAGE_KEY); | |
newlyPlacedObjects = []; // Clear the array in memory too | |
console.log("Cleared unsaved state from memory and sessionStorage."); | |
} | |
// --- Object Creation Functions (MUST add userData.type and obj_id) --- | |
function createObjectBase(type) { // Helper to assign common data | |
const obj = { userData: { type: type, obj_id: THREE.MathUtils.generateUUID() } }; | |
return obj; | |
} | |
function createSimpleHouse() { /* ... unchanged, uses createObjectBase ... */ | |
const base = createObjectBase("Simple House"); | |
const group = new THREE.Group(); Object.assign(group, base); | |
const mainMaterial = new THREE.MeshStandardMaterial({ color: 0xffccaa, roughness: 0.8 }); | |
const roofMaterial = new THREE.MeshStandardMaterial({ color: 0xaa5533, roughness: 0.7 }); | |
const baseMesh = new THREE.Mesh(new THREE.BoxGeometry(2, 1.5, 2.5), mainMaterial); | |
baseMesh.position.y = 1.5 / 2; baseMesh.castShadow = true; baseMesh.receiveShadow = true; group.add(baseMesh); | |
const roof = new THREE.Mesh(new THREE.ConeGeometry(1.8, 1, 4), roofMaterial); | |
roof.position.y = 1.5 + 1 / 2; roof.rotation.y = Math.PI / 4; roof.castShadow = true; roof.receiveShadow = true; group.add(roof); | |
return group; | |
} | |
function createTree() { /* ... unchanged, uses createObjectBase ... */ | |
const base = createObjectBase("Tree"); const group = new THREE.Group(); Object.assign(group, base); | |
const trunkMaterial = new THREE.MeshStandardMaterial({ color: 0x8B4513, roughness: 0.9 }); | |
const leavesMaterial = new THREE.MeshStandardMaterial({ color: 0x228B22, roughness: 0.8 }); | |
const trunk = new THREE.Mesh(new THREE.CylinderGeometry(0.3, 0.4, 2, 8), trunkMaterial); | |
trunk.position.y = 2 / 2; trunk.castShadow = true; trunk.receiveShadow = true; group.add(trunk); | |
const leaves = new THREE.Mesh(new THREE.IcosahedronGeometry(1.2, 0), leavesMaterial); | |
leaves.position.y = 2 + 0.8; leaves.castShadow = true; leaves.receiveShadow = true; group.add(leaves); | |
return group; | |
} | |
function createRock() { /* ... unchanged, uses createObjectBase ... */ | |
const base = createObjectBase("Rock"); | |
const rockMaterial = new THREE.MeshStandardMaterial({ color: 0xaaaaaa, roughness: 0.8, metalness: 0.1 }); | |
const rock = new THREE.Mesh(new THREE.IcosahedronGeometry(0.7, 0), rockMaterial); Object.assign(rock, base); | |
rock.position.y = 0.7 / 2; rock.rotation.x = Math.random() * Math.PI; rock.rotation.y = Math.random() * Math.PI; | |
rock.castShadow = true; rock.receiveShadow = true; | |
return rock; | |
} | |
function createFencePost() { /* ... unchanged, uses createObjectBase ... */ | |
const base = createObjectBase("Fence Post"); | |
const postMaterial = new THREE.MeshStandardMaterial({ color: 0xdeb887, roughness: 0.9 }); | |
const post = new THREE.Mesh(new THREE.BoxGeometry(0.2, 1.5, 0.2), postMaterial); Object.assign(post, base); | |
post.position.y = 1.5 / 2; post.castShadow = true; post.receiveShadow = true; | |
return post; | |
} | |
// --- Event Handlers --- | |
function onMouseMove(event) { /* ... unchanged ... */ | |
mouse.x = (event.clientX / window.innerWidth) * 2 - 1; | |
mouse.y = -(event.clientY / window.innerHeight) * 2 + 1; | |
} | |
function onDocumentClick(event) { | |
if (selectedObjectType === "None" || !groundMesh) return; | |
raycaster.setFromCamera(mouse, camera); | |
const intersects = raycaster.intersectObject(groundMesh); // Intersect ground ONLY | |
if (intersects.length > 0) { | |
const intersectPoint = intersects[0].point; | |
let newObjectToPlace = null; // Use a different name to avoid confusion | |
switch (selectedObjectType) { | |
case "Simple House": newObjectToPlace = createSimpleHouse(); break; | |
case "Tree": newObjectToPlace = createTree(); break; | |
case "Rock": newObjectToPlace = createRock(); break; | |
case "Fence Post": newObjectToPlace = createFencePost(); break; | |
default: return; | |
} | |
if (newObjectToPlace) { | |
// Position in WORLD coordinates where clicked | |
newObjectToPlace.position.copy(intersectPoint); | |
// Adjust Y based on object's geometry center if needed | |
// (Create functions mostly handle placing base at y=0) | |
scene.add(newObjectToPlace); | |
newlyPlacedObjects.push(newObjectToPlace); // Add to list for saving | |
// *** ADDED: Save state to sessionStorage immediately after placing *** | |
saveUnsavedState(); | |
console.log(`Placed new ${selectedObjectType}. Total unsaved: ${newlyPlacedObjects.length}`); | |
} | |
} | |
} | |
function onKeyDown(event) { keysPressed[event.code] = true; } | |
function onKeyUp(event) { keysPressed[event.code] = false; } | |
// --- Functions called by Python via streamlit-js-eval --- | |
function teleportPlayer(targetX) { /* ... unchanged ... */ | |
console.log("JS teleportPlayer called with targetX:", targetX); | |
if (playerMesh) { | |
playerMesh.position.x = targetX + 2.0; | |
playerMesh.position.z = 5.0; | |
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."); } | |
} | |
function getSaveData() { // Called by Python when save button is clicked | |
console.log(`JS getSaveData called. Returning ${newlyPlacedObjects.length} new objects.`); | |
// Prepare data in the format Python expects (world positions) | |
const objectsToSave = newlyPlacedObjects.map(obj => { | |
if (!obj.userData || !obj.userData.type) { return null; } | |
const rotation = { _x: obj.rotation.x, _y: obj.rotation.y, _z: obj.rotation.z, _order: obj.rotation.order }; | |
return { | |
obj_id: obj.userData.obj_id, | |
type: obj.userData.type, | |
position: { x: obj.position.x, y: obj.position.y, z: obj.position.z }, | |
rotation: rotation | |
}; | |
}).filter(obj => obj !== null); | |
console.log("Prepared data for saving:", objectsToSave); | |
return JSON.stringify(objectsToSave); // Return as JSON string | |
} | |
function resetNewlyPlacedObjects() { // Called by Python AFTER successful save | |
console.log(`JS resetNewlyPlacedObjects called.`); | |
clearUnsavedState(); // Clear memory array AND sessionStorage | |
} | |
// --- Animation Loop --- | |
function updatePlayerMovement() { /* ... unchanged ... */ | |
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; | |
if (moveDirection.lengthSq() > 0) { | |
moveDirection.normalize().multiplyScalar(playerSpeed); | |
playerMesh.position.add(moveDirection); | |
playerMesh.position.y = Math.max(playerMesh.position.y, 0.4 + 0.8/2); | |
} | |
} | |
function updateCamera() { /* ... unchanged ... */ | |
if (!playerMesh) return; | |
const offset = new THREE.Vector3(0, 15, 20); | |
const targetPosition = playerMesh.position.clone().add(offset); | |
camera.position.lerp(targetPosition, 0.08); | |
camera.lookAt(playerMesh.position); | |
} | |
function onWindowResize() { /* ... unchanged ... */ | |
camera.aspect = window.innerWidth / window.innerHeight; | |
camera.updateProjectionMatrix(); | |
renderer.setSize(window.innerWidth, window.innerHeight); | |
} | |
function animate() { | |
requestAnimationFrame(animate); | |
updatePlayerMovement(); | |
updateCamera(); | |
renderer.render(scene, camera); | |
} | |
// --- Start --- | |
init(); | |
</script> | |
</body> | |
</html> |