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

              
                <canvas id="webgl" width="500" height="1758"></canvas>

<script id="vertexShader" type="x-shader/x-vertex">
  attribute vec4 a_position;
  
  uniform mat4 u_modelViewMatrix;
  uniform mat4 u_projectionMatrix;
  
  void main() {
    gl_Position = a_position;
  }
</script>
<script id="fragmentShader" type="x-shader/x-fragment">
 precision highp float;
  precision highp int;
  
  uniform vec2 u_resolution;
  uniform vec2 u_mouse;
  uniform float u_time;
  uniform sampler2D u_noise;
  
  uniform float u_bump_strength;
  
  uniform float u_shininess;
  uniform float u_strength;
  
  uniform float u_light_1_strength;
  uniform float u_light_2_strength;
  
  // movement variables
  vec3 movement = vec3(.0);
  
  const int maxIterations = 256;
  const float stopThreshold = 0.001;
  const float stepScale = .7;
  const float eps = 0.005;
  const vec3 clipColour = vec3(0.);
  const vec3 fogColour = vec3(0.);
  
  const vec3 light1_position = vec3(0, 1., -1.);
  const vec3 light1_colour = vec3(.8, .8, .85);
  
  struct Surface {
    int object_id;
    float distance;
    vec3 position;
    vec3 colour;
    float shininess;
    float specularStrength;
    vec3 normal;
    float steps;
  };
  struct Light {
    vec3 position;
    vec3 colour;
    float ambience;
  };
  
  const int octaves = 4;
  
  float bumps(in vec3 p, float phase, float size, vec3 frequency) {
    return size * sin(p.x * frequency.x + phase) * cos(p.y * frequency.y + phase) * cos(p.z * frequency.z + phase);
  }
  float fractalBumps(in vec3 p, float phase, float size, vec3 frequency, float multiplier) {
    // const float octaves = 2.;
    float _bumps = bumps(p, phase, size, frequency);
    for(int i = 1; i < octaves; i++) {
      float f = float(i);
      _bumps += bumps(p + f, phase + f * 10., size * multiplier * 1./f, frequency * f);
    }

    return _bumps * u_bump_strength;
  }
  
  // This function describes the world in distances from any given 3 dimensional point in space
  float world(in vec3 position, inout int object_id, inout float field) {
    vec3 pos = floor(position * .5);
    object_id = int(floor(pos.x + pos.y + pos.z));
    
    field = fractalBumps(position, u_time*5., .002, vec3(20.), 20.);
    
    return length(position) - .3 + field;
  }
  float world(in vec3 position) {
    int dummy = 0;
    float field = 0.;
    return world(position, dummy, field);
  }
  
  // Calculated the normal of any given point in space. Intended to be cast from the point of a surface
  vec3 calculate_normal(in vec3 position) {
    vec3 grad = vec3(
      world(vec3(position.x + eps, position.y, position.z)) - world(vec3(position.x - eps, position.y, position.z)),
      world(vec3(position.x, position.y + eps, position.z)) - world(vec3(position.x, position.y - eps, position.z)),
      world(vec3(position.x, position.y, position.z + eps)) - world(vec3(position.x, position.y, position.z - eps))
    );
    
    return normalize(grad);
  }
  
  Surface getSurface(int object_id, float rayDepth, vec3 sp, float field, vec3 colour) {
    return Surface(
      object_id,              // The object ID, used for when we have multiple objects in a scene
      rayDepth,               // The depth that the view ray travelled to get here
      sp,                     // The 3D position of the surface
      colour,                 // The oclour of the surface at this psition
      u_shininess,            // The shininess of the material
      u_strength,                     // The specular strength component. For lower shininess values, we normally want much lower values here
      calculate_normal(sp),   // The normal of the surface
      field
    );
  }
  
  // The raymarch loop
  Surface rayMarch(vec3 ro, vec3 rd, float start, float end) {
    float sceneDist = 1e4;
    float rayDepth = start;
    float field = 0.;
    int object_id = 0;
    for(int i = 0; i < maxIterations; i++) {
      sceneDist = world(ro + rd * rayDepth, object_id, field);
      
      if(sceneDist < stopThreshold || rayDepth > end) {
        break;
      }
      
      field += float(i);
      
      rayDepth += sceneDist * stepScale;
    }
    
    vec3 colour = mix(vec3(.5), vec3(0,0,1.), clamp(field*10., 0., 1.));
    
    return getSurface(object_id, rayDepth, ro + rd * rayDepth, field, colour);
  }
  
  vec3 lighting(Surface surface_object, vec3 cam, Light light) {
    
    // start with black
    vec3 sceneColour = vec3(0);
    
    // Surface normal
    vec3 normal = surface_object.normal;
    
    // Light
    // Light position
    vec3 lp = light.position;
    // Light direction
    vec3 ld = lp - surface_object.position;
    
    // Ambient lighting
    const float ambientStrength = .1;
    // Ambient light component
    vec3 ambient = light.ambience * light.colour;
    
    // Blinn-phong
    // View direction
    vec3 vd = normalize(cam - surface_object.position);
    // The halfway vector
    vec3 h = normalize(normalize(ld) + vd);
    
    // Diffuse component
    float diff = max(dot(normal, normalize(ld)), 0.);
    vec3 diffuse = diff * light.colour;
    
    // Specularity
    float spec = pow( max(dot(normal, h), 0.), surface_object.shininess );
    vec3 specular = light.colour * spec * surface_object.specularStrength;
    
    sceneColour = (diffuse + specular + ambient) * surface_object.colour;
    
    return sceneColour;
  }
  
  vec3 path(float z) {
    return vec3(0,0,0.);
    return vec3(0,0,-100.+z);
  }

  void main() {
    vec2 uv = (gl_FragCoord.xy - 0.5 * u_resolution.xy) / min(u_resolution.y, u_resolution.x);
    
    // movement
    movement = path(u_time);
    
    // Camera and look-at
    vec3 cam = vec3(1,1,-2);
    vec3 lookAt = vec3(0,0,0);
    
    // add movement
    lookAt += movement;
    cam += movement;
    
    // Unit vectors
    vec3 forward = normalize(lookAt - cam);
    vec3 right = normalize(vec3(forward.z, 0., -forward.x));
    vec3 up = normalize(cross(forward, right));
    
    // FOV
    float FOV = .4;
    
    // Ray origin and ray direction
    vec3 ro = cam;
    vec3 rd = normalize(forward + FOV * uv.x * right + FOV * uv.y * up);
    
    // Ray marching
    const float clipNear = 0.;
    const float clipFar = 32.;
    Surface objectSurface = rayMarch(ro, rd, clipNear, clipFar);
    if(objectSurface.distance > clipFar) {
      gl_FragColor = vec4(clipColour, 1.);
      return;
    }
    
    // With this setup, we can have multiple lights
    vec3 sceneColour = lighting(objectSurface, cam, Light(cam + vec3(1, 1, 1.5), vec3(u_light_1_strength), .0));
    sceneColour += lighting(objectSurface, cam, Light(cam + vec3(-1, -2, 2.), vec3(u_light_2_strength), 0.));
    // sceneColour *= 1. - clamp((objectSurface.steps)*10., 0., 1.);
    
    gl_FragColor = vec4(sceneColour, 1.);
  }
  
