
// stroke_quad.frag

//#version 430 compatibility  // Expect program to set this and other defines in prologue.

layout(binding = 0) uniform sampler2D frieze; 

void main(void)
{
  // Arc length texturing needs bilinear (rather than triangle barycentric) interpolation.
  // Fake this for trapezoids using projective texturing in just the arc length coordinate.
  // Use projective interpolation for arc length, so X/Y.
  // But non-projective interpolation for frieze height, so Z ranging [0,1].
  float X = gl_TexCoord[0].x;
  float Y = gl_TexCoord[0].y;
  float Z = gl_TexCoord[0].z;
  float arc_length = X/Y;
  float frieze_height = Z;  
  vec4 frieze_texel = texture(frieze, vec2(arc_length, frieze_height));
  gl_FragColor = gl_Color * frieze_texel;
  
  // The W component of  is assigned per-vertex as either -1*Y or +1*Y. 

  // re-rasterize: check if every sample is really in quad...
#if ALIASED
  // Aliased rendering doesn't initialize gl_SampleMask; so use discard instead.
  // No need for interpolateAtSample when aliased; conventional interpolation
  // is at the fragment center, same as where aliased coverage is determined.
  float W = gl_TexCoord[0].w;
  if (abs(Y) < abs(W)) {
    // this sample is invalid overlap, ignore it
    discard;
  }
#else
  // This same code path works for all multisample configurations.
  int sample_mask = gl_SampleMaskIn[0];
  int new_sample_mask = 0;
  while (sample_mask != 0) {
    int bit = findLSB(sample_mask);
    float W = interpolateAtSample(gl_TexCoord[0].w, bit);
    float Y = interpolateAtSample(gl_TexCoord[0].y, bit);    
    // Is W/Y inside [-1..+1] range?
    int sample_bit = (1<<bit);
    if (abs(W) <= abs(Y)) {
      new_sample_mask |= sample_bit;  // keep this coverage
    } // else this sample is invalid overlap, ignore it
    sample_mask &= ~sample_bit;  // clear this bit to find next bit
  }
  gl_SampleMask[0] = new_sample_mask; // output revised coverage
#endif
}

