GLSLShader.cpp 26.7 KB
Newer Older
Pierre Kraemer's avatar
Pierre Kraemer committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
/*******************************************************************************
* CGoGN: Combinatorial and Geometric modeling with Generic N-dimensional Maps  *
* version 0.1                                                                  *
* Copyright (C) 2009, IGG Team, LSIIT, University of Strasbourg                *
*                                                                              *
* This library is free software; you can redistribute it and/or modify it      *
* under the terms of the GNU Lesser General Public License as published by the *
* Free Software Foundation; either version 2.1 of the License, or (at your     *
* option) any later version.                                                   *
*                                                                              *
* This library is distributed in the hope that it will be useful, but WITHOUT  *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or        *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License  *
* for more details.                                                            *
*                                                                              *
* You should have received a copy of the GNU Lesser General Public License     *
* along with this library; if not, write to the Free Software Foundation,      *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.           *
*                                                                              *
* Web site: https://iggservis.u-strasbg.fr/CGoGN/                              *
* Contact information: cgogn@unistra.fr                                        *
*                                                                              *
*******************************************************************************/
#define EXPORTING 1

#include "Utils/GLSLShader.h"
#include <iostream>
#include <fstream>
29
#include <vector>
Pierre Kraemer's avatar
Pierre Kraemer committed
30

Sylvain Thery's avatar
Sylvain Thery committed
31 32
#include "glm/gtx/inverse_transpose.hpp"

Pierre Kraemer's avatar
Pierre Kraemer committed
33 34 35 36 37 38

