#include "StdAfx.h"
#include "CameraMeasure.h"

#include <C2/gl/OpenGLUT/OpenGlutStringExt.h>



void CameraMeasure::Render(void)
{
	if (m_Camera->m_ProjMode != gl::Camera::PROJ_ORTHO)
		return;

	float rect_dst = m_Camera->m_Manip.GetDistanceToLookPos();
	if (rect_dst <= 0.0f)
		return;

	float w, h;
	m_Camera->m_Projection.GetViewRangeOrtho(rect_dst, w, h);

	float world_scale = m_Scene->m_WorldTransform.GetScale();
	w /= world_scale;
	h /= world_scale;

	glPushAttrib(GL_ENABLE_BIT | GL_TRANSFORM_BIT);
	glDisable(GL_DEPTH_TEST);
	glDisable(GL_LIGHTING);
	
	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadIdentity();

	glMatrixMode(GL_MODELVIEW);
	glPushMatrix();
	glLoadIdentity();

	glColor3d(0, 1, 1);
	lm::vec2f a(1.0f, 0.0f);
	lm::vec2f b(0.0f, 1.0f);
	RenderCameraMeasureAxis(a, b, w);
	RenderCameraMeasureAxis(b, a, h);

	glMatrixMode(GL_MODELVIEW);
	glPopMatrix();

	glMatrixMode(GL_PROJECTION);
	glPopMatrix();

	glPopAttrib();
}

void CameraMeasure::RenderCameraMeasureAxis(const lm::vec2f& axis_a, const lm::vec2f& axis_b, float abs_len)
{
	lm::vec2f axis_ar = -axis_a;
	lm::vec2f p0 = axis_a * 0.9f;
	lm::vec2f p1 = axis_ar * 0.9f;
	lm::vec2f d = 0.05f * axis_b;
	lm::vec2f dl = 0.02f * axis_b;

	glBegin(GL_LINES);
	glVertex2fv(axis_a.v());
	glVertex2fv(axis_ar.v());
	glEnd();

	float gauge_pos = abs_len * 0.9f;
	float unit = float(gauge_pos);
	if (unit <= 0.0f)
		return;

	float ul = log10(unit);
	float un = floor(ul);
	unit = pow(10.0f, un) / 1.0f;

	float count_prd = gauge_pos / unit;
	if (count_prd <= 3.0f)
		unit /= 10.0f;

	glBegin(GL_LINES);
	float f = unit;
	while(f < gauge_pos)
	{
		lm::vec2f p = axis_a * f / abs_len;
		glVertex2fv((p - dl).v());
		glVertex2fv((p + dl).v());
		glVertex2fv((-p - dl).v());
		glVertex2fv((-p + dl).v());
		f += unit;
	}
	glEnd();

	glBegin(GL_LINES);
	glVertex2fv((p0 - d).v());
	glVertex2fv((p0 + d).v());
	glVertex2fv((p1 - d).v());
	glVertex2fv((p1 + d).v());
	glVertex2fv((p0 * 0.5f - d).v());
	glVertex2fv((p0 * 0.5f + d).v());
	glVertex2fv((p1 * 0.5f - d).v());
	glVertex2fv((p1 * 0.5f + d).v());
	glEnd();

	glutBitmapStringVal2f(-p0 + d, gauge_pos);
	glutBitmapStringVal2f(-p0 * 0.5f + d, gauge_pos * 0.5f);
}
