#include "StdAfx.h"
#include "SelRange.h"

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



SelRange::SelRange(void)
{
	m_IsOnSelect = false;
}

void SelRange::ReleaseSelect(void)
{
	m_IsOnSelect = false;
}


void SelRange::DrawRange(const lib_gl::Viewport& parent_vp)
{
	if(!m_IsOnSelect)
		return;

	glPushAttrib(GL_ENABLE_BIT|GL_TRANSFORM_BIT|GL_LINE_BIT);
	glDisable(GL_DEPTH_TEST);
	glEnable(GL_LINE_STIPPLE);
	glLineStipple(4, 0xaaaa);
	glLineWidth(1.0f);

	BeginDrawBillboard(parent_vp);

	double l = m_Pos0.x();
	double r = m_Pos1.x();
	double t = parent_vp.Height - m_Pos0.y();
	double b = parent_vp.Height - m_Pos1.y();

	glBegin(GL_LINE_LOOP);
	glVertex3d(l, b, 0);
	glVertex3d(r, b, 0);
	glVertex3d(r, t, 0);
	glVertex3d(l, t, 0);
	glEnd();

	EndDrawBillboard();

	glPopAttrib();
}

void SelRange::DrawCenterCross(const lib_gl::Viewport& parent_vp)
{
	if(!m_IsOnSelect)
		return;
	
	glPushAttrib(GL_ENABLE_BIT|GL_TRANSFORM_BIT|GL_POINT_BIT);
	glDisable(GL_DEPTH_TEST);
	glPointSize(3.0f);

	BeginDrawBillboard(parent_vp);

	double l = m_Pos0.x();
	double r = m_Pos1.x();
	double t = parent_vp.Height - m_Pos0.y();
	double b = parent_vp.Height - m_Pos1.y();

	double cx = (l + r) * 0.5;
	double cy = (t + b) * 0.5;

	glBegin(GL_POINTS);
	glVertex3d(cx, cy, 0);
	glEnd();

	EndDrawBillboard();

	glPopAttrib();
}

void SelRange::DrawTitle(const lib_gl::Viewport& parent_vp, const char* title)
{
	if(!m_IsOnSelect)
		return;

	glPushAttrib(GL_ENABLE_BIT|GL_TRANSFORM_BIT);
	glDisable(GL_DEPTH_TEST);

	BeginDrawBillboard(parent_vp);
	
	double l = m_Pos0.x();
	double r = m_Pos1.x();
	double t = parent_vp.Height - m_Pos0.y();
	double b = parent_vp.Height - m_Pos1.y();
	double x = (std::min)(l, r);
	double y = (std::max)(t, b);

	glutBitmapStringVal3f(lm::vec3f(x, y, 0.0), title);

	EndDrawBillboard();

	glPopAttrib();
}

void SelRange::BeginDrawBillboard(const lib_gl::Viewport& parent_vp)
{
	glMatrixMode(GL_PROJECTION);
	glPushMatrix();
	glLoadIdentity();

	gluOrtho2D(parent_vp.Left, parent_vp.GetRight(), parent_vp.Bottom, parent_vp.GetTop());

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

}

void SelRange::EndDrawBillboard(void)
{
	glPopMatrix();
	glMatrixMode(GL_PROJECTION);
	glPopMatrix();
}

void SelRange::SetFirst(const QPoint& p)
{
	m_Pos0 = p;
	m_Pos1 = p;

	m_IsOnSelect = true;
}

void SelRange::SetSecond(const QPoint& p)
{
	m_Pos1 = p;
}

QPoint SelRange::GetCenter(void) const
{
	int x = (m_Pos0.x() + m_Pos1.x()) / 2;
	int y = (m_Pos0.y() + m_Pos1.y()) / 2;
	return QPoint(x, y);
}

int SelRange::GetWidth(void) const
{
	return abs(m_Pos0.x() - m_Pos1.x());
}

int SelRange::GetHeight(void) const
{
	return abs(m_Pos0.y() - m_Pos1.y());
}