namespace CGoGN
{

namespace Utils
{
39
unsigned int GLSLShader::CURRENT_OGL_VERSION=2;
Sylvain Thery's avatar
Sylvain Thery committed
40 41 42

std::string GLSLShader::DEFINES_GL2=\
"#version 110\n"
43
"#define PRECISON\n"
Sylvain Thery's avatar
Sylvain Thery committed
44 45 46 47 48 49
"#define ATTRIBUTE attribute\n"
"#define VARYING_VERT varying\n"
"#define VARYING_FRAG varying\n"
"#define FRAG_OUT_DEF \n"
"#define INVARIANT_POS \n";

Pierre Kraemer's avatar
Pierre Kraemer committed
50

Sylvain Thery's avatar
Sylvain Thery committed
51
std::string GLSLShader::DEFINES_GL3=\
52
"#version 150\n"
Sylvain Thery's avatar
Sylvain Thery committed
53 54 55 56 57 58 59 60
"#define PRECISON precision highp float;\n"
"#define ATTRIBUTE in\n"
"#define VARYING_VERT smooth out\n"
"#define VARYING_FRAG smooth in\n"
"#define FRAG_OUT_DEF out vec4 gl_FragColor\n"
"#define INVARIANT_POS \n";

std::string* GLSLShader::DEFINES_GL =NULL;
61 62 63

std::vector<std::string> GLSLShader::m_pathes;

64 65
std::set< std::pair<void*, GLSLShader*> > GLSLShader::m_registredRunning;

Sylvain Thery's avatar
Sylvain Thery committed
66 67 68 69
GLSLShader::GLSLShader():
			m_vertex_shader_object(0),
			m_fragment_shader_object(0),
			m_geom_shader_object(0),
70 71 72 73 74 75 76 77
			m_program_object(0),
			m_uniMat_Proj(-1),
			m_uniMat_Model(-1),
			m_uniMat_ModelProj(-1),
			m_uniMat_Normal(-1),
			m_vertex_shader_source(NULL),
			m_fragment_shader_source(NULL),
			m_geom_shader_source(NULL)
Pierre Kraemer's avatar
Pierre Kraemer committed
78
{
Sylvain Thery's avatar
Sylvain Thery committed
79 80
	if (DEFINES_GL==NULL)
		DEFINES_GL = &DEFINES_GL3;
Pierre Kraemer's avatar
Pierre Kraemer committed
81 82 83
}


84 85
void GLSLShader::registerRunning(GLSLShader* ptr)
{
Sylvain Thery's avatar
Sylvain Thery committed
86
	m_registredRunning.insert(std::pair<void*,GLSLShader*>(reinterpret_cast<void*>(NULL),ptr));
87 88 89 90
}

void GLSLShader::unregisterRunning(GLSLShader* ptr)
{
Sylvain Thery's avatar
Sylvain Thery committed
91
	m_registredRunning.erase(std::pair<void*,GLSLShader*>(reinterpret_cast<void*>(NULL),ptr));
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130
}


std::string GLSLShader::defines_Geom(const std::string& primitivesIn, const std::string& primitivesOut, int maxVert)
{
	if (CURRENT_OGL_VERSION==3)
	{
		std::string str("#version 150\n");
		str.append("precision highp float;\n");
		str.append("layout (");
		str.append(primitivesIn);
		str.append(") in;\n");

		str.append("layout (");
		str.append(primitivesOut);
		str.append(", max_vertices = ");
		std::stringstream ss;
		ss << maxVert;
		str.append(ss.str());
		str.append(") out;\n");
		str.append("#define VARYING_IN in\n");
		str.append("#define VARYING_OUT smooth out\n");
		str.append("#define POSITION_IN(X) gl_in[X].gl_Position\n");
		return str;
	}
	else
	{
		std::string str("#extension GL_EXT_geometry_shader4 : enable\n");
		str.append("#define PRECISION\n");
		str.append("#define ATTRIBUTE attribute\n");
		str.append("#define VARYING_IN varying in\n");
		str.append("#define VARYING_OUT varying out\n");
		str.append("#define POSITION_IN(X) gl_PositionIn[X]\n");
		return str;
	}
}



Pierre Kraemer's avatar
Pierre Kraemer committed
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
bool GLSLShader::areGeometryShadersSupported()
{
	if ( ! glewGetExtension("GL_EXT_geometry_shader4")) return false;
	return true;
}

bool GLSLShader::areShadersSupported()
{
	if ( ! glewGetExtension("GL_ARB_vertex_shader")) return false;
	if ( ! glewGetExtension("GL_ARB_fragment_shader")) return false;
	if ( ! glewGetExtension("GL_ARB_shader_objects")) return false;
	if ( ! glewGetExtension("GL_ARB_shading_language_100")) return false;

	return true;
}


bool GLSLShader::areVBOSupported()
{
	if (!glewGetExtension("GL_ARB_vertex_buffer_object"))
		return false;
	return true;
}



char* GLSLShader::loadSourceFile(  const std::string& filename)
{
	std::ifstream	file;
	int				file_size;
	char*			shader_source;


	/*** opening file ***/
	file.open( filename.c_str() , std::ios::in | std::ios::binary );

	if( !file.good() )
	{
		std::cerr << "ERROR - GLSLShader::loadSourceFile() - unable to open the file " << filename << "." << std::endl;
		return NULL;
	}


	/*** reading file ***/
	try
	{
		/* get file size */
		file.seekg( 0, std::ios::end );
		file_size = file.tellg();
		file.seekg( 0, std::ios::beg );

		/* allocate shader source table */
		shader_source = new char [ file_size+1 ];

		/* read source file */
		file.read( shader_source, file_size );
		shader_source[ file_size ] = '\0';
	}
	catch( std::exception& io_exception )
	{
		std::cerr << "ERROR - GLSLShader::loadSourceFile() - " << io_exception.what() << std::endl;
		file.close();
		return NULL;
	}


	/*** termination ***/
	file.close();
	return shader_source;
}


bool GLSLShader::loadVertexShader(  const std::string& filename )
{
	bool	flag;
206
//	char	*vertex_shader_source;
Pierre Kraemer's avatar
Pierre Kraemer committed
207

208 209
	if (m_vertex_shader_source)
		delete [] m_vertex_shader_source;
Pierre Kraemer's avatar
Pierre Kraemer committed
210

211
	m_vertex_shader_source = loadSourceFile( filename );
Pierre Kraemer's avatar
Pierre Kraemer committed
212

213
	if( !m_vertex_shader_source )
Pierre Kraemer's avatar
Pierre Kraemer committed
214 215 216 217 218 219
	{
		std::cerr << "ERROR - GLSLShader::loadVertexShader() - error occured while loading source file." << std::endl;
		return false;
	}


220 221
	flag = loadVertexShaderSourceString( m_vertex_shader_source );
//	delete [] vertex_shader_source;
Pierre Kraemer's avatar
Pierre Kraemer committed
222 223 224 225 226

	return flag;
}


227
bool GLSLShader::loadFragmentShader(const std::string& filename )
Pierre Kraemer's avatar
Pierre Kraemer committed
228 229
{
	bool	flag;
230
//	char	*fragment_shader_source;
Pierre Kraemer's avatar
Pierre Kraemer committed
231

232 233
	if (m_fragment_shader_source)
		delete [] m_fragment_shader_source;
Pierre Kraemer's avatar
Pierre Kraemer committed
234

235
	m_fragment_shader_source = loadSourceFile( filename );
Pierre Kraemer's avatar
Pierre Kraemer committed
236

237
	if( !m_fragment_shader_source )
Pierre Kraemer's avatar
Pierre Kraemer committed
238
	{
239
		std::cerr << "ERROR - GLSLShader::loadFragmentShader() - error occured while loading source file." << std::endl;
Pierre Kraemer's avatar
Pierre Kraemer committed
240 241 242 243
		return false;
	}


244 245
	flag = loadFragmentShaderSourceString( m_fragment_shader_source );
//	delete [] fragment_shader_source;
Pierre Kraemer's avatar
Pierre Kraemer committed
246 247 248 249 250 251 252 253 254


	return flag;
}


bool GLSLShader::loadGeometryShader(const std::string& filename )
{
	bool	flag;
255
//	char	*geom_shader_source;
Pierre Kraemer's avatar
Pierre Kraemer committed
256 257


258 259
	if (m_geom_shader_source)
		delete [] m_geom_shader_source;
Pierre Kraemer's avatar
Pierre Kraemer committed
260

261
	m_geom_shader_source = loadSourceFile( filename );
Pierre Kraemer's avatar
Pierre Kraemer committed
262

263 264 265


	if( !m_geom_shader_source )
Pierre Kraemer's avatar
Pierre Kraemer committed
266 267 268 269 270
	{
		std::cerr << "ERROR - GLSLShader::loadGeometryShader() - error occured while loading source file." << std::endl;
		return false;
	}

271 272
	flag = loadGeometryShaderSourceString( m_geom_shader_source );
//	delete [] geom_shader_source;
Pierre Kraemer's avatar
Pierre Kraemer committed
273 274 275 276 277 278 279 280 281 282 283


	return flag;
}


bool GLSLShader::loadVertexShaderSourceString( const char *vertex_shader_source )
{
	int		status;
	char	*info_log;

Sylvain Thery's avatar
Sylvain Thery committed
284 285 286 287 288
	if (m_vertex_shader_object==0)
	{
		glDeleteShader(m_vertex_shader_object);
		m_vertex_shader_object=0;
	}
Pierre Kraemer's avatar
Pierre Kraemer committed
289 290

	/*** create shader object ***/
Sylvain Thery's avatar
Sylvain Thery committed
291
	m_vertex_shader_object = glCreateShader( GL_VERTEX_SHADER );
Pierre Kraemer's avatar
Pierre Kraemer committed
292

293
	if( !m_vertex_shader_object )
Pierre Kraemer's avatar
Pierre Kraemer committed
294 295 296 297 298 299 300 301 302 303 304
	{
		std::cerr << "ERROR - GLSLShader::loadVertexShader() - unable to create shader object." << std::endl;
		return false;
	}


	/*** load source file ***/
	if( !vertex_shader_source )
	{
		std::cerr << "ERROR - GLSLShader::loadVertexShader() - source string is empty." << std::endl;

305 306
		glDeleteObjectARB( m_vertex_shader_object );
		m_vertex_shader_object = 0;
Pierre Kraemer's avatar
Pierre Kraemer committed
307 308 309 310

		return false;
	}

311
	glShaderSourceARB( m_vertex_shader_object, 1, (const char**)&vertex_shader_source, NULL );
Pierre Kraemer's avatar
Pierre Kraemer committed
312 313 314


	/*** compile shader object ***/
315
	glCompileShaderARB( m_vertex_shader_object );
Pierre Kraemer's avatar
Pierre Kraemer committed
316

317
	glGetObjectParameterivARB( m_vertex_shader_object, GL_OBJECT_COMPILE_STATUS_ARB, &status );
Pierre Kraemer's avatar
Pierre Kraemer committed
318 319 320
	if( !status )
	{
		std::cerr << "ERROR - GLshader::loadVertexShader() - error occured while compiling shader." << std::endl;
321
		info_log = getInfoLog( m_vertex_shader_object );
Sylvain Thery's avatar
Sylvain Thery committed
322 323
		std::cerr << "  COMPILATION OF "<< m_nameVS<< std::endl;
		std::cerr << info_log << std::endl;
Pierre Kraemer's avatar
Pierre Kraemer committed
324 325
		delete [] info_log;

326 327
		glDeleteObjectARB( m_vertex_shader_object );
		m_vertex_shader_object = 0;
Pierre Kraemer's avatar
Pierre Kraemer committed
328 329 330 331 332 333 334 335 336 337

		return false;
	}


	/*** termination ***/
	return true;
}


338
bool GLSLShader::loadFragmentShaderSourceString( const char *fragment_shader_source )
Pierre Kraemer's avatar
Pierre Kraemer committed
339 340 341 342
{
	int		status;
	char	*info_log;

Sylvain Thery's avatar
Sylvain Thery committed
343 344 345 346 347
	if (m_fragment_shader_object==0)
	{
		glDeleteShader(m_fragment_shader_object);
		m_fragment_shader_object=0;
	}
Pierre Kraemer's avatar
Pierre Kraemer committed
348 349

	/*** create shader object ***/
Sylvain Thery's avatar
Sylvain Thery committed
350
	m_fragment_shader_object = glCreateShader( GL_FRAGMENT_SHADER );
Pierre Kraemer's avatar
Pierre Kraemer committed
351

352
	if( !m_fragment_shader_object )
Pierre Kraemer's avatar
Pierre Kraemer committed
353
	{
354
		std::cerr << "ERROR - GLSLShader::loadFragmentShader() - unable to create shader object." << std::endl;
Pierre Kraemer's avatar
Pierre Kraemer committed
355 356 357 358 359
		return false;
	}


	/*** load source file ***/
360
	if( !fragment_shader_source )
Pierre Kraemer's avatar
Pierre Kraemer committed
361
	{
362
		std::cerr << "ERROR - GLSLShader::loadFragmentShader() - source string is empty." << std::endl;
Pierre Kraemer's avatar
Pierre Kraemer committed
363

364 365
		glDeleteObjectARB( m_fragment_shader_object );
		m_fragment_shader_object = 0;
Pierre Kraemer's avatar
Pierre Kraemer committed
366 367 368 369

		return false;
	}

370
	glShaderSourceARB( m_fragment_shader_object, 1, (const char**)&fragment_shader_source, NULL );
Pierre Kraemer's avatar
Pierre Kraemer committed
371 372 373


	/*** compile shader object ***/
374
	glCompileShaderARB( m_fragment_shader_object );
Pierre Kraemer's avatar
Pierre Kraemer committed
375

376
	glGetObjectParameterivARB( m_fragment_shader_object, GL_OBJECT_COMPILE_STATUS_ARB, &status );
Pierre Kraemer's avatar
Pierre Kraemer committed
377 378
	if( !status )
	{
379 380
		std::cerr << "ERROR - GLshader::loadFragmentShader() - error occured while compiling shader." << std::endl;
		info_log = getInfoLog( m_fragment_shader_object );
Sylvain Thery's avatar
Sylvain Thery committed
381
		std::cerr << "  COMPILATION OF "<< m_nameFS<< std::endl << info_log << std::endl;
Pierre Kraemer's avatar
Pierre Kraemer committed
382 383
		delete [] info_log;

384 385
		glDeleteObjectARB( m_fragment_shader_object );
		m_fragment_shader_object = 0;
Pierre Kraemer's avatar
Pierre Kraemer committed
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401

		return false;
	}


	/*** termination ***/
	return true;
}



bool GLSLShader::loadGeometryShaderSourceString( const char *geom_shader_source )
{
	int		status;
	char	*info_log;

Sylvain Thery's avatar
Sylvain Thery committed
402 403 404 405 406
	if (m_geom_shader_object==0)
	{
		glDeleteShader(m_geom_shader_object);
		m_geom_shader_object=0;
	}
Pierre Kraemer's avatar
Pierre Kraemer committed
407
	/*** create shader object ***/
408
	m_geom_shader_object = glCreateShader(GL_GEOMETRY_SHADER_EXT);
Pierre Kraemer's avatar
Pierre Kraemer committed
409 410


411
	if( !m_geom_shader_object )
Pierre Kraemer's avatar
Pierre Kraemer committed
412 413 414 415 416 417 418 419 420 421 422
	{
		std::cerr << "ERROR - GLSLShader::loadGeometryShader() - unable to create shader object." << std::endl;
		return false;
	}


	/*** load source file ***/
	if( !geom_shader_source )
	{
		std::cerr << "ERROR - GLSLShader::loadGeometryShader() - source string is empty." << std::endl;

423 424
		glDeleteObjectARB( m_geom_shader_object );
		m_geom_shader_object = 0;
Pierre Kraemer's avatar
Pierre Kraemer committed
425 426 427 428

		return false;
	}

429
	glShaderSourceARB( m_geom_shader_object, 1, (const char**)&geom_shader_source, NULL );
Pierre Kraemer's avatar
Pierre Kraemer committed
430 431 432


	/*** compile shader object ***/
433
	glCompileShaderARB( m_geom_shader_object );
Pierre Kraemer's avatar
Pierre Kraemer committed
434

435
	glGetObjectParameterivARB( m_geom_shader_object, GL_OBJECT_COMPILE_STATUS_ARB, &status );
Pierre Kraemer's avatar
Pierre Kraemer committed
436 437 438
	if( !status )
	{
		std::cerr << "ERROR - GLshader::loadGeometryShader() - error occured while compiling shader." << std::endl;
439
		info_log = getInfoLog( m_geom_shader_object );
Sylvain Thery's avatar
Sylvain Thery committed
440 441
		std::cerr << "  COMPILATION OF "<< m_nameGS<< std::endl;
		std::cerr << info_log << std::endl;
Pierre Kraemer's avatar
Pierre Kraemer committed
442 443
		delete [] info_log;

444 445
		glDeleteObjectARB( m_geom_shader_object );
		m_geom_shader_object = 0;
Pierre Kraemer's avatar
Pierre Kraemer committed
446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477

		return false;
	}


	/*** termination ***/
	return true;
}


char* GLSLShader::getInfoLog( GLhandleARB obj )
{
	char	*info_log;
	int		info_log_length;
	int		length;


	glGetObjectParameterivARB( obj, GL_OBJECT_INFO_LOG_LENGTH_ARB, &info_log_length );

	info_log = new char [info_log_length];
	glGetInfoLogARB( obj, info_log_length, &length, info_log );


	return info_log;
}


bool GLSLShader::create(GLint inputGeometryPrimitive,GLint outputGeometryPrimitive)
{
	int		status;
	char	*info_log;

478 479
	m_geom_inputPrimitives = inputGeometryPrimitive;
	m_geom_outputPrimitives = outputGeometryPrimitive;
Pierre Kraemer's avatar
Pierre Kraemer committed
480 481

	/*** check if shaders are loaded ***/
482
	if( !m_vertex_shader_object || !m_fragment_shader_object )
Pierre Kraemer's avatar
Pierre Kraemer committed
483
	{
484
		std::cerr << "ERROR - GLSLShader::create() - shaders are not defined." << std::endl;
Pierre Kraemer's avatar
Pierre Kraemer committed
485 486 487 488 489
		return false;
	}


	/*** create program object ***/
490
	m_program_object = glCreateProgramObjectARB();
Pierre Kraemer's avatar
Pierre Kraemer committed
491

492
	if( !m_program_object )
Pierre Kraemer's avatar
Pierre Kraemer committed
493 494 495 496 497 498 499
	{
		std::cerr << "ERROR - GLSLShader::create() - unable to create program object." << std::endl;
		return false;
	}


	/*** attach shaders to program object ***/
500 501 502
	glAttachObjectARB( m_program_object, m_vertex_shader_object );
	glAttachObjectARB( m_program_object, m_fragment_shader_object );
	if (m_geom_shader_object)
Pierre Kraemer's avatar
Pierre Kraemer committed
503
	{
504
		glAttachObjectARB( m_program_object, m_geom_shader_object );
Pierre Kraemer's avatar
Pierre Kraemer committed
505

506 507
		glProgramParameteriEXT(m_program_object,GL_GEOMETRY_INPUT_TYPE_EXT,inputGeometryPrimitive);
		glProgramParameteriEXT(m_program_object,GL_GEOMETRY_OUTPUT_TYPE_EXT,outputGeometryPrimitive);
Pierre Kraemer's avatar
Pierre Kraemer committed
508 509
		int temp;
		glGetIntegerv(GL_MAX_GEOMETRY_OUTPUT_VERTICES_EXT,&temp);
510
		glProgramParameteriEXT(m_program_object,GL_GEOMETRY_VERTICES_OUT_EXT,temp);
Pierre Kraemer's avatar
Pierre Kraemer committed
511 512 513 514
	}


	/*** link program object ***/
515
	glLinkProgramARB( m_program_object );
Pierre Kraemer's avatar
Pierre Kraemer committed
516

517
	glGetObjectParameterivARB( m_program_object, GL_OBJECT_LINK_STATUS_ARB, &status );
Pierre Kraemer's avatar
Pierre Kraemer committed
518 519 520
	if( !status )
	{
		std::cerr << "ERROR - GLSLShader::create() - error occured while linking shader program." << std::endl;
521
		info_log = getInfoLog( m_program_object );
Pierre Kraemer's avatar
Pierre Kraemer committed
522 523 524
		std::cerr << "  LINK " << info_log << std::endl;
		delete [] info_log;

525 526 527 528 529 530
		glDetachObjectARB( m_program_object, m_vertex_shader_object );
		glDetachObjectARB( m_program_object, m_fragment_shader_object );
		if (m_geom_shader_object)
			glDetachObjectARB( m_program_object, m_geom_shader_object );
		glDeleteObjectARB( m_program_object );
		m_program_object = 0;
Pierre Kraemer's avatar
Pierre Kraemer committed
531 532 533 534

		return false;
	}

535 536 537 538 539
	m_uniMat_Proj		= glGetUniformLocation(m_program_object,"ProjectionMatrix");
	m_uniMat_Model		= glGetUniformLocation(m_program_object,"ModelViewMatrix");
	m_uniMat_ModelProj	= glGetUniformLocation(m_program_object,"ModelViewProjectionMatrix");
	m_uniMat_Normal		= glGetUniformLocation(m_program_object,"NormalMatrix");

Pierre Kraemer's avatar
Pierre Kraemer committed
540 541 542 543
	return true;
}


544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576
bool GLSLShader::link()
{
	int		status;
	char	*info_log;


	/*** link program object ***/
	glLinkProgramARB( m_program_object );

	glGetObjectParameterivARB( m_program_object, GL_OBJECT_LINK_STATUS_ARB, &status );
	if( !status )
	{
		std::cerr << "ERROR - GLSLShader::create() - error occured while linking shader program." << std::endl;
		info_log = getInfoLog( m_program_object );
		std::cerr << "  LINK " << info_log << std::endl;
		delete [] info_log;

		glDetachObjectARB( m_program_object, m_vertex_shader_object );
		glDetachObjectARB( m_program_object, m_fragment_shader_object );
		if (m_geom_shader_object)
			glDetachObjectARB( m_program_object, m_geom_shader_object );
		glDeleteObjectARB( m_program_object );
		m_program_object = 0;

		return false;
	}

	return true;
}




577
bool GLSLShader::bind() const
Pierre Kraemer's avatar
Pierre Kraemer committed
578
{
579
	if( m_program_object )
Pierre Kraemer's avatar
Pierre Kraemer committed
580
	{
581
		glUseProgramObjectARB( m_program_object );
Pierre Kraemer's avatar
Pierre Kraemer committed
582 583 584 585 586 587 588

		return true;
	}
	else  return false;
}


589
void GLSLShader::unbind() const
Pierre Kraemer's avatar
Pierre Kraemer committed
590
{
591
	if( m_program_object )
Pierre Kraemer's avatar
Pierre Kraemer committed
592 593 594 595 596 597 598 599
	{
		glUseProgramObjectARB( 0 );
	}
}


bool GLSLShader::isBinded()
{
600
	return ( m_program_object && m_program_object == glGetHandleARB(GL_PROGRAM_OBJECT_ARB) );
Pierre Kraemer's avatar
Pierre Kraemer committed
601 602 603 604 605
}


GLSLShader::~GLSLShader()
{
606
	if( m_program_object )
Pierre Kraemer's avatar
Pierre Kraemer committed
607 608 609
	{
		unbind();

610
		if( m_vertex_shader_object )
Pierre Kraemer's avatar
Pierre Kraemer committed
611
		{
612 613
			glDetachObjectARB( m_program_object, m_vertex_shader_object );
			glDeleteObjectARB( m_vertex_shader_object );
Pierre Kraemer's avatar
Pierre Kraemer committed
614
		}
615
		if( m_fragment_shader_object )
Pierre Kraemer's avatar
Pierre Kraemer committed
616
		{
617 618
			glDetachObjectARB( m_program_object, m_fragment_shader_object );
			glDeleteObjectARB( m_fragment_shader_object );
Pierre Kraemer's avatar
Pierre Kraemer committed
619
		}
620
		if (m_geom_shader_object)
Pierre Kraemer's avatar
Pierre Kraemer committed
621
		{
622 623
			glDetachObjectARB( m_program_object, m_geom_shader_object );
			glDeleteObjectARB( m_geom_shader_object );
Pierre Kraemer's avatar
Pierre Kraemer committed
624 625
		}

626
		glDeleteObjectARB( m_program_object );
Pierre Kraemer's avatar
Pierre Kraemer committed
627
	}
628 629

//	m_registredRunning.erase(this);
Pierre Kraemer's avatar
Pierre Kraemer committed
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
}


std::string GLSLShader::findFile(const std::string filename)
{
// cherche d'abord dans le repertoire courant
	std::ifstream file;
	file.open(filename.c_str(),std::ios::in );
	if (!file.fail())
	{
		file.close();
		return filename;
	}
	file.close();

645 646 647 648 649 650 651 652 653 654 655 656 657 658
	for (std::vector<std::string>::const_iterator ipath = m_pathes.begin(); ipath != m_pathes.end(); ++ipath)
	{
		std::string st(*ipath);
		st.append(filename);

		std::ifstream file2;
		file2.open(st.c_str(),std::ios::in);
		if (!file2.fail())
		{
			file2.close();
			return st;
		}
	}

Pierre Kraemer's avatar
Pierre Kraemer committed
659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
// LA MACRO SHADERPATH contient le chemin du repertoire qui contient les fichiers textes
	std::string st(SHADERPATH);
	st.append(filename);

	std::ifstream file2; // on ne peut pas réutiliser file ????
	file2.open(st.c_str(),std::ios::in);
	if (!file2.fail())
	{
		file2.close();
		return st;
	}

	return filename;
}


bool GLSLShader::init()
{
	GLenum error = glewInit();

	if (error != GLEW_OK)
		std::cerr << "Error: " << glewGetErrorString(error) << std::endl;
	else
		std::cout << "Status: Using GLEW " << glewGetString(GLEW_VERSION) << std::endl;

	if (!areVBOSupported())
		std::cout << "VBO not supported !" << std::endl;

	if(!areShadersSupported()) {
		std::cout << "Shaders not supported !" << std::endl;
		return false;
	}
	return true; 
}

bool GLSLShader::loadShaders(const std::string& vs, const std::string& ps)
{
Sylvain Thery's avatar
Sylvain Thery committed
696 697
	m_nameVS = vs;
	m_nameFS = ps;
698

Pierre Kraemer's avatar
Pierre Kraemer committed
699 700 701 702
	std::string vss = findFile(vs);
	if(!loadVertexShader(vss)) return false;
	
	std::string pss = findFile(ps);
703
	if(!loadFragmentShader(pss)) return false;
Pierre Kraemer's avatar
Pierre Kraemer committed
704 705 706 707 708 709 710 711 712 713 714

	if(!create()) {
		std::cout << "Unable to create the shaders !" << std::endl;
		return false;
	}
	std::cout << "Shaders loaded (" << vs << "," << ps << ")" << std::endl;
	return true; 
}

bool GLSLShader::loadShaders(const std::string& vs, const std::string& ps, const std::string& gs, GLint inputGeometryPrimitive,GLint outputGeometryPrimitive)
{
Sylvain Thery's avatar
Sylvain Thery committed
715 716 717 718
	m_nameVS = vs;
	m_nameFS = ps;
	m_nameGS = gs;

Pierre Kraemer's avatar
Pierre Kraemer committed
719 720 721 722
	std::string vss = findFile(vs);
	if(!loadVertexShader(vss)) return false;

	std::string pss = findFile(ps);
723
	if(!loadFragmentShader(pss)) return false;
Pierre Kraemer's avatar
Pierre Kraemer committed
724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743

	std::string gss = findFile(gs);
	bool geomShaderLoaded = loadGeometryShader(gss);

	if (!geomShaderLoaded)
	{
		std::cerr << "Error while loading geometry shader" << std::endl;
	}


	if(!create(inputGeometryPrimitive,outputGeometryPrimitive))
	{
		std::cout << "Unable to create the shaders !" << std::endl;
		return false;
	}

	std::cout << "Shaders loaded (" << vs << "," << ps << "," << gs <<")" << std::endl;
	return true;
}

744

745

Sylvain Thery's avatar
Sylvain Thery committed
746 747
bool GLSLShader::loadShadersFromMemory(const char* vs, const char* fs)
{
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763
	if (m_vertex_shader_source)
		delete [] m_vertex_shader_source;

	unsigned int sz = strlen(vs);
	m_vertex_shader_source = new char[sz+1];
	strcpy(m_vertex_shader_source,vs);


	if (m_fragment_shader_source)
		delete [] m_fragment_shader_source;

	sz = strlen(fs);
	m_fragment_shader_source = new char[sz+1];
	strcpy(m_fragment_shader_source,fs);


Sylvain Thery's avatar
Sylvain Thery committed
764 765 766 767 768 769 770 771 772 773 774 775 776 777
	if(!loadVertexShaderSourceString(vs)) return false;

	if(!loadFragmentShaderSourceString(fs)) return false;

	if(!create())
	{
		std::cout << "Unable to create the shaders !" << std::endl;
		return false;
	}
	return true;
}

bool GLSLShader::loadShadersFromMemory(const char* vs, const char* fs, const char* gs, GLint inputGeometryPrimitive,GLint outputGeometryPrimitive)
{
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799

	if (m_vertex_shader_source)
		delete [] m_vertex_shader_source;

	unsigned int sz = strlen(vs);
	m_vertex_shader_source = new char[sz+1];
	strcpy(m_vertex_shader_source,vs);

	if (m_fragment_shader_source)
		delete [] m_fragment_shader_source;

	sz = strlen(fs);
	m_fragment_shader_source = new char[sz+1];
	strcpy(m_fragment_shader_source,fs);

	if (m_geom_shader_source)
		delete [] m_geom_shader_source;

	sz = strlen(gs);
	m_geom_shader_source = new char[sz+1];
	strcpy(m_geom_shader_source,gs);

Sylvain Thery's avatar
Sylvain Thery committed
800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815
	if(!loadVertexShaderSourceString(vs)) return false;

	if(!loadFragmentShaderSourceString(fs)) return false;

	if(!loadGeometryShaderSourceString(gs)) return false;

	if(!create(inputGeometryPrimitive,outputGeometryPrimitive))
	{
		std::cout << "Unable to create the shaders !" << std::endl;
		return false;
	}

	return true;
}


816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866
bool GLSLShader::reloadVertexShaderFromMemory(const char* vs)
{

	if (m_vertex_shader_source)
		delete [] m_vertex_shader_source;

	unsigned int sz = strlen(vs);
	m_vertex_shader_source = new char[sz+1];
	strcpy(m_vertex_shader_source,vs);

	return true;
}

bool GLSLShader::reloadFragmentShaderFromMemory(const char* fs)
{
	if (m_fragment_shader_source)
		delete [] m_fragment_shader_source;

	unsigned int sz = strlen(fs);
	m_fragment_shader_source = new char[sz+1];
	strcpy(m_fragment_shader_source,fs);

	return true;
}

bool GLSLShader::reloadGeometryShaderFromMemory(const char* gs)
{
	if (m_geom_shader_source)
		delete [] m_geom_shader_source;

	unsigned int sz = strlen(gs);
	m_geom_shader_source = new char[sz+1];
	strcpy(m_geom_shader_source,gs);

	return true;
}

bool GLSLShader::recompile()
{
	if (m_vertex_shader_source)
		if(!loadVertexShaderSourceString(m_vertex_shader_source)) return false;
	if (m_fragment_shader_source)
		if(!loadFragmentShaderSourceString(m_fragment_shader_source)) return false;
	if (m_geom_shader_source)
		if(!loadGeometryShaderSourceString(m_geom_shader_source)) return false;

	if(!create(m_geom_inputPrimitives,m_geom_outputPrimitives))
	{
		std::cout << "Unable to create the shaders !" << std::endl;
		return false;
	}
Sylvain Thery's avatar
Sylvain Thery committed
867
std::cout << "DDDD"<< std::endl;
868 869 870 871 872

	m_uniMat_Proj		= glGetUniformLocation(m_program_object,"ProjectionMatrix");
	m_uniMat_Model		= glGetUniformLocation(m_program_object,"ModelViewMatrix");
	m_uniMat_ModelProj	= glGetUniformLocation(m_program_object,"ModelViewProjectionMatrix");
	m_uniMat_Normal		= glGetUniformLocation(m_program_object,"NormalMatrix");
Sylvain Thery's avatar
Sylvain Thery committed
873
std::cout << "EEEE"<< std::endl;
874 875 876 877 878 879 880

	restoreUniformsAttribs();

	return true;
}


881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951
bool GLSLShader::validateProgram()
{
	if(!m_program_object)
		return false;

	glValidateProgram(m_program_object);
	GLint Result = GL_FALSE;
	glGetProgramiv(m_program_object, GL_VALIDATE_STATUS, &Result);

	if(Result == GL_FALSE)
	{
		std::cout << "Validate program:" << std::endl;
		int InfoLogLength;
		glGetProgramiv(m_program_object, GL_INFO_LOG_LENGTH, &InfoLogLength);
		std::vector<char> Buffer(InfoLogLength);
		glGetProgramInfoLog(m_program_object, InfoLogLength, NULL, &Buffer[0]);
		std::cout <<  &(Buffer[0]) << std::endl;
		return false;
	}

	return true;
}

bool GLSLShader::checkProgram()
{
	GLint Result = GL_FALSE;
	glGetProgramiv(m_program_object, GL_LINK_STATUS, &Result);

	int InfoLogLength;
	glGetProgramiv(m_program_object, GL_INFO_LOG_LENGTH, &InfoLogLength);
	std::vector<char> Buffer(std::max(InfoLogLength, int(1)));
	glGetProgramInfoLog(m_program_object, InfoLogLength, NULL, &Buffer[0]);
	std::cout << &Buffer[0] << std::endl;

	return Result == GL_TRUE;
}

bool GLSLShader::checkShader(int shaderType)
{
	GLint Result = GL_FALSE;
	int InfoLogLength;
	GLhandleARB id;

	switch(shaderType)
	{
	case VERTEX_SHADER:
		id = m_vertex_shader_object;
		break;
	case FRAGMENT_SHADER:
		id = m_fragment_shader_object;
		break;
	case GEOMETRY_SHADER:
		id = m_geom_shader_object;
		break;
	default:
		std::cerr << "Error unkown shader type"<< std::endl;
		return false;
		break;
	}

	glGetShaderiv(id, GL_COMPILE_STATUS, &Result);
	glGetShaderiv(id, GL_INFO_LOG_LENGTH, &InfoLogLength);
	std::vector<char> Buffer(InfoLogLength);
	glGetShaderInfoLog(id, InfoLogLength, NULL, &Buffer[0]);
	std::cout << &Buffer[0] << std::endl;

	return Result == GL_TRUE;
}



Sylvain Thery's avatar
Sylvain Thery committed
952
void GLSLShader::bindAttrib(unsigned int att, const char* name) const
953
{
954
	glBindAttribLocation(m_program_object,att,name);
955 956 957
}


958 959 960 961 962
void GLSLShader::addPathFileSeach(const std::string& path)
{
	m_pathes.push_back(path);
}

Sylvain Thery's avatar
Sylvain Thery committed
963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
void GLSLShader::unbindVBO(VBO* ptr)
{
	unsigned int nb = m_va_vbo_binding.size();
	for (unsigned int i =0; i<nb; ++i)
	{
		if (m_va_vbo_binding[i].vbo_ptr == ptr)
		{
			if (i != (nb-1))
				m_va_vbo_binding[i] = m_va_vbo_binding[nb-1];
			m_va_vbo_binding.pop_back();
			return;
		}
	}
}

978
unsigned int GLSLShader::bindVA_VBO(const std::string& name, VBO* vbo)
Sylvain Thery's avatar
Sylvain Thery committed
979
{
980
	vbo->ref(this);
Sylvain Thery's avatar
Sylvain Thery committed
981 982 983 984 985 986

	GLint idVA = glGetAttribLocation(this->m_program_object, name.c_str());
	//valid ?
	if (idVA < 0)
	{
		std::cerr << "GLSLShader: Attribute "<<name<< " does not exist in shader"<< std::endl;
987
		return idVA;
Sylvain Thery's avatar
Sylvain Thery committed
988 989 990 991 992 993
	}
	// search if name already exist
	for (std::vector<VAStr>::iterator it = m_va_vbo_binding.begin(); it != m_va_vbo_binding.end(); ++it)
	{
		if (it->va_id == idVA)
		{
994 995
			it->vbo_ptr = vbo;
			return (it - m_va_vbo_binding.begin());
Sylvain Thery's avatar
Sylvain Thery committed
996 997 998 999 1000
		}
	}
	// new one:
	VAStr temp;
	temp.va_id = idVA;
1001
	temp.vbo_ptr = vbo;
Sylvain Thery's avatar
Sylvain Thery committed
1002
	m_va_vbo_binding.push_back(temp);
1003 1004 1005 1006 1007 1008
	return (m_va_vbo_binding.size() -1);
}

void GLSLShader::changeVA_VBO(unsigned int id, VBO* vbo)
{
	m_va_vbo_binding[id].vbo_ptr = vbo;
Sylvain Thery's avatar
Sylvain Thery committed
1009 1010
}

1011

Sylvain Thery's avatar
Sylvain Thery committed
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056
void GLSLShader::unbindVA(const std::string& name)
{
	GLint idVA = glGetAttribLocation(this->m_program_object, name.c_str());
	//valid ?
	if (idVA < 0)
	{
		std::cerr << "GLSLShader: Attribute "<<name<< " does not exist in shader, not unbinded"<< std::endl;
		return;
	}
	// search if name already exist
	unsigned int nb = m_va_vbo_binding.size();
	for (unsigned int i =0; i<nb; ++i)
	{
		if (m_va_vbo_binding[i].va_id == idVA)
		{
			if (i != (nb-1))
				m_va_vbo_binding[i] = m_va_vbo_binding[nb-1];
			m_va_vbo_binding.pop_back();
			return;
		}
	}
	std::cerr << "GLSLShader: Attribute "<<name<< " not binded"<< std::endl;
}

void GLSLShader::setCurrentOGLVersion(unsigned int version)
{
	CURRENT_OGL_VERSION=version;
	switch(version)
	{
	case 2:
		DEFINES_GL = &DEFINES_GL2;
		break;
	case 3:
		DEFINES_GL = &DEFINES_GL3;
		break;
	}
}

/**
 * update projection, modelview, ... matrices
 */
void GLSLShader::updateMatrices(const glm::mat4& projection, const glm::mat4& modelview)
{
	this->bind();
	glm::mat4 PMV = projection*modelview;
1057
	glm::mat4 normalMatrix = glm::gtx::inverse_transpose::inverseTranspose(modelview);
Sylvain Thery's avatar
Sylvain Thery committed
1058

1059

1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081
	if (m_uniMat_Proj>=0)
		glUniformMatrix4fv(m_uniMat_Proj,		1 , false, &projection[0][0]);
	if (m_uniMat_Model>=0)
		glUniformMatrix4fv(m_uniMat_Model,		1 , false, &modelview[0][0]);
	if (m_uniMat_ModelProj>=0)
		glUniformMatrix4fv(m_uniMat_ModelProj,	1 , false, &PMV[0][0]);
	if (m_uniMat_Normal>=0)
		glUniformMatrix4fv(m_uniMat_Normal, 	1 , false, &normalMatrix[0][0]);

}

void GLSLShader::enableVertexAttribs(unsigned int stride) const
{
	this->bind();
	for (std::vector<Utils::GLSLShader::VAStr>::const_iterator it= m_va_vbo_binding.begin(); it != m_va_vbo_binding.end(); ++it)
	{
		glBindBuffer(GL_ARRAY_BUFFER, it->vbo_ptr->id());
		glEnableVertexAttribArray(it->va_id);
		glVertexAttribPointer(it->va_id ,it->vbo_ptr->dataSize(), GL_FLOAT, false, stride, 0);

	}
}
Sylvain Thery's avatar
Sylvain Thery committed
1082

1083 1084 1085 1086
void GLSLShader::disableVertexAttribs() const
{
	for (std::vector<Utils::GLSLShader::VAStr>::const_iterator it= m_va_vbo_binding.begin(); it != m_va_vbo_binding.end(); ++it)
		glEnableVertexAttribArray(it->va_id);
Sylvain Thery's avatar
Sylvain Thery committed
1087
}
Pierre Kraemer's avatar
Pierre Kraemer committed
1088 1089 1090

} // namespace Utils
} // namespace CGoGN