</script>
              
            
!

CSS

              
                body {
  margin:0;
}

canvas {
  position: fixed;
}
              
            
!

JS

              
                console.clear();

const twodWebGL = new WTCGL(
  document.querySelector('canvas#webgl'), 
  document.querySelector('script#vertexShader').textContent, 
  document.querySelector('script#fragmentShader').textContent,
  window.innerWidth,
  window.innerHeight,
  1
);
twodWebGL.startTime = -.5;
// twodWebGL.startTime = -100 + Math.random() * 50;

window.addEventListener('resize', () => {
  twodWebGL.resize(window.innerWidth, window.innerHeight);
});

const uniforms = {
  shininess: 10,
  strength: .3,
  light_1_strength: 1.3,
  light_2_strength: .3,
  bump_strength: 1.
};

// // Dat gui
var gui = new dat.GUI();
const bump_strength = gui.add(uniforms, 'bump_strength', 0, 2).name("Bump Strength").step(0.01);
const shininess = gui.add(uniforms, 'shininess', 1, 200).name("Shininess").step(0.5);
const strength = gui.add(uniforms, 'strength', 0, 2).name("Specular Strength").step(0.01);
const light_1_strength = gui.add(uniforms, 'light_1_strength', 0, 2).name("Light Strength main").step(0.01);
const light_2_strength = gui.add(uniforms, 'light_2_strength', 0, 2).name("Light Strength rim").step(0.01);

