Shader.cpp 17.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
/*
 *	(c) LSIIT, UMR CNRS/UdS
 *	Authors: F. Larue.
 *
 *	See licence.txt for additional information.
 */


#include "GPUdefs.h"
#include "Shader.h"
#include "VBO.h"
#include <fstream>
#include <string>
#include <iostream>




19
bool GPU::GenericShader::PgObject::Allocate()
20
{
21
    gpuAssert( m_Id = glCreateShaderObjectARB( m_PgType ) );
22 23 24 25
    return m_Id != 0;
}


26
bool GPU::GenericShader::PgObject::Unallocate()
27
{
28
    gpuAssert( glDeleteObjectARB( m_Id ) );
29 30 31 32 33
    m_Id = 0;
    return true;
}


34 35 36
bool GPU::GenericShader::PgObject::CompileSrcFile( const std::string &filename,
                                                   const GLenum pgType,
                                                   std::string *logs )
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
{
    // Open the source files.
	std::ifstream file( filename.c_str(), std::ios::binary );
    if( file.fail() )
        return false;

	// Map the content of the shader source file into a memory buffer.
    file.seekg( 0, std::ios::end );
	int fileSize = (int) file.tellg();
	file.seekg( 0, std::ios::beg );

	char *sourceString = new char [ fileSize+1 ];
	file.read( sourceString, fileSize );
	sourceString[ fileSize ] = '\0';

    file.close();

	// Create the shader object.
    bool ok = CompileSrcString( sourceString, pgType, logs );

    // Termination.
    delete [] sourceString;
    return ok;
}


63
bool GPU::GenericShader::PgObject::CompileSrcString( const char *sourceString,
64 65 66 67 68 69 70 71
                                              const GLenum pgType,
                                              std::string *logs )
{
    // Ask for a free shader object name to OpenGL.
    m_PgType = pgType;
    if( Instantiate() )
    {
        // Create the shader object.
72 73
	    gpuAssert( glShaderSourceARB ( m_Id, 1, (const GLcharARB**) &sourceString, NULL ) );
	    gpuAssert( glCompileShaderARB( m_Id ) );
74 75 76

        // Check the compilation status.
	    GLint status;
77
        gpuAssert( glGetObjectParameterivARB( m_Id, GL_OBJECT_COMPILE_STATUS_ARB, &status ) );
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92

        if( status )
            return true;
        else if( logs )
            *logs = GPU::Shader::GetLogs( m_Id );

        Release();
    }

    return false;
}




93
std::string GPU::GenericShader::GetLogs( GLuint pgId )
94 95
{
    GLint logLength;
96
    gpuAssert( glGetObjectParameterivARB( pgId, GL_OBJECT_INFO_LOG_LENGTH_ARB, &logLength ) );
97 98 99

    std::string infoLog;
    infoLog.resize( logLength );
100
    gpuAssert( glGetInfoLogARB( pgId, logLength, &logLength, &infoLog[0] ) );
101 102 103 104 105

    return infoLog;
}


106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
bool GPU::GenericShader::Allocate()
{
    if( !m_Id )
        gpuAssert( m_Id = glCreateProgramObjectARB() );
    return m_Id != 0;
}


bool GPU::GenericShader::Unallocate()
{
    if( m_Id )
    {
        gpuAssert( glDeleteObjectARB( m_Id ) );
        m_Id = 0;
    }
    return true;
}




