three打造三维能量球效果代码

代码语言:html

所属分类:三维

代码描述:three打造三维能量球效果代码

代码标签: 能量 效果

下面为部分代码预览,完整代码请点击下载或在bfwstudio webide中打开

<!DOCTYPE html>
<html lang="en" >

<head>

  <meta charset="UTF-8">
  

  
  
<style>
body {
  margin:0;
}

canvas {
  position: fixed;
}
</style>



</head>

<body >
  <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;
  
  // movement variables
  vec3 movement = vec3(.0);
  
  uniform int u_maxIterations;
  uniform float u_stopThreshold;
  uniform float u_stepScale;
  uniform float u_eps;
  uniform int u_octaves;
  uniform vec3 u_clipBGColour;
  uniform vec3 u_blobColour;
  uniform vec3 u_light_position;
  uniform vec3 u_lightColour;
  uniform float u_lightStrength;
  uniform float u_sceneWeight;
  uniform float u_internalStep;
  
  const int maxIterations = 1024;
  
  const vec3 light1_position = vec3(0, 1., -1.);
  const vec3 light1_colour = vec3(.5, .8, 1.85);
  
  const int octaves = 3;
  const int max_octaves = 16;
  
  struct Surface {
    int object_id;
    float distance;
    vec3 position;
    vec3 colour;
    float ambient;
    float spec;
  };
  
  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 = 0.;
    for(int i = 1; i < max_octaves; i++) {
      if(i > u_octaves) break;
      float f = float(i);
      _bumps += bumps(p, phase + f * 10., size * multiplier * 1./f, frequency * f);
    }
    
    return _bumps;
  }
  
  // This function describes the world in distances from any given 3 dimensional point in space
  float world(in vec3 position, inout int object_id) {
    vec3 pos = floor(position * .5);
    object_id = int(floor(pos.x + pos.y + pos.z));
    // position = mod(position, 1.) - .5;
    float gradient = max(0., (position.y + .3));
    float bumps = fractalBumps(position, u_time * 2., .5 * gradient, vec3(10. + sin(u_time) * 5.), 2.8);
    
    float world = length(position) - .4 + bumps * .15;
    
    // world = max(world, -position.y);
    
    return world;
  }
  float world(in vec3 position) {
    int dummy = 0;
    return world(position, dummy);
  }
  
  Surface getSurface(int object_id, float rayDepth, vec3 sp) {
    return Surface(
      object_id, 
      rayDepth, 
      sp, 
      vec3(1.), 
      .5, 
      200.);
  }
  
  // The raymarch loop
  Surface rayMarch(vec3 ro, vec3 rd, float start, float end, inout vec3 col) {
    float sceneDist = 1e4;
    float rayDepth = start;
    int object_id = 0;
    
    // Light position
    vec3 lp = ro + vec3(2, 2, -5.);
    
    bool hit = false;
    
    for(int i = 0; i < maxIterations; i++) {
      if(i > u_maxIterations) break;
      vec3 r = ro + rd * rayDepth;
      sceneDist = world(r, object_id);
      
      vec3 normal = normalize(r);
      vec3 ld = lp - r;
      float len = length( ld );
      ld = normalize(ld);
      float diffuse = max(0., dot(normal, ld))+.2;
      
      float weighting = length(r);
     
      col += clamp((1./abs(sceneDist)*u_sceneWeight)*weighting*(diffuse*.005*u_blobColour)*(u_lightColour*u_lightStrength), 0.0, 1.);
      
      if(sceneDist < u_stopThreshold) {
        rayDepth += u_internalStep;
      } else {
        rayDepth += sceneDist * u_stepScale;
      }
      
      if(rayDepth > end) {
        break;
      }
    }
    
    col = sqrt(col);
    
    return getSurface(object_id, rayDepth, ro + rd * rayDepth);
  }

  void main() {
    vec2 uv = (gl_FragCoord.xy - 0.5 * u_resolution.xy) / min(u_resolution.y, u_resolution.x);
    
    // Camera and look-at
    vec3 cam = vec3(cos(u_mouse.x * 5.)*3.,u_mouse.y * 3.,sin(u_mouse.x * 5.)*3.);
    vec3 lookAt = vec3(0,0,0);
    
    // 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.;
    vec3 col = u_clipBGColour;
    Surface objectSurface = rayMarch(ro, rd, clipNear, clipFar, col);
    
    gl_FragColor = vec4(col, 1.);
  }
  
