import com.cult3d.Cult3DScript;
import com.cult3d.device.CultWindow;
import com.cult3d.device.MouseDevice;
import com.cult3d.world.CultObject;

import java.awt.Point;

/**
 * This code demonstrates how to test which node are under the current mouse position
 * It works with Cult3D 5.3 and later
 */
public class HitTest implements Cult3DScript, Runnable
{
	private static final int SLEEP_TIME = 18;
	
	private volatile boolean stillGoing = true;
	
	private MouseDevice mouse;
	private CultWindow cultwin;
	private CultObject currentlySelectedObject;
	
	public HitTest()
	{
		System.out.println("Java Started");
		mouse = new MouseDevice();
		cultwin = CultWindow.getReference();
		
		new Thread(this).start();
	}
	
	public void run()
	{
		System.out.println("Thread started");
		
		CultObject hittedObject;
		Point mousepos;
		
		try
		{
			while (stillGoing)
			{
				mousepos = mouse.getMousePosition();
				
				hittedObject = (CultObject)cultwin.getNodeAtCoordinate(mousepos.x, mousepos.y);
				// if mose left the object, remove the boundingbox
				if ((hittedObject == null) && (currentlySelectedObject != null))
				{
					currentlySelectedObject.setBoundingBoxVisible(false);
				}
				// else.... if a object was hitted
				else if (hittedObject != null)
				{
					if ((currentlySelectedObject != null) && (currentlySelectedObject.isBoundingBoxVisible()))
					{
						currentlySelectedObject.setBoundingBoxVisible(false);
					}
						
					currentlySelectedObject = hittedObject;
					currentlySelectedObject.setBoundingBoxVisible(true);
				}
					
				try
				{
					Thread.currentThread().sleep(SLEEP_TIME);
				}
				catch (InterruptedException e)
				{
				}
			}
		}
		catch (IllegalStateException e)
		{
		}
		
		System.out.println("Thread ended");
	}
	
	public void cult3dDestroy()
	{
		System.out.println("Entererd cult3dDestroy()");
		stillGoing = false;
	}
}
