Spaces:
Runtime error
Runtime error
| <html> | |
| <head> | |
| <title>Three.js Infinite World</title> | |
| <style> | |
| body { margin: 0; overflow: hidden; } | |
| canvas { display: block; } | |
| </style> | |
| </head> | |
| <body> | |
| <script type="importmap"> | |
| { | |
| "imports": { | |
| "three": "https://unpkg.com/three@0.163.0/build/three.module.js", | |
| "three/addons/": "https://unpkg.com/three@0.163.0/examples/jsm/" | |
| } | |
| } | |
| </script> | |
| <script type="module"> | |
| import * as THREE from 'three'; | |
| let scene, camera, renderer, playerMesh; | |
| let raycaster, mouse; | |
| const keysPressed = {}; | |
| const playerSpeed = 0.15; | |
| let newlyPlacedObjects = []; // Track objects added THIS session for saving | |
| // --- Access State from Streamlit --- | |
| const allInitialObjects = window.ALL_INITIAL_OBJECTS || []; | |
| const plotsMetadata = window.PLOTS_METADATA || []; | |
| const selectedObjectType = window.SELECTED_OBJECT_TYPE || "None"; | |
| const plotWidth = window.PLOT_WIDTH || 50.0; | |
| const plotDepth = window.PLOT_DEPTH || 50.0; | |
| const globalState = window.GLOBAL_STATE || { objects: [] }; | |
| // --- Setup materials and scene | |
| const groundMaterial = new THREE.MeshStandardMaterial({ | |
| color: 0x55aa55, roughness: 0.9, metalness: 0.1, side: THREE.DoubleSide | |
| }); | |
| 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, 4000); | |
| camera.position.set(0, 15, 20); | |
| camera.lookAt(0, 0, 0); | |
| scene.add(camera); | |
| setupLighting(); | |
| setupInitialGround(); | |
| 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(); | |
| 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); | |
| // Define global functions for Streamlit callbacks. | |
| window.teleportPlayer = teleportPlayer; | |
| window.getSaveDataAndPosition = getSaveDataAndPosition; | |
| window.resetNewlyPlacedObjects = resetNewlyPlacedObjects; | |
| console.log("Three.js Initialized. World ready."); | |
| animate(); | |
| } | |
| function setupLighting() { | |
| const ambientLight = new THREE.AmbientLight(0xffffff, 0.5); | |
| scene.add(ambientLight); | |
| const directionalLight = new THREE.DirectionalLight(0xffffff, 1.0); | |
| directionalLight.position.set(50, 150, 100); | |
| directionalLight.castShadow = true; | |
| directionalLight.shadow.mapSize.width = 4096; | |
| directionalLight.shadow.mapSize.height = 4096; | |
| directionalLight.shadow.camera.near = 0.5; | |
| directionalLight.shadow.camera.far = 500; | |
| directionalLight.shadow.camera.left = -150; | |
| directionalLight.shadow.camera.right = 150; | |
| directionalLight.shadow.camera.top = 150; | |
| directionalLight.shadow.camera.bottom = -150; | |
| directionalLight.shadow.bias = -0.001; | |
| scene.add(directionalLight); | |
| } | |
| function setupInitialGround() { | |
| console.log(`Setting up initial ground for ${plotsMetadata.length} plots.`); | |
| plotsMetadata.forEach(plot => { | |
| createGroundPlane(plot.grid_x, plot.grid_z, false); | |
| }); | |
| if (plotsMetadata.length === 0) { | |
| createGroundPlane(0, 0, false); | |
| } | |
| } | |
| function createGroundPlane(gridX, gridZ, isPlaceholder) { | |
| const gridKey = `${gridX}_${gridZ}`; | |
| const groundGeometry = new THREE.PlaneGeometry(plotWidth, plotDepth); | |
| const material = groundMaterial; | |
| const groundMesh = new THREE.Mesh(groundGeometry, material); | |
| groundMesh.rotation.x = -Math.PI / 2; | |
| groundMesh.position.x = gridX * plotWidth + plotWidth / 2; | |
| groundMesh.position.z = gridZ * plotDepth + plotDepth / 2; | |
| groundMesh.receiveShadow = true; | |
| scene.add(groundMesh); | |
| } | |
| function setupPlayer() { | |
| 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(plotWidth/2, 1, plotDepth/2); | |
| playerMesh.castShadow = true; | |
| scene.add(playerMesh); | |
| } | |
| function loadInitialObjects() { | |
| console.log(`Loading ${allInitialObjects.length} initial objects from Python.`); | |
| allInitialObjects.forEach(objData => { createAndPlaceObject(objData, false); }); | |
| // Also load objects from the global state (if any). | |
| console.log(`Loading ${globalState.objects ? globalState.objects.length : 0} objects from global state.`); | |
| if(globalState.objects) { | |
| globalState.objects.forEach(objData => { createAndPlaceObject(objData, false); }); | |
| } | |
| console.log("Finished loading objects."); | |
| } | |
| function createAndPlaceObject(objData, isNewObject) { | |
| let loadedObject = null; | |
| 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:", objData.type); break; | |
| } | |
| if (loadedObject) { | |
| // Prefer properties from objData using either new or old key names. | |
| 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) { | |
| loadedObject.position.set(objData.pos_x, objData.pos_y, objData.pos_z); | |
| } | |
| if (objData.rotation) { | |
| loadedObject.rotation.set(objData.rotation._x, objData.rotation._y, objData.rotation._z, objData.rotation._order || 'XYZ'); | |
| } else if (objData.rot_x !== undefined) { | |
| loadedObject.rotation.set(objData.rot_x, objData.rot_y, objData.rot_z, objData.rot_order || 'XYZ'); | |
| } | |
| loadedObject.userData.obj_id = objData.obj_id || loadedObject.userData.obj_id; | |
| scene.add(loadedObject); | |
| if (isNewObject) { newlyPlacedObjects.push(loadedObject); } | |
| return loadedObject; | |
| } | |
| return null; | |
| } | |
| // Sample object creation functions. | |
| function createSimpleHouse() { | |
| const group = new THREE.Group(); | |
| const mat1 = new THREE.MeshStandardMaterial({color:0xffccaa}); | |
| const m1 = new THREE.Mesh(new THREE.BoxGeometry(2,1.5,2.5), mat1); | |
| m1.position.y = 0.75; | |
| group.add(m1); | |
| return group; | |
| } | |
| function createTree() { | |
| const group = new THREE.Group(); | |
| const mat1 = new THREE.MeshStandardMaterial({color:0x8B4513}); | |
| const m1 = new THREE.Mesh(new THREE.CylinderGeometry(0.3,0.4,2,8), mat1); | |
| m1.position.y = 1; | |
| group.add(m1); | |
| const mat2 = new THREE.MeshStandardMaterial({color:0x228B22}); | |
| const m2 = new THREE.Mesh(new THREE.IcosahedronGeometry(1.2,0), mat2); | |
| m2.position.y = 2.8; | |
| group.add(m2); | |
| return group; | |
| } | |
| function createRock() { | |
| const mat = new THREE.MeshStandardMaterial({color:0xaaaaaa}); | |
| const rock = new THREE.Mesh(new THREE.IcosahedronGeometry(0.7,0), mat); | |
| rock.position.y = 0.35; | |
| rock.rotation.set(Math.random()*Math.PI, Math.random()*Math.PI, 0); | |
| return rock; | |
| } | |
| function createFencePost() { | |
| const mat = new THREE.MeshStandardMaterial({color:0xdeb887}); | |
| const post = new THREE.Mesh(new THREE.BoxGeometry(0.2,1.5,0.2), mat); | |
| post.position.y = 0.75; | |
| return post; | |
| } | |
| function onMouseMove(event) { | |
| mouse.x = (event.clientX / window.innerWidth) * 2 - 1; | |
| mouse.y = -(event.clientY / window.innerHeight) * 2 + 1; | |
| } | |
| function onDocumentClick(event) { | |
| if (selectedObjectType === "None") return; | |
| raycaster.setFromCamera(mouse, camera); | |
| const intersects = raycaster.intersectObjects(scene.children); | |
| if (intersects.length > 0) { | |
| const intersectPoint = intersects[0].point; | |
| let newObject = null; | |
| switch (selectedObjectType) { | |
| case "Simple House": newObject = createSimpleHouse(); break; | |
| case "Tree": newObject = createTree(); break; | |
| case "Rock": newObject = createRock(); break; | |
| case "Fence Post": newObject = createFencePost(); break; | |
| default: return; | |
| } | |
| if (newObject) { | |
| newObject.position.copy(intersectPoint); | |
| scene.add(newObject); | |
| newlyPlacedObjects.push(newObject); | |
| console.log(`Placed new ${selectedObjectType}. Total new objects: ${newlyPlacedObjects.length}`); | |
| } | |
| } | |
| } | |
| function onKeyDown(event) { keysPressed[event.code] = true; } | |
| function onKeyUp(event) { keysPressed[event.code] = false; } | |
| function teleportPlayer(targetX, targetZ) { | |
| if (playerMesh) { | |
| playerMesh.position.x = targetX; | |
| playerMesh.position.z = targetZ; | |
| camera.position.x = targetX; | |
| camera.position.z = targetZ + 20; | |
| console.log("Player teleported."); | |
| } | |
| } | |
| // This function packages new object data and player position for Streamlit. | |
| function getSaveDataAndPosition() { | |
| const objectsToSave = newlyPlacedObjects.map(obj => { | |
| return { | |
| obj_id: obj.userData.obj_id, | |
| type: selectedObjectType, | |
| 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 } | |
| }; | |
| }); | |
| // Use the player mesh's position as the player position. | |
| const playerPos = playerMesh ? { x: playerMesh.position.x, y: playerMesh.position.y, z: playerMesh.position.z } : {x:0, y:0, z:0}; | |
| const payload = { | |
| playerPosition: playerPos, | |
| objectsToSave: objectsToSave | |
| }; | |
| console.log("Prepared payload:", payload); | |
| // Clear newlyPlacedObjects after packaging. | |
| newlyPlacedObjects = []; | |
| return JSON.stringify(payload); | |
| } | |
| function resetNewlyPlacedObjects() { | |
| newlyPlacedObjects = []; | |
| } | |
| function animate() { | |
| requestAnimationFrame(animate); | |
| renderer.render(scene, camera); | |
| } | |
| init(); | |
| </script> | |
| </body> | |
| </html> | |