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

Last change on this file since 313 was 313, checked in by epyon, 11 years ago
  • cleanup of context and device interfaces
  • create_vertex_array moved to context (as it's context bound)
  • added partial framebuffer functions to context
File size: 13.4 KB
RevLine 
[38]1// Copyright (C) 2012-2013 Kornel Kisielewicz
2// This file is part of NV Libraries.
3// For conditions of distribution and use, see copyright notice in nv.hh
4
5#include "nv/gl/gl_device.hh"
6
7#include "nv/gl/gl_window.hh"
8#include "nv/logging.hh"
[170]9#include "nv/lib/sdl.hh"
[90]10#include "nv/lib/sdl_image.hh"
[301]11#include "nv/gl/gl_enum.hh"
12#include "nv/lib/gl.hh"
[38]13
14using namespace nv;
15
[228]16window* gl_device::create_window( uint16 width, uint16 height, bool fullscreen )
[38]17{
[228]18        return new gl_window( this, width, height, fullscreen );
[38]19}
20
[245]21window* nv::gl_device::adopt_window( void* sys_w_handle, void* sys_dc )
22{
23        return new gl_window( this, sys_w_handle, sys_dc );
24}
25
26
27
[38]28gl_device::gl_device()
29{
30        nv::load_sdl_library();
31        m_info = NULL;
32
[184]33        if ( SDL_Init( SDL_INIT_VIDEO | SDL_INIT_JOYSTICK ) < 0 )
[38]34        {
35                NV_LOG( LOG_CRITICAL, "Video initialization failed: " << SDL_GetError( ) );
36                return; // TODO: Error report
37        }
38
[171]39#if NV_SDL_VERSION == NV_SDL_12
[38]40        m_info = SDL_GetVideoInfo( );
41
42        if ( !m_info )
43        {
44                NV_LOG( LOG_CRITICAL, "Video query failed: " << SDL_GetError( ) );
45                return; // TODO: Error report
46        }
[171]47#endif
[38]48
49}
50
[303]51program gl_device::create_program( const string& vs_source, const string& fs_source )
[38]52{
[303]53        program result = m_programs.create();
54        gl_program_info* info = m_programs.get( result );
55
56        info->glid = glCreateProgram();
57        compile( info, vs_source, fs_source );
58        prepare_program( result );
59        return result;
[38]60}
61
[90]62// this is a temporary function that will be removed once we find a way to
63// pass binary file data around
64image_data* nv::gl_device::create_image_data( const std::string& filename )
65{
66        load_sdl_image_library();
67        SDL_Surface* image = IMG_Load( filename.c_str() );
[120]68        if (!image)
69        {
70                NV_LOG( LOG_ERROR, "Image file " << filename.c_str() << " not found!" );
71                return nullptr;
72        }
[292]73        // TODO: BGR vs RGB, single channel
74        assert( image->format->BytesPerPixel > 2 );
75        image_format format(image->format->BytesPerPixel == 3 ? RGB : RGBA, UBYTE );
76        image_data* data = new image_data( format, glm::ivec2( image->w, image->h ), (nv::uint8*)image->pixels );
[90]77        return data;
78}
79
[92]80uint32 gl_device::get_ticks()
81{
82        return SDL_GetTicks();
83}
84
85void gl_device::delay( uint32 ms )
86{
87        return SDL_Delay( ms );
88}
89
[38]90gl_device::~gl_device()
91{
[302]92        while ( m_textures.size() > 0 )
93                release( m_textures.get_handle(0) );
94        while ( m_buffers.size() > 0 )
95                release( m_buffers.get_handle(0) );
[303]96        while ( m_programs.size() > 0 )
97                release( m_programs.get_handle(0) );
[38]98        SDL_Quit();
99}
[301]100
101nv::texture nv::gl_device::create_texture( ivec2 size, image_format aformat, sampler asampler, void* data /*= nullptr */ )
102{
103        unsigned glid = 0;
104        glGenTextures( 1, &glid );
105
106        glBindTexture( GL_TEXTURE_2D, glid );
107
108        // Detect if mipmapping was requested
109        if (( asampler.filter_min != sampler::LINEAR && asampler.filter_min != sampler::NEAREST ) ||
110                ( asampler.filter_max != sampler::LINEAR && asampler.filter_max != sampler::NEAREST ))
111        {
112                glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP, GL_TRUE);
113        }
114
115        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, (int)nv::sampler_filter_to_enum( asampler.filter_min ) );
116        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, (int)nv::sampler_filter_to_enum( asampler.filter_max ) );
117        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, (int)nv::sampler_wrap_to_enum( asampler.wrap_s) );
118        glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, (int)nv::sampler_wrap_to_enum( asampler.wrap_t) );
119
120        if (data)
121        {
122                glTexImage2D( GL_TEXTURE_2D, 0, (GLint)nv::image_format_to_enum(aformat.format), size.x, size.y, 0, nv::image_format_to_enum(aformat.format), nv::datatype_to_gl_enum(aformat.type), data );
123        }
124
125        glBindTexture( GL_TEXTURE_2D, 0 );
126
127        texture result = m_textures.create();
128        gl_texture_info* info = m_textures.get( result );
129        info->format  = aformat;
130        info->sampler = asampler;
131        info->size    = size;
132        info->glid    = glid;
133        return result;
134}
135
[302]136void nv::gl_device::release( texture t )
[301]137{
138        gl_texture_info* info = m_textures.get( t );
139        if ( info )
140        {
[302]141                if ( info->glid != 0 )
142                {
143                        glDeleteTextures( 1, &(info->glid) );
144                }
[301]145                m_textures.destroy( t );
146        }
147}
148
[302]149void nv::gl_device::release( buffer b )
150{
151        gl_buffer_info* info = m_buffers.get( b );
152        if ( info )
153        {
154                if ( info->glid != 0 )
155                {
156                        glDeleteBuffers( 1, &(info->glid) );
157                }
158                m_buffers.destroy( b );
159        }
160}
161
[303]162const texture_info* nv::gl_device::get_texture_info( texture t ) const
[301]163{
164        return m_textures.get( t );
165}
166
[302]167nv::buffer nv::gl_device::create_buffer( buffer_type type, buffer_hint hint, size_t size, const void* source /*= nullptr */ )
168{
169        unsigned glid   = 0;
170        unsigned glenum = buffer_type_to_enum( type );
171        glGenBuffers( 1, &glid );
172
173        glBindBuffer( glenum, glid );
174        glBufferData( glenum, (GLsizeiptr)size, source, buffer_hint_to_enum( hint ) );
175        glBindBuffer( glenum, 0 );
176
177        buffer result = m_buffers.create();
178        gl_buffer_info* info = m_buffers.get( result );
179        info->type = type;
180        info->hint = hint;
181        info->size = size;
182        info->glid = glid;
183        return result;
184}
185
[303]186const buffer_info* nv::gl_device::get_buffer_info( buffer t ) const
[302]187{
188        return m_buffers.get( t );
189}
[303]190
191void nv::gl_device::release( program p )
192{
193        gl_program_info* info = m_programs.get( p );
194        if ( info )
195        {
196                for ( auto& i : info->m_uniform_map )
197                        delete i.second;
198
199                glDetachShader( info->glid, info->glidv );
200                glDetachShader( info->glid, info->glidf );
201                glDeleteShader( info->glidv );
202                glDeleteShader( info->glidf );
203                glDeleteProgram( info->glid );
204
205                m_programs.destroy( p );
206        }
207}
208
209void nv::gl_device::prepare_program( program p )
210{
211        gl_program_info* info = m_programs.get( p );
212        if ( info )
213        {
214                auto& map  = get_uniform_factory();
215                auto& lmap = get_link_uniform_factory();
216
217                for ( auto& i : info->m_uniform_map )
218                {
219                        auto j = lmap.find( i.first );
220                        if ( j != lmap.end() )
221                        {
222                                j->second->set( i.second );
223                        }                       
224
225                        auto k = map.find( i.first );
226                        if ( k != map.end() )
227                        {
228                                info->m_engine_uniforms.push_back( k->second->create( i.second ) );
229                        }                               
230                }
231        }
232}
233
234uniform_base* nv::gl_device::get_uniform( program p, const string& name, bool fatal /*= true */ ) const
235{
236        const gl_program_info* info = m_programs.get( p );
237        {
238                uniform_map::const_iterator i = info->m_uniform_map.find( name );
239                if ( i != info->m_uniform_map.end() )
240                {
241                        return i->second;
242                }
243                if ( fatal )
244                {
245                        NV_LOG( LOG_ERROR, "Uniform '" << name << "' not found in program!" );
246                        NV_THROW( runtime_error, ( "Uniform '"+name+"' not found!" ) );
247                }
248        }
249        return nullptr;
250}
251
252int nv::gl_device::get_attribute_location( program p, const string& name, bool fatal /*= true */ ) const
253{
254        const gl_program_info* info = m_programs.get( p );
255        if ( info )
256        {
257                attribute_map::const_iterator i = info->m_attribute_map.find( name );
258                if ( i != info->m_attribute_map.end() )
259                {
260                        return i->second.location;
261                }
262                if ( fatal )
263                {
264                        NV_LOG( LOG_ERROR, "Attribute '" << name << "' not found in program!" );
265                        NV_THROW( runtime_error, ( "Attribute '"+name+"' not found!" ) );
266                }
267        }
268        return -1;
269}
270
271bool nv::gl_device::compile( gl_program_info* p, const string& vertex_program, const string& fragment_program )
272{
273        if (!compile( GL_VERTEX_SHADER,   vertex_program, p->glidv ))   { return false; }
274        if (!compile( GL_FRAGMENT_SHADER, fragment_program, p->glidf )) { return false; }
275
276        glBindAttribLocation( p->glid, static_cast<GLuint>( slot::POSITION   ), "nv_position"  );
277        glBindAttribLocation( p->glid, static_cast<GLuint>( slot::TEXCOORD   ), "nv_texcoord"  );
278        glBindAttribLocation( p->glid, static_cast<GLuint>( slot::NORMAL     ), "nv_normal"    );
279        glBindAttribLocation( p->glid, static_cast<GLuint>( slot::COLOR      ), "nv_color"     );
280        glBindAttribLocation( p->glid, static_cast<GLuint>( slot::TANGENT    ), "nv_tangent"   );
281        glBindAttribLocation( p->glid, static_cast<GLuint>( slot::BONEINDEX  ), "nv_boneindex" );
282        glBindAttribLocation( p->glid, static_cast<GLuint>( slot::BONEWEIGHT ), "nv_boneweight");
283
284        glAttachShader( p->glid, p->glidf );
285        glAttachShader( p->glid, p->glidv );
286        glLinkProgram( p->glid );
287
288        const uint32 buffer_size = 2048;
289        char buffer[ buffer_size ] = { 0 };
290        int length;
291        int status;
292
293        glGetProgramiv( p->glid, GL_LINK_STATUS, &status );
294        glGetProgramInfoLog( p->glid, buffer_size, &length, buffer );
295
296        NV_LOG( LOG_INFO, "Program #" << p->glid << (status == GL_FALSE ? " failed to compile!" : " compiled successfully.") );
297
298        if ( length > 0 )
299        {
300                NV_LOG( LOG_INFO, "Program #" << p->glid << " log: " << buffer );
301        }
302
303        if ( status == GL_FALSE )
304        {
305                return false;
306        }
307
308        glValidateProgram( p->glid );
309        glGetProgramiv( p->glid, GL_VALIDATE_STATUS, &status );
310
311        if ( status == GL_FALSE )
312        {
313                glGetProgramInfoLog( p->glid, buffer_size, &length, buffer );
314                NV_LOG( LOG_ERROR, "Program #" << p->glid << " validation error : " << buffer );
315                return false;
316        }
317        load_attributes( p );
318        load_uniforms( p );
319        return true;
320}
321
322void nv::gl_device::update_uniforms( gl_program_info* p )
323{
324        for ( uniform_map::iterator i = p->m_uniform_map.begin();       i != p->m_uniform_map.end(); ++i )
325        {
326                uniform_base* ubase = i->second;
327                if ( ubase->is_dirty() )
328                {
329                        int uloc = ubase->get_location();
330                        switch( ubase->get_type() )
331                        {
332                        case FLOAT          : glUniform1fv( uloc, ubase->get_length(), ((uniform< enum_to_type< FLOAT >::type >*)( ubase ))->get_value() ); break;
333                        case INT            : glUniform1iv( uloc, ubase->get_length(), ((uniform< enum_to_type< INT >::type >*)( ubase ))->get_value() ); break;
334                        case FLOAT_VECTOR_2 : glUniform2fv( uloc, ubase->get_length(), (GLfloat*)((uniform< enum_to_type< FLOAT_VECTOR_2 >::type >*)( ubase ))->get_value()); break;
335                        case FLOAT_VECTOR_3 : glUniform3fv( uloc, ubase->get_length(), (GLfloat*)((uniform< enum_to_type< FLOAT_VECTOR_3 >::type >*)( ubase ))->get_value()); break;
336                        case FLOAT_VECTOR_4 : glUniform4fv( uloc, ubase->get_length(), (GLfloat*)((uniform< enum_to_type< FLOAT_VECTOR_4 >::type >*)( ubase ))->get_value()); break;
337                        case INT_VECTOR_2   : glUniform2iv( uloc, ubase->get_length(), (GLint*)((uniform< enum_to_type< INT_VECTOR_2 >::type >*)( ubase ))->get_value()); break;
338                        case INT_VECTOR_3   : glUniform3iv( uloc, ubase->get_length(), (GLint*)((uniform< enum_to_type< INT_VECTOR_3 >::type >*)( ubase ))->get_value()); break;
339                        case INT_VECTOR_4   : glUniform4iv( uloc, ubase->get_length(), (GLint*)((uniform< enum_to_type< INT_VECTOR_4 >::type >*)( ubase ))->get_value()); break;
340                        case FLOAT_MATRIX_2 : glUniformMatrix2fv( uloc, ubase->get_length(), GL_FALSE, (GLfloat*)((uniform< enum_to_type< FLOAT_MATRIX_2 >::type >*)( ubase ))->get_value()); break;
341                        case FLOAT_MATRIX_3 : glUniformMatrix3fv( uloc, ubase->get_length(), GL_FALSE, (GLfloat*)((uniform< enum_to_type< FLOAT_MATRIX_3 >::type >*)( ubase ))->get_value()); break;
342                        case FLOAT_MATRIX_4 : glUniformMatrix4fv( uloc, ubase->get_length(), GL_FALSE, (GLfloat*)((uniform< enum_to_type< FLOAT_MATRIX_4 >::type >*)( ubase ))->get_value()); break;
343                        default : break; // error?
344                        }
345                        ubase->clean();
346                }
347        }
348}
349
350void nv::gl_device::load_attributes( gl_program_info* p )
351{
352        int params;
353        glGetProgramiv( p->glid, GL_ACTIVE_ATTRIBUTES, &params );
354
355        for ( unsigned i = 0; i < (unsigned)params; ++i )
356        {
357                int attr_nlen;
358                int attr_len;
359                unsigned attr_type;
360                char name_buffer[128];
361
362                glGetActiveAttrib( p->glid, i, 128, &attr_nlen, &attr_len, &attr_type, name_buffer );
363
364                string name( name_buffer, size_t(attr_nlen) );
365
366                // skip built-ins
367                if ( name.substr(0,3) == "gl_" ) continue;
368
369                int attr_loc = glGetAttribLocation( p->glid, name.c_str() );
370
371                attribute& attr = p->m_attribute_map[ name ];
372                attr.name     = name;
373                attr.location = attr_loc;
374                attr.type     = gl_enum_to_datatype( attr_type );
375                attr.length   = attr_len;
376        }
377}
378
379void nv::gl_device::load_uniforms( gl_program_info* p )
380{
381        int params;
382        glGetProgramiv( p->glid, GL_ACTIVE_UNIFORMS, &params );
383
384        for ( unsigned i = 0; i < size_t(params); ++i )
385        {
386                int uni_nlen;
387                int uni_len;
388                unsigned uni_type;
389                char name_buffer[128];
390
391                glGetActiveUniform( p->glid, i, 128, &uni_nlen, &uni_len, &uni_type, name_buffer );
392
393                string name( name_buffer, size_t(uni_nlen) );
394
395                // skip built-ins
396                if ( name.substr(0,3) == "gl_" ) continue;
397
398                int uni_loc = glGetUniformLocation( p->glid, name.c_str() );
399                datatype utype = gl_enum_to_datatype( uni_type );
400
401                // check for array
402                string::size_type arrchar = name.find('[');
403                if ( arrchar != string::npos )
404                {
405                        name = name.substr( 0, arrchar );
406                }
407
408                uniform_base* u = uniform_base::create( utype, name, uni_loc, uni_len );
409                NV_ASSERT( u, "Unknown uniform type!" );
410                p->m_uniform_map[ name ] = u;
411        }
412}
413
414bool nv::gl_device::compile( uint32 sh_type, const std::string& shader_code, unsigned& glid )
415{
416        glid = glCreateShader( sh_type );
417
418        const char* pc = shader_code.c_str();
419
420        glShaderSource( glid,   1, &pc, 0 );
421        glCompileShader( glid );
422
423        const uint32 buffer_size = 1024;
424        char buffer[ buffer_size ] = { 0 };
425        int length;
426        int compile_ok = GL_FALSE;
427        glGetShaderiv(glid, GL_COMPILE_STATUS, &compile_ok);
428        glGetShaderInfoLog( glid, buffer_size, &length, buffer );
429
430        if ( length > 0 )
431        {
432                if ( compile_ok == 0 )
433                {
434                        NV_LOG( LOG_ERROR, "Shader #" << glid << " error: " << buffer );
435                }
436                else
437                {
438                        NV_LOG( LOG_INFO, "Shader #" << glid << " compiled successfully: " << buffer );
439                }
440        }
441        else
442        {
443                NV_LOG( LOG_INFO, "Shader #" << glid << " compiled successfully." );
444        }
445        return compile_ok != 0;
446
447}
448
Note: See TracBrowser for help on using the repository browser.