Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <script async src="https://unpkg.com/es-module-shims@0.13.1/dist/es-module-shims.js"></script>

<script type="importmap">
			{
				"imports": {
					"three": "https://unpkg.com/three@0.133.0/build/three.module.js"
				}
			}
</script>
              
            
!

CSS

              
                canvas {
        
        position:fixed;
        top:0;
        left:0;    
    }
              
            
!

JS

              
                
import * as THREE from "https://unpkg.com/three@0.133.0/build/three.module.js";
import { OrbitControls } from "https://unpkg.com/three@0.133.0/examples/jsm/controls/OrbitControls.js";
import { RGBELoader } from 'https://unpkg.com/three@0.133.0/examples/jsm/loaders/RGBELoader.js';
import { Geometry } from 'https://unpkg.com/three@0.133.0/examples/jsm/deprecated/Geometry.js';
import { RoundedBoxGeometry } from 'https://unpkg.com/three@0.133.0/examples/jsm/geometries/RoundedBoxGeometry.js';



class App {
    constructor() {
        this.initThree();

        const box = new THREE.Mesh(
            new THREE.BoxGeometry(4,2.5,4),
            new THREE.MeshStandardMaterial({side:THREE.BackSide,
                
                    
 
                                            map:this.gradientBox(0.3,0.3,0.2)})
        );
        // this.scene.add(box);
        box.position.y = 1.25;
        // this.sun = new THREE.PointLight(0xf0e0d0,0.8);
        // this.sun.position.y = 2;
        this.initHDR();
        // this.scene.add(this.sun);
        this.intersectables = [];

        this.floor = new THREE.Mesh(new THREE.PlaneGeometry(20,20), 
        new THREE.MeshStandardMaterial());
        this.floor.rotation.x = -Math.PI/2;
        this.scene.add(this.floor);
        // this.fillWithBoxes();

        this.walls = [];
        for(var i =0;i<4;i++) {
                var wall = new THREE.Mesh(new THREE.CircleGeometry(0.5, 64),
                new THREE.MeshStandardMaterial({ color:0xc0c0c0,
                    roughnessMap:this.gradientBox(0.6,0.6,1),
                    roughness:0.75,
                    metalnessMap:this.noiseMap(512,0.1,0.9),
                    map:this.gradientBox(0.16,0.3,0.13)})        
            );
            var a = wall.geometry.attributes.position.array;
            for(var n =0;n<a.length;n+=3) {
              a[n]+=0.5;
              a[n] = a[n]*a[n]*(3-2*a[n])*3.2-1.6;

              a[n+1]+=0.5;
              a[n+1] = a[n+1]*a[n+1]*(3-2*a[n+1])*2.4-1.2;

            }
            var wallPivot = new THREE.Object3D();

            const wallShadow = new THREE.Mesh(new THREE.PlaneGeometry(3.7,0.4), 
                    new THREE.MeshBasicMaterial({
                        transparent:true,
                        color:'black',
                        alphaMap:this.blurBox(512,32,0.9,0.3,10)
                    })
            );

            wallShadow.position.y = -1.22;
            wallShadow.rotation.x = -Math.PI/2;
            wallShadow.position.z = -1.95;
            wallPivot.add(wallShadow);
            wall.position.z = -1.95;
            wallPivot.add(wall);
            wall.shadow = wallShadow;
            this.walls.push(wall);
            // wall.scale.setScalar(0.9);
            this.scene.add(wallPivot);
            wallPivot.position.y = 1.25;
            wallPivot.rotation.y = -i/4*2*Math.PI;
            wall.curPage = i;
            this.setLabel(wall,i);
        }

        
        // for(var i =0;i<100;i++) {
        //     const label = this.Label(i);
        //     label.position.set(Math.random()*4-2, Math.random()*2.5, Math.random()*4-2);
        //     this.scene.add(label);
        //     label.rotation.setFromVector3(new THREE.Vector3(Math.random(),Math.random(),Math.random()));
        //     this.intersectables.push(label);
        // }
    }
  
  bumpToNormal(canvas,offset=1, intensity = 1) {
    const g = canvas.getContext('2d');
    const src = g.getImageData(0,0, canvas.width, canvas.height);
    const dest = g.getImageData(0,0, canvas.width, canvas.height);


    for(var i=0;i< src.data.length;i+=4) {

        //TODO this doens't resolve over the width boundary!
        var red = (src.data[i+0]-src.data[i+4*offset])*intensity;
        var green = (src.data[i+0]-src.data[i+4*offset*canvas.width])*intensity;
        var blue = 255-Math.abs(red)-Math.abs(green);

        dest.data[i+0] = 128+red;
        dest.data[i+1] = 128+green;
        dest.data[i+2] = blue;
        dest.data[i+3] = 255;
    }

    g.putImageData(dest, 0,0);
    return canvas;
}
  
