#include "gedit.h"
#include <math.h>

#define NUM_POINTS	12

extern polygon_t *BeginPolygon();
extern void PointToXYZ();

static point_t	drag;

void
ScaleCircle(p, poly, scale)
view_info_t	*p;
polygon_t	*poly;
double		scale;
{
	double a = 0.0, a_incr = M_PI * 2.0 / NUM_POINTS;
	double other = 0.0, ocos, osin;
	int i;

	for (i=0; i<NUM_POINTS; ++i) {

		osin = sin (a);
		ocos = cos (a);
		poly->point[i] = drag;
		switch (p->layout) {
		case VL_NYX:
		case VL_NXNY:
			poly->point[i].point.x += osin * scale;
			poly->point[i].point.y += ocos * scale;
			poly->point[i].point.z += other;
			break;
		case VL_NYZ:
			poly->point[i].point.x += other;
			poly->point[i].point.y += ocos * scale;
			poly->point[i].point.z += osin * scale;
			break;
		case VL_NXZ:
			poly->point[i].point.x += osin * scale;
			poly->point[i].point.y += other;
			poly->point[i].point.z += ocos * scale;		
			break;
		default:
			poly->point[i].point.x += osin * scale;
			poly->point[i].point.y += ocos * scale;
			poly->point[i].point.z += other;
			break;	
		}
		a += a_incr;	
		PointToXYZ (p, &poly->point[i]);
	}
	
	if (scale > 0.0) {
		ComputePlaneEquation (poly);
	}
}

void
BeginCirclePoint (w, p, x, y)
Widget	 w;
view_info_t	*p;
int	x, y;
{
	polygon_t *poly;
	
	poly = BeginPolygon();
	poly->num_points = NUM_POINTS;
	drag_origin.x = x;
	drag_origin.y = y;
	PointXY (w, p, x, y, &drag);
	ScaleCircle (p, poly, 0.0);
}

void
DragCirclePoint(w, p, x, y)
Widget	 w;
view_info_t	*p;
int	x, y;
{
	double dx = x - drag_origin.x, dy = y - drag_origin.y;
	double scale = sqrt (dx * dx + dy * dy) * pixel_scale;
	Display *dpy = XtDisplay(w);

	XSetFunction (dpy, p->gc, GXxor);
	XSetFunction (dpy, p->other_view->gc, GXxor);
	
	DrawPolygon (w, cur_polygon, True);
	DrawPolygon (p->other_widget, cur_polygon, True);

	ScaleCircle (p, cur_polygon, scale);
	DrawPolygon (w, cur_polygon, True);
	DrawPolygon (p->other_widget, cur_polygon, True);

	XSetFunction (dpy, p->gc, GXcopy);
	XSetFunction (dpy, p->other_view->gc, GXcopy);
}

void
CompleteCirclePoint(w, p, x, y)
Widget	 w;
view_info_t	*p;
int	x, y;
{
	CompletePolygon (w, cur_polygon);
}
