Hey, thanks for the explanation. I understand now and got a nice alpha-gradient working…
Since you’re here, I’ll trouble you with another question… how can I displace rectangles that have a shader texture on them? If I do this:
void ofApp::draw(){
m_shader1.begin();
m_shader1.setUniformTexture("u_tex", m_tex1, 0);
m_shader1.setUniform2f("u_resolution", m_tex1.getWidth(), m_tex1.getHeight());
ofDrawRectangle(500, 0, m_tex1.getWidth(), m_tex1.getHeight()); //translate rectangle 500 pixels to the right
m_shader1.end();
m_gui.draw();
}
void main()
{
vec2 coord = gl_FragCoord.xy / u_resolution;
coord.y = 1.0 - coord.y;
vec4 color = texture2D(u_tex,coord);
gl_FragColor = color;
}
…the result is this:
ie. the rectangle’s being translated but not the texture.
I tried adding coord.x += 500 / u_resolution
to the shader, but that doesn’t help.
EDIT: OK, I got it working with
coord.x -= 500.0/u_resolution.x;
…which makes sense now that I think about it. Is there a method in oF to automate this offsetting, or do I just always need to update it with a u_translate value?
EDIT2: This is more complicated with resizing. To get the shader to draw properly for an image drawn at half-size I have to do this:
vec2 coord = gl_FragCoord.xy / u_resolution;
coord.y = coord.y * 2.0 - 0.5;
coord.x = coord.x * 2.0;
coord.y = 1.0 - coord.y;
vec4 color = texture2D(u_tex,coord);
gl_FragColor = color;
and this isn’t quite right either, as there’s some distortion at the bottom- probably because I’m not taking aspect ratio into account with my calculations. This seems oddly cumbersome though, am I supposed to be doing something with the vertex shader instead? Right now it only contains this:
void main() {
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}
I read through the first page of the shaders tutorial @zach linked me to, but it doesn’t seem to mention this. I thought maybe mapTexCoordsFromTexture() would be relevant, but it seems to be for 3d shapes exclusively,
EDIT 3: OK, looking at the 4th example project, it looks like you have to use ofPlane instead of ofRectangle, which translates the texture/shader together with it.
EDIT 4: For my purposes this time, it seems like it’s easier to just set the position inside the shader and leave the ofRectangle in the same spot, making sure to pass both the resolution of the screen and the resolution of the image into the shader. But I would like to know other ways to do this, eg. when I’m using shaders on something like ofBox2d