#include "StdAfx.h"
#include "PolylineContext.h"

#include "MeshBuf.h"

using namespace std;



namespace geom
{


void PolylineContext::CreateLengthInfo(const MeshBuf& meshbuf)
{
	const lib_geo::BaseMesh& m = meshbuf.m_Mesh;

	LenInfo.clear();
	LenInfo.resize(m.m_Polylines.size());

	for(size_t i = 0; i < m.m_Polylines.size(); ++i)
	{
		const lib_geo::BasePolyline& pl = m.m_Polylines[i];
		PolylineLenInfo& len_info = LenInfo[i];

		if(pl.m_VertIds.empty())
			continue;

		vector<lm::vec3f> points(pl.m_VertIds.size());
		for(size_t j = 0; j < pl.m_VertIds.size(); ++j)
		{
			int vid = pl.m_VertIds[j];
			points[j] = m.m_Verts[vid];
		}

		vector<float> seg_len(pl.m_VertIds.size() - 1);
		for(size_t j = 1; j < pl.m_VertIds.size(); ++j)
		{
			seg_len[j - 1] = (points[j - 1] - points[j]).length();
		}

		float total_len = 0.0f;
		for(size_t j = 0; j < seg_len.size(); ++j)
		{
			total_len += seg_len[j];
		}

		len_info.Length = total_len;

		float half_len = total_len * 0.5f;
		float past = 0.0;
		for(size_t j = 1; j < pl.m_VertIds.size(); ++j)
		{
			float next = past + seg_len[j - 1];
			if(next >= half_len)
			{
				float rest = next - half_len;
				float rest_n = rest / seg_len[j - 1];

				const lm::vec3f& v0 = points[j - 1];
				const lm::vec3f& v1 = points[j];

				len_info.TargetPos = v1 * rest_n + v0 * (1.0f - rest_n);
				break;
			}

			past = next;
		}
	}
}

bool PolylineContext::HasLengthInfo(void) const
{
	return !LenInfo.empty();
}


}
