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

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