/* CS184 Fall 1998 - Project 2
 * Raul 'Joni' Chu - cs184-bq - 12782756
 * Yuan Kui Shen   - cs184-ac - 12940472
 *
 * Atmosphere shader - a semi-transparent shader that creates a cloud-like look.
 * Takes in optional parameters for offset, scale, and twist. The first two 
 * control the scaling of the coulds and the later, of course, the twist effect
 * of the clouds.
 *
 *
 * NOTE: the 'thickness' or transparency of the shader has to be REALLY small ~0.005 to
 * start looking realistic
 *
 */

surface atmosphere (float Ka = 1, Kd = 1; float offset = 1; float scale = 0.6; float twist = 0.22; float omega = 0.65; float octaves = 8; float thickness = 1.0;) {
	point Ptxt;		/* the shade point in texture space */
	point PtN;              /* normalized version of Ptexture */
	point PP;               /* Point after rotation by coriolis twist */
	float rsq;              /* Used in calculation of twist */
	float angle;            /* Twist angle */
	float sine, cosine;     /* sin and cos of angle */
	float l, o, a, i;       /* Loop control for fractal sum */
	float value;            /* Fractal sum is stored here */

	Ptxt = transform ("shader", P);
	/* Do that swirl thing */
	PtN = normalize (Ptxt);
	rsq = xcomp(PtN)*xcomp(PtN) + ycomp(PtN)*ycomp(PtN);
	angle = twist * 2 * PI * rsq;
	sine = sin (angle);
	cosine = cos (angle);
	PP = point (xcomp(Ptxt)*cosine - ycomp(Ptxt)*sine, xcomp(Ptxt)*sine + ycomp(Ptxt)*cosine, zcomp(Ptxt));
	/* go for a walk in the clouds */
	l = 1;  
	o = 1;  
	a = 0;
	for (i = 0;  i < octaves;  i += 1) {
      		a += o * (2 * noise(PP * l) - 1);  
      		l *= 2;
      		o *= omega;
    	}
	/* put everything together */
  	value = abs(offset + scale * a);
  	Oi = thickness;
  	Ci = Os * (value * Cs) * (Ka * ambient() + Kd * diffuse(faceforward(normalize(N),I)));
}