shininess.onChange(function(value) {
  twodWebGL.addUniform('shininess', WTCGL.TYPE_FLOAT, value);
});
strength.onChange(function(value) {
  twodWebGL.addUniform('strength', WTCGL.TYPE_FLOAT, value);
});
light_1_strength.onChange(function(value) {
  twodWebGL.addUniform('light_1_strength', WTCGL.TYPE_FLOAT, value);
});
light_2_strength.onChange(function(value) {
  twodWebGL.addUniform('light_2_strength', WTCGL.TYPE_FLOAT, value);
});
bump_strength.onChange(function(value) {
  twodWebGL.addUniform('bump_strength', WTCGL.TYPE_FLOAT, value);
});

twodWebGL.addUniform('shininess', WTCGL.TYPE_FLOAT, uniforms.shininess);
twodWebGL.addUniform('strength', WTCGL.TYPE_FLOAT, uniforms.strength);
twodWebGL.addUniform('light_1_strength', WTCGL.TYPE_FLOAT, uniforms.light_1_strength);
twodWebGL.addUniform('light_2_strength', WTCGL.TYPE_FLOAT, uniforms.light_2_strength);
twodWebGL.addUniform('bump_strength', WTCGL.TYPE_FLOAT, uniforms.bump_strength);


// track mouse move
let mousepos = [0,0];
const u_mousepos = twodWebGL.addUniform('mouse', WTCGL.TYPE_V2, mousepos);
window.addEventListener('pointermove', (e) => {
  let ratio = window.innerHeight / window.innerWidth;
  if(window.innerHeight > window.innerWidth) {
    mousepos[0] = (e.pageX - window.innerWidth / 2) / window.innerWidth;
    mousepos[1] = (e.pageY - window.innerHeight / 2) / window.innerHeight * -1 * ratio;
  } else {
    mousepos[0] = (e.pageX - window.innerWidth / 2) / window.innerWidth / ratio;
    mousepos[1] = (e.pageY - window.innerHeight / 2) / window.innerHeight * -1;
  }
  twodWebGL.addUniform('mouse', WTCGL.TYPE_V2, mousepos);
});









// Load all our textures. We only initiate the instance once all images are loaded.
const textures = [
  {
    name: 'noise',
    url: 'https://s3-us-west-2.amazonaws.com/s.cdpn.io/982762/noise.png',
    type: WTCGL.IMAGETYPE_TILE,
    img: null
  }
];
const loadImage = function (imageObject) {
  let img = document.createElement('img');
  img.crossOrigin="anonymous";
  
  return new Promise((resolve, reject) => {
    img.addEventListener('load', (e) => {
      imageObject.img = img;
      resolve(imageObject);
    });
    img.addEventListener('error', (e) => {
      reject(e);
    });
    img.src = imageObject.url
  });
}
const loadTextures = function(textures) {
  return new Promise((resolve, reject) => {
    const loadTexture = (pointer) => {
      if(pointer >= textures.length || pointer > 10) {
        resolve(textures);
        return;
      };
      const imageObject = textures[pointer];

      const p = loadImage(imageObject);
      p.then(
        (result) => {
          twodWebGL.addTexture(result.name, result.type, result.img);
        },
        (error) => {
          console.log('error', error)
        }).finally((e) => {
          loadTexture(pointer+1);
      });
    }
    loadTexture(0);
  });
  
}

loadTextures(textures).then(
  (result) => {
    twodWebGL.initTextures();
    // twodWebGL.render();
    twodWebGL.running = true;
  },
  (error) => {
    console.log('error');
  }
);
              
            
!
999px

Console