127 128 129 130 131 132 133 134 135
void GPU::Shader::RecoverActiveUniforms()
{
    m_Uniforms.clear();
    m_Samplers.clear();
    m_SamplerBinding.clear();

	GLint count;
	GLcharARB nameBuffer[512];

136
    gpuAssert( glGetObjectParameterivARB( Id(), GL_OBJECT_ACTIVE_UNIFORMS_ARB, &count ) );
137 138 139 140 141 142 143

	for( GLint i=0; i<count; ++i )
	{
		GLsizei length;
        GLint   size;
        GLenum  type;

144
		gpuAssert( glGetActiveUniformARB(
145
            Id(),
146 147 148 149 150 151
            i,
            sizeof(nameBuffer),
            &length,
            &size,
            &type,
            nameBuffer
152
            ) );
153 154 155

		std::string name( nameBuffer );

156
        switch( type )
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
            case GL_SAMPLER_1D:
            case GL_SAMPLER_2D:
            case GL_SAMPLER_3D:
            case GL_SAMPLER_CUBE:
            case GL_SAMPLER_1D_SHADOW:
            case GL_SAMPLER_2D_SHADOW:
            case GL_SAMPLER_1D_ARRAY:
            case GL_SAMPLER_2D_ARRAY:
            case GL_SAMPLER_1D_ARRAY_SHADOW:
            case GL_SAMPLER_2D_ARRAY_SHADOW:
            case GL_SAMPLER_2D_MULTISAMPLE:
            case GL_SAMPLER_2D_MULTISAMPLE_ARRAY:
            case GL_SAMPLER_CUBE_SHADOW:
            case GL_SAMPLER_BUFFER:
            case GL_SAMPLER_2D_RECT:
            case GL_SAMPLER_2D_RECT_SHADOW:
            case GL_INT_SAMPLER_1D:
            case GL_INT_SAMPLER_2D:
            case GL_INT_SAMPLER_3D:
            case GL_INT_SAMPLER_CUBE:
            case GL_INT_SAMPLER_1D_ARRAY:
            case GL_INT_SAMPLER_2D_ARRAY:
            case GL_INT_SAMPLER_2D_MULTISAMPLE:
            case GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY:
            case GL_INT_SAMPLER_BUFFER:
            case GL_INT_SAMPLER_2D_RECT:
            case GL_UNSIGNED_INT_SAMPLER_1D:
            case GL_UNSIGNED_INT_SAMPLER_2D:
            case GL_UNSIGNED_INT_SAMPLER_3D:
            case GL_UNSIGNED_INT_SAMPLER_CUBE:
            case GL_UNSIGNED_INT_SAMPLER_1D_ARRAY:
            case GL_UNSIGNED_INT_SAMPLER_2D_ARRAY:
            case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE:
            case GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY:
            case GL_UNSIGNED_INT_SAMPLER_BUFFER:
            case GL_UNSIGNED_INT_SAMPLER_2D_RECT:
            {
                Uniform &smpl = m_Samplers[name];
196
                gpuAssert( smpl.location = glGetUniformLocationARB( Id(), nameBuffer ) );
197 198 199 200 201 202 203
                smpl.size = size;
                smpl.type = type;
                break;
            }
            default:
            {
                Uniform &unif = m_Uniforms[name];
204
                gpuAssert( unif.location = glGetUniformLocationARB( Id(), nameBuffer ) );
205 206 207 208
		        unif.size = size;
    		    unif.type = type;
                break;
            }
209 210 211 212 213 214 215 216
        }
    }
}


void GPU::Shader::RecoverActiveAttributes()
{
    m_Attributes.clear();
217

218 219 220
    GLint count;
	GLcharARB nameBuffer[512];

221
	gpuAssert( glGetObjectParameterivARB( Id(), GL_OBJECT_ACTIVE_ATTRIBUTES_ARB, &count ) );
222 223 224 225 226 227 228

	for( GLint i=0; i<count; ++i )
	{
		GLsizei length;
        GLint   size;
        GLenum  type;

229
		gpuAssert( glGetActiveAttribARB(
230
            Id(),
231 232 233 234 235 236
            i,
            sizeof(nameBuffer),
            &length,
            &size,
            &type,
            nameBuffer
237
            ) );
238

239
		GLint attribId;
240
        gpuAssert( attribId = glGetAttribLocationARB( Id(), nameBuffer ) );
241 242 243 244 245 246 247 248
		if( attribId != -1 )
            m_Attributes[ std::string(nameBuffer) ] = attribId;
	}
}


