RaytracerEngine/sphere.cs

48 lines
1.5 KiB
C#
Executable File

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RaytracerEngine
{
public class sphere : hitable
{
vec3 center;
float radius;
public sphere() { }
public sphere(vec3 cen, float r) { center = cen; radius = r; }
public override bool hit(ray r, float t_min, float t_max, out hit_record rec)
{
vec3 oc = r.origin - center;
float a = vec3.dot(r.direction, r.direction);
float b = vec3.dot(oc, r.direction);
float c = vec3.dot(oc, oc) - radius * radius;
float discriminant = b * b - a * c;
if (discriminant > 0)
{
float temp = (float)((-b - Math.Sqrt(discriminant)) / a);
if (temp < t_max && temp > t_min)
{
rec.t = temp;
rec.p = r.pap(rec.t);
rec.normal = (rec.p - center) / radius;
return true;
}
temp = (float)((-b + Math.Sqrt(discriminant)) / a);
if (temp < t_max && temp > t_min)
{
rec.t = temp;
rec.p = r.pap(rec.t);
rec.normal = (rec.p - center) / radius;
return true;
}
}
rec = new hit_record();
return false;
}
}
}