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

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

              
                .p-summary
  h1 Particles

canvas(id="canvas-webgl", class="p-canvas-webgl")

script(id="vs-physics-renderer" type="x-shader/x-vertex").
  varying vec2 vUv;

  void main(void) {
    vUv = uv;
    gl_Position = vec4(position, 1.0);
  }

script(id="fs-physics-renderer-velocity-init" type="x-shader/x-fragment").
  uniform sampler2D velocity;

  varying vec2 vUv;

  void main(void) {
    gl_FragColor = texture2D(velocity, vUv);
  }

script(id="fs-physics-renderer-velocity" type="x-shader/x-fragment").
  uniform sampler2D velocity;
  uniform sampler2D acceleration;
  uniform float time;

  varying vec2 vUv;

  vec3 polar(float radian1, float radian2, float radius) {
    return vec3(
      cos(radian1) * cos(radian2) * radius,
      sin(radian1) * radius,
      cos(radian1) * sin(radian2) * radius
    );
  }

  void main(void) {
    vec3 v = texture2D(acceleration, vUv).xyz + texture2D(velocity, vUv).xyz;
    float vStep = step(1000.0, length(v));
    gl_FragColor = vec4(
      v * (1.0 - vStep) + normalize(v + polar(time, -time, 1.0)) * 80.0 * vStep,
      1.0
    );
  }

script(id="fs-physics-renderer-acceleration" type="x-shader/x-fragment").
  uniform vec2 resolution;
  uniform sampler2D velocity;
  uniform sampler2D acceleration;
  uniform float time;
  uniform vec2 vTouchMove;

  varying vec2 vUv;

  //
  // GLSL textureless classic 3D noise "cnoise",
  // with an RSL-style periodic variant "pnoise".
  // Author:  Stefan Gustavson ([email protected])
  // Version: 2011-10-11
  //
  // Many thanks to Ian McEwan of Ashima Arts for the
  // ideas for permutation and gradient selection.
  //
  // Copyright (c) 2011 Stefan Gustavson. All rights reserved.
  // Distributed under the MIT license. See LICENSE file.
  // https://github.com/ashima/webgl-noise
  //

  vec3 mod289(vec3 x)
  {
    return x - floor(x * (1.0 / 289.0)) * 289.0;
  }

  vec4 mod289(vec4 x)
  {
    return x - floor(x * (1.0 / 289.0)) * 289.0;
  }

  vec4 permute(vec4 x)
  {
    return mod289(((x*34.0)+1.0)*x);
  }

  vec4 taylorInvSqrt(vec4 r)
  {
    return 1.79284291400159 - 0.85373472095314 * r;
  }

  vec3 fade(vec3 t) {
    return t*t*t*(t*(t*6.0-15.0)+10.0);
  }

  // Classic Perlin noise
  float cnoise(vec3 P)
  {
    vec3 Pi0 = floor(P); // Integer part for indexing
    vec3 Pi1 = Pi0 + vec3(1.0); // Integer part + 1
    Pi0 = mod289(Pi0);
    Pi1 = mod289(Pi1);
    vec3 Pf0 = fract(P); // Fractional part for interpolation
    vec3 Pf1 = Pf0 - vec3(1.0); // Fractional part - 1.0
    vec4 ix = vec4(Pi0.x, Pi1.x, Pi0.x, Pi1.x);
    vec4 iy = vec4(Pi0.yy, Pi1.yy);
    vec4 iz0 = Pi0.zzzz;
    vec4 iz1 = Pi1.zzzz;

    vec4 ixy = permute(permute(ix) + iy);
    vec4 ixy0 = permute(ixy + iz0);
    vec4 ixy1 = permute(ixy + iz1);

    vec4 gx0 = ixy0 * (1.0 / 7.0);
    vec4 gy0 = fract(floor(gx0) * (1.0 / 7.0)) - 0.5;
    gx0 = fract(gx0);
    vec4 gz0 = vec4(0.5) - abs(gx0) - abs(gy0);
    vec4 sz0 = step(gz0, vec4(0.0));
    gx0 -= sz0 * (step(0.0, gx0) - 0.5);
    gy0 -= sz0 * (step(0.0, gy0) - 0.5);

    vec4 gx1 = ixy1 * (1.0 / 7.0);
    vec4 gy1 = fract(floor(gx1) * (1.0 / 7.0)) - 0.5;
    gx1 = fract(gx1);
    vec4 gz1 = vec4(0.5) - abs(gx1) - abs(gy1);
    vec4 sz1 = step(gz1, vec4(0.0));
    gx1 -= sz1 * (step(0.0, gx1) - 0.5);
    gy1 -= sz1 * (step(0.0, gy1) - 0.5);

    vec3 g000 = vec3(gx0.x,gy0.x,gz0.x);
    vec3 g100 = vec3(gx0.y,gy0.y,gz0.y);
    vec3 g010 = vec3(gx0.z,gy0.z,gz0.z);
    vec3 g110 = vec3(gx0.w,gy0.w,gz0.w);
    vec3 g001 = vec3(gx1.x,gy1.x,gz1.x);
    vec3 g101 = vec3(gx1.y,gy1.y,gz1.y);
    vec3 g011 = vec3(gx1.z,gy1.z,gz1.z);
    vec3 g111 = vec3(gx1.w,gy1.w,gz1.w);

    vec4 norm0 = taylorInvSqrt(vec4(dot(g000, g000), dot(g010, g010), dot(g100, g100), dot(g110, g110)));
    g000 *= norm0.x;
    g010 *= norm0.y;
    g100 *= norm0.z;
    g110 *= norm0.w;
    vec4 norm1 = taylorInvSqrt(vec4(dot(g001, g001), dot(g011, g011), dot(g101, g101), dot(g111, g111)));
    g001 *= norm1.x;
    g011 *= norm1.y;
    g101 *= norm1.z;
    g111 *= norm1.w;

    float n000 = dot(g000, Pf0);
    float n100 = dot(g100, vec3(Pf1.x, Pf0.yz));
    float n010 = dot(g010, vec3(Pf0.x, Pf1.y, Pf0.z));
    float n110 = dot(g110, vec3(Pf1.xy, Pf0.z));
    float n001 = dot(g001, vec3(Pf0.xy, Pf1.z));
    float n101 = dot(g101, vec3(Pf1.x, Pf0.y, Pf1.z));
    float n011 = dot(g011, vec3(Pf0.x, Pf1.yz));
    float n111 = dot(g111, Pf1);

    vec3 fade_xyz = fade(Pf0);
    vec4 n_z = mix(vec4(n000, n100, n010, n110), vec4(n001, n101, n011, n111), fade_xyz.z);
    vec2 n_yz = mix(n_z.xy, n_z.zw, fade_xyz.y);
    float n_xyz = mix(n_yz.x, n_yz.y, fade_xyz.x);
    return 2.2 * n_xyz;
  }

  #define PRECISION 0.000001
  vec3 drag(vec3 a, float value) {
    return normalize(a * -1.0 + PRECISION) * length(a) * value;
  }

  void main(void) {
    vec3 v = texture2D(velocity, vUv).xyz;
    vec3 a = texture2D(acceleration, vUv).xyz;
    vec3 d = drag(a, 0.02);
    float fx = cnoise(vec3(time * 0.1, v.y / 500.0, v.z / 500.0));
    float fy = cnoise(vec3(v.x / 500.0, time * 0.1, v.z / 500.0));
    float fz = cnoise(vec3(v.x / 500.0, v.y / 500.0, time * 0.1));
    vec3 f1 = vec3(fx, fy, fz) * 0.12;
    vec3 f2 = vec3(vTouchMove * 10.0, 0.0);
    gl_FragColor = vec4(a + f1 + f2 + d, 1.0);
  }

