Integrating webgl codepen

Hi Webflow family,

I’m looking for some help integrating the following webgl codepen into my website: https://codepen.io/shubniggurath/pen/dyOKjLG

I’m not a codepen/webflow expert but I’ve been able to successfully integrate other JS codepens before. I just cannot seem to get this one to work.

I created a new page, added an HTML embed, gave it an ID of webgl, and then added the codepen HTML and CSS to the embed code editor:

<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);
  }
  
  vec3 getNormal(vec3 p, float eps) {
    vec3 n;
    n.y = world(p);    
    n.x = world(vec3(p.x+eps,p.y,p.z)) - n.y;
    n.z = world(vec3(p.x,p.y,p.z+eps)) - n.y;
    n.y = eps;
    return normalize(n);
  }
  
  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;
    
    float energy = u_lightStrength*2.;
    bool inside = false;
    
    for(int i = 0; i < maxIterations; i++) {
      if(i > u_maxIterations) break;
      if(energy <= 0.) break;
      vec3 r = ro + rd * rayDepth;
      sceneDist = world(r, object_id);
      
      // if(inside == true && sceneDist > 0.) {
      //   rayDepth -= sceneDist;
      //   rayDepth += .01;
      //   sceneDist = world(r, object_id);
      // }
      
      vec3 normal = normalize(r);
      vec3 ld = lp - r;
      float len = length( ld );
      ld = normalize(ld);
      float lightAtten = min( 1.0 / ( 0.15*len ), 1.0 );
      float diffuse = max(0., dot(normal, ld))+.2;
      
      float weighting = length(r);
      
      energy -= .1;
     
      col += clamp((1./abs(sceneDist)*u_sceneWeight)*weighting*(diffuse*.0005*u_blobColour)*(u_lightColour*energy*lightAtten), 0.0, 1.);
      
      if(sceneDist < u_stopThreshold) {
        // if(inside == false) {
          // vec3 n = getNormal(r, .01);
          // rd = normalize(refract(rd, n, 1.01));
        // }
        inside = true;
        // vec3 r = ro + (rd+u_internalStep) * rayDepth;
        // sceneDist = world(r, object_id);
        // if(sceneDist>0.) {
        //   rayDepth += u_internalStep*.1;
        // } else {
          rayDepth += u_internalStep;
        // }
      } else {
        inside = false;
        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>
<style>
body {
  margin:0;
  background: #666;
}

canvas {
  mix-blend-mode: lighten;
  position: fixed;
}
</style>

Then I added the JS and script imports into the before body tag custom code area:

<script type="text/javascript" src=”https://cdn.skypack.dev/dat.gui”></script>
<script type="text/javascript" src=”https://codepen.io/shubniggurath/pen/aPxLMx.js”></script>

<script>import * as dat from 'https://cdn.skypack.dev/dat.gui';
console.clear();

const twodWebGL = new WTCGL(
  document.querySelector('canvas#webgl'), 
  document.querySelector('script#vertexShader').textContent, 
  document.querySelector('script#fragmentShader').textContent,
  window.innerWidth,
  window.innerHeight,
  window.devicePixelRatio
);

console.log(twodWebGL)

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



// 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);
});

const uniforms = {
  octaves: {
    v: 3,
    max: 12,
    min: 0,
    type: WTCGL.TYPE_INT },
  sceneWeight: {
    v: 1,
    max: 10,
    min: .01,
    type: WTCGL.TYPE_FLOAT },
  maxIterations: {
    v: 256,
    max: 512,
    min: 2,
    type: WTCGL.TYPE_INT },
  internalStep: {
    v: .003,
    max: 1,
    min: 0.0001,
    type: WTCGL.TYPE_FLOAT },
  stopThreshold: {
    v: .01,
    max: .1,
    min: .0001,
    type: WTCGL.TYPE_FLOAT },
  stepScale: {
    v: .8,
    max: 2.,
    min: .1,
    type: WTCGL.TYPE_FLOAT },
  clipBGColour: {
    v: '#000000',
    type: 'COLOUR' },
  blobColour: {
    v: '#FFFFFF',
    type: 'COLOUR' },
  lightColour: {
    v: '#3F66FF',
    type: 'COLOUR' },
  lightStrength: {
    v: 2,
    min: .1,
    max: 5,
    type: WTCGL.TYPE_FLOAT }
  
}

const hexToGL = (hex) => {
  const components = /^#?([A-F0-9]{2})([A-F0-9]{2})([A-F0-9]{2})/i.exec(hex);
  if(components && components.length === 4) {
    const r = Math.round(`0x${components[1]}` / 255 * 1000) / 1000;
    const g = Math.round(`0x${components[2]}` / 255 * 1000) / 1000;
    const b = Math.round(`0x${components[3]}` / 255 * 1000) / 1000;
    return [r,g,b]
  } else {
    return [];
  }
}
const updateUniform = (e, n) => {
  const prop = uniforms[e];
  if(prop.type === 'COLOUR') {
    const c = hexToGL(n);
    twodWebGL.addUniform(e, WTCGL.TYPE_V3, c);
  } else {
    twodWebGL.addUniform(e, prop.type, n);
  }
}

// const updateUniform(name, value) => {
  
// }

// const gui = new dat.GUI();
Object.entries(uniforms).forEach((u, v) => {
  console.log(u);
  const prop = uniforms[u[0]];
  if(prop.type === 'COLOUR') {
    const c = hexToGL(prop.v);
    console.log(c)
    twodWebGL.addUniform(u[0], WTCGL.TYPE_V3, c);
  } else {
    twodWebGL.addUniform(u[0], prop.type, prop.v);
  }
  if(prop.type === 'COLOUR') {
    // gui.addColor(prop, 'v').name(u[0]).onChange((v) => { updateUniform(u[0], v) });
  } else {
    // gui.add(prop, 'v', prop.min, prop.max).name(u[0]).onChange((v) => { updateUniform(u[0], v) });
  }
});










// 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');
  }
);
</script>

I’ve been struggling with this for a few days and would really appreciate any pointers. Thank you for your time

@Grooving2502 - The guidelines for this topic category include you sharing a read-only link, and a link to a published URL where you are trying to implement your custom code. Please update your post. Thanks.