/*-
 *  Copyright 2020 Beuth Hochschule für Technik Berlin, Hochschule für Technik Stuttgart
 * 
 *  This file is part of CityDoctor2.
 *
 *  CityDoctor2 is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Lesser General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  CityDoctor2 is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public License
 *  along with CityDoctor2.  If not, see <https://www.gnu.org/licenses/>.
 */
package de.hft.stuttgart.citydoctor2.math;

/**
 * A line described by a point and a direction
 * 
 * @author Matthias Betz
 *
 */
public class Line3d {

	public static final double EPSILON = 0.00001;

	private Vector3d point;
	private Vector3d direction;

	public Line3d(Vector3d point, Vector3d direction) {
		super();
		this.point = point;
		this.direction = direction;
	}

	/**
	 * @return the point
	 */
	public Vector3d getPoint() {
		return point;
	}

	/**
	 * @return the direction
	 */
	public Vector3d getDirection() {
		return direction;
	}

	public double distanceToPoint(Vector3d v) {
		double x = v.getX() - point.getX();
		double y = v.getY() - point.getY();
		double z = v.getZ() - point.getZ();
		Vector3d temp = new Vector3d(x, y, z);
		return direction.cross(temp).getLength();
	}

	public Vector3d intersection(Triangle3d triangle) {
		Vector3d v0 = triangle.getP1();
		Vector3d v1 = triangle.getP2();
		Vector3d v2 = triangle.getP3();
		Vector3d edge1 = v1.minus(v0);
		Vector3d edge2 = v2.minus(v0);

		Vector3d p = direction.cross(edge2);
		double det = edge1.dot(p);

		if (det > -EPSILON && det < EPSILON) {
			return null;
		}

		double invDet = 1 / det;

		Vector3d s = point.minus(v0);

		double u = invDet * s.dot(p);
		if (u < 0.0 || u > 1.0) {
			return null;
		}

		Vector3d q = s.cross(edge1);

		double v = invDet * direction.dot(q);

		if (v < 0.0 || u + v > 1.0) {
			return null;
		}

		double t = edge2.dot(q) * invDet;
		return getPointOnLine(t);
	}

	private Vector3d getPointOnLine(double distanceFromOrigin) {
		return point.plus(direction.mult(distanceFromOrigin));
	}

}