script(id="vs-points" type="x-shader/x-vertex").
  attribute vec3 position;
  attribute vec2 uvVelocity;

  uniform mat4 modelViewMatrix;
  uniform mat4 projectionMatrix;
  uniform float time;
  uniform sampler2D acceleration;
  uniform sampler2D velocity;

  varying vec3 vAcceleration;

  void main() {
    vec3 a = texture2D(acceleration, uvVelocity).xyz;
    vec3 v = texture2D(velocity, uvVelocity).xyz;
    vec4 mvPosition = modelViewMatrix * vec4(v, 1.0);
    vAcceleration = a;
    gl_PointSize = 1.0 * (1200.0 / length(mvPosition.xyz));
    gl_Position = projectionMatrix * mvPosition;
  }

script(id="fs-points" type="x-shader/x-fragment").
  precision highp float;

  uniform float time;

  varying vec3 vAcceleration;

  vec3 convertHsvToRgb(vec3 c) {
    vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);
    vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www);
    return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y);
  }

  void main() {
    float start = smoothstep(time, 0.0, 1.0);
    vec3 n;
    n.xy = gl_PointCoord * 2.0 - 1.0;
    n.z = 1.0 - dot(n.xy, n.xy);
    if (n.z < 0.0) discard;
    float aLength = length(vAcceleration);
    vec3 color = convertHsvToRgb(vec3(aLength * 0.08 + time * 0.05, 0.5, 0.8));
    gl_FragColor = vec4(color, 0.4 * start);
  }

              
            