  roundBox(w,h) {
    
    var c = document.createElement('canvas');
    c.height = 1024;
    c.width = 1024;
    var g= c.getContext('2d');
    g.fillStyle = "white";
    g.beginPath();
    const smoothstep = (low, high, f)=>{
      f = (f-low)/(high-low);
      f = Math.max(0, Math.min(1,f));
      return f*f*(3-2*f);
    }
    
    for(var i =0;i<100;i++) {
      var theta = i/100*2*Math.PI;
      var p = new THREE.Vector2(Math.sin(theta), Math.cos(theta));
      p.x = 2*smoothstep(-1,1, p.x)-1;
      p.y = 2*smoothstep(-1,1, p.y)-1;
      g.lineTo(512+512*p.x, 512+512*p.y);
      
    }
    g.fill();
    return new THREE.CanvasTexture(c);
    
  }
  
  
  
  initHDR() {
      this.renderer.physicallyCorrectLights = true;
        this.renderer.toneMapping = THREE.LinearToneMapping;
        this.renderer.outputEncoding = THREE.sRGBEncoding;
        this.renderer.toneMappingExposure  = 0.4;

      new RGBELoader()
					.setDataType( THREE.HalfFloatType )
					.setPath( 'https://dl.polyhaven.org/file/ph-assets/HDRIs/hdr/' )
					.load( '2k/hotel_room_2k.hdr', texture=> {
            const pmremGenerator = new THREE.PMREMGenerator( this.renderer );
    				pmremGenerator.compileEquirectangularShader();
						const envMap = pmremGenerator.fromEquirectangular( texture ).texture;

						// this.scene.background = envMap;

						this.scene.environment = envMap;
            this.worldEnvMap  = envMap;
						texture.dispose();
						pmremGenerator.dispose();
					});
    }


    setLabel(wall,i) {

        while(wall.children.length>0) wall.remove(wall.children[0]);
        wall.curPage = i;
        var label = this.Label(i);
        wall.add(label);
        label.position.z = 0.2;
      label.position.y = .2;
    }

    blurBox(canvasWidth, canvasHeight, elementWidth, elementHeight, blurSize) {
        const c = document.createElement('canvas');
        const g = c.getContext('2d');
        c.width = canvasWidth;
        c.height = canvasHeight;
        g.fillStyle = "black";
        g.fillRect(0,0,c.width, c.height);
        g.shadowBlur = blurSize;
        g.shadowOffsetX = 0;
        g.shadowOffsetY = 2*canvasHeight;
        g.shadowColor = "white";
        g.fillRect(
            (0.5-elementWidth/2)*canvasWidth,
            (0.5-elementHeight/2)*canvasHeight-2*canvasHeight,
            elementWidth*canvasWidth,elementHeight*canvasHeight
        )
        

        return new THREE.CanvasTexture(c);
    }

    Label(text) {
        const { w, size, SCALE, c } = this.labelCanvas(text,1);
        const blurType = this.labelCanvas(text,15).c;
        const plane = new THREE.Mesh(
                new THREE.PlaneGeometry((w+size)/SCALE,(size*1.2)/SCALE),
                new THREE.MeshStandardMaterial({
                    transparent:true, 
                    color:0xc0c0c0,
                  roughness:0.25,
                  metalness:1,
                  depthTest:false,
                  depthWrite:false,
                    map:this.noiseMap(256,0.8,0.9),
                    normalMap:new THREE.CanvasTexture(this.bumpToNormal(blurType,1,-3)),
                    // bumpScale:0.01,
                    alphaMap:new THREE.CanvasTexture(c)
                })
        );

        return plane;    

    }

    labelCanvas(text,blurSize) {
        const size = 1000;
        const SCALE = 800;
        const c = document.createElement('canvas');
        const g = c.getContext('2d');
        g.font = `${size}px Arial`;
        const w = g.measureText(text).width;
        c.width = w + size;
        c.height = size * 1.2;
        g.font = `${size}px Arial`;
        g.fillStyle = "black";
        g.fillRect(0, 0, c.width, c.height);
        g.fillStyle = "white";
        g.shadowOffsetX = 0;
        g.shadowOffsetY = 3000;
        g.shadowColor = "white";
        g.shadowBlur = blurSize;
        g.fillText(text, size * 0.5, size * 1.1 - 3000);
        return { w, size, SCALE, c };
    }

    fillWithBoxes() {
        for(var i =0;i<100;i++) {

            const lilBox = new THREE.Mesh(
                    new THREE.BoxBufferGeometry(0.1,0.1,0.1),
                    new THREE.MeshStandardMaterial({
                        color : Math.floor(Math.random()*0xffffff)
                    })
                );
            lilBox.position.set(Math.random()*4-2, Math.random()*2.5, Math.random()*4-2);
            this.scene.add(lilBox);
            lilBox.rotation.setFromVector3(new THREE.Vector3(Math.random(),Math.random(),Math.random()));
            this.intersectables.push(lilBox);

        }
    }

