package renderer.primitive;

import basics.math.algebra.Ray;
import basics.math.algebra.Vector;

public class Sphere implements Primitive {

    private Vector center;
    private double radius;

    public Sphere(Vector center, double radius) {
        this.center = center;
        this.radius = radius;
    }

    @Override
    public double intersect(Ray ray) {
        Vector oc = ray.getOrigin().sub(this.center);

        double b = ray.getDirection().scale(2).dot(oc);
        double c = oc.dot(oc) - this.radius * this.radius;
        double h = b * b - 4.0 * c;

        if (h < 0.0)
            return -1.0;

        h = Math.sqrt(h);

        double u = -b - h;
        double v = -b + h;

        return (u > ray.getNear() ? u : u > ray.getNear() ? v : 0) * 0.5;
    }

    @Override
    public Vector normalAt(Vector surfacePoint, Vector incoming) {
        return surfacePoint.sub(center).normalize();
    }
}
