/*
 星形を回転させる
*/

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <eggx.h>

/*
 rotateX , rotateY
 座標 (posX, posY) を、(orgX, orgY) を中心に angle 度だけ回転させた
 座標位置の X, Y 成分を得る
*/
double rotateX(double orgX, double orgY, double posX, double posY, double angle)
{
  double x, y; // (orgX, orgY) を原点とした場合の (posX, posY) 座標位置 
  double rotX; // (x, y) を angle 度回転させた座標位置（の X 成分）
  x = posX - orgX;
  y = posY - orgY;
  rotX = x * cos(angle) - y * sin(angle);
  return rotX + orgX; // 戻り値には orgX の値を加えておく
}

double rotateY(double orgX, double orgY, double posX, double posY, double angle)
{
  double x, y; // (orgX, orgY) を原点とした場合の (posX, posY) 座標位置 
  double rotY; // (x, y) を angle 度回転させた座標位置（の Y 成分）
  x = posX - orgX;
  y = posY - orgY;
  rotY = x * sin(angle) + y * cos(angle);
  return rotY + orgY; // 戻り値には orgX の値を加えておく
}

/*
 多角形は fillpoly() を使っている。fillpoly() 関数については別途マニュアル
 参照のこと。
 */

#define POLYNUM 12 // 多角形の角の数
int main()
{
  int win;
  int i;
  double th, l; // 作業用変数
  double x, y, length; // 図形中心位置と、その半径
  double posx[POLYNUM], posy[POLYNUM]; // 元の頂点位置座標配列
  double newx[POLYNUM], newy[POLYNUM]; // 回転させた後の座標位置配列

  win=gopen(400,400);  
  winname(win, "rotation");
  x=200.0;
  y=200.0;
  length=150.0; 
  
  /* 各頂点座標位置を決めて配列に格納 */
  for(i=0;i<POLYNUM;i++) {
    th=2.0*M_PI/(double)POLYNUM*(double)i;
    if(i%2==0) { // 頂点番号が偶数の時は外郭
      l=length;
    } else { // 奇数の時は内郭
      l=length * 0.4; 
    }
    posx[i]=cos(th)*l + x;
    posy[i]=sin(th)*l + y;
  }

  newpen(win, 1);  // 白色に設定

  th=0.0;
  while(1) { // 回転させながら描く
    gclr(win);
    for(i=0;i<POLYNUM;i++) { // 頂点ごとに th だけ回転させた座標位置を求める
      newx[i]=rotateX(x, y, posx[i], posy[i], th);
      newy[i]=rotateY(x, y, posx[i], posy[i], th);
    }
    fillpoly(win, newx, newy, POLYNUM, 0); // 多角形を描く
    th+=M_PI/150.0; // 少しだけ回転を進める
    msleep(20);
  }

}