#include <iostream>
#include <cstdlib>
#include <cmath>

using namespace std;

double f(double x, double y)
{
   if (x>0 && y<0)
      return -2;
   double r= hypot(x,y);
   double s= 5;
   if (r==0)
       return s;
   else
       return s * sin(r)/r;
}


bool test(double a, double b, double c, double h)
{
    double d1= fabs(a-b);
    double d2= fabs(a-c);
    double d3= fabs(b-c);
 
    double r= d1>d2 ? d1>d3 ? d1 : d3 : d2>d3 ? d2 : d3; 
    return r<h;
}


int main(void)
{
    double a= -3*M_PI;
    double b=  3*M_PI;
    int n= 150;
    double hx = (b-a) / n;

    double c= - 3*M_PI;
    double d=   3*M_PI;
    int m= 150;
    double hy = (d-c) / m;

    double eps= hx<hy? hy : hx;
    eps= 0.9;

    cout << "#include \"colors.inc\"\n";
    cout << "light_source { <0,   0, 0> color Blue }\n";
    cout << "light_source { <0,  30, 0> color White }\n";
    cout << "camera { location <0,5,-20> direction z look_at <0,0,0> }\n";
    cout << "#declare green_plastic =\n"
         << "   texture {\n"
         << "   pigment { color rgb <0, 1, 0> }\n"
         << "   finish {ambient 0.1 diffuse 0.8 phong 0.5 phong_size 100 }\n"
         << "}\n";
    cout << "#declare white_plastic =\n"
         << "   texture {\n"
         << "   pigment { color rgb <1, 1, 1> }\n"
         << "   finish {ambient 0.1 diffuse 0.8 phong 0.5 phong_size 100 }\n"
         << "}\n";

    
    for (int i=0; i<n; ++i)
       {
        double x = a + i*hx;
        double x1= x + hx;
        for (int j=0; j<m; ++j)
           {
            double y= c+j*hy;
            double y1= y + hy;
            double z0= f(x,y);
            double z1= f(x1,y);
            double z2= f(x,y1);
            double z3= f(x1,y1);

            if (test(z0,z1,z3, eps))
            cout << "triangle {\n" 
                 << "  <" << x  << "," << z0 << "," << y  << ">,\n"
                 << "  <" << x1 << "," << z1 << "," << y  << ">,\n"
                 << "  <" << x1 << "," << z3 << "," << y1 << ">\n"
                 << "  texture {\n"
                    "     green_plastic\n"
                    "  }\n"
                    "}\n";
             
            if (test(z0,z2,z3, eps)) 
            cout << "triangle {\n" 
                 << "  <" << x  << "," << z0 << "," << y  << ">,\n"
                 << "  <" << x  << "," << z2 << "," << y1 << ">,\n"
                 << "  <" << x1 << "," << z3 << "," << y1 << ">\n"
                 << "  texture {\n"
                    "     white_plastic\n"
                    "  }\n"
                    "}\n";
           }
       }

}

