// Sphere object. By John Haggerty (Slime).
// http://www.slimeland.com/
// Created January 21, 2003

// requires objects.js.

function Sphere(pos,rad)
{
	this.pos = pos;
	this.rad = rad;
	this.setupdefaultmodifiers();
}
Sphere.prototype = new Obj();
Sphere.prototype.copy = function()
{
	return this.copymodifiers(new Sphere(this.pos.copy(),this.rad));
}
Sphere.prototype.initialize = function()
{
	this.boundedby = new Box(Vector.add(new Vector(-this.rad,-this.rad,-this.rad),this.pos),Vector.add(new Vector(this.rad,this.rad,this.rad),this.pos), true);
	this.radsquared = this.rad*this.rad;
	this.negpos = this.pos.neg();
	this.generalLowLevelObjectInitialization();
}
Sphere.prototype.findIntersectionsUntransformed = function(ray)
{
	var startminusthispos = Vector.add(ray.start,this.negpos);

	var a = Vector.dot(ray.dir,ray.dir);
	var b = 2*Vector.dot(startminusthispos,ray.dir);
	var c = Vector.dot(startminusthispos,startminusthispos) - this.radsquared;

	var discriminant = b*b-4*a*c;
	if (discriminant < 0) return [];
	if (discriminant == 0) return [new Intersection(-b/(2*a),ray,this)];

	var sqrtdiscriminant = Math.sqrt(discriminant);
	var oneovertwoa = 1/(2*a);

	return [new Intersection((-b-sqrtdiscriminant)*oneovertwoa,ray,this),new Intersection((sqrtdiscriminant-b)*oneovertwoa,ray,this)];
};
Sphere.prototype.isPointInsideUntransformed = function(pos) {
	var a = Vector.add(pos,this.negpos);
	return (a.lengthsquared() <= this.radsquared);
}
Sphere.prototype.getNormalAtUntransformed = function(pos)
{
	return Vector.add(pos,this.negpos);
}