Question

Let's pretend I'm making a compute shader using WebGL and GLSL.

In this shader, each fragment (or pixel) would like to look at every pixel on a texture, then decide on it's own color.

Normally a fragment samples it's provided texture coordinate (UV value) from a few textures, but I want to sample effectively all UV values from a single texture for a single fragment.

Is this possible?

Was it helpful?

Solution

EDIT: I was able to sample from each pixel in a 128x128 texture, but moving to 256x256 causes Chrome to fail. Meaning each pixel can sample roughly 16384 different pixels from the same texture in one draw call. Very useful for machine learning!

Note: There may be an unsquare power of 2 texture to support a higher pixel sample count under 256x256 (65536 pixels), but I only use square textures so this wasn't tested.

GIST OF SOURCE CODE

void main() {
    vec4 tcol = vec4(0, 0, 0, 0);
    for (float x = 0.0; x < PIXELS_WIDE; x++) 
        for (float y = 0.0; y < PIXELS_TALL; y++) 
            tcol += texture2D(tex0, vec2(x / PIXELS_WIDE, y / PIXELS_TALL));
    tcol /= 100.;
    gl_FragColor = tcol;
}

In Chrome I was able to execute the following loops:

100 Passes (Works):

void main() {
    float reg = 0.0;
    for (int i = 0; i < 100; i++) {
        reg += 1.0 / 255.0;
    }
    gl_FragColor = vec4(reg, 0, 0, 1);
}

1 000 Passes (Works):

void main() {
    float reg = 0.0;
    for (int i = 0; i < 1000; i++) {
        reg += 0.1 / 255.0;
    }
    gl_FragColor = vec4(reg, 0, 0, 1);
}

10 000 Passes (Works):

void main() {
    float reg = 0.0;
    for (int i = 0; i < 10000; i++) {
        reg += 0.01 / 255.0;
    }
    gl_FragColor = vec4(reg, 0, 0, 1);
}

100 000 Passes (Shits the bed):

void main() {
    float reg = 0.0;
    for (int i = 0; i < 100000; i++) {
        reg += 0.001 / 255.0;
    }
    gl_FragColor = vec4(reg, 0, 0, 1);
}
GL_INVALID_ENUM : glBindFramebuffer: target was GL_READ_FRAMEBUFFER_ANGLE 
GL_INVALID_ENUM : glBindFramebuffer: target was GL_DRAW_FRAMEBUFFER_ANGLE 
WebGL: CONTEXT_LOST_WEBGL: loseContext: context lost

OTHER TIPS

Is this possible?

It certainly is, however since each texture access requires a number of GPU instruction cycles you'll likely run into a hard limit on how many cycles a fragment shader may spend on each fragment, before it gets aborted.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top