/* Polka Dot Shader              LAB #7
 * by Rimas Avizienis cs184-bs SID #12495774
 *
 * This shader creates a regular n x n array of polka dots
 * where n can be specified (as the parameter numdots)
 * other parameters that can be specified are:
 *      dotsize:        a value between 1 and 0 that sets how big the dots
 *                      are, a value of 1 means the edges of adjacent dots
 *                      touch
 *      dotcolor:       the desired color for the dots
 *
 *      the color of the object is used as the background color
 *
 *      also Ka and Kd do the usual things
 */

surface
lab7 ( float Ka = 0.5, Kd = 0.75;
                    color dotcolor = color "rgb" (0.1,0.1,1);
                    float numdots = 4;
                    float dotsize = 0.3; )
{
  normal Nf;
  color Ct;
  float ss,tt,dotspacing,dist,spot;

/* first normalize s & t so they are between 0 and 1
 * instead of -1 and 1 */

  dotspacing = 1/numdots;
  ss = (s + 1) / 2; tt = (t + 1) / 2;

/* now we determine how close we are to the nearest dot by making ss and tt
 * the coordinates relative to the nearest dot (with the nearest dot
 * centered at 0) */

  ss = mod(ss, dotspacing);
  tt = mod(tt, dotspacing);
  ss = ss - dotspacing/2; tt = tt - dotspacing/2;

  dist = sqrt(ss*ss + tt*tt);

/* if we are within a dot, use the dotcolor, otherwise use the background
 * color */

  if (dist < dotsize * dotspacing/2)
     spot = 1;
  else
     spot = 0;

  Ct = mix (Cs, dotcolor, spot);

  Nf = faceforward (normalize(N),I);
  Oi = Os;
  Ci = Os * Ct * (Ka*ambient() + Kd*diffuse(Nf));
}