#ifdef GL_ES
precision mediump float;
#endif
// this is a modified spritebatch shader

uniform sampler2D texSampler;
uniform sampler2D rgbTable;
uniform float testAlpha;
uniform float size;

varying lowp vec4 vColor;
varying vec2 vTexCoords;

vec4 sample3D(sampler2D tex, vec3 texCoord, float size) {
   float sliceSize = 1.0 / size;                         // space of 1 slice
   float slicePixelSize = sliceSize / size;              // space of 1 pixel
   float sliceInnerSize = slicePixelSize * (size - 1.0); // space of size pixels
   float zSlice0 = min(floor(texCoord.z * (size - 1.0)), size - 1.0);
   float zSlice1 = min(zSlice0 + 1.0, size - 1.0);
   float xOffset = slicePixelSize * 0.5 + texCoord.x * sliceInnerSize;
   float s0 = xOffset + (zSlice0 * sliceSize);
   float s1 = xOffset + (zSlice1 * sliceSize);
   float yOffset = (1.0 / size) * 0.5 + texCoord.y * (size - 1.0) / size;
   vec4 slice0Color = texture2D(tex, vec2(s0, yOffset));
   vec4 slice1Color = texture2D(tex, vec2(s1, yOffset));
   float zOffset = mod(texCoord.z * (size - 1.0), 1.0);
   return mix(slice0Color, slice1Color, zOffset);
}

vec4 sample3DNearest(sampler2D tex, vec3 texCoord, float size) {
   float sliceSize = 1.0 / size;                         // space of 1 slice
   float slicePixelSize = sliceSize / size;              // space of 1 pixel
   float sliceInnerSize = slicePixelSize * (size - 1.0); // space of size pixels
   float zSlice0 = min(floor(texCoord.z * (size - 1.0)), size - 1.0);
   float zSlice1 = min(zSlice0 + 1.0, size - 1.0);
   float xOffset = slicePixelSize * 0.5 + texCoord.x * sliceInnerSize;
   float s0 = xOffset + (zSlice0 * sliceSize);
   float s1 = xOffset + (zSlice1 * sliceSize);
   float yOffset = (1.0 / size) * 0.5 + texCoord.y * (size - 1.0) / size;
   vec4 slice0Color = texture2D(tex, vec2(s0, yOffset));
   vec4 slice1Color = texture2D(tex, vec2(s1, yOffset));
   float zOffset = mod(texCoord.z * (size - 1.0), 1.0);
   return mix(slice0Color, slice1Color, floor(0.5 + zOffset));
}

void main() {
	vec4 frag = texture2D(texSampler, vTexCoords);
#ifdef NEAREST
    gl_FragColor = sample3DNearest(rgbTable, frag.rgb, size);
#else
    gl_FragColor = sample3D(rgbTable, frag.rgb, size);
#endif
}