Skip to content
TheChatArchiveThe Chat Archive
Geminigemini-2.5-flash-preview-04-17· GoogleHugging Face LMArena Human Preference 140K

Make it so that the player can't see a voxel if another voxel is blocking its view from…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with DeepSeekdeepseek-v3-0324’s answer.
  1. User

    Make it so that the player can't see a voxel if another voxel is blocking its view from the player, so as a performance fix.

  2. Gemini Assistant

    Okay, implementing true occlusion culling (checking if a voxel is blocked by other voxels from the player's view) in a performant way for a large number of individual voxels is quite complex in real-time rendering, especially in a browser with WebGL.

    However, there are highly effective performance optimizations we can apply:

    1. Instanced Rendering (THREE.InstancedMesh): This is the most significant performance improvement. Instead of creating thousands of separate THREE.Mesh objects (each requiring its own drawing command), we use InstancedMesh to render many copies of the same geometry (the voxel cube) in a single, highly optimized draw call. Three.js can then frustum-cull individual instances efficiently.
    2. Generating Only Visible/Surface Voxels: We can refine the generation logic to only create voxels on or near the surface, and perhaps the water volume, avoiding generating blocks deep inside the planet that would never be seen.

    Let's implement these two optimizations. We'll still generate voxels within a certain depth range from the noisy surface, including water below a certain level.

    First, we need a simple 3D noise function, as Math.sin/Math.cos isn't great for complex terrain. I'll include a minimal 3D Simplex Noise implementation.

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <title>High-Resolution Voxel Planet Generator (Optimized)</title>
        <style>
            body { 
                margin: 0;
                overflow: hidden;
            }
            canvas { 
                width: 100%;
                height: 100%;
                display: block; /* Prevent default margin issues */
            }
        </style>
    </head>
    <body>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
        <script>
            // Simple 3D Simplex Noise (Public Domain, recommended for procedural generation)
            // Source: https://gist.github.com/dontstudyus/6526195 (slightly adapted)
            class SimplexNoise {
                constructor(random) {
                    if (random == undefined) random = Math.random;
                    this.p = new Uint8Array(256);
                    this.perm = new Uint8Array(512);
                    this.permMod12 = new Uint8Array(512);
                    for (let i = 0; i < 256; i++) this.p[i] = i;
                    for (let i = 0; i < 255; i++) {
                        const r = i + ~~(random() * (256 - i));
                        const temp = this.p[i];
                        this.p[i] = this.p[r];
                        this.p[r] = temp;
                    }
                    for (let i = 0; i < 512; i++) {
                        this.perm[i] = this.p[i & 255];
                        this.permMod12[i] = this.perm[i] % 12;
                    }
                }
                dot2(g, x, y) { return g[0] * x + g[1] * y; }
                dot3(g, x, y, z) { return g[0] * x + g[1] * y + g[2] * z; }
                dot4(g, x, y, z, w) { return g[0] * x + g[1] * y + g[2] * z + g[3] * w; }
                noise3d(xin, yin, zin) {
                    const F3 = 1.0/3.0;
                    const s = (xin + yin + zin) * F3;
                    const i = Math.floor(xin + s);
                    const j = Math.floor(yin + s);
                    const k = Math.floor(zin + s);
                    const G3 = 1.0/6.0;
                    const t = (i + j + k) * G3;
                    const X0 = i - t;
                    const Y0 = j - t;
                    const Z0 = k - t;
                    const x0 = xin - X0;
                    const y0 = yin - Y0;
                    const z0 = zin - Z0;
                    let i1, j1, k1;
                    let i2, j2, k2;
                    if (x0 >= y0) { if (y0 >= z0) { i1=1;j1=0;k1=0; i2=1;j2=1;k2=0; } else if (x0 >= z0) { i1=1;j1=0;k1=0; i2=1;j2=0;k2=1; } else { i1=0;j1=0;k1=1; i2=1;j2=0;k2=1; } } else { if (y0 < z0) { i1=0;j1=0;k1=1; i2=0;j2=1;k2=1; } else if (x0 < z0) { i1=0;j1=1;k1=0; i2=0;j2=1;k2=1; } else { i1=0;j1=1;k1=0; i2=1;j2=1;k2=0; } }
                    const x1 = x0 - i1 + G3;
                    const y1 = y0 - j1 + G3;
                    const z1 = z0 - k1 + G3;
                    const x2 = x0 - i2 + 2.0*G3;
                    const y2 = y0 - j2 + 2.0*G3;
                    const z2 = z0 - k2 + 2.0*G3;
                    const x3 = x0 - 1.0 + 3.0*G3;
                    const y3 = y0 - 1.0 + 3.0*G3;
                    const z3 = z0 - 1.0 + 3.0*G3;
                    const ii = i & 255;
                    const jj = j & 255;
                    const kk = k & 255;
                    const gi0 = this.permMod12[ii+this.perm[jj+this.perm[kk]]];
                    const gi1 = this.permMod12[ii+i1+this.perm[jj+j1+this.perm[kk+k1]]];
                    const gi2 = this.permMod12[ii+i2+this.perm[jj+j2+this.perm[kk+k2]]];
                    const gi3 = this.permMod12[ii+1+this.perm[jj+1+this.perm[kk+1]]];
                    const grad3 = [
                        [1,1,0],[-1,1,0],[1,-1,0],[-1,-1,0],
                        [1,0,1],[-1,0,1],[1,0,-1],[-1,0,-1],
                        [0,1,1],[0,-1,1],[0,1,-1],[0,-1,-1]
                    ];
                    const n0 = dot3(grad3[gi0], x0, y0, z0);
                    const n1 = dot3(grad3[gi1], x1, y1, z1);
                    const n2 = dot3(grad3[gi2], x2, y2, z2);
                    const n3 = dot3(grad3[gi3], x3, y3, z3);
                    const t0 = 0.6 - x0*x0 - y0*y0 - z0*z0;
                    const t1 = 0.6 - x1*x1 - y1*y1 - z1*z1;
                    const t2 = 0.6 - x2*x2 - y2*y2 - z2*z2;
                    const t3 = 0.6 - x3*x3 - y3*y3 - z3*z3;
                    let a0 = 0, a1 = 0, a2 = 0, a3 = 0;
                    if (t0 < 0) a0 = 0; else a0 = t0*t0*t0*t0*n0;
                    if (t1 < 0) a1 = 0; else a1 = t1*t1*t1*t1*n1;
                    if (t2 < 0) a2 = 0; else a2 = t2*t2*t2*t2*n2;
                    if (t3 < 0) a3 = 0; else a3 = t3*t3*t3*t3*n3;
                    return 32.0 * (a0 + a1 + a2 + a3); // Range [-1, 1]
                }
            }
            // Create a noise instance (using Math.random for randomness)
            const noise = new SimplexNoise();
    
    
            let scene, camera, renderer;
            let planetGroup; // Use a group to hold the instanced meshes
            const baseRadius = 10;        // Base size of the planet
            let resolutionStep = 0.5;   // Voxel size and grid step (lower is higher res)
            const noiseScale = 0.2;     // How spread out the noise is (lower is larger features)
            const noiseAmplitude = 3;   // How much the terrain varies in height
            const seaLevelOffset = -1; // Offset from baseRadius for sea level
            const sandHeight = 1;       // Height range for sand above sea level
            const terrainThickness = 2; // How many layers of voxels below surface/sea level to generate
    
            // Arrays to store positions for each voxel type
            let waterPositions = [];
            let sandPositions = [];
            let grassPositions = [];
            let matrix = new THREE.Matrix4(); // Reusable matrix for setting instance positions
    
            function init() {
                // Setup scene
                scene = new THREE.Scene();
                camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 2000); // Increased far plane
                renderer = new THREE.WebGLRenderer({ antialias: true }); // Add antialiasing
                renderer.setSize(window.innerWidth, window.innerHeight);
                document.body.appendChild(renderer.domElement);
    
                // Add lighting
                const sunLight = new THREE.DirectionalLight(0xffffff, 1);
                sunLight.position.set(50, 50, 50).normalize(); // Position the sun
                scene.add(sunLight);
                scene.add(new THREE.AmbientLight(0x404040)); // Soft ambient light
    
                // Setup camera position
                camera.position.set(0, baseRadius + noiseAmplitude + 15, 0); // Start camera above the planet
    
                // Generate planet using instancing
                generatePlanetInstanced();
    
                // Add stars
                addStars();
    
                // Start animation loop
                animate();
    
                // Add controls
                setupControls();
    
                // Handle window resize
                window.addEventListener('resize', onWindowResize, false);
            }
    
            function generatePlanetInstanced() {
                // Clear previous planet if any
                if (planetGroup) {
                    scene.remove(planetGroup);
                    planetGroup.children.forEach(mesh => mesh.dispose()); // Dispose geometry/materials if not shared
                }
                planetGroup = new THREE.Group();
    
                waterPositions = [];
                sandPositions = [];
                grassPositions = [];
    
                const voxelSize = resolutionStep;
    
                // Determine the bounding box for the generation grid
                // We need to iterate over a volume that covers the noisy sphere
                const maxExtent = baseRadius + noiseAmplitude + terrainThickness + voxelSize;
    
                // First Pass: Determine where voxels should *potentially* exist and what material they are
                // We'll store positions in arrays keyed by material type
                // This version generates a solid volume up to the noisy surface
                // and layers materials based on height.
                // We limit iteration to save time, only where terrain could be.
                for (let x = -maxExtent; x <= maxExtent; x += voxelSize) {
                    for (let y = -maxExtent; y <= maxExtent; y += voxelSize) {
                        for (let z = -maxExtent; z <= maxExtent; z += voxelSize) {
    
                            const position = new THREE.Vector3(x, y, z);
                            const dist = position.length();
    
                            // Normalize position for 3D noise sampling across the sphere's surface
                            const normalizedPos = position.clone().normalize();
                            // Sample 3D noise. Noise returns [-1, 1], map to [0, 1]
                            const n = (noise.noise3d(
                                normalizedPos.x * noiseScale,
                                normalizedPos.y * noiseScale,
                                normalizedPos.z * noiseScale
                            ) + 1) / 2;
    
                            // Calculate the height of the terrain surface at this point based on noise
                            const surfaceHeight = baseRadius + n * noiseAmplitude;
    
                            const seaLevel = baseRadius + seaLevelOffset;
    
                            // Only place a voxel if it's below the surface height
                            if (dist <= surfaceHeight + 0.5 * voxelSize) { // Add half voxel size tolerance
    
                                // Determine material based on height
                                if (dist < seaLevel) {
                                    // Below sea level, only add water if the surface is also below or at this level
                                    // This prevents water appearing inside mountains above sea level
                                    if (dist <= surfaceHeight + 0.5 * voxelSize) {
                                       waterPositions.push(position);
                                    }
                                } else if (dist < seaLevel + sandHeight) {
                                    // Between sea level and seaLevel + sandHeight
                                    sandPositions.push(position);
                                } else {
                                    // Above sand height and below surfaceHeight
                                    grassPositions.push(position);
                                }
                            }
                        }
                    }
                }
                
                // Second Pass: Create Instanced Meshes
                const voxelGeometry = new THREE.BoxGeometry(voxelSize, voxelSize, voxelSize);
                const waterMaterial = new THREE.MeshPhongMaterial({ color: 0x0077be, flatShading: true }); // flatShading makes blocky look better
                const sandMaterial = new THREE.MeshPhongMaterial({ color: 0xc2b280, flatShading: true });
                const grassMaterial = new THREE.MeshPhongMaterial({ color: 0x567d46, flatShading: true });
    
                // Create instanced meshes for each material type
                if (waterPositions.length > 0) {
                    const waterMesh = new THREE.InstancedMesh(voxelGeometry, waterMaterial, waterPositions.length);
                     for (let i = 0; i < waterPositions.length; i++) {
                        matrix.setPosition(waterPositions[i]);
                        waterMesh.setMatrixAt(i, matrix);
                    }
                    waterMesh.instanceMatrix.needsUpdate = true;
                    planetGroup.add(waterMesh);
                }
    
                 if (sandPositions.length > 0) {
                    const sandMesh = new THREE.InstancedMesh(voxelGeometry, sandMaterial, sandPositions.length);
                     for (let i = 0; i < sandPositions.length; i++) {
                        matrix.setPosition(sandPositions[i]);
                        sandMesh.setMatrixAt(i, matrix);
                    }
                    sandMesh.instanceMatrix.needsUpdate = true;
                    planetGroup.add(sandMesh);
                }
    
                 if (grassPositions.length > 0) {
                    const grassMesh = new THREE.InstancedMesh(voxelGeometry, grassMaterial, grassPositions.length);
                     for (let i = 0; i < grassPositions.length; i++) {
                        matrix.setPosition(grassPositions[i]);
                        grassMesh.setMatrixAt(i, matrix);
                    }
                    grassMesh.instanceMatrix.needsUpdate = true;
                     // Frustum culling is enabled by default for InstancedMesh instances
                    planetGroup.add(grassMesh);
                }
    
                scene.add(planetGroup);
                console.log(`Generated Planet: Water=${waterPositions.length}, Sand=${sandPositions.length}, Grass=${grassPositions.length} voxels.`);
            }
    
            function addStars() {
                const starGeometry = new THREE.BufferGeometry();
                const starMaterial = new THREE.PointsMaterial({
                    color: 0xFFFFFF,
                    size: 0.2, // Slightly larger stars
                    transparent: true,
                    opacity: 0.8
                });
    
                const starVertices = [];
                const starCount = 20000; // More stars
                const starFieldRadius = 1500; // Larger star field
    
                for (let i = 0; i < starCount; i++) {
                    // Position stars randomly in a sphere far away
                    const x = (Math.random() - 0.5) * 2 * starFieldRadius;
                    const y = (Math.random() - 0.5) * 2 * starFieldRadius;
                    const z = (Math.random() - 0.5) * 2 * starFieldRadius;
                    const pos = new THREE.Vector3(x, y, z);
                    if (pos.length() > starFieldRadius * 0.8) { // Ensure stars are mostly on the outer shell
                       starVertices.push(x, y, z);
                    } else {
                        i--; // Redo if too close
                    }
                }
    
                starGeometry.setAttribute('position', new THREE.Float32BufferAttribute(starVertices, 3));
                const stars = new THREE.Points(starGeometry, starMaterial);
                scene.add(stars);
            }
    
            // Camera controls
            const moveSpeed = 1.0;
            const rotateSpeed = 0.005; // Reduced sensitivity
            let isDragging = false;
            let previousMousePosition = { x: 0, y: 0 };
    
            function setupControls() {
                 // Mouse look
                document.addEventListener('mousedown', (e) => {
                    if (e.button === 0) { // Left mouse button
                        isDragging = true;
                        previousMousePosition.x = e.clientX;
                        previousMousePosition.y = e.clientY;
                        document.body.style.cursor = 'grabbing'; // Optional visual feedback
                    }
                });
    
                document.addEventListener('mouseup', (e) => {
                    if (e.button === 0) {
                        isDragging = false;
                        document.body.style.cursor = 'grab'; // Optional visual feedback
                    }
                });
    
                document.addEventListener('mousemove', (e) => {
                    if (isDragging) {
                        const deltaX = e.clientX - previousMousePosition.x;
                        const deltaY = e.clientY - previousMousePosition.y;
    
                        // Rotate camera based on mouse movement
                        // Horizontal movement rotates around camera's Y axis
                        // Vertical movement rotates around camera's local X axis
                        camera.rotation.order = 'YXZ'; // Or 'ZYX' depending on desired effect
                        camera.rotation.y -= deltaX * rotateSpeed;
                        camera.rotation.x -= deltaY * rotateSpeed;
    
                        // Clamp vertical rotation to prevent flipping
                        const PI_HALF = Math.PI / 2;
                        camera.rotation.x = Math.max(-PI_HALF, Math.min(PI_HALF, camera.rotation.x));
    
    
                        previousMousePosition.x = e.clientX;
                        previousMousePosition.y = e.clientY;
                    }
                });
                 document.body.style.cursor = 'grab'; // Initial cursor
    
    
                // Keyboard movement (relative to camera's orientation)
                document.addEventListener('keydown', handleKeyDown);
            }
    
    
            function handleKeyDown(event) {
                const velocity = new THREE.Vector3();
                const direction = new THREE.Vector3();
    
                switch(event.key.toLowerCase()) { // Use toLowerCase for case-insensitivity
                    case 'w': velocity.z = 1; break; // Move forward
                    case 's': velocity.z = -1; break; // Move backward
                    case 'a': velocity.x = -1; break; // Move left
                    case 'd': velocity.x = 1; break; // Move right
                    case ' ': velocity.y = 1; break; // Move up
                    case 'shift': velocity.y = -1; break; // Move down
                    case '+': // Increase resolution
                         resolutionStep = Math.max(0.25, resolutionStep - 0.25);
                         generatePlanetInstanced(); // Regenerate the planet
                         console.log("Resolution Step:", resolutionStep);
                         break;
                    case '-': // Decrease resolution
                         resolutionStep = Math.min(2.0, resolutionStep + 0.25); // Don't go too low
                         generatePlanetInstanced(); // Regenerate the planet
                         console.log("Resolution Step:", resolutionStep);
                         break;
                }
    
                // Apply velocity relative to camera's direction
                direction.copy(velocity).applyQuaternion(camera.quaternion);
    
                // Prevent upward/downward movement from affecting forward/backward unless explicitly Space/Shift
                // Only apply Y velocity if Space or Shift is pressed
                 if (event.key.toLowerCase() !== ' ' && event.key.toLowerCase() !== 'shift') {
                    direction.y = 0; // Keep movement on the horizontal plane relative to current view
                    direction.normalize(); // Normalize horizontal movement
                    direction.y = velocity.y; // Add vertical movement back
                 } else {
                    // For Space/Shift, just normalize the raw velocity before applying quaternion
                     direction.copy(velocity).normalize().applyQuaternion(camera.quaternion);
                 }
    
    
                camera.position.addScaledVector(direction, moveSpeed);
            }
    
    
            function animate() {
                requestAnimationFrame(animate);
                if (planetGroup) {
                    // Optional: make the planet slowly rotate
                    // planetGroup.rotation.y += 0.0005; 
                }
                renderer.render(scene, camera);
            }
    
            window.addEventListener('resize', onWindowResize, false);
    
            function onWindowResize() {
                camera.aspect = window.innerWidth / window.innerHeight;
                camera.updateProjectionMatrix();
                renderer.setSize(window.innerWidth, window.innerHeight);
            }
    
            init();
        </script>
    </body>
    </html>
    

    Key Changes and Why They Improve Performance:

    1. THREE.InstancedMesh:

      • Instead of creating new THREE.Mesh(...) inside the loops, we collect all the positions for each material type (waterPositions, sandPositions, grassPositions).
      • After determining all the positions, we create one THREE.InstancedMesh for each material type (waterMesh, sandMesh, grassMesh).
      • We tell the InstancedMesh how many instances there will be (waterPositions.length).
      • We then loop through the collected positions and use setMatrixAt(index, matrix) to tell the InstancedMesh where to render that specific instance.
      • Performance Benefit: The graphics card receives commands like "Draw 50,000 water voxels at these 50,000 locations" in one go, instead of "Draw one water voxel here, draw one water voxel there, draw another...". This dramatically reduces the number of draw calls, which is a major bottleneck with many small objects. Three.js's frustum culling works very well with InstancedMesh, automatically preventing instances outside the camera's view from being sent to the GPU.
    2. Refined Generation Logic:

      • Used a proper 3D Simplex Noise function (noise.noise3d) for more natural-looking terrain variations. The noise is sampled based on the normalized position, making the terrain follow the spherical shape.
      • The generation loop iterates through a 3D grid covering the potential volume of the planet (base radius + amplitude + thickness).
      • It calculates a surfaceHeight based on the noise value for each point's direction.
      • A voxel is only added if its position is below or at the calculated surfaceHeight. This prevents generating a solid sphere and instead creates a hollow-ish volume capped by the noisy terrain surface.
      • Water is added only below the sea level and if that point is also below the terrain surface.
      • Materials (sand/grass) are assigned based on the voxel's height relative to the seaLevel.
      • Performance Benefit: While it still iterates a 3D grid, it only adds voxels to the position arrays if they meet the surface/volume criteria. This significantly reduces the total number of voxels created compared to filling the whole sphere.
    3. Voxel Size and Grid Step: The resolutionStep now directly controls the voxel size (voxelGeometry) and the step size in the generation loops. Smaller resolutionStep means a finer grid, smaller voxels, and more detail, but also many more voxels, impacting generation time and GPU load. You can press + and - to change the resolutionStep and see the effect on performance and detail.

    4. Camera Controls: Improved mouse look (more intuitive rotation) and movement relative to the camera's direction. Added grab/grabbing cursor feedback.

    This optimized version should handle higher resolutions much better than the previous one, primarily due to THREE.InstancedMesh and generating a more reasonable number of voxels. True occlusion culling (hiding voxels blocked by other voxels within the frustum) is still not implemented, but the performance gains from instancing and basic frustum culling are usually sufficient for this type of application.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.