#include "3dmath.h"

const Matrix	Matrix::Unit = Matrix();

using namespace std;

void Vector4::PlaneClipPolygonHomogeneous(vector<Vector4> &out_polygon, const vector<Vector4> &in_polygon) const
{
	if (in_polygon.empty())
		return;
		
	Vector4 S = in_polygon.back();
	bool is_S_in = (Dot(S) > 0.0f);
	for (auto &E : in_polygon)
	{
		bool is_E_in = (Dot(E) > 0.0f);

		if (is_E_in != is_S_in)
			out_polygon.push_back(PlaneLineIntersectionHomogeneous(S, E));
		if (is_E_in)
			out_polygon.push_back(E);
			
		S = E;
		is_S_in = is_E_in;
	}
}

void Vector4::PlaneClipPolygonHomogeneous(vector<Vector4> &polygon, vector<Vector4> &tmp_array, const vector<Vector4> &planes)
{
	if (polygon.empty())
		return;

	for (auto &plane : planes)
	{
		assert(!polygon.empty());		// Initial polygon is not empty, and after each plane there is a test whether the polygon is fully clipped
		tmp_array = polygon;
		polygon.clear();

		plane.PlaneClipPolygonHomogeneous(polygon, tmp_array);
				
		if (polygon.empty())
			break;		// The polygon is fully out
	}
}
