Пример #1
0
    public override bool Hit(RTRay ray, float t_min, float t_max, out HitRecord rec)
    {
        rec = new HitRecord();

        Vector3 oc           = ray.origin - center;
        float   a            = Vector3.Dot(ray.direction, ray.direction);
        float   b            = 2.0f * Vector3.Dot(oc, ray.direction);
        float   c            = Vector3.Dot(oc, oc) - radius * radius;
        float   discriminant = b * b - 4 * a * c;

        if (discriminant < 0)
        {
            return(false);
        }
        else
        {
            float t = (-b - Mathf.Sqrt(discriminant)) / (2 * a);
            if (t < t_max && t > t_min)
            {
                rec.t        = t;
                rec.p        = ray.PointAt(t);
                rec.n        = (rec.p - center) / radius;
                rec.material = material;
                return(true);
            }
            t = (-b + Mathf.Sqrt(discriminant)) / (2 * a);
            if (t < t_max && t > t_min)
            {
                rec.t        = t;
                rec.p        = ray.PointAt(t);
                rec.n        = (rec.p - center) / radius;
                rec.material = material;
                return(true);
            }

            return(false);
        }
    }
    public override Color GetColor(RTRay ray, int depth)
    {
        Vector3 sphereCenter = new Vector3(0, 0, -1);
        float   sphereRadius = 0.5f;
        float   hit          = HitSphere(sphereCenter, sphereRadius, ray);

        if (hit >= 0)
        {
            Vector3 n = (ray.PointAt(hit) - sphereCenter).normalized;
            return(new Color((n.x + 1) * 0.5f, (n.y + 1) * 0.5f, (n.z + 1) * 0.5f));
        }

        return(GetBackgroundColor(ray));
    }