    gradientBox(cutInX, cutInY, opacity) {
        const c = document.createElement('canvas');

        const g = c.getContext('2d');
        c.width = c.height = 128;
        g.fillStyle = "white";
        g.fillRect(0,0,128,128);
        let grad = g.createLinearGradient(0,0,128,0);
        grad.addColorStop(0, `rgba(0,0,0,${opacity})`);
        grad.addColorStop(cutInX, `rgba(0,0,0,0)`);
        grad.addColorStop(1-cutInX, `rgba(0,0,0,0)`);
        grad.addColorStop(1, `rgba(0,0,0,${opacity})`);
        g.fillStyle = grad;
        g.fillRect(0,0,128,128);

         grad = g.createLinearGradient(0,0,0,128);
        grad.addColorStop(0, `rgba(255,255,255,${opacity})`);
        grad.addColorStop(cutInY, `rgba(255,255,255,0)`);
        grad.addColorStop(1-cutInY, `rgba(0,0,0,0)`);
        grad.addColorStop(1, `rgba(0,0,0,${opacity})`);
        g.fillStyle = grad;
        g.fillRect(0,0,128,128);
        
        return new THREE.CanvasTexture(c);
    }

    noiseMap(size,low,high) {
        const c = document.createElement('canvas');

        const g = c.getContext('2d');
        c.width = c.height = size;
        
        const range = low-high;
        const data = g.getImageData(0,0,c.width,c.height);
        for(var i =0;i<data.data.length;i+=4) {
            var rand = Math.floor((Math.random()*range+low)*255);
            data.data[i+0] = rand;
            data.data[i+1] = rand;
            data.data[i+2] = rand;
            data.data[i+3] = 255;
        }
        g.putImageData(data,0,0);
        return new THREE.CanvasTexture(c);
    }

    initThree() {
        this.scene = new THREE.Scene();
        this.scene.fog = new THREE.Fog(0x406090,5,10);
        this.renderer = new THREE.WebGLRenderer({ antialias: true });
this.renderer.setPixelRatio(devicePixelRatio);        this.renderer.setClearColor(0x406090);
        this.camera = new THREE.PerspectiveCamera(45, innerWidth / innerHeight, 0.2, 100);
        this.renderer.setSize(innerWidth, innerHeight);
        document.body.appendChild(this.renderer.domElement);
        this.renderer.setAnimationLoop(e => this.update(e));
        this.VR = location.href.toLowerCase().indexOf('vr')>-1;
        this.viewCaster = new THREE.Raycaster();
        let btn;
        try {


          


        } catch(err) {
            // debugger;
         }
            this.camera.position.z = 2;
            this.camera.position.y = 1;
            this.camera.lookAt(new THREE.Vector3(0,1,0));
            this.controls = new OrbitControls(this.camera, this.renderer.domElement);
            this.controls.target.y = 1;            
            this.controls.update();
    }

    update() {
        this.renderer.render(this.scene, this.camera);

        
            this.walls.forEach((wall,i)=>{

                const oscValue = Math.sin(Date.now()/1000+i*Math.PI/2);
                wall.position.y = 0.03*oscValue;
                wall.shadow.scale.setScalar(1+0.03*oscValue)

            });
      
            this.intersectables.forEach(el=>el.lookAt(this.camera.position));
            this.viewCaster.set(
                this.camera.position,
                this.camera.getWorldDirection(new THREE.Vector3(0,0,1))
            );
            
            if(this.selected) {
                // this.selected.scale.setScalar(0.9);

            }
           const hit = this.viewCaster.intersectObjects(this.walls).pop();
            if(hit) {
                
                      this.selected = hit.object;

                this.updateAllWalls();

            }

    }


  
  updateAllWalls() {
      const newIndex = this.walls.indexOf(this.selected);
     let diff = newIndex-this.prevIndex;
      if(!isNaN(diff)) {

          if(Math.abs(diff)>2) {
              diff = -Math.sign(diff);
          }
        if(diff!=0) {
         
      
          const opposite = (newIndex+2)%this.walls.length;
          const otherOne = (newIndex+diff+this.walls.length)%this.walls.length;
         
          
          this.setLabel(this.walls[opposite], this.selected.curPage+diff*2);
          this.setLabel(this.walls[otherOne], this.selected.curPage+diff*1);
          
        }
      }
      this.prevIndex = newIndex;
  }
    
  
    updateBackWall() {

                const newIndex = this.walls.indexOf(this.selected);
                if(newIndex!=this.prevIndex) {
                    const opposite = (newIndex+2)%this.walls.length;
                    let diff = newIndex-this.prevIndex;
                    if(!isNaN(diff)) {

                        if(Math.abs(diff)>2) {
                            diff = -Math.sign(diff);
                        }
                        console.log('so now we know that this wall\'s cur index is ', this.walls[newIndex].curPage);

                        //let's do it by its immediate neighbour instead.
                        const neighbour = this.walls[(newIndex+diff+this.walls.length)%this.walls.length];
                        const neighbourPage = neighbour.curPage;
                        this.setLabel(this.walls[opposite], neighbourPage+diff);
                    }
                    
                }
                this.prevIndex = newIndex;
    }
  
}



const app = new App();
              
            
!
999px

Console