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

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