Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel is required to process package imports. If you need a different preprocessor remove all packages first.

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

Behavior

Save Automatically?

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

              
                <!-- use Red/Blue Glasses for full 3D effect -->

<!-- VertexShader code here -->
<script id="vertexShader" type="x-shader/x-vertex">
attribute vec4 vPosition;
void main (void) {
  gl_Position = vPosition;
}
</script>
<!-- FragmentShader code here -->
<script id="fragmentShader" type="x-shader/x-fragment">
precision mediump float;
uniform vec2 resolution;
uniform float size;
uniform float smoothing;
uniform float time;

const float PI = 3.14159;
const float divergence = 0.3;

// Define Basic ray_marching Parameters
#define MAX_STEPS 100
#define MAX_DIST 45.
#define MIN_DIST .01
#define EPSILON .0001

//https://www.iquilezles.org/www/articles/smin/smin.htm
float smin( float a, float b, float k ){
    float res = exp2( -k*a ) + exp2( -k*b );
    return -log2( res )/k;
}

mat2 r2(float a){ 
  float c = cos(a); 
  float s = sin(a); 
  return mat2(c, s, -s, c); 
}
  
float sphereSDF(vec3 p, float s) {
  return length(p-vec3(0.)) - s;
}

float boxSDF(vec3 p, vec3 s) {
  vec3 d = abs(p-vec3(0.)) - s;
  return min(max(d.x,max(d.y,d.z)),0.0) + length(max(d,0.0));
}

float planeSDF(vec3 p, vec4 n) {
  return dot(p,n.xyz) + n.w;
}

vec2 rotate(vec2 p, float t) {
  return p * cos(t) + vec2(p.y, -p.x) * sin(t);
}

float map_scene(vec3 p) {
  float displacement = sin(20. * p.x) * sin(20. * p.y) * sin(20. * p.z) * .04;
  float floorDist = boxSDF(vec3(p.x,p.y + 5.,p.z), vec3(15.5, .1, 15.5))+ displacement;
  
  vec3 q = p;
  
  q.xz *= r2(-sin(time*.6));
  q.xy *= r2(-sin(time)*.4);
  float boxDist = boxSDF(q, vec3(2.5, .1, 2.5));
  float cullDist = sphereSDF(q, size * 2.5);

  float shapeDist = max(-cullDist, boxDist);
  
  p.y += 1.1 * cos(time) + .5;
  p.x -= sin(time * .7);
  float spA = sphereSDF(p, size * .5);

  q.z -= .35 * sin(time * 2.) + .6;
  q.x -= cos(time* 2.);
  float spB = sphereSDF(q, size * .5);
  
  p.y -= 1.25 * cos(125. + time) + 2.2;
  p.x += sin(125. + time * 2.);
  float spC = sphereSDF(p, size * .5);

  q.z += .95 * sin(time * 1.5) * 1.5;
  q.x += .25 * cos(time* 2.) + .65;
  float spD = sphereSDF(q, size * .5);
  
  float sphereA = smin(spA, spB, smoothing);
  float sphereB = smin(spC, spD, smoothing);
  float sphereDist = smin(sphereA, sphereB, smoothing);

  float unionDist = smin(sphereDist, floorDist, smoothing);

  return smin(unionDist, shapeDist, smoothing);
}

float ray_march(vec3 rayorigin, vec3 raydirection) {
  float distance = 0.0;
  float position = map_scene(rayorigin);
  for(int i=0; i < MAX_STEPS; i++) {
    position = map_scene(rayorigin + distance * raydirection);
    distance += position;
    if(distance>MAX_DIST || position<MIN_DIST) break;
  }
  return distance;
}

vec3 get_normal(vec3 p) {
   return normalize(vec3(
    map_scene(vec3(p.x + EPSILON, p.y, p.z)) - map_scene(vec3(p.x - EPSILON, p.y, p.z)),
    map_scene(vec3(p.x, p.y + EPSILON, p.z)) - map_scene(vec3(p.x, p.y - EPSILON, p.z)),
    map_scene(vec3(p.x, p.y, p.z  + EPSILON)) - map_scene(vec3(p.x, p.y, p.z - EPSILON))
  ));
}