!

CSS

              
                @import url('https://fonts.googleapis.com/css?family=Homenaje');

.p-canvas-webgl {
  position: fixed;;
  z-index: 1;
  top: 0; left: 0;
}

.p-summary {
  position: absolute;
  top: 5%; left: 5%;
  z-index: 2;
  color: #fff;
  font-family: 'Homenaje', sans-serif;
  h1 {
    font-weight: 400;
    letter-spacing: 0.2em;
  }
  p {
    letter-spacing: 0.2em;
  }
  a {
    color: #fff;
  }
}
              
            
!

JS

              
                class PhysicsRenderer {
  constructor(aVertexShader, aFragmentShader, vVertexShader, vFragmentShader) {
    this.length = 0;
    this.aScene = new THREE.Scene();
    this.vScene = new THREE.Scene();
    this.camera = new THREE.PerspectiveCamera(45, 1, 1, 1000);
    this.option = {
      type: THREE.FloatType,
      minFilter: THREE.LinearFilter,
      magFilter: THREE.NearestFilter
    };
    this.acceleration = [
      new THREE.WebGLRenderTarget(length, length, this.option),
      new THREE.WebGLRenderTarget(length, length, this.option),
    ];
    this.velocity = [
      new THREE.WebGLRenderTarget(length, length, this.option),
      new THREE.WebGLRenderTarget(length, length, this.option),
    ];
    this.aUniforms = {
      resolution: {
        type: 'v2',
        value: new THREE.Vector2(window.innerWidth, window.innerHeight),
      },
      velocity: {
        type: 't',
        value: null,
      },
      acceleration: {
        type: 't',
        value: null,
      },
      time: {
        type: 'f',
        value: 0
      }
    };
    this.vUniforms = {
      resolution: {
        type: 'v2',
        value: new THREE.Vector2(window.innerWidth, window.innerHeight),
      },
      velocity: {
        type: 't',
        value: null,
      },
      acceleration: {
        type: 't',
        value: null,
      },
      time: {
        type: 'f',
        value: 0
      }
    };
    this.accelerationMesh = this.createMesh(
      this.aUniforms,
      aVertexShader,
      aFragmentShader
    );
    this.velocityMesh = this.createMesh(
      this.vUniforms,
      vVertexShader,
      vFragmentShader
    );
    this.uvs = [];
    this.targetIndex = 0;
  }
  init(renderer, velocityArrayBase) {
    this.length = Math.ceil(Math.sqrt(velocityArrayBase.length / 3));
    const velocityArray = [];
    for (var i = 0; i < Math.pow(this.length, 2) * 3; i += 3) {
      if(velocityArrayBase[i] != undefined) {
        velocityArray[i + 0] = velocityArrayBase[i + 0];
        velocityArray[i + 1] = velocityArrayBase[i + 1];
        velocityArray[i + 2] = velocityArrayBase[i + 2];
        this.uvs[i / 3 * 2 + 0] = (i / 3) % this.length / (this.length - 1);
        this.uvs[i / 3 * 2 + 1] = Math.floor((i / 3) / this.length) / (this.length - 1);
      } else {
        velocityArray[i + 0] = 0;
        velocityArray[i + 1] = 0;
        velocityArray[i + 2] = 0;
      }
    }
    const velocityInitTex = new THREE.DataTexture(new Float32Array(velocityArray), this.length, this.length, THREE.RGBFormat, THREE.FloatType);
    velocityInitTex.needsUpdate = true;
    const velocityInitMesh = new THREE.Mesh(
      new THREE.PlaneBufferGeometry(2, 2),
      new THREE.ShaderMaterial({
        uniforms: {
          velocity: {
            type: 't',
            value: velocityInitTex,
          },
        },
        vertexShader: document.getElementById('vs-physics-renderer').textContent,
        fragmentShader: document.getElementById('fs-physics-renderer-velocity-init').textContent,
      })
    );
    for (var i = 0; i < 2; i++) {
      this.acceleration[i].setSize(this.length, this.length);
      this.velocity[i].setSize(this.length, this.length);
    }
    this.vScene.add(this.camera);
    this.vScene.add(velocityInitMesh);
    renderer.render(this.vScene, this.camera, this.velocity[0]);
    renderer.render(this.vScene, this.camera, this.velocity[1]);
    this.vScene.remove(velocityInitMesh);
    this.vScene.add(this.velocityMesh);
    this.aScene.add(this.accelerationMesh);
  }
  createMesh(uniforms, vs, fs) {
    return new THREE.Mesh(
      new THREE.PlaneBufferGeometry(2, 2),
      new THREE.ShaderMaterial({
        uniforms: uniforms,
        vertexShader: vs,
        fragmentShader: fs,
      })
    );
  }
  render(renderer, time) {
    const prevIndex = Math.abs(this.targetIndex - 1);
    const nextIndex = this.targetIndex;
    this.aUniforms.acceleration.value = this.acceleration[prevIndex].texture;
    this.aUniforms.velocity.value = this.velocity[nextIndex].texture;
    renderer.render(this.aScene, this.camera, this.acceleration[nextIndex]);
    this.vUniforms.acceleration.value = this.acceleration[nextIndex].texture;
    this.vUniforms.velocity.value = this.velocity[nextIndex].texture;
    renderer.render(this.vScene, this.camera, this.velocity[prevIndex]);
    this.targetIndex = prevIndex;
    this.aUniforms.time.value += time;
    this.vUniforms.time.value += time;
  }
  getBufferAttributeUv() {
    return new THREE.BufferAttribute(new Float32Array(this.uvs), 2);
  }
  getCurrentVelocity() {
    return this.velocity[Math.abs(this.targetIndex - 1)].texture;
  }
  getCurrentAcceleration() {
    return this.acceleration[Math.abs(this.targetIndex - 1)].texture;
  }
  mergeAUniforms(obj) {
    this.aUniforms = Object.assign(this.aUniforms, obj);
  }
  mergeVUniforms(obj) {
    this.vUniforms = Object.assign(this.vUniforms, obj);
  }
  resize(length) {
    this.length = length;
    this.velocity[0].setSize(length, length);
    this.velocity[1].setSize(length, length);
    this.acceleration[0].setSize(length, length);
    this.acceleration[1].setSize(length, length);
  }
}