</script>

  
      <script type="module">
/**
 * A basic Web GL class. This provides a very basic setup for GLSL shader code.
 * Currently it doesn't support anything except for clip-space 3d, but this was
 * done so that we could start writing fragments right out of the gate. My
 * Intention is to update it with particle and polygonal 3d support later on.
 *
 * @class WTCGL
 * @author Liam Egan <liam@wethecollective.com>
 * @version 0.0.8
 * @created Jan 16, 2019
 */
class WTCGL {

  /**
   * The WTCGL Class constructor. If construction of the webGL context fails 
    * for any reason this will return null.
    * 
    * @TODO make the dimension properties properly optional
    * @TODO provide the ability to allow for programmable buffers
   *
   * @constructor
   * @param {HTMLElement} el The canvas element to use as the root
   * @param {string} vertexShaderSource The vertex shader source
   * @param {string} fragmentShaderSource The fragment shader source
    * @param {number} [width] The width of the webGL context. This will default to the canvas dimensions
    * @param {number} [height] The height of the webGL context. This will default to the canvas dimensions
    * @param {number} [pxratio=1] The pixel aspect ratio of the canvas
    * @param {boolean} [styleElement] A boolean indicating whether to apply a style property to the canvas (resizing the canvas by the inverse of the pixel ratio)
    * @param {boolean} [webgl2] A boolean indicating whether to try to create a webgl2 context instead of a regulart context
   */
  constructor(el, vertexShaderSource, fragmentShaderSource, width, height, pxratio, styleElement, webgl2) {
    this.run = this.run.bind(this);

    this._onRun = () => {};

    // Destructure if an object is aprovided instead a series of parameters
    if (el instanceof Object && el.el) {
      ({ el, vertexShaderSource, fragmentShaderSource, width, height, pxratio, webgl2, styleElement } = el);
    }

    // If the HTML element isn't a canvas, return null
    if (!el instanceof HTMLElement || el.nodeName.toLowerCase() !== 'canvas') {
      console.log('Provided element should be a canvas element');
      return null;
    }

    this._el = el;
    // The context should be either webgl2, webgl or experimental-webgl
    if (webgl2 === true) {
      this.isWebgl2 = true;
      this._ctx = this._el.getContext("webgl2", this.webgl_params) || this._el.getContext("webgl", this.webgl_params) || this._el.getContext("experimental-webgl", this.webgl_params);
    } else {
      this.isWebgl2 = false;
      this._ctx = this._el.getContext("webgl", this.webgl_params) || this._el.getContext("experimental-webgl", this.webgl_params);
    }

    // Set up the extensions
    this._ctx.getExtension('OES_standard_derivatives');
    this._ctx.getExtension('EXT_shader_texture_lod');
    this._ctx.getExtension('OES_texture_float');
    this._ctx.getExtension('WEBGL_color_buffer_float');
    this._ctx.getExtension('OES_texture_float_linear');
    this._ctx.getExtension('EXT_color_buffer_float');

    // We can't make the context so return an error
    if (!this._ctx) {
      console.log('Browser doesn\'t support WebGL ');
      return null;
    }

    // Create the shaders
    this._vertexShader = WTCGL.createShaderOfType(this._ctx, this._ctx.VERTEX_SHADER, vertexShaderSource);
    this._fragmentShader = WTCGL.createShaderOfType(this._ctx, this._ctx.FRAGMENT_SHADER, fragmentShaderSource);

    // Create the program and link the shaders
    this._program = this._ctx.createProgram();
    this._ctx.attachShader(this._program, this._vertexShader);
    this._ctx.attachShader(this._program, this._fragmentShader);
    this._ctx.linkProgram(this._program);

    // If we can't set up the params, this means the shaders have failed for some reason
    if (!this._ctx.getProgramParameter(this._program, this._ctx.LINK_STATUS)) {
      console.log('Unable to initialize the shader program: ' + this._ctx.getProgramInfoLog(this._program));
      return null;
    }

    // Initialise the vertex buffers
    this.initBuffers([
    -1.0, 1.0, -1.,
    1.0, 1.0, -1.,
    -1.0, -1.0, -1.,
    1.0, -1.0, -1.]);


    // Initialise the frame buffers
    this.frameBuffers = [];

    // The program information object. This is essentially a state machine for the webGL instance
    this._programInfo = {
      attribs: {
        vertexPosition: this._ctx.getAttribLocation(this._program, 'a_position') },

      uniforms: {
        projectionMatrix: this._ctx.getUniformLocation(this._program, 'u_projectionMatrix'),
        modelViewMatrix: this._ctx.getUniformLocation(this._program, 'u_modelViewMatrix'),
        resolution: this._ctx.getUniformLocation(this._program, 'u_resolution'),
        time: this._ctx.getUniformLocation(this._program, 'u_time') } };



    // Tell WebGL to use our program when drawing
    this._ctx.useProgram(this._program);

    this.pxratio = pxratio;

    this.styleElement = styleElement !== true;

    this.resize(width, height);
  }


