Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

In this Discussion

Shader troubles, neighboring pixels

edited May 15 in Questions Posts: 166

I’m having trouble with a shader, it looks at neighbor pixels, and if any of those has a non zero alpha value, it copies its color to the current pixel. Then I bake the shader result back to it’s texture img. The idea is to have any drawn pixels grow outward until eventualy the entire img is colored.

It does something but behaves unexpectedly, instead of growing outward to all sides, it grows to the right for a bit and then stops. Besides it’s functionality the code itself seems weirdly instable; if you copy the top nw vec to the bottom of the list, it gives an error...

Fragment code below (I dont know what is up with the forum code display, but it seems to ignore its tags....?)

highp float w = 1.;
highp float h = 1.;
highp float at = .01; // alpha threshold

void main()
    //Sample the texture at the interpolated coordinate
    lowp vec4 col = texture2D( texture, vTexCoord ) * vColor;

    lowp vec2 nw = vTexCoord+vec2(-w,h);  // if you copy this line to the bottom of the list, it breaks!
    lowp vec2 n = vTexCoord+vec2(0.,h);
    lowp vec2 ne = vTexCoord+vec2(w,h);
    lowp vec2 e = vTexCoord+vec2(w,0.);
    lowp vec2 se = vTexCoord+vec2(w,-h);
    lowp vec2 s = vTexCoord+vec2(0.,-h);
    lowp vec2 sw = vTexCoord+vec2(-w,-h);
    lowp vec2 w = vTexCoord+vec2(-w,0.);

    if (texture2D(texture, n).a > at)col = texture2D(texture, n);
    if (texture2D(texture, ne).a >at)col = texture2D(texture, ne);
    if (texture2D(texture, e).a > at)col = texture2D(texture, e);
    if (texture2D(texture, se).a >at)col = texture2D(texture, se);
    if (texture2D(texture, s).a > at)col = texture2D(texture, s);
    if (texture2D(texture, sw).a >at)col = texture2D(texture, sw);
    if (texture2D(texture, w).a > at)col = texture2D(texture, w);
    if (texture2D(texture, nw).a >at)col = texture2D(texture, nw);

    //Set the output color to the texture color
    gl_FragColor = col;


  • Posts: 402

    Setting w and h to 1. means that they wrap around the texture. The texture coordinates are scaled so that the texture fills the square from (0,0) to (1,1). To move by a single pixel, you need to pass in the texture dimensions and set w and h to their reciprocals.

  • Posts: 402

    Oh, and the reason it breaks if you move the nw line is because you redefine w on the previous line.

  • Posts: 166

    Doh, 2 stupid errors, shame on me...
    Thanks so much!

Sign In or Register to comment.