float get_light(vec3 p, vec3 lightPos){
  vec3 tolight = normalize(lightPos - p);
  vec3 n = get_normal(p);
  float diffuse = dot(n, tolight);
  float distance_tolight = ray_march(p + n * .1 * 2., n);
  
  /** shadow */
  if(distance_tolight<length(lightPos-p)) diffuse *= .1;

  // diffuse *= clamp(distance_tolight, 0., 1.);
  return clamp(diffuse, 0., 1.);
}

mat3 get_camera(vec3 rayorigin, vec3 ta, float rotation) {
	vec3 cw = normalize(ta-rayorigin);
	vec3 cp = vec3(sin(rotation), cos(rotation),0.0);
	vec3 cu = normalize( cross(cw,cp) );
	vec3 cv = normalize( cross(cu,cw) );
	return mat3( cu, cv, cw );
}

void main() {
  /** normalizing center coords */
  vec2 uv = (gl_FragCoord.xy - .5 * resolution.xy ) / resolution.y;
  vec3 col = vec3(0.);
  float red = 0.;
  float cyan = 0.;

  /** ray origin and ray direction for camera */

  vec3 rayorigin = vec3(0.,3.25,-16.);
  vec3 target = vec3(0.);
	mat3 cameraMatrix = mat3(0.);
  vec3 rd = vec3(0.);

  /** lights - movment and pre render */
  vec3 lightPos =  vec3(5., 3., -5.);

  // float fstop = time * 0.1;
  // rayorigin.xz = rotate(rayorigin.xz, fstop);
  // rd.xz = rotate(rd.xz, fstop);

  /** Anaglyph process */
  float d = 0.; 
  vec3 p = vec3(.0);
  float zoomLevel = 2.;

  /** Red Shift */
  rayorigin.x += divergence;
	cameraMatrix = get_camera(rayorigin, target, 0. );
  rd = cameraMatrix * normalize( vec3(uv.xy, zoomLevel) );
  d = ray_march(rayorigin, rd);
  p = d * rd + rayorigin;
  red += get_light(p, lightPos);

  /** Cyan Shift */
  rayorigin.x -= divergence;
	cameraMatrix = get_camera(rayorigin, target, 0. );
  rd = cameraMatrix * normalize( vec3(uv.xy, zoomLevel) );
  d = ray_march(rayorigin, rd);
  p = d * rd + rayorigin;
  cyan += get_light(p, lightPos);
  
  /** Mixdown */
  col = vec3( red, vec2(cyan) );

  if (d > MAX_DIST - 0.0001) {
    col = vec3(uv.y) * vec3(.8);
  } 

  gl_FragColor = vec4(col, 1.0);
}
  </script>
              
            
!

CSS

              
                html {
  height: 100%;
}
body {
  background: #999;
  font-family: Arial,"Helvetica Neue",Helvetica,sans-serif;
  font-size: 16px;
  overflow: hidden;
  padding: 0;
  margin: 0;
  width: 100%;
  height: 100%;
}
              
            
!

JS

              
                // Render Class //
// Boostrap for WebGL and Attaching Shaders //
// Fragment & Vertex Shaders in HTML window //
class Render {
  constructor() {
    this.frame = 0;
    this.spheresize = 0.92;
    this.smoothing = 2.88;
    this.start = Date.now();
    // Setup WebGL canvas and surface object //
    this.createCanvas("GLShaders");
    window.addEventListener("resize", this.setViewport, true);
    setTimeout(() => {
      this.createGUI();
      this.init();
    }, 1);
  }
  // Canvas Helper Function //
  createCanvas = name => {
    this.canvas =
      document.getElementById(name) || document.createElement("canvas");
    this.canvas.id = name;
    if (!document.getElementById(name)) {
      document.body.appendChild(this.canvas);
    }
    const context = this.canvas.getContext("webgl");
    if (!context) {
      console.error("no webgl avaiable");
    }
    this.setViewport();
  };
  // Viewport Helper Function //
  setViewport = () => {
    this.width = ~~(document.documentElement.clientWidth,
    window.innerWidth || 0);
    this.height = ~~(document.documentElement.clientHeight,
    window.innerHeight || 0);
    this.gl = this.canvas.getContext("webgl");
    this.canvas.width = this.width;
    this.canvas.height = this.height;
    this.gl.viewport(0, 0, this.width, this.height);
    this.clearCanvas();
  };

