/* samp3.c */

# include <stdio.h>
# include <math.h>
# include "nanzan.h"

double theta(double x[],double y[],double z[])
{
    double xc,yc,zc, n1,n2,ret;
    double xl = 10, yl = -10, zl = -10;
    xc=(y[1]-y[0])*(z[3]-z[0])-(z[1]-z[0])*(y[3]-y[0]);
    yc=(z[1]-z[0])*(x[3]-x[0])-(x[1]-x[0])*(z[3]-z[0]);
    zc=(x[1]-x[0])*(y[3]-y[0])-(y[1]-y[0])*(x[3]-x[0]);
    n1 = xl*xc + yl*yc + zl*zc;
    n2 = sqrt(xl*xl + yl*yl + zl*zl) * sqrt(xc*xc + yc*yc + zc*zc);
    if ( n2 < 0.00001 ) return 0;
    ret = n1/n2;
    if ( ret > 1.0 ) return 0;
    if ( ret < -1.0 ) return 3.141592;
    return acos(ret);
}

double lambert(double r)
{
    double ret;
    ret = -cos(r);
    if ( ret <= 0.0 ) ret = 0;
    return ret;
}


void Calculate( double rx, double ry, double rz, double x[],
    double y[],double z[] )
{
    int i; double x2, x3, x4, y2, y3, y4, z2, z3, z4;
    for ( i=0; i<4; i++ ) {
	x2 = x[i];
	y2 = y[i] * cos(rx) - z[i] * sin(rx);
	z2 = y[i] * sin(rx) + z[i] * cos(rx);
	x3 = x2 * cos(ry) + z2 * sin(ry);
	y3 = y2;
	z3 = -x2 * sin(ry) + z2 * cos(ry);
	x4 = x3 * cos(rz) - y3 * sin(rz);
	y4 = x3 * sin(rz) + y3 * cos(rz);
	z4 = z3;
	x[i] = x4;
	y[i] = y4;
	z[i] = z4;
    }
}

void Draw( double x[],double y[],double z[] )
{
    int j, rgb; double l = -1000; XPoint points[4]; XColor xcol;
    _XSetBlack;
    _XFillRectangle( 0,0, 500,500 );
    for( j=0; j<4; j++) {
	points[j].x = (short)( x[j]*l/(z[j]+l) ) + 250;
	points[j].y = -(short)( y[j]*l/(z[j]+l) ) + 250;
    }
    rgb = ((int)( lambert(theta(x,y,z)) * 50))*1000+15000;
    xcol.red = xcol.green = xcol.blue = rgb;
    _XAllocColor( &xcol );
    _XSetForeground( xcol.pixel );
    _XFillPolygon( points, 4, Convex, CoordModeOrigin );
}

main()
{
    double x[4] = { -100, -100, 100, 100 };
    double y[4] = { 100, -100, -100, 100 };
    double z[4] = { 0, 0, 0, 0 };
    _XOpen;
    Draw(x,y,z);
    while(1) {
	usleep(200000);
        Calculate((double)3.1415/15,(double)0,(double)0,x,y,z);
	Draw(x,y,z);
	_XFlush;
    }
}

/* End of file --------------------- */
