Search code examples
glsl

How I can port a shadertoy into a vertex that is using a projection matrix?


I'm trying to port this shadertoy into OpenGL https://www.shadertoy.com/view/7lBBR3

Shadertoday has a vec4 fragCoord and a vec3 iResolution; that I'm not sure how to translate into my OpenGL shader.

I have a 2D plane that is projeted like this:

glm::vec3 camera = {0.f, 0.f, -5.f};
glm::vec3 projection = glm::perspective(glm::radians(45.f), app.aspectRatio, 0.1f, 100.f);
projection = glm::scale(projection, {1.f, -1.f, 1.f});
glm::mat view = glm::translate(projection, camera);

And then my vertex shader uses this view like this

layout(location = 0) in vec2 vPosition;
layout(location = 1) in vec2 vTexturePosition;

layout(location = 0) out vec2 position;
layout(location = 1) out vec2 texturePosition;

layout(binding = 0) uniform ubo {
  mat4 uView;
};

void main() {
  gl_Position = uView * vec4(vPosition, 0.f, 1.f);
  texturePosition = vTexturePosition;
}

So now is where I'm not sure how to proceed, in the shadertoy shader you can see lines like this

vec3 planeposition = vec3(fragCoord.xy / iResolution.y, 0.0);
vec2 cursorposition = iMouse.xy / iResolution.y;
vec2 uv = fract(fragCoord.xy / iResolution.y);
vec2 noise = fract(fragCoord.xy * 0.5);

Since I'm using a projection matrix I don't think iResolution is relevant, since it's just the size in pixels of the viewport. Also, fragCoord what it is? Is my vPosition from the vertex buffer?


Solution

  • Shadertoy's shaders are designed for a screen space render pass. iResolution is always the size of the viewport. iMouse is the window coordinate of the mouse pointer. fragCoord is the same as the fragment shader built-in uniform gl_FragCoord. So if your rectangles cover the entire viewport, you just need to create and set the iResolution and iMouse uniforms and replace fragCoord with gl_FragCoord. Note that you cannot omit iResolution entirely, as it also includes the aspect ratio of the viewport.