bool GPU::Shader::Link( std::string *logs )
{
249 250
    if( !IsCreated()  &&  !Allocate() )
        return false;
251 252 253


    if( m_VertPg.IsInstantiated() )
254
        gpuAssert( glAttachObjectARB( Id(), m_VertPg.Id() ) );
255 256

    if( m_FragPg.IsInstantiated() )
257
        gpuAssert( glAttachObjectARB( Id(), m_FragPg.Id() ) );
258 259

    if( m_GeomPg.IsInstantiated() )
260
        gpuAssert( glAttachObjectARB( Id(), m_GeomPg.Id() ) );
261

262
    gpuAssert( glLinkProgramARB( Id() ) );
263 264

    GLint status;
265
    gpuAssert( glGetObjectParameterivARB( Id(), GL_OBJECT_LINK_STATUS_ARB, &status ) );
266 267 268
    if( !status )
    {
        if( logs )
269
            *logs = GetLogs( Id() );
270

271
        Unallocate();
272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290

        return false;
    }


    RecoverActiveUniforms();
    RecoverActiveAttributes();

    return true;
}



GPU::Shader& GPU::Shader::Attach( const PgObject &pg )
{
    switch( pg.Type() )
    {
        case GL_VERTEX_SHADER_ARB:
        {
291 292
            if( IsCreated()  &&  m_VertPg.IsInstantiated() )
                gpuAssert( glDetachObjectARB( Id(), m_VertPg.Id() ) );
293 294 295 296 297
            m_VertPg = * (VertPg*) &pg;
            break;
        }
        case GL_FRAGMENT_SHADER_ARB:
        {
298 299
            if( IsCreated()  &&  m_FragPg.IsInstantiated() )
                gpuAssert( glDetachObjectARB( Id(), m_FragPg.Id() ) );
300 301 302 303 304
            m_FragPg = * (FragPg*) &pg;
            break;
        }
        case GL_GEOMETRY_SHADER_EXT:
        {
305 306
            if( IsCreated()  &&  m_GeomPg.IsInstantiated() )
                gpuAssert( glDetachObjectARB( Id(), m_GeomPg.Id() ) );
307 308 309 310 311 312 313 314 315 316 317
            m_GeomPg = * (GeomPg*) &pg;
            break;
        }
    }

    return *this;
}


GPU::Shader& GPU::Shader::DetachVertPg()
{
318 319
    if( IsCreated()  &&  m_VertPg.IsInstantiated() )
        gpuAssert( glDetachObjectARB( Id(), m_VertPg.Id() ) );
320 321 322 323 324 325 326
    m_VertPg.Release();
    return *this;
}


GPU::Shader& GPU::Shader::DetachFragPg()
{
327 328
    if( IsCreated()  &&  m_FragPg.IsInstantiated() )
        gpuAssert( glDetachObjectARB( Id(), m_FragPg.Id() ) );
329 330 331 332 333 334 335
    m_FragPg.Release();
    return *this;
}


GPU::Shader& GPU::Shader::DetachGeomPg()
{
336 337
    if( IsCreated()  &&  m_GeomPg.IsInstantiated() )
        gpuAssert( glDetachObjectARB( Id(), m_GeomPg.Id() ) );
338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370
    m_GeomPg.Release();
    return *this;
}


/*
bool GPU::Shader::CreateFromFiles( const std::string &vshFilename,
                                   const std::string &fshFilename )
{
    VertPg vsh;
    FragPg fsh;

    return vsh.LoadFile( vshFilename ) &&
           fsh.LoadFile( fshFilename ) &&
           Create( vsh, fsh );
}


bool GPU::Shader::CreateFromSources( const char *vshSourceStr,
                                     const char *fshSourceStr )
{
    VertPg vsh;
    FragPg fsh;

    return vsh.LoadSource( vshSourceStr ) &&
           fsh.LoadSource( fshSourceStr ) &&
           Create( vsh, fsh );
}
*/