class Points {
  constructor() {
    this.uniforms = {
      time: {
        type: 'f',
        value: 0
      },
      velocity: {
        type: 't',
        value: null
      },
      acceleration: {
        type: 't',
        value: null
      }
    };
    this.physicsRenderer = null;
    this.vectorTouchMove = new THREE.Vector2(0, 0);
    this.vectorTouchMoveDiff = new THREE.Vector2(0, 0);
    this.obj = null;
  }
  init(renderer) {
    this.obj = this.createObj(renderer);
  }
  createObj(renderer) {
    const detail = (window.innerWidth > 768) ? 7 : 6;
    const geometry = new THREE.OctahedronBufferGeometry(400, detail);
    const verticesBase = geometry.attributes.position.array;
    const vertices = [];
    for (var i = 0; i < verticesBase.length; i+= 3) {
      vertices[i + 0] = verticesBase[i + 0] + (Math.random() * 2 - 1) * 400;
      vertices[i + 1] = verticesBase[i + 1] + (Math.random() * 2 - 1) * 400;
      vertices[i + 2] = verticesBase[i + 2] + (Math.random() * 2 - 1) * 400;
    }
    this.physicsRenderer = new PhysicsRenderer(
      document.getElementById('vs-physics-renderer').textContent,
      document.getElementById('fs-physics-renderer-acceleration').textContent,
      document.getElementById('vs-physics-renderer').textContent,
      document.getElementById('fs-physics-renderer-velocity').textContent,
    );
    this.physicsRenderer.init(renderer, vertices);
    this.physicsRenderer.mergeAUniforms({
      vTouchMove: {
        type: 'v2',
        value: this.vectorTouchMoveDiff
      }
    });
    this.uniforms.velocity.value = this.physicsRenderer.getCurrentVelocity();
    this.uniforms.acceleration.value = this.physicsRenderer.getCurrentAcceleration();
    geometry.addAttribute('uvVelocity', this.physicsRenderer.getBufferAttributeUv());
    return new THREE.Points(
      geometry,
      new THREE.RawShaderMaterial({
        uniforms: this.uniforms,
        vertexShader: document.getElementById('vs-points').textContent,
        fragmentShader: document.getElementById('fs-points').textContent,
        transparent: true,
        depthWrite: false,
        blending: THREE.AdditiveBlending,
      })
    )
  }
  render(renderer, time) {
    this.physicsRenderer.render(renderer, time);
    this.uniforms.time.value += time;
  }
  touchStart(v) {
    this.vectorTouchMove.copy(v);
  }
  touchMove(v) {
    this.vectorTouchMoveDiff.set(
      v.x - this.vectorTouchMove.x,
      v.y - this.vectorTouchMove.y
    );
    this.vectorTouchMove.copy(v);
  }
  touchEnd() {
    this.vectorTouchMove.set(0, 0);
    this.vectorTouchMoveDiff.set(0, 0);
  }
}

