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

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