void GPU::Shader::Release()
{
371
    if( m_VertPg.Id() )
372
    {
373 374 375 376 377 378 379 380 381 382 383 384 385
        gpuAssert( glDetachObjectARB( Id(), m_VertPg.Id() ) );
        m_VertPg.Release();
    }
    if( m_FragPg.Id() )
    {
        gpuAssert( glDetachObjectARB( Id(), m_FragPg.Id() ) );
        m_FragPg.Release();
    }
    if( m_GeomPg.Id() )
    {
        gpuAssert( glDetachObjectARB( Id(), m_GeomPg.Id() ) );
        m_GeomPg.Release();
    }
386

387 388 389 390
    m_Uniforms.clear();
    m_Attributes.clear();
    m_Samplers.clear();
    m_SamplerBinding.clear();
391

392
    Unallocate();
393 394 395 396 397 398 399 400 401
}


void GPU::Shader::SetUniform( const std::string& name,
                              const void *value )
{
    UniformMap::iterator uu = m_Uniforms.find( name );
    if( uu != m_Uniforms.end() )
    {
402 403
	    GLuint activeProgBackup;
        gpuAssert( activeProgBackup = glGetHandleARB( GL_PROGRAM_OBJECT_ARB ) );
404
	    gpuAssert( glUseProgramObjectARB( Id() ) );
405 406 407 408

        Uniform &u = uu->second;
	    switch( u.type )
	    {
409 410 411 412
		    case GL_FLOAT:          gpuAssert( glUniform1fvARB( u.location, u.size, (GLfloat*) value ) ); break;
		    case GL_FLOAT_VEC2_ARB: gpuAssert( glUniform2fvARB( u.location, u.size, (GLfloat*) value ) ); break;
		    case GL_FLOAT_VEC3_ARB: gpuAssert( glUniform3fvARB( u.location, u.size, (GLfloat*) value ) ); break;
		    case GL_FLOAT_VEC4_ARB: gpuAssert( glUniform4fvARB( u.location, u.size, (GLfloat*) value ) ); break;
413 414 415 416
		    case GL_DOUBLE:         gpuAssert( glUniform1dv( u.location, u.size, (GLdouble*) value ) ); break;
		    case GL_DOUBLE_VEC2:    gpuAssert( glUniform2dv( u.location, u.size, (GLdouble*) value ) ); break;
		    case GL_DOUBLE_VEC3:    gpuAssert( glUniform3dv( u.location, u.size, (GLdouble*) value ) ); break;
		    case GL_DOUBLE_VEC4:    gpuAssert( glUniform4dv( u.location, u.size, (GLdouble*) value ) ); break;
417 418 419 420 421 422 423 424 425 426 427
		    case GL_INT:            gpuAssert( glUniform1ivARB( u.location, u.size, (GLint*) value ) ); break;
		    case GL_INT_VEC2_ARB:   gpuAssert( glUniform2ivARB( u.location, u.size, (GLint*) value ) ); break;
		    case GL_INT_VEC3_ARB:   gpuAssert( glUniform3ivARB( u.location, u.size, (GLint*) value ) ); break;
		    case GL_INT_VEC4_ARB:   gpuAssert( glUniform4ivARB( u.location, u.size, (GLint*) value ) ); break;
		    case GL_BOOL_ARB:       gpuAssert( glUniform1ivARB( u.location, u.size, (GLint*) value ) ); break;
		    case GL_BOOL_VEC2_ARB:  gpuAssert( glUniform2ivARB( u.location, u.size, (GLint*) value ) ); break;
		    case GL_BOOL_VEC3_ARB:  gpuAssert( glUniform3ivARB( u.location, u.size, (GLint*) value ) ); break;
		    case GL_BOOL_VEC4_ARB:  gpuAssert( glUniform4ivARB( u.location, u.size, (GLint*) value ) ); break;
		    case GL_FLOAT_MAT2_ARB: gpuAssert( glUniformMatrix2fvARB( u.location, u.size, GL_FALSE, (GLfloat*) value ) ); break;
		    case GL_FLOAT_MAT3_ARB: gpuAssert( glUniformMatrix3fvARB( u.location, u.size, GL_FALSE, (GLfloat*) value ) ); break;
		    case GL_FLOAT_MAT4_ARB: gpuAssert( glUniformMatrix4fvARB( u.location, u.size, GL_FALSE, (GLfloat*) value ) ); break;
428 429 430
		    case GL_DOUBLE_MAT2:    gpuAssert( glUniformMatrix2dv( u.location, u.size, GL_FALSE, (GLdouble*) value ) ); break;
		    case GL_DOUBLE_MAT3:    gpuAssert( glUniformMatrix3dv( u.location, u.size, GL_FALSE, (GLdouble*) value ) ); break;
		    case GL_DOUBLE_MAT4:    gpuAssert( glUniformMatrix4dv( u.location, u.size, GL_FALSE, (GLdouble*) value ) ); break;
431 432
	    }

433
	    gpuAssert( glUseProgramObjectARB( activeProgBackup ) );
434 435 436 437
    }
}


