// P1002.java:$B5e$N2sE>(B

package applet;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import Glib.*;

public class P1002 extends xApplet
	implements Runnable,ActionListener
{	JButton bt0,bt1;
	Thread th=null;
	Image[]Im;
	xGraphics3 G3,ImG3;
	int n=18,r=200,count=0,bkc=7;
	double rtx=22.5,rty=0.0;
	double step1=Math.PI/12,step2=Math.PI/60;

	public void init()
	{	app_init(bkc);
		Container cp=getContentPane();
		cp.setBackground(getBackground());
		cp.setLayout(new FlowLayout(FlowLayout.LEFT));
		bt0=new JButton("Start");
		bt0.addActionListener(this);
		cp.add(bt0);
 		bt1=new JButton("Exit");
		bt1.addActionListener(this);
		cp.add(bt1);
		G3=new xGraphics3(getGraphics());
		G3.set0(CA,1);
	}

	public void actionPerformed(ActionEvent evt)
	{	if(evt.getSource()==bt0)
		{	if(th==null)
			{	th=new Thread(this);
				th.start();
			}
		}
		if(evt.getSource()==bt1)
			System.exit(0);
	}

	public void start(){}

	public void stop()
	{	if(th!=null)
			th=null;
	}

	public void run()
	{	Im=new Image[n];
		for(int i=0;i<n;i++)
			Im[i]=createImage(2*r+1,2*r+1);
		G3.textout(10,60,"Drawing Images",0,16);
		for(int i=0;i<n;i++)
		{	ImG3=new xGraphics3(Im[i].getGraphics());
			ImG3.set0(r,r,1);
			ImG3.setproj(rtx,rty);
			sphere(i*step1/n);
		}
		G3.frectangle(-CA.x+10,CA.y-44,-CA.x+122,CA.y-64,bkc);
		Thread th0=Thread.currentThread();
		while(th==th0)
		{	paint2();
			try
			{	th.sleep(200);
			}
			catch(InterruptedException e){}
		}
	}

	public void paint2()
	{	G3.putimage(Im[count],-r,r,this);
		count++;count=count%n;
	}

	private xPoint3D getxyz(double th,double fi)
	{	double x=Math.sin(th)*Math.sin(fi);
		double y=Math.cos(th);
		double z=Math.sin(th)*Math.cos(fi);
		return new xPoint3D(x,y,z);
	}

	private void sphere(double ang)
	{	int z_;
		double th,fi;
		xPoint3D p,pr;
		xPoint3D pr_=new xPoint3D(0,0,0);
		ImG3.circle(P0,r,0);
		for(th=0.0;th<Math.PI+step1/2;th=th+step1)
		{	for(fi=ang;fi<ang+2*Math.PI+step2/2;fi=fi+step2)
			{	p=getxyz(th,fi);
				pr=ImG3.getproj(xMath.mlt(r,p));
				z_=xMath.fint((pr_.z+pr.z)/2);
				if(fi>ang && z_>0)
					ImG3.line(xMath.fint(pr_.x),xMath.fint(pr_.y),
						xMath.fint(pr.x),xMath.fint(pr.y),0);
				pr_=pr;
			}
		}
		for(fi=ang;fi<ang+2*Math.PI+step1/2;fi=fi+step1)
		{	for(th=0.0;th<Math.PI+step2/2;th=th+step2)
			{	p=getxyz(th,fi);
				pr=ImG3.getproj(xMath.mlt(r,p));
				z_=xMath.fint((pr_.z+pr.z)/2);
				if(th>0 && z_>0)
					ImG3.line(xMath.fint(pr_.x),xMath.fint(pr_.y),
						xMath.fint(pr.x),xMath.fint(pr.y),0);
				pr_=pr;
			}
		}
	}
}

