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

Last change on this file since 504 was 501, checked in by epyon, 9 years ago
  • particle engine updates
  • device/context redesign
  • caching of GL state - texture bindings and programs
  • camera view_perspective and view_perspective_inv
File size: 14.2 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        unsigned glenum = buffer_type_to_enum( type );
148        glGenBuffers( 1, &glid );
149
150        buffer result = m_buffers.create();
151        gl_buffer_info* info = m_buffers.get( result );
152        info->type = type;
153        info->hint = hint;
154        info->size = 0;
155        info->glid = glid;
156        return result;
157}
158
159const buffer_info* nv::gl_device::get_buffer_info( buffer t ) const
160{
161        return m_buffers.get( t );
162}
163
164void nv::gl_device::release( program p )
165{
166        gl_program_info* info = m_programs.get( p );
167        if ( info )
168        {
169                for ( auto& i : *info->m_uniform_map )
170                        delete i.second;
171
172                glDetachShader( info->glid, info->glidv );
173                glDetachShader( info->glid, info->glidf );
174                glDeleteShader( info->glidv );
175                glDeleteShader( info->glidf );
176                glDeleteProgram( info->glid );
177
178                delete info->m_attribute_map;
179                delete info->m_engine_uniforms;
180                delete info->m_uniform_map;
181
182                m_programs.destroy( p );
183        }
184}
185
186nv::gl_texture_info* nv::gl_device::get_full_texture_info( texture t )
187{
188        return m_textures.get( t );
189
190}
191
192nv::gl_buffer_info* nv::gl_device::get_full_buffer_info( buffer t )
193{
194        return m_buffers.get( t );
195}
196
197void nv::gl_device::prepare_program( program p )
198{
199        gl_program_info* info = m_programs.get( p );
200        if ( info )
201        {
202                auto& map  = get_uniform_factory();
203                auto& lmap = get_link_uniform_factory();
204
205                for ( auto& i : *info->m_uniform_map )
206                {
207                        auto j = lmap.find( i.first );
208                        if ( j != lmap.end() )
209                        {
210                                j->second->set( i.second );
211                        }                       
212
213                        auto k = map.find( i.first );
214                        if ( k != map.end() )
215                        {
216                                info->m_engine_uniforms->push_back( k->second->create( i.second ) );
217                        }                               
218                }
219        }
220}
221
222uniform_base* nv::gl_device::get_uniform( program p, const string_view& name, bool fatal /*= true */ ) const
223{
224        const gl_program_info* info = m_programs.get( p );
225        {
226                nv::uniform_map::const_iterator i = info->m_uniform_map->find( name );
227                if ( i != info->m_uniform_map->end() )
228                {
229                        return i->second;
230                }
231                if ( fatal )
232                {
233                        NV_LOG_CRITICAL( "gl_device : uniform '", name, "' not found in program!" );
234                        NV_ABORT( "gl_device : uniform not found!" );
235                }
236        }
237        return nullptr;
238}
239
240int nv::gl_device::get_attribute_location( program p, const string_view& name, bool fatal /*= true */ ) const
241{
242        const gl_program_info* info = m_programs.get( p );
243        if ( info )
244        {
245                attribute_map::const_iterator i = info->m_attribute_map->find( name );
246                if ( i != info->m_attribute_map->end() )
247                {
248                        return i->second.location;
249                }
250                if ( fatal )
251                {
252                        NV_LOG_CRITICAL( "gl_device : attribute '", name, "' not found in program!" );
253                        NV_ABORT( "gl_device : attribute not found!" );
254                }
255        }
256        return -1;
257}
258
259bool nv::gl_device::bind_block( program p, const string_view& name, uint32 index )
260{
261        const gl_program_info* info = m_programs.get( p );
262        if ( info )
263        {
264                int id = get_block_location( p, name, false );
265                if ( id < 0 ) return false;
266                glUniformBlockBinding( info->glid, unsigned( id ), index );
267                return true;
268        }
269        return false;
270}
271
272int nv::gl_device::get_block_location( program p, const string_view& name, bool fatal /*= true */ ) const
273{
274        const gl_program_info* info = m_programs.get( p );
275        if ( info )
276        {
277                GLuint result = glGetUniformBlockIndex( info->glid, name.data() );
278                if ( result != GL_INVALID_INDEX ) return static_cast<int>( result );
279                if ( fatal )
280                {
281                        NV_LOG_CRITICAL( "gl_device : block '", name, "' not found in program!" );
282                        NV_ABORT( "gl_device : block not found!" );
283                }
284        }
285        return -1;
286}
287
288bool nv::gl_device::compile( gl_program_info* p, string_view vertex_program, string_view fragment_program )
289{
290        if (!compile( GL_VERTEX_SHADER,   vertex_program, p->glidv ))   { return false; }
291        if (!compile( GL_FRAGMENT_SHADER, fragment_program, p->glidf )) { return false; }
292
293        glBindAttribLocation( p->glid, static_cast<GLuint>( slot::POSITION   ), "nv_position"  );
294        glBindAttribLocation( p->glid, static_cast<GLuint>( slot::TEXCOORD   ), "nv_texcoord"  );
295        glBindAttribLocation( p->glid, static_cast<GLuint>( slot::NORMAL     ), "nv_normal"    );
296        glBindAttribLocation( p->glid, static_cast<GLuint>( slot::COLOR      ), "nv_color"     );
297        glBindAttribLocation( p->glid, static_cast<GLuint>( slot::TANGENT    ), "nv_tangent"   );
298        glBindAttribLocation( p->glid, static_cast<GLuint>( slot::BONEINDEX  ), "nv_boneindex" );
299        glBindAttribLocation( p->glid, static_cast<GLuint>( slot::BONEWEIGHT ), "nv_boneweight");
300
301        glAttachShader( p->glid, p->glidf );
302        glAttachShader( p->glid, p->glidv );
303        glLinkProgram( p->glid );
304
305        const uint32 buffer_size = 2048;
306        char buffer[ buffer_size ] = { 0 };
307        int length;
308        int status;
309
310        glGetProgramiv( p->glid, GL_LINK_STATUS, &status );
311        glGetProgramInfoLog( p->glid, buffer_size, &length, buffer );
312
313        NV_LOG_INFO( "Program #", p->glid, (status == GL_FALSE ? " failed to compile!" : " compiled successfully.") );
314
315        if ( length > 0 )
316        {
317                NV_LOG_INFO( "Program #", p->glid, " log: ", string_view( buffer, size_t( length ) ) );
318        }
319
320        if ( status == GL_FALSE )
321        {
322                return false;
323        }
324
325        load_attributes( p );
326        load_uniforms( p );
327        return true;
328}
329
330void nv::gl_device::update_uniforms( gl_program_info* p )
331{
332        for ( auto& i : *p->m_uniform_map )
333        {
334                uniform_base* ubase = i.second;
335                if ( ubase->is_dirty() )
336                {
337                        GLint   uloc = ubase->get_location();
338                        GLsizei size = static_cast<GLsizei>( ubase->get_length() );
339                        switch( ubase->get_type() )
340                        {
341                        case FLOAT          : glUniform1fv( uloc, size, static_cast< uniform< enum_to_type< FLOAT >::type >*>( ubase )->get_value() ); break;
342                        case INT            : glUniform1iv( uloc, size, static_cast< uniform< enum_to_type< INT >::type >*>( ubase )->get_value() ); break;
343                        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;
344                        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;
345                        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;
346                        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;
347                        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;
348                        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;
349                        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;
350                        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;
351                        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;
352                        default : break; // error?
353                        }
354                        ubase->clean();
355                }
356        }
357}
358
359void nv::gl_device::load_attributes( gl_program_info* p )
360{
361        int params;
362        glGetProgramiv( p->glid, GL_ACTIVE_ATTRIBUTES, &params );
363
364        for ( unsigned i = 0; i < unsigned( params ); ++i )
365        {
366                int attr_nlen;
367                int attr_len;
368                unsigned attr_type;
369                char name_buffer[128];
370
371                glGetActiveAttrib( p->glid, i, 128, &attr_nlen, &attr_len, &attr_type, name_buffer );
372
373                string_view name( name_buffer, size_t( attr_nlen ) );
374
375                // skip built-ins
376                if ( name.substr(0,3) == "gl_" ) continue;
377
378                int attr_loc = glGetAttribLocation( p->glid, name.data() );
379
380                attribute& attr = (*p->m_attribute_map)[ name ];
381                attr.location = attr_loc;
382                attr.type     = gl_enum_to_datatype( attr_type );
383                attr.length   = attr_len;
384        }
385}
386
387void nv::gl_device::load_uniforms( gl_program_info* p )
388{
389        int params;
390        int bparams;
391        glGetProgramiv( p->glid, GL_ACTIVE_UNIFORMS, &params );
392        glGetProgramiv( p->glid, GL_ACTIVE_UNIFORM_BLOCKS, &bparams );
393
394        for ( unsigned i = 0; i < unsigned( params ); ++i )
395        {
396                int uni_nlen;
397                int uni_len;
398                unsigned uni_type;
399                char name_buffer[128];
400
401                glGetActiveUniform( p->glid, i, 128, &uni_nlen, &uni_len, &uni_type, name_buffer );
402
403                string_view name( name_buffer, size_t( uni_nlen ) );
404
405                // skip built-ins
406                if ( name.substr(0,3) == "gl_" ) continue;
407
408                int uni_loc = glGetUniformLocation( p->glid, name.data() );
409                datatype utype = gl_enum_to_datatype( uni_type );
410
411                // check for array
412                size_t arrchar = name.find( '[' );
413                if ( arrchar != string_view::npos )
414                {
415                        name = name.substr( 0, arrchar );
416                }
417
418                uniform_base* u = uniform_base::create( utype, uni_loc, size_t( uni_len ) );
419                NV_ASSERT( u, "Unknown uniform type!" );
420                (*p->m_uniform_map)[ name ] = u;
421                //NV_LOG_DEBUG( "Uniform : ", name, " - ", utype, "/", uni_len );
422
423        }
424
425        for ( unsigned i = 0; i < unsigned( bparams ); ++i )
426        {
427                int uni_len;
428                char name_buffer[128];
429
430                glGetActiveUniformBlockName( p->glid, i, 128, &uni_len, name_buffer );
431                NV_LOG_INFO( string_view( name_buffer, size_t( uni_len ) ) );
432        }
433}
434
435bool nv::gl_device::compile( uint32 sh_type, string_view shader_code, unsigned& glid )
436{
437        glid = glCreateShader( sh_type );
438
439        const char* pc = shader_code.data();
440        int l = int( shader_code.length() );
441
442        glShaderSource( glid, 1, &pc, &l );
443        glCompileShader( glid );
444
445        const uint32 buffer_size = 1024;
446        char buffer[ buffer_size ] = { 0 };
447        int length;
448        int compile_ok = GL_FALSE;
449        glGetShaderiv(glid, GL_COMPILE_STATUS, &compile_ok);
450        glGetShaderInfoLog( glid, buffer_size, &length, buffer );
451
452        if ( length > 0 )
453        {
454                if ( compile_ok == 0 )
455                {
456                        NV_LOG_ERROR( "Shader #", glid, " error: ", string_view( buffer, size_t( length ) ) );
457                }
458                else
459                {
460                        NV_LOG_INFO( "Shader #", glid, " compiled successfully: ", string_view( buffer, size_t( length ) ) );
461                }
462        }
463        else
464        {
465                NV_LOG_INFO( "Shader #", glid, " compiled successfully." );
466        }
467        return compile_ok != 0;
468
469}
470
Note: See TracBrowser for help on using the repository browser.