438 439 440 441 442 443 444 445 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 478 479 480 481 482 483 484 485 486 487 488 489 490 491
void GPU::Shader::SetUniform( const std::string& name, GLint value )
{
    UniformMap::iterator uu = m_Uniforms.find( name );
    if( uu != m_Uniforms.end() )
    {
        GLuint activeProgBackup;
        gpuAssert( activeProgBackup = glGetHandleARB( GL_PROGRAM_OBJECT_ARB ) );
        gpuAssert( glUseProgramObjectARB( Id() ) );

        Uniform &u = uu->second;
        assert( (u.type == GL_INT  ||  u.type == GL_BOOL_ARB)  &&  u.size == 1 );
        gpuAssert( glUniform1ivARB( u.location, u.size, &value ) );

        gpuAssert( glUseProgramObjectARB( activeProgBackup ) );
    }
}


void GPU::Shader::SetUniform( const std::string& name, GLfloat value )
{
    UniformMap::iterator uu = m_Uniforms.find( name );
    if( uu != m_Uniforms.end() )
    {
        GLuint activeProgBackup;
        gpuAssert( activeProgBackup = glGetHandleARB( GL_PROGRAM_OBJECT_ARB ) );
        gpuAssert( glUseProgramObjectARB( Id() ) );

        Uniform &u = uu->second;
        assert( u.type == GL_FLOAT  &&  u.size == 1 );
        gpuAssert( glUniform1fvARB( u.location, u.size, &value ) );

        gpuAssert( glUseProgramObjectARB( activeProgBackup ) );
    }
}


void GPU::Shader::SetUniform( const std::string& name, GLdouble value )
{
    UniformMap::iterator uu = m_Uniforms.find( name );
    if( uu != m_Uniforms.end() )
    {
        GLuint activeProgBackup;
        gpuAssert( activeProgBackup = glGetHandleARB( GL_PROGRAM_OBJECT_ARB ) );
        gpuAssert( glUseProgramObjectARB( Id() ) );

        Uniform &u = uu->second;
        assert( u.type == GL_DOUBLE  &&  u.size == 1 );
        gpuAssert( glUniform1dv( u.location, u.size, &value ) );

        gpuAssert( glUseProgramObjectARB( activeProgBackup ) );
    }
}


492 493
void GPU::Shader::SetSamplers( const std::string& name,
                               const GLint* texUnit )
494
{
495
    UniformMap::iterator s = m_Samplers.find( name );
496 497
    if( s != m_Samplers.end() )
    {
498 499
	    GLuint activeProgBackup;
        gpuAssert( activeProgBackup = glGetHandleARB( GL_PROGRAM_OBJECT_ARB ) );
500
	    gpuAssert( glUseProgramObjectARB( Id() ) );
501

502
        gpuAssert( glUniform1ivARB( s->second.location, s->second.size, (GLint*) texUnit ) );
503

504
	    gpuAssert( glUseProgramObjectARB( activeProgBackup ) );
505 506 507 508
    }
}