  /**
   * Public methods
   */

  addFrameBuffer(w, h, tiling = 0, buffertype = 0) {
    // create to render to
    const gl = this._ctx;
    const targetTextureWidth = w * this.pxratio;
    const targetTextureHeight = h * this.pxratio;
    const targetTexture = gl.createTexture();
    gl.bindTexture(gl.TEXTURE_2D, targetTexture);
    {
      // define size and format of level 0
      const level = 0;
      let internalFormat = gl.RGBA;
      const border = 0;
      let format = gl.RGBA;
      let t;
      if (buffertype & WTCGL.TEXTYPE_FLOAT) {
        const e = gl.getExtension('OES_texture_float');
        window.extension = e;
        t = e.FLOAT;
        // internalFormat = gl.RGBA32F;
      } else if (buffertype & WTCGL.TEXTYPE_HALF_FLOAT_OES) {
        // t = gl.renderer.isWebgl2 ? e.HALF_FLOAT : e.HALF_FLOAT_OES;
        //     gl.renderer.extensions['OES_texture_half_float'] ? gl.renderer.extensions['OES_texture_half_float'].HALF_FLOAT_OES : 
        //     gl.UNSIGNED_BYTE;
        const e = gl.getExtension('OES_texture_half_float');
        t = this.isWebgl2 ? gl.HALF_FLOAT : e.HALF_FLOAT_OES;
        // format = gl.RGBA;
        if (this.isWebgl2) {
          internalFormat = gl.RGBA16F;
        }
        // internalFormat = gl.RGB32F;
        // format = gl.RGB32F;
        // window.gl = gl
        // t = e.HALF_FLOAT_OES;
      } else {
        t = gl.UNSIGNED_BYTE;
      }
      const type = t;
      const data = null;
      gl.texImage2D(gl.TEXTURE_2D, level, internalFormat,
      targetTextureWidth, targetTextureHeight, border,
      format, type, data);
      // gl.generateMipmap(gl.TEXTURE_2D);

      // set the filtering so we don't need mips
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
      gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);

      // Set the parameters based on the passed type
      if (tiling === WTCGL.IMAGETYPE_TILE) {
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT);
      } else if (tiling === WTCGL.IMAGETYPE_MIRROR) {
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.MIRRORED_REPEAT);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.MIRRORED_REPEAT);
      } else if (tiling === WTCGL.IMAGETYPE_REGULAR) {
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
        gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
      }
    }

    // Create and bind the framebuffer
    const fb = gl.createFramebuffer();
    gl.bindFramebuffer(gl.FRAMEBUFFER, fb);

    // attach the texture as the first color attachment
    const attachmentPoint = gl.COLOR_ATTACHMENT0;
    const level = 0;
    gl.framebufferTexture2D(gl.FRAMEBUFFER, attachmentPoint, gl.TEXTURE_2D, targetTexture, level);

    return {
      w: w * this.pxratio,
      h: h * this.pxratio,
      fb: fb,
      frameTexture: targetTexture };

  }


  /**
   * Resizes the canvas to a specified width and height, respecting the pixel ratio
   *
   * @param  {number} w The width of the canvas
   * @param  {number} h The height of the canvas
   * @return {Void}
   */
  resize(w, h) {
    this.width = w;
    this.height = h;
    this._el.width = w * this.pxratio;
    this._el.height = h * this.pxratio;
    this._size = [w * this.pxratio, h * this.pxratio];
    if (this.styleElement) {
      this._el.style.width = w + 'px';
      this._el.style.height = h + 'px';
    }

    this._ctx.viewportWidth = w * this.pxratio;
    this._ctx.viewportHeight = h * this.pxratio;

    this._ctx.uniform2fv(this._programInfo.uniforms.resolution, this._size);

    this.initBuffers(this._positions);
  }

  /**
   * Initialise a provided vertex buffer
   *
   * @param  {array} positions The vertex positions to initialise
   * @return {Void}
   */
  initBuffers(positions) {
    this._positions = positions;
    this._positionBuffer = this._ctx.createBuffer();

    this._ctx.bindBuffer(this._ctx.ARRAY_BUFFER, this._positionBuffer);

    this._ctx.bufferData(this._ctx.ARRAY_BUFFER,
    new Float32Array(positions),
    this._ctx.STATIC_DRAW);
  }

  /**
   * Add a uniform to the program. At this time the following types are supported:
    * - Float - WTCGL.TYPE_FLOAT
    * - Vector 2 - WTCGL.TYPE_V2
    * - Vector 3 - WTCGL.TYPE_V3
    * - Vector 4 - WTCGL.TYPE_V4
   *
   * @param  {string} name The name of the uniform. N.B. your name will be prepended with a `u_` in your shaders. So providing a name of `foo` here will result in a uniform named `u_foo`
   * @param  {WTCGL.UNIFORM_TYPE} type The unfiform type 
   * @param  {number|array} value The unfiform value. The type depends on the uniform type being created 
   * @return {WebGLUniformLocation} The uniform location for later reference
   */
  addUniform(name, type, value) {
    let uniform = this._programInfo.uniforms[name];
    uniform = this._ctx.getUniformLocation(this._program, `u_${name}`);
    switch (type) {
      case WTCGL.TYPE_INT:
        if (!isNaN(value)) this._ctx.uniform1i(uniform, value);
        break;
      case WTCGL.TYPE_FLOAT:
        if (!isNaN(value)) this._ctx.uniform1f(uniform, value);
        break;
      case WTCGL.TYPE_V2:
        if (value instanceof Array && value.length === 2.) this._ctx.uniform2fv(uniform, value);
        break;
      case WTCGL.TYPE_V3:
        if (value instanceof Array && value.length === 3.) this._ctx.uniform3fv(uniform, value);
        break;
      case WTCGL.TYPE_V4:
        if (value instanceof Array && value.length === 4.) this._ctx.uniform4fv(uniform, value);
        break;
      case WTCGL.TYPE_BOOL:
        if (!isNaN(value)) this._ctx.uniform1i(uniform, value);
        break;}

    this._programInfo.uniforms[name] = uniform;
    return uniform;
  }

  /**
   * Adds a texture to the program and links it to a named uniform. Providing the type changes the tiling properties of the texture. Possible values for type:
   * - WTCGL.IMAGETYPE_REGULAR - No tiling, clamp to edges and doesn't need to be power of 2.
   * - WTCGL.IMAGETYPE_TILE - full x and y tiling, needs to be power of 2.
   * - WTCGL.IMAGETYPE_MIRROR - mirror tiling, needs to be power of 2.
   *
   * @public
  * @param  {string} name The name of the uniform. N.B. your name will be prepended with a `u_` in your shaders. So providing a name of `foo` here will result in a uniform named `u_foo`
   * @param  {WTCGL.TYPE_IMAGETYPE} type The type of texture to create. This is basically the tiling behaviour of the texture as described above
  * @param  {Image} image The image object to add to the texture
   * @return {WebGLTexture} The texture object
   */
  addTexture(name, type, image, liveUpdate = false) {

    var texture = this._ctx.createTexture();
    this._ctx.pixelSto.........完整代码请登录后点击上方下载按钮下载查看

网友评论0