  // Shader Bootstrap code //
  createShader = (type, source) => {
    const shader = this.gl.createShader(type);
    this.gl.shaderSource(shader, source);
    this.gl.compileShader(shader);
    const success = this.gl.getShaderParameter(shader, this.gl.COMPILE_STATUS);
    if (!success) {
      console.log(this.gl.getShaderInfoLog(shader));
      this.gl.deleteShader(shader);
      return false;
    }
    return shader;
  };

  createProgram = (vertexSource, fragmentSource) => {
    // Setup Vertext/Fragment Shader functions //
    this.vertexShader = this.createShader(this.gl.VERTEX_SHADER, vertexSource);
    this.fragmentShader = this.createShader(
      this.gl.FRAGMENT_SHADER,
      fragmentSource
    );

    // Setup Program and Attach Shader functions //
    const program = this.gl.createProgram();
    this.gl.attachShader(program, this.vertexShader);
    this.gl.attachShader(program, this.fragmentShader);
    this.gl.linkProgram(program);
    this.gl.useProgram(program);

    return program;
  };

  createGraphics = (vertexSource, fragmentSource) => {
    // Create the Program //
    this.program = this.createProgram(vertexSource, fragmentSource);
    // Create and Bind buffer //
    this.buffer = this.gl.createBuffer();
    this.gl.bindBuffer(this.gl.ARRAY_BUFFER, this.buffer);

    this.gl.bufferData(
      this.gl.ARRAY_BUFFER,
      new Float32Array([-1, 1, -1, -1, 1, -1, 1, 1]),
      this.gl.STATIC_DRAW
    );

    this.vPosition = this.gl.getAttribLocation(this.program, "vPosition");
    this.gl.vertexAttribPointer(
      this.vPosition,
      2, // size: 2 components per iteration
      this.gl.FLOAT, // type: the data is 32bit floats
      false, // normalize: don't normalize the data
      0, // stride: 0 = move forward size * sizeof(type) each iteration to get the next position
      0 // start at the beginning of the buffer
    );
    this.gl.enableVertexAttribArray(this.vPosition);
    this.importProgram();
  };

  clearCanvas = () => {
    this.gl.clearColor(0, 0, 0, 0);
    this.gl.clear(this.gl.COLOR_BUFFER_BIT);
  };

  updateUniforms = () => {
    this.importUniforms();
    this.gl.drawArrays(
      this.gl.TRIANGLE_FAN, // primitiveType
      0, // Offset
      4 // Count
    );
  };

  // DatGUI Bootstrap code //
  createGUI = () => {
    this.options = {
      smoothing: this.smoothing,
      spheresize: this.spheresize
    };
    this.gui = new dat.GUI();
    const folderRender = this.gui.addFolder("Render Options");
    folderRender
      .add(this.options, "spheresize", 0.0, 2.0)
      .step(0.01)
      .onFinishChange(value => {
        this.spheresize = value;
        this.gl.uniform1f(this.size, this.spheresize);
      });
    folderRender
      .add(this.options, "smoothing", 0.1, 10)
      .step(0.01)
      .onFinishChange(value => {
        this.smoothing = value;
        this.gl.uniform1f(this.dst, this.smoothing);
      });
    // folderRender.open();
  };

  init = () => {
    this.createGraphics(
      document.getElementById("vertexShader").textContent,
      document.getElementById("fragmentShader").textContent
    );
    this.renderLoop();
  };

  importProgram = () => {
    // get the uniform ins from the shader fragments
 this.ut = this.gl.getUniformLocation(this.program, "time");
    this.size = this.gl.getUniformLocation(this.program, "size");
    this.dst = this.gl.getUniformLocation(this.program, "smoothing");
    this.resolution = new Float32Array([this.canvas.width, this.canvas.height]);
    this.gl.uniform2fv(
      this.gl.getUniformLocation(this.program, "resolution"),
      this.resolution
    );
    // set them puppies 
    this.gl.uniform1f(this.size, this.spheresize);
    this.gl.uniform1f(this.dst, this.smoothing);
  };

  importUniforms = () => {
    this.gl.uniform1f(this.ut, (Date.now() - this.start) / 1000);
  };

  renderLoop = () => {
    this.frame++;
    this.updateUniforms();
    this.animation = window.requestAnimationFrame(this.renderLoop);
  };
}

const demo = new Render(document.body);

              
            
!
999px

Console