
using System;
using System.Drawing;

using OpenTK;
using OpenTK.Graphics;
using OpenTK.Graphics.OpenGL;

namespace PlanetExpress.Tools {
		
	public class PlanetRenderClass {
		
		private TexClass Tex;
		private TexClass Ring;
		public PlanetRenderClass(TexClass tex, float size) {
			Tex = tex;
			Size = size;
			Bitmap img = new Bitmap((int)size*2+8, (int)size*2+8);
			Graphics g = Graphics.FromImage(img);
			g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
			g.DrawEllipse(
			              new Pen(Color.Black, 8),
			              3, 3, img.Width-9, img.Height-9);
			
			Ring = TexMan.LoadTexture(img);
		}
		
		public void Action() {
			
		}
		
		public void Render(float x, float y) {
			if (Ring==null) return;
			if (Tex==null) return;
			
			float rt = ((float)Environment.TickCount/90000f);
			GL.PushMatrix(); {
			GL.Translate(x, y, 1f);
			GL.Scale(Size/Sectors, Size/Sectors, 0f);				          
			Tex.Bind();				
			
			float ts = 1f/Sectors;
			for (int r=-Sectors; r<Sectors; r++) {
				float col0 = (float)Math.Sqrt(
				                    Math.Pow(Sectors, 2) -
				                    Math.Pow(r, 2));
				float col1 = (float)Math.Sqrt(
				                    Math.Pow(Sectors, 2) -
				                    Math.Pow(r+1, 2));			
				for (int c=-Sectors; c<Sectors; c++) {						
					float f0 = (float)c / Sectors;
					//float f1 = (float)(c+1) / Sectors;
					float td = (float)Math.PI*2f;
					float cFac0 = 1f- (float)Math.Abs(c+Sectors/2)/(Sectors*1.8f);
					float cFac1 = 1f- (float)Math.Abs(c+1+Sectors/2)/(Sectors*1.8f);
					GL.Begin(BeginMode.Quads); {
						GL.Color3(new float[] {cFac0, cFac0, cFac0});
						/*4*/GL.TexCoord2(c*ts/td+rt, 		(r+1)*ts);	GL.Vertex2(col1*f0, 	r+1);
						/*1*/GL.TexCoord2(c*ts/td+rt, 		r*ts); 		GL.Vertex2(col0*f0, 	r);
							
						GL.Color3(new float[] {cFac1, cFac1, cFac1});							
						/*2*/GL.TexCoord2((c+1)*ts/td+rt, 	r*ts); 		GL.Vertex2(col0*f0+1, 	r);
						/*3*/GL.TexCoord2((c+1)*ts/td+rt, 	(r+1)*ts);	GL.Vertex2(col1*f0+1, 	r+1);													
					} GL.End();
				}
			}
			} GL.PopMatrix();
			GL.PushMatrix(); {
				GL.Translate(0, 0, 1f);
				Ring.Render(x - Ring.Width/2,
				            y - Ring.Height/2);
			} GL.PopMatrix();
		}
		
		public float Size = 256;
		public int Sectors = 16;
	}
}
