uniform sampler1D surfcolormap;
uniform sampler1D labelcolormap;
uniform sampler1D heatcolormap;
uniform bool heatmap;
uniform bool labels;
uniform bool blending;
uniform float opacity;
uniform float brightness;
uniform int nb_colors;
uniform vec2 signalBounds;
uniform vec2 heatBounds;
uniform float infinite;

/*varying vec3 normal;*/
/*varying vec3 lightDir[4], halfVector[4];*/

varying vec3 texCoord;

int fmod(int value, int div)
{
  int rat = value / div;
  int mul = rat * div;
  return value - mul;
}

bool isfinite(float value)
{
  return value != infinite;
}

// Triangles are colored based on mesh signal, label, or heatmap color
void setColor()
{
  // Texture coords are (label, signal, heat)
  float label = texCoord.x;
  float heat = texCoord.z;
  float signal = (texCoord.y - signalBounds.x) / (signalBounds.y - signalBounds.x);
  if(signal > 1.) signal = 1.;
  if(signal < 0.) signal = 0.;

  // Valid heatmap label is set to negative, flip it back and update heat status
  bool has_heatmap = heatmap;
  if(label < 0)
    label = -label;
  else if(has_heatmap)
    has_heatmap = false;

  vec4 color;

  float opac = opacity + signal - opacity*signal;

  if(labels && label > 0.0) {
    // Draw Label Color
    float value = floor(label+0.5);
    float col_idx = (value+0.5)/float(nb_colors);
    vec4 col = texture1D(labelcolormap, col_idx);
    color.rgb = brightness * col.rgb * opac;
    color.a = col.a;
  } else if(has_heatmap) {
    // Draw heatmap color
    heat = (heat - heatBounds.x) / (heatBounds.y - heatBounds.x);
    vec4 col = texture1D(heatcolormap, heat);
    color.rgb = brightness * col.rgb * opac;
    color.a = col.a;
  } else {
    // Draw signal
    vec4 col = texture1D(surfcolormap, signal);
    color.rgb = brightness * col.rgb;
    color.a = col.a;
  }

  gl_FragColor = light(color);
  if(blending)
    gl_FragColor.a *= opacity;
  else
    gl_FragColor.a = 1.0;
}

