#include <stdio.h>
#include <math.h>
#include "GrWin.h"


void GWsllipse(float x1, float y1, float x2, float y2, float angle, int c){
	
	float a, b;			//「長軸の長さの1/2」と「短軸の長さの1/2」
	float points[100][2];		//中心を原点とした楕円の座標
	float moved_points[100][2];	//回転後，指定された位置に移動させた楕円の座標

	int i, j;			//ループ用変数
	float x;
	float f;
	float swap;
	
	
	//「x1 <= x2」の状態にする
	if(x1 > x2){
		swap = x1;
		x1 = x2;
		x2 = swap;
	}
	
	//「y1 <= y2」の状態にする
	if(y1 > y2){
		swap = y1;
		y1 = y2;
		y2 = swap;
	}	

	//度数法で入力された角度を弧度法に変換する
	angle = angle / 180.0 * 3.14159;
	
	//「長軸の長さの1/2」と「短軸の長さの1/2」を計算する
	a = (x2 - x1) / 2.0;
	b = (y2 - y1) / 2.0;	

	//-------------------------------------------------------------------------------------
	//中心を原点とした楕円の，各描画点座標を計算
	//y >= 0 の座標 
	for(i = 0, x = a; i < 50; i++, x -= (a / 24.5)){
		points[i][0] = x;
		points[i][1] = (f = sqrt((b * b) - (b * b) * (x * x) / (a * a))) > 0.0 ? f : 0.0;
	}
	//y < 0の座標	
	for(i = 50, j = 50; i < 100; ++i, --j){
		points[i][0] = points[j][0];
		points[i][1] = 0.0 - (points[j][1]);	
	}
	

	//---------------------------------------------------------------------------------------
	//楕円を回転させ，平行移動させる
	for(i = 0; i < 100; ++i){
			
		//楕円を回転させる（まだ、楕円の中心は原点）
		moved_points[i][0] = points[i][0] * cos(angle) - points[i][1] * sin(angle);
		moved_points[i][1] = points[i][0] * sin(angle) + points[i][1] * cos(angle);

		//楕円を指定された位置に平行移動
		moved_points[i][0] += (x2 - a);
		moved_points[i][1] += (y2 - b);
		
	}
		
	//------------------------------------------------------------------------------------------
	//楕円を描画
	GWsetpen(c, -1, -1, 4);
  	GWsetbrs(c, 1, -1);  
	GWpolygon(moved_points, 100, 0);
		
}

int main()
{
	float x1, x2, y1, y2, angle;
	int c, i;

	GWopen(0);
	GWindow(-100.0, -100.0, 100.0, 100.0);
	
	//ます目を描く
	for(i = -90; i < 100; i += 10){
		GWxline(i, -90, i, 90, 0);
		GWxline(-90, i, 90, i, 0);
	}
	//x軸，y軸を描く
		GWxline(0, -90, 0, 90, 13);
		GWxline(-90, 0, 90, 0, 13);	

	x1 = 20.0;
	y1 = 20.0;
	
	x2 = 50.0;
	y2 = 30.0;
	
	angle = 370.0;
	c = 13;

	//指定した座標を表示する
	GWsrect(x1 - 2.0, y1 - 2.0, x1 + 2.0, y1 + 2.0, c);
	GWsrect(x2 - 2.0, y2 - 2.0, x2 + 2.0, y2 + 2.0, c);
	
	GWsellipse(x1, y1, x2, y2, angle, c);

	return 0;
}