Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

creating a dynamic uniform for shader #25

Open
cdaein opened this issue Jan 31, 2022 · 0 comments
Open

creating a dynamic uniform for shader #25

cdaein opened this issue Jan 31, 2022 · 0 comments

Comments

@cdaein
Copy link

cdaein commented Jan 31, 2022

Hi,
thank you for the great work.
I see that I can use dynamic sketch props such as time as a uniform,
but is there a way that I can create my own dynamic uniform that updates every frame?

What I ultimately want to do is to create array uniforms that update in the sketch and send them to the fragment shader that will update each frame.

I appreciate any help you might be able to give.

Below is a simple example code:

const canvasSketch = require("canvas-sketch");
const createShader = require("canvas-sketch-util/shader");
const glsl = require("glslify");

// Setup our sketch
const settings = {
  dimensions: [800, 800],
  context: "webgl",
  animate: true,
  duration: 3,
  fps: 30,
};

// Your glsl code
const frag = glsl(/* glsl */ `
  precision highp float;

  varying vec2 vUv;
  uniform float sizes[3];

  float sdCircle( vec2 p, float r ) {
    return length(p) - r;
  }

  void main () {
    vec2 p = vec2(vUv);
    p.y = 1.0 - p.y;
    
    vec3 col = vec3(0.1);

    for (int i = 0; i < 3; i++) {
      float circ = sdCircle(p - vec2(0.25 + float(i)/4., 0.5), sizes[i] * 0.1);
      circ = 1.0 - smoothstep(0.0, 0.05, circ);
      col += circ;
    }

    gl_FragColor = vec4(col, 1.);
  }
`);

// Your sketch, which simply returns the shader
const sketch = ({ gl, playhead }) => {
  let sizes = [0.2, 0.5, 0.8];

  // Q: how to update array values each frame and send as uniforms?
  sizes = sizes.map((el) => Math.sin(el + playhead));

  // regl does not take array uniforms at once, so this is a workaround..
  const uniforms = {};
  for (let i = 0; i < sizes.length; i++) {
    uniforms[`sizes[${i}]`] = sizes[i];
  }

  return createShader({
    gl,
    frag,
    uniforms: {
      ...uniforms,
    },
  });
};

canvasSketch(sketch, settings);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant