As an exercise in gl shaders, I’m trying to figure out how to send a texture to the fragment shader, and then use the fragment shader to blur it with a horizontal gaussian blur. Unfortunately, the ofShader documentation is a bit lacking, so I’ve spent a bunch of time reading through the source trying to piece together how to do this, without much success. Right now I can draw an image (a black circle on a white background) and then load the shader; but as soon as I add the shader the screen goes solid black.
I think that something isn’t quite right with
shader.setUniformTexture("inputBuffer", fbo.getTextureReference(),1);
; but I’m not really sure how else to pass the texture as a uniform.
Any suggestions?
blur_h.frag:
uniform sampler2D inputBuffer;
uniform vec2 resolution;
uniform float time;
const float blurSize = 1.0/512.0;
void main(void)
{
vec4 sum = vec4(0.0);
vec2 position = (gl_FragCoord.xy / resolution.xy);
// blur in y (vertical)
// take nine samples, with the distance blurSize between them
sum += texture2D(inputBuffer, vec2(position.x - 4.0*blurSize, position.y)) * 0.05;
sum += texture2D(inputBuffer, vec2(position.x - 3.0*blurSize, position.y)) * 0.09;
sum += texture2D(inputBuffer, vec2(position.x - 2.0*blurSize, position.y)) * 0.12;
sum += texture2D(inputBuffer, vec2(position.x - blurSize, position.y)) * 0.15;
sum += texture2D(inputBuffer, vec2(position.x, position.y)) * 0.16;
sum += texture2D(inputBuffer, vec2(position.x + blurSize, position.y)) * 0.15;
sum += texture2D(inputBuffer, vec2(position.x + 2.0*blurSize, position.y)) * 0.12;
sum += texture2D(inputBuffer, vec2(position.x + 3.0*blurSize, position.y)) * 0.09;
sum += texture2D(inputBuffer, vec2(position.x + 4.0*blurSize, position.y)) * 0.05;
gl_FragColor = texture2D(inputBuffer, vec2(position.x, position.y));
}
testApp.cpp:
void testApp::setup(){
ofEnableSmoothing();
ofSetFrameRate(1);
//ofSetVerticalSync(true);
width = ofGetWidth();
height = ofGetHeight();
shader.load("blur_h");
fbo.allocate(width,height);
fbo.begin();
ofSetColor(0);
ofCircle(width/2, height/2, 100, 100);
fbo.end();
}
//--------------------------------------------------------------
void testApp::update(){
}
//--------------------------------------------------------------
void testApp::draw(){
fbo.begin();
shader.begin();
setUniforms();
//ofRect(0,0,width,height);
shader.end();
fbo.end();
fbo.draw(0,0,width,height);
}
//--------------------------------------------------------------
void testApp::setUniforms(){
float resolution[] = {width, height};
float time = ofGetElapsedTimef();
shader.setUniform1f("time",time);
shader.setUniform2fv("resolution",resolution);
shader.setUniformTexture("inputBuffer", fbo.getTextureReference(),0);
}