1
\$\begingroup\$

I'm making a WebGL game in a 90s DOS games style. I'm trying to use a shader which would quantize colors to get reduced colors look. I found this solution: Palette reduction to pre-defined palette, however I only get 4 colors when I apply the shader (as in the picture). Any help would be greatly appreciated.

enter image description here

\$\endgroup\$
  • \$\begingroup\$ You want the code of the other question giving an output of only 4 colours, is that it? \$\endgroup\$ – Vaillancourt Nov 14 '15 at 16:33
  • \$\begingroup\$ I get only 4 colors, but I would like to get 256. I edited the question. \$\endgroup\$ – Nvs Nov 14 '15 at 16:34
  • 1
    \$\begingroup\$ Could you edit to clarify what code you're using, and what it's intended to do? Have you tried debugging the problem, and if so, how? \$\endgroup\$ – Anko Nov 19 '15 at 1:41
1
\$\begingroup\$

Unless you have a specific 256 colors palette in mind, you could just use the "8-bit truecolor" as described at 8-bit color Wikipedia page.

To do that, you need to map R and G channels onto 8 values (3 bits each), and B onto 4 values (2 bits). Those 8 bits together make up 256 possible colors.

Provided your gl_FragColor is already determined, the lines below will map its color to one of 256 values:

vec3 color_resolution = vec3(8.0, 8.0, 4.0);
vec3 color_bands = floor(gl_FragColor.rgb * color_resolution) / (color_resolution - 1.0);
gl_FragColor = vec4(min(color_bands, 1.0), gl_FragColor.a);

The min clamping in the last line might not be necessary, this depends on the color buffer's format, you might keep it if unsure or take a look at https://stackoverflow.com/questions/26786711/will-the-fragment-shader-automatically-clamp-the-color-value-to-its-range.

| improve this answer | |
\$\endgroup\$
  • 1
    \$\begingroup\$ Note that this code does not minimise the color difference with the original pixel. Another formula which does is: floor(gl_FragColor.rgb * (color_resolution - 1.0) + 0.5) / (color_resolution - 1.0);. In a perfect world you would also have to perform gamma correction before quantisation. \$\endgroup\$ – sam hocevar Apr 15 '16 at 14:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.