/********************************************************************/
/* Copyright (c) 2019 System fugen G.K. and Yuzi Mizuno          */
/* All rights reserved.                                             */
/********************************************************************/
// GLTessPView.cpp : インプリメンテーション ファイル

#include "stdafx.h"
#include "mgGL/VBO.h"
#include "TL2/TL2Parameter.h"
#include "TL2/TL2Face.h"
#include "fugen.h"
#include "topo/Shell.h"
#include "GLTessWView.h"
#include "GLTessPView.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif

/////////////////////////////////////////////////////////////////////////////
// CGLTessPView

IMPLEMENT_DYNCREATE(CGLTessPView, fugenView2D)

CGLTessPView::CGLTessPView():fugenView2D(3,'u','v'),m_f(0){;}
CGLTessPView::~CGLTessPView(){;}


BEGIN_MESSAGE_MAP(CGLTessPView, fugenView2D)
	//{{AFX_MSG_MAP(CGLTessPView)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CGLTessPView メッセージ ハンドラ

///Initialize model.
void CGLTessPView::initializeModel(){
	if(!m_f)
		return;
	m_param_box=m_f->param_range();
	cplane().setGridDataByBox(m_param_box,2,getUserPrefGridColor());
	initializeViewingEnvironmentByBox(m_param_box);
	set_display_list(&m_vbo);//glv->set_display_list(name);	
}

//Make openGL display list in the input glview.
void CGLTessPView::makeDisplayList(){
	if(!m_f)
		return;

	fugenDoc* pDoc = GetDocument();
	ASSERT_VALID(pDoc);

	const MGObject* obj=m_f->object_pointer();
	const mgTLInputParam& tlparam = pDoc->context()->tessellate_param();

	double cerr=tlparam.crvTol();
	double serr=tlparam.surfTol();
	double elen=tlparam.max_edge_len();
	mgTL2Face face(*m_f,cerr,serr,elen);
	mgTL2Triangles tris(MGCL::UV,m_f->get_surface_pointer());
	face.tessellate(tris);
	m_vbo.LineWidth(1.f);// glLineWidth(1.f);
	m_vbo.drawShade(tris, MGCL::WIRE,GL_LINE);
	m_vbo.setDirty(false);
}

void CGLTessPView::OnInitialUpdate(){
	CWaitCursor wait;
	fugenDoc& doc=document();

	// Set Window's title.
	CString strTitle;
	strTitle.Format(
		IDS_FORMAT_VIEW_TITLE_TESSP,
		doc.GetTitle()
		);
	GetParent()->SetWindowText(strTitle);

	MGPickObjects picked(current_objects());

	m_f=picked.get_object_to_tessellate();

/////////Generate OpenGL display list.//////////////////////
	InitOpenGL();
	const MGContext* ct = doc.context();
	importDrawAttribFromContext(*ct);

	setEyePositionUpVector(MGVector(0.,0.,1.),MGVector(0.,1.,0.));
	set_perspective(false);
	initializeModel();

	makeDisplayList();
	cplane().set_disable();
}

void CGLTessPView::OnUpdate(CView* pSender, LPARAM lHint, CObject* pHint){
	ASSERT(pSender != this);
	fugenView2D::OnUpdate(pSender, lHint, pHint);
}

void CGLTessPView::redrawOnlythis(){
	make_RC_current();
	setViewMode(MGCL::WIREVIEW);
	updateAxisPictures();
	drawScene();
	release_dc();
}