509 510 511 512 513 514 515 516 517 518
void GPU::Shader::SetSamplers( const std::string& name,
                               const GLint firstTexUnit )
{
    UniformMap::iterator s = m_Samplers.find( name );
    if( s != m_Samplers.end() )
    {
        GLint *texUnits = new GLint [ s->second.size ];
        for( GLint i=0; i<s->second.size; ++i )
            texUnits[i] = firstTexUnit + i;

519 520
	    GLuint activeProgBackup;
        gpuAssert( activeProgBackup = glGetHandleARB( GL_PROGRAM_OBJECT_ARB ) );
521
	    gpuAssert( glUseProgramObjectARB( Id() ) );
522

523
        gpuAssert( glUniform1ivARB( s->second.location, s->second.size, texUnits ) );
524

525
	    gpuAssert( glUseProgramObjectARB( activeProgBackup ) );
526 527 528 529 530 531

        delete[] texUnits;
    }
}


532 533 534 535 536 537 538 539 540 541 542 543 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 577 578
void GPU::Shader::SetAttrib( const std::string& name,
                             VBOAttribBuffer *attrib )
{
    attrib->SetLocation( AttribLoc(name) );
}


void GPU::Shader::UniformNames( std::vector<std::string> &names ) const
{
    names.clear();
    names.reserve( m_Uniforms.size() );

    for( auto &u : m_Uniforms )
        names.push_back( u.first );
}


void GPU::Shader::SamplerNames( std::vector<std::string> &names ) const
{
    names.clear();
    names.reserve( m_Samplers.size() );

    for( auto& s : m_Samplers )
        names.push_back( s.first );
}


void GPU::Shader::AttribNames( std::vector<std::string> &names ) const
{
    names.clear();
    names.reserve( m_Attributes.size() );

    for( auto& a : m_Attributes )
        names.push_back( a.first );
}




bool GPU::CreateShaderFromSources( GPU::Shader &shader,
                                   const char *vpgSrc,
                                   const char *gpgSrc,
                                   const char *fpgSrc,
                                   std::string *logs )
{
    shader.Release();

Frédéric Larue's avatar
Frédéric Larue committed
579
    if( vpgSrc  &&  vpgSrc[0] != '\0' )
580 581 582 583 584 585 586 587 588 589 590
    {
        GPU::Shader::VertPg vpg;
        if( !vpg.CompileSrcString( vpgSrc, logs ) )
        {
            if( logs )
                *logs = std::string(__FUNCTION__) + " - Vertex program compilation error:\n" + *logs + '\n';
            return false;
        }
        shader.Attach( vpg );
    }

Frédéric Larue's avatar
Frédéric Larue committed
591
    if( gpgSrc  &&  gpgSrc[0] != '\0' )
592 593 594 595 596 597 598 599 600 601 602
    {
        GPU::Shader::GeomPg gpg;
        if( !gpg.CompileSrcString( gpgSrc, logs ) )
        {
            if( logs )
                *logs = std::string(__FUNCTION__) + " - Geometry program compilation error:\n" + *logs + '\n';
            return false;
        }
        shader.Attach( gpg );
    }

Frédéric Larue's avatar
Frédéric Larue committed
603
    if( fpgSrc  &&  fpgSrc[0] != '\0' )
604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623
    {
        GPU::Shader::FragPg fpg;
        if( !fpg.CompileSrcString( fpgSrc, logs ) )
        {
            if( logs )
                *logs = std::string(__FUNCTION__) + " - Fragment program compilation error:\n" + *logs + '\n';
            return false;
        }
        shader.Attach( fpg );
    }

    if( !shader.Link( logs ) )
    {
        if( logs )
            *logs = std::string(__FUNCTION__) + " - Shader link error:\n" + *logs + '\n';
        return false;
    }

    return true;
}