title: Count pixels by color in webgl fragment shader
body: <p>I have 2d texture S and want to return 3d texture H, such that pixel H[r,g,b] is equal to number of pixels of color rgb in texture S. Basically histogram of colors in texture S.</p>
  
  <p>I know about occlusion queries, but it's only available in webgl2, and IIUC even there only with boolean results, and besides I would need to do separate query for each color. Ideally I'd like to do this in one fragment shader pass. Is there any way to do reduce (fold) operations in fragment shaders?</p>
  
  <p>Why I need this (if you're interested):</p>
  
  <p>I'm trying to do pixel-perfect 2d collision detection between objects and static terrain in webgl fragment shaders.</p>
  
  <p>The plan is to use trick from old days - drawing a sprite 4 times - moved by (0,0), (0, dy), (dx, 0), and (dx, dy) pixels - and count the pixels of the sprite colliding with terrain each time - from that I can calculate vector (nx, ny) that represents the direction that the object should move to bounce of the terrain as quickly as possible. Simply adding that vector to the velocity of the object makes the object slide nicely along the terrain (down the hills, jumping on the bumps, etc). I've used that in old C++ game and that works great, but it's too slow in js.</p>
  
  <p>I want to draw the whole vertex buffer of all sprites in game (each in different color to be able to recognize which objects collide) 4 times, each time drawing the black terrain over them, and then count the pixels of each color in the resulting 4 framebuffers.</p>
  
  <p>The problem is - how to count the pixels in fragment shader?</p>