I’m trying to code a simple shader which will take the mouse position to assign the color of the shader.
#ifdef GL_ES
precision mediump float;
#endif
uniform vec2 u_resolution;
uniform vec2 u_mouse;
uniform float u_time;
void main() {
//vec2 st = gl_FragCoord.xy/u_mouse;
gl_FragColor = vec4(u_mouse.x,u_mouse.y,0.0,1.0);
}
PShader s;
PImage img ;
void setup() {
size(640, 360, P2D);
noStroke();
s = loadShader("blur.glsl");
//monjori.set("resolution", float(width), float(height));
img = loadImage("frog.jpg");
}
void draw() {
//s.set("u_time", millis() / 1000.0);
//if(mouseY>0)
s.set("u_mouse",new PVector(mouseX,mouseY));
shader(s);
rect(0, 0, width, height);
}
This is my first time coding a shader so I dont know all the basics yet.
code from the book of shaders.
raron
September 24, 2020, 1:24am
2
Thanks for the tip, seems like a nice place to start looking into the magic of shaders!
(links are always nice though - The Book of Shaders )
As for your question, you forgot to normalize the mouse coordinates (between 0.0 and 1.0).
#ifdef GL_ES
precision mediump float;
#endif
uniform vec2 u_resolution;
uniform vec2 u_mouse;
uniform float u_time;
void main() {
vec2 mo = u_mouse/u_resolution; // Normalize mouse coordinates
gl_FragColor = vec4(mo.x, mo.y, 0.0, 1.0);
}
As for showing an image with the shader I have no idea atm (I’m new to shaders as well - just did the odd test here and there made by others).
You need to add in the “u_resolution” variable to get the shader to work:
s.set("u_resolution", float(width), float(height));
(The picture thing doesn’t work with the shader here. That’s probably a bit further in the book)
PShader s;
PImage img ;
void setup() {
size(640, 360, P2D);
noStroke();
s = loadShader("blur.glsl");
//monjori.set("resolution", float(width), float(height));
img = loadImage("tokyo.jpg");
}
void draw() {
s.set("u_resolution", float(width), float(height));
s.set("u_mouse", float(mouseX), float(mouseY));
//s.set("u_time", millis() / 1000.0);
shader(s);
//rect(0, 0, width, height);
image(img, 0, 0, width, height);
}
1 Like
Its a really good book which really takes you from the basics. The processing reference is also good too though and will be able to show you how to link the shaders to the sketch, which I didnt notice in the book of shaders (likely an oversight on my part). In any case I’m glad I took the plunge because shaders tremendously increase the speed, and dispite what I’d feared for ages the code is very approachable.
I noticed the normalization issue, a little while later, but wasnt online so I couldnt update the post.
also for those who want the pdf version of the book.
2 Likes