source: trunk/src/gl/gl_device.cc @ 511

Last change on this file since 511 was 506, checked in by epyon, 9 years ago
  • split shader objects from programs to allow separate compilation
  • minor additions
File size: 15.0 KB
Line 
1// Copyright (C) 2012-2015 ChaosForge Ltd
2// http://chaosforge.org/
3//
4// This file is part of Nova libraries.
5// For conditions of distribution and use, see copying.txt file in root folder.
6
7#include "nv/gl/gl_device.hh"
8
9#include "nv/gl/gl_window.hh"
10#include "nv/core/logging.hh"
11#include "nv/lib/sdl_image.hh"
12#include "nv/gl/gl_enum.hh"
13#include "nv/lib/gl.hh"
14
15using namespace nv;
16
17gl_device::gl_device()
18{
19        m_shader_header.append( "#version 330 core\n" );
20        for ( auto& i : get_uniform_factory() )
21                m_shader_header.append( "uniform "+datatype_to_glsl_type( i.second->get_datatype() )+" "+ i.first +";\n" );
22        for ( auto& i : get_link_uniform_factory() )
23                m_shader_header.append( "uniform sampler2D "+i.first +";\n" );
24}
25
26// this is a temporary function that will be removed once we find a way to
27// pass binary file data around
28image_data* gl_device::create_image_data( string_view filename )
29{
30        load_sdl_image_library();
31        SDL_Surface* image = IMG_Load( filename.data() );
32        if (!image)
33        {
34                NV_LOG_ERROR( "Image file ", filename, " not found!" );
35                return nullptr;
36        }
37        // TODO: BGR vs RGB, single channel
38        pixel_format pformat = RGBA;
39        switch ( image->format->BytesPerPixel )
40        {
41        case 4: pformat = RGBA; break;
42        case 3: pformat = RGB; break;
43        case 1: pformat = RED; break;
44        default: NV_ASSERT( false, "BytesPerPixel != 4,3 or 1!" );
45        }
46        image_format format( pformat, UBYTE );
47        image_data* data = new image_data( format, ivec2( image->w, image->h ), static_cast<nv::uint8*>( image->pixels ) );
48        return data;
49}
50
51// this is a temporary function that will be removed once we find a way to
52// pass binary file data around
53image_data* gl_device::create_image_data( const uint8* data, uint32 size )
54{
55        load_sdl_image_library();
56        SDL_Surface* image = IMG_LoadTyped_RW( SDL_RWFromMem( const_cast<uint8*>( data ), int( size ) ), 1, "png" );
57        if ( !image )
58        {
59                NV_LOG_ERROR( "Image binary data cannot be loaded found!" );
60                return nullptr;
61        }
62        // TODO: BGR vs RGB, single channel
63        NV_ASSERT( image->format->BytesPerPixel > 2, "bytes per pixel > 2!" );
64        image_format format( image->format->BytesPerPixel == 3 ? RGB : RGBA, UBYTE );
65        image_data* idata = new image_data( format, ivec2( image->w, image->h ), static_cast<nv::uint8*>( image->pixels ) );
66        return idata;
67}
68
69
70gl_device::~gl_device()
71{
72        while ( m_textures.size() > 0 )
73                release( m_textures.get_handle(0) );
74        while ( m_buffers.size() > 0 )
75                release( m_buffers.get_handle(0) );
76        while ( m_programs.size() > 0 )
77                release( m_programs.get_handle(0) );
78        while ( m_shaders.size() > 0 )
79                release( m_shaders.get_handle( 0 ) );
80}
81
82nv::shader nv::gl_device::create_shader( shader_type type, string_view sh_source )
83{
84        uint32 glid = 0;
85        if ( !compile( shader_type_to_enum( type ), sh_source, glid ) )
86                return shader();
87
88        shader result = m_shaders.create();
89        gl_shader_info* info = m_shaders.get( result );
90        info->type = type;
91        info->glid = glid;
92        info->ref  = 0;
93
94        return result;
95}
96
97nv::program nv::gl_device::create_program( shader vs, shader fs )
98{
99        program result = m_programs.create();
100        gl_program_info* info = m_programs.get( result );
101
102        info->m_attribute_map = new attribute_map;
103        info->m_engine_uniforms = new engine_uniform_list;
104        info->m_uniform_map = new uniform_map;
105
106        info->glid = glCreateProgram();
107        info->validated = false;
108
109        compile( result, vs, fs );
110        prepare_program( result );
111        return result;
112
113}
114
115nv::texture nv::gl_device::create_texture( texture_type type, pixel_format format )
116{
117        unsigned glid = 0;
118
119        glGenTextures( 1, &glid );
120
121        texture result = m_textures.create();
122        gl_texture_info* info = m_textures.get( result );
123        info->type = type;
124        info->format = format;
125        info->tsampler = sampler();
126        info->size = ivec3( 1, 1, 1 );
127        info->glid = glid;
128
129        return result;
130}
131
132void nv::gl_device::release( texture t )
133{
134        gl_texture_info* info = m_textures.get( t );
135        if ( info )
136        {
137                if ( info->glid != 0 )
138                {
139                        glDeleteTextures( 1, &(info->glid) );
140                }
141                m_textures.destroy( t );
142        }
143}
144
145void nv::gl_device::release( buffer b )
146{
147        gl_buffer_info* info = m_buffers.get( b );
148        if ( info )
149        {
150                if ( info->glid != 0 )
151                {
152                        glDeleteBuffers( 1, &(info->glid) );
153                }
154                m_buffers.destroy( b );
155        }
156}
157
158const texture_info* nv::gl_device::get_texture_info( texture t ) const
159{
160        return m_textures.get( t );
161}
162
163nv::buffer nv::gl_device::create_buffer( buffer_type type, buffer_hint hint )
164{
165        unsigned glid = 0;
166        glGenBuffers( 1, &glid );
167
168        buffer result = m_buffers.create();
169        gl_buffer_info* info = m_buffers.get( result );
170        info->type = type;
171        info->hint = hint;
172        info->size = 0;
173        info->glid = glid;
174        return result;
175}
176
177void nv::gl_device::attach( program p, shader s )
178{
179        gl_program_info* pinfo = m_programs.get( p );
180        gl_shader_info*  sinfo = m_shaders.get( s );
181
182        if ( sinfo && pinfo )
183        {
184                glAttachShader( pinfo->glid, sinfo->glid );
185                sinfo->ref++;
186        }
187
188}
189
190void nv::gl_device::detach( program p, shader s )
191{
192        gl_program_info* pinfo = m_programs.get( p );
193        gl_shader_info*  sinfo = m_shaders.get( s );
194        if ( sinfo && pinfo )
195        {
196                glDetachShader( pinfo->glid, sinfo->glid );
197                sinfo->ref--;
198        }
199}
200const buffer_info* nv::gl_device::get_buffer_info( buffer t ) const
201{
202        return m_buffers.get( t );
203}
204
205void nv::gl_device::release( program p )
206{
207        gl_program_info* info = m_programs.get( p );
208        if ( info )
209        {
210                for ( auto& i : *info->m_uniform_map )
211                        delete i.second;
212
213                detach( p, info->vertex );
214                detach( p, info->fragment );
215                glDeleteProgram( info->glid );
216
217                delete info->m_attribute_map;
218                delete info->m_engine_uniforms;
219                delete info->m_uniform_map;
220
221                m_programs.destroy( p );
222        }
223}
224
225void nv::gl_device::release( shader s )
226{
227        gl_shader_info* info = m_shaders.get( s );
228        if ( info && info->ref == 0 )
229        {
230                glDeleteShader( info->glid );
231                m_shaders.destroy( s );
232        }
233}
234
235
236nv::gl_texture_info* nv::gl_device::get_full_texture_info( texture t )
237{
238        return m_textures.get( t );
239
240}
241
242nv::gl_buffer_info* nv::gl_device::get_full_buffer_info( buffer t )
243{
244        return m_buffers.get( t );
245}
246
247void nv::gl_device::prepare_program( program p )
248{
249        gl_program_info* info = m_programs.get( p );
250        if ( info )
251        {
252                auto& map  = get_uniform_factory();
253                auto& lmap = get_link_uniform_factory();
254
255                for ( auto& i : *info->m_uniform_map )
256                {
257                        auto j = lmap.find( i.first );
258                        if ( j != lmap.end() )
259                        {
260                                j->second->set( i.second );
261                        }                       
262
263                        auto k = map.find( i.first );
264                        if ( k != map.end() )
265                        {
266                                info->m_engine_uniforms->push_back( k->second->create( i.second ) );
267                        }                               
268                }
269        }
270}
271
272uniform_base* nv::gl_device::get_uniform( program p, const string_view& name, bool fatal /*= true */ ) const
273{
274        const gl_program_info* info = m_programs.get( p );
275        {
276                nv::uniform_map::const_iterator i = info->m_uniform_map->find( name );
277                if ( i != info->m_uniform_map->end() )
278                {
279                        return i->second;
280                }
281                if ( fatal )
282                {
283                        NV_LOG_CRITICAL( "gl_device : uniform '", name, "' not found in program!" );
284                        NV_ABORT( "gl_device : uniform not found!" );
285                }
286        }
287        return nullptr;
288}
289
290int nv::gl_device::get_attribute_location( program p, const string_view& name, bool fatal /*= true */ ) const
291{
292        const gl_program_info* info = m_programs.get( p );
293        if ( info )
294        {
295                attribute_map::const_iterator i = info->m_attribute_map->find( name );
296                if ( i != info->m_attribute_map->end() )
297                {
298                        return i->second.location;
299                }
300                if ( fatal )
301                {
302                        NV_LOG_CRITICAL( "gl_device : attribute '", name, "' not found in program!" );
303                        NV_ABORT( "gl_device : attribute not found!" );
304                }
305        }
306        return -1;
307}
308
309bool nv::gl_device::bind_block( program p, const string_view& name, uint32 index )
310{
311        const gl_program_info* info = m_programs.get( p );
312        if ( info )
313        {
314                int id = get_block_location( p, name, false );
315                if ( id < 0 ) return false;
316                glUniformBlockBinding( info->glid, unsigned( id ), index );
317                return true;
318        }
319        return false;
320}
321
322int nv::gl_device::get_block_location( program p, const string_view& name, bool fatal /*= true */ ) const
323{
324        const gl_program_info* info = m_programs.get( p );
325        if ( info )
326        {
327                GLuint result = glGetUniformBlockIndex( info->glid, name.data() );
328                if ( result != GL_INVALID_INDEX ) return static_cast<int>( result );
329                if ( fatal )
330                {
331                        NV_LOG_CRITICAL( "gl_device : block '", name, "' not found in program!" );
332                        NV_ABORT( "gl_device : block not found!" );
333                }
334        }
335        return -1;
336}
337
338bool nv::gl_device::compile( program pp, shader vp, shader fp )
339{
340        gl_program_info* p = m_programs.get( pp );
341        p->vertex = vp;
342        p->fragment = fp;
343
344        glBindAttribLocation( p->glid, static_cast<GLuint>( slot::POSITION   ), "nv_position"  );
345        glBindAttribLocation( p->glid, static_cast<GLuint>( slot::TEXCOORD   ), "nv_texcoord"  );
346        glBindAttribLocation( p->glid, static_cast<GLuint>( slot::NORMAL     ), "nv_normal"    );
347        glBindAttribLocation( p->glid, static_cast<GLuint>( slot::COLOR      ), "nv_color"     );
348        glBindAttribLocation( p->glid, static_cast<GLuint>( slot::TANGENT    ), "nv_tangent"   );
349        glBindAttribLocation( p->glid, static_cast<GLuint>( slot::BONEINDEX  ), "nv_boneindex" );
350        glBindAttribLocation( p->glid, static_cast<GLuint>( slot::BONEWEIGHT ), "nv_boneweight");
351
352        attach( pp, p->vertex );
353        attach( pp, p->fragment );
354        glLinkProgram( p->glid );
355
356        const uint32 buffer_size = 2048;
357        char buffer[ buffer_size ] = { 0 };
358        int length;
359        int status;
360
361        glGetProgramiv( p->glid, GL_LINK_STATUS, &status );
362        glGetProgramInfoLog( p->glid, buffer_size, &length, buffer );
363
364        NV_LOG_INFO( "Program #", p->glid, (status == GL_FALSE ? " failed to compile!" : " compiled successfully.") );
365
366        if ( length > 0 )
367        {
368                NV_LOG_INFO( "Program #", p->glid, " log: ", string_view( buffer, size_t( length ) ) );
369        }
370
371        if ( status == GL_FALSE )
372        {
373                return false;
374        }
375
376        load_attributes( p );
377        load_uniforms( p );
378        return true;
379}
380
381void nv::gl_device::update_uniforms( gl_program_info* p )
382{
383        for ( auto& i : *p->m_uniform_map )
384        {
385                uniform_base* ubase = i.second;
386                if ( ubase->is_dirty() )
387                {
388                        GLint   uloc = ubase->get_location();
389                        GLsizei size = static_cast<GLsizei>( ubase->get_length() );
390                        switch( ubase->get_type() )
391                        {
392                        case FLOAT          : glUniform1fv( uloc, size, static_cast< uniform< enum_to_type< FLOAT >::type >*>( ubase )->get_value() ); break;
393                        case INT            : glUniform1iv( uloc, size, static_cast< uniform< enum_to_type< INT >::type >*>( ubase )->get_value() ); break;
394                        case FLOAT_VECTOR_2 : glUniform2fv( uloc, size, reinterpret_cast<const GLfloat*>( static_cast< uniform< enum_to_type< FLOAT_VECTOR_2 >::type >*>( ubase )->get_value())); break;
395                        case FLOAT_VECTOR_3 : glUniform3fv( uloc, size, reinterpret_cast<const GLfloat*>( static_cast< uniform< enum_to_type< FLOAT_VECTOR_3 >::type >*>( ubase )->get_value())); break;
396                        case FLOAT_VECTOR_4 : glUniform4fv( uloc, size, reinterpret_cast<const GLfloat*>( static_cast< uniform< enum_to_type< FLOAT_VECTOR_4 >::type >*>( ubase )->get_value())); break;
397                        case INT_VECTOR_2   : glUniform2iv( uloc, size, reinterpret_cast<const GLint*>( static_cast< uniform< enum_to_type< INT_VECTOR_2 >::type >*>( ubase )->get_value())); break;
398                        case INT_VECTOR_3   : glUniform3iv( uloc, size, reinterpret_cast<const GLint*>( static_cast< uniform< enum_to_type< INT_VECTOR_3 >::type >*>( ubase )->get_value())); break;
399                        case INT_VECTOR_4   : glUniform4iv( uloc, size, reinterpret_cast<const GLint*>( static_cast< uniform< enum_to_type< INT_VECTOR_4 >::type >*>( ubase )->get_value())); break;
400                        case FLOAT_MATRIX_2 : glUniformMatrix2fv( uloc, size, GL_FALSE, reinterpret_cast<const GLfloat*>( static_cast< uniform< enum_to_type< FLOAT_MATRIX_2 >::type >*>( ubase )->get_value())); break;
401                        case FLOAT_MATRIX_3 : glUniformMatrix3fv( uloc, size, GL_FALSE, reinterpret_cast<const GLfloat*>( static_cast< uniform< enum_to_type< FLOAT_MATRIX_3 >::type >*>( ubase )->get_value())); break;
402                        case FLOAT_MATRIX_4 : glUniformMatrix4fv( uloc, size, GL_FALSE, reinterpret_cast<const GLfloat*>( static_cast< uniform< enum_to_type< FLOAT_MATRIX_4 >::type >*>( ubase )->get_value())); break;
403                        default : break; // error?
404                        }
405                        ubase->clean();
406                }
407        }
408}
409
410void nv::gl_device::load_attributes( gl_program_info* p )
411{
412        int params;
413        glGetProgramiv( p->glid, GL_ACTIVE_ATTRIBUTES, &params );
414
415        for ( unsigned i = 0; i < unsigned( params ); ++i )
416        {
417                int attr_nlen;
418                int attr_len;
419                unsigned attr_type;
420                char name_buffer[128];
421
422                glGetActiveAttrib( p->glid, i, 128, &attr_nlen, &attr_len, &attr_type, name_buffer );
423
424                string_view name( name_buffer, size_t( attr_nlen ) );
425
426                // skip built-ins
427                if ( name.substr(0,3) == "gl_" ) continue;
428
429                int attr_loc = glGetAttribLocation( p->glid, name.data() );
430
431                attribute& attr = (*p->m_attribute_map)[ name ];
432                attr.location = attr_loc;
433                attr.type     = gl_enum_to_datatype( attr_type );
434                attr.length   = attr_len;
435        }
436}
437
438void nv::gl_device::load_uniforms( gl_program_info* p )
439{
440        int params;
441        int bparams;
442        glGetProgramiv( p->glid, GL_ACTIVE_UNIFORMS, &params );
443        glGetProgramiv( p->glid, GL_ACTIVE_UNIFORM_BLOCKS, &bparams );
444
445        for ( unsigned i = 0; i < unsigned( params ); ++i )
446        {
447                int uni_nlen;
448                int uni_len;
449                unsigned uni_type;
450                char name_buffer[128];
451
452                glGetActiveUniform( p->glid, i, 128, &uni_nlen, &uni_len, &uni_type, name_buffer );
453
454                string_view name( name_buffer, size_t( uni_nlen ) );
455
456                // skip built-ins
457                if ( name.substr(0,3) == "gl_" ) continue;
458
459                int uni_loc = glGetUniformLocation( p->glid, name.data() );
460                datatype utype = gl_enum_to_datatype( uni_type );
461
462                // check for array
463                size_t arrchar = name.find( '[' );
464                if ( arrchar != string_view::npos )
465                {
466                        name = name.substr( 0, arrchar );
467                }
468
469                uniform_base* u = uniform_base::create( utype, uni_loc, size_t( uni_len ) );
470                NV_ASSERT( u, "Unknown uniform type!" );
471                (*p->m_uniform_map)[ name ] = u;
472                //NV_LOG_DEBUG( "Uniform : ", name, " - ", utype, "/", uni_len );
473
474        }
475
476        for ( unsigned i = 0; i < unsigned( bparams ); ++i )
477        {
478                int uni_len;
479                char name_buffer[128];
480
481                glGetActiveUniformBlockName( p->glid, i, 128, &uni_len, name_buffer );
482                NV_LOG_INFO( string_view( name_buffer, size_t( uni_len ) ) );
483        }
484}
485
486bool nv::gl_device::compile( uint32 sh_type, string_view shader_code, unsigned& glid )
487{
488        glid = glCreateShader( sh_type );
489
490        const char* pc = shader_code.data();
491        int l = int( shader_code.length() );
492
493        glShaderSource( glid, 1, &pc, &l );
494        glCompileShader( glid );
495
496        const uint32 buffer_size = 1024;
497        char buffer[ buffer_size ] = { 0 };
498        int length;
499        int compile_ok = GL_FALSE;
500        glGetShaderiv(glid, GL_COMPILE_STATUS, &compile_ok);
501        glGetShaderInfoLog( glid, buffer_size, &length, buffer );
502
503        if ( length > 0 )
504        {
505                if ( compile_ok == 0 )
506                {
507                        NV_LOG_ERROR( "Shader #", glid, " error: ", string_view( buffer, size_t( length ) ) );
508                }
509                else
510                {
511                        NV_LOG_INFO( "Shader #", glid, " compiled successfully: ", string_view( buffer, size_t( length ) ) );
512                }
513        }
514        else
515        {
516                NV_LOG_INFO( "Shader #", glid, " compiled successfully." );
517        }
518        return compile_ok != 0;
519
520}
521
Note: See TracBrowser for help on using the repository browser.