package geometry.scene;

import basics.math.algebra.Ray;
import renderer.mesh.Mesh;

import java.util.ArrayList;
import java.util.Optional;

public class LinearList implements AccelerationStructure {

    private ArrayList<Mesh> meshes = new ArrayList<>();

    @Override
    public Optional<Hit> intersect(Ray ray) {
        Mesh closestHit = null;
        double closetDistance = ray.getFar();

        for (Mesh mesh : this.meshes) {
            double distance = mesh.intersect(ray);

            if (distance > ray.getNear() && distance < closetDistance) {
                closetDistance = distance;
                closestHit = mesh;
            }
        }

        if (closestHit == null)
            return Optional.empty();

        return Optional.of(new Hit(closestHit, closetDistance));
    }

    @Override
    public void addMesh(Mesh mesh) {
        this.meshes.add(mesh);
    }

    @Override
    public void removeMesh(Mesh mesh) {
        this.meshes.remove(mesh);
    }
}
