
// sg - A scene graph representation.

// Copyright (C) 2005-2006 Editopia Inc.
// Released under the LGPL.
// For more information, see http://www.openlibraries.org.

// simple example to exercise Cg shaders in the draw action.

#include <GL/glew.h>

#ifdef HAVE_CONFIG_H
#include <openlibraries_global_config.hpp>
#endif

#include <openpluginlib/pl/openpluginlib.hpp>
#include <openpluginlib/pl/utf8_utils.hpp>

#include <openobjectlib/sg/openobjectlib_plugin.hpp>
#include <openobjectlib/sg/hw_GL_renderer.hpp>

#if defined ( WIN32 ) || defined ( HAVE_GL_GLUT_H )
#include <GL/glut.h>
#else
#include <GLUT/glut.h>
#endif

const int WIN_WIDTH		= 400;
const int WIN_HEIGHT	= 350;

using namespace std;

namespace opl = olib::openpluginlib;
namespace fs  = boost::filesystem;
namespace sg  = olib::openobjectlib::sg;

namespace
{
#ifdef WIN32
	const opl::string plugin_path( "./plugins" );
#else
	const opl::string plugin_path( OPENPLUGINS );
#endif

	sg::scene_ptr		scene;
	sg::hw_GL_renderer	r;

	struct query_traits
	{
		query_traits( const opl::wstring& filename )
			: filename_( filename )
		{ }
		
		opl::wstring libname( ) const
		{ return L"openobjectlib"; }
		
		opl::wstring to_match( ) const
		{ return filename_; }

		opl::wstring type( ) const
		{ return L""; }
		
		int merit( ) const
		{ return 0; }
		
		opl::wstring filename_;
	};
}

static sg::scene_ptr load_scene( const fs::path& path )
{
	typedef opl::discovery<query_traits> ool_discovery;
	
	ool_discovery plugins( query_traits( opl::to_wstring( path.native_file_string( ).c_str( ) ) ) );
	
	ool_discovery::const_iterator i = plugins.begin( );
	boost::shared_ptr<sg::openobjectlib_plugin> plug = boost::shared_static_cast<sg::openobjectlib_plugin>( i->create_plugin( "" ) );
	
	return plug->load( path );
}

static void display( void )
{
	r.render_scene( scene );

#ifndef NDEBUG
	GLenum error;
	while( ( error = glGetError( ) ) != GL_NO_ERROR )
		fprintf( stderr, "GLerror:%s\n", gluErrorString( error ) );
#endif // NDEBUG

	glutSwapBuffers( );
}

static void idle( void )
{
	scene->update( );

	glutPostRedisplay( );
}

static void reshape( int w, int h )
{
	scene->set_viewport_extents( 0, 0, w, h );
}

int main( int argc, char* argv[ ] )
{
	glutInit( &argc, argv );
	glutInitWindowSize( WIN_WIDTH, WIN_HEIGHT );
	glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGBA );
	glutCreateWindow( "OpenGL 3D Texture draw" );
	glutDisplayFunc( display );
	glutIdleFunc( idle );
	glutReshapeFunc( reshape );
	
	glewInit( );

	opl::init( plugin_path );

	scene = load_scene( "../../../../media/models/reflections_refractions.x3d" );
	scene->update( );
	
	glutMainLoop( );
}