class ConsoleSignature {
  constructor() {
    this.message = `created by yoichi kobayashi`;
    this.url = `http://www.tplh.net`;
    this.show();
  }
  show() {
    if (navigator.userAgent.toLowerCase().indexOf('chrome') > -1) {
      const args = [
        `\n%c ${this.message} %c%c ${this.url} \n\n`,
        'color: #fff; background: #222; padding:3px 0;',
        'padding:3px 1px;',
        'color: #fff; background: #47c; padding:3px 0;',
      ];
      console.log.apply(console, args);
    } else if (window.console) {
      console.log(`${this.message} ${this.url}`);
    }
  }
}

const normalizeVector2 = function(vector) {
  vector.x = (vector.x / window.innerWidth) * 2 - 1;
  vector.y = - (vector.y / window.innerHeight) * 2 + 1;
};

const debounce = function(callback, duration) {
  var timer;
  return function(event) {
    clearTimeout(timer);
    timer = setTimeout(function(){
      callback(event);
    }, duration);
  };
}

const canvas = document.getElementById('canvas-webgl');
const renderer = new THREE.WebGLRenderer({
  antialias: false,
  canvas: canvas,
});
const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 10000);
const clock = new THREE.Clock();

const vectorTouchStart = new THREE.Vector2();
const vectorTouchMove = new THREE.Vector2();
const vectorTouchEnd = new THREE.Vector2();
let isDrag = false;

const consoleSignature = new ConsoleSignature();

//
// process for this sketch.
//

const points = new Points();
points.init(renderer);

//
// common process
//
const resizeWindow = () => {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
  camera.aspect = window.innerWidth / window.innerHeight;
  camera.updateProjectionMatrix();
  renderer.setSize(window.innerWidth, window.innerHeight);
}
const render = () => {
  const time = clock.getDelta();
  points.render(renderer, time);
  renderer.render(scene, camera);
}
const renderLoop = () => {
  render();
  requestAnimationFrame(renderLoop);
}
const touchStart = (isTouched) => {
  isDrag = true;
  points.touchStart(vectorTouchStart);
};
const touchMove = (isTouched) => {
  if (isDrag) points.touchMove(vectorTouchMove);
};
const touchEnd = (isTouched) => {
  isDrag = false;
  points.touchEnd();
};
const mouseOut = () => {
  isDrag = false;
  points.touchEnd();
};
const on = () => {
  window.addEventListener('resize', debounce(() => {
    resizeWindow();
  }), 1000);
  canvas.addEventListener('mousedown', function (event) {
    event.preventDefault();
    vectorTouchStart.set(event.clientX, event.clientY);
    normalizeVector2(vectorTouchStart);
    touchStart(false);
  });
  canvas.addEventListener('mousemove', function (event) {
    event.preventDefault();
    vectorTouchMove.set(event.clientX, event.clientY);
    normalizeVector2(vectorTouchMove);
    touchMove(false);
  });
  canvas.addEventListener('mouseup', function (event) {
    event.preventDefault();
    vectorTouchEnd.set(event.clientX, event.clientY);
    normalizeVector2(vectorTouchEnd);
    touchEnd(false);
  });
  canvas.addEventListener('touchstart', function (event) {
    event.preventDefault();
    vectorTouchStart.set(event.touches[0].clientX, event.touches[0].clientY);
    normalizeVector2(vectorTouchStart);
    touchStart(event.touches[0].clientX, event.touches[0].clientY, true);
  });
  canvas.addEventListener('touchmove', function (event) {
    event.preventDefault();
    vectorTouchMove.set(event.touches[0].clientX, event.touches[0].clientY);
    normalizeVector2(vectorTouchMove);
    touchMove(true);
  });
  canvas.addEventListener('touchend', function (event) {
    event.preventDefault();
    normalizeVector2(vectorTouchEnd);
    vectorTouchEnd.set(event.changedTouches[0].clientX, event.changedTouches[0].clientY);
    touchEnd(true);
  });
  window.addEventListener('mouseout', function () {
    event.preventDefault();
    vectorTouchEnd.set(0, 0);
    mouseOut();
  });
}

const init = () => {
  renderer.setSize(window.innerWidth, window.innerHeight);
  renderer.setClearColor(0x111111, 1.0);
  camera.position.set(0, 0, 1000);
  camera.lookAt(new THREE.Vector3());

  scene.add(points.obj);

  on();
  resizeWindow();
  renderLoop();
}
init();
              
            
!
999px

Console