将属性传递给 OpenGL 顶点着色器的行为很奇怪
Posted
技术标签:
【中文标题】将属性传递给 OpenGL 顶点着色器的行为很奇怪【英文标题】:Passing attributes to OpenGL vertex shader acts strangely 【发布时间】:2014-01-12 21:00:54 【问题描述】:问题:
结果 1: 我将顶点属性传递给着色器,程序运行 5 秒,然后显卡驱动停止响应并恢复,但程序没有。
结果 2: 我将帧速率限制在 60,然后做同样的事情。程序运行良好,但是当我尝试在同一运行时为顶点属性传递不同的值时,它不会更新几何图形(只有传递的第一个顶点属性有效)。
我正在使用 GLSL 140 的 OpenGL 3.1 版。(我的显卡/驱动程序将支持的最高版本)
我尝试过的:
互联网浏览和阅读教程。由于我不太了解 OpenGL,但我认为问题在于我只是不知道要搜索什么。
注意:抱歉,如果我有一些不好的 OpenGL 编码习惯,我仍在学习中。
代码:
opengl2_vert.glsl
#version 140
in vec4 offset;
void main(void)
// Declare a hard-coded array of positions
vec4 vertices[3] = vec4[3](vec4( 0.25, -0.25, 0.5, 1.0),
vec4(-0.25, -0.25, 0.5, 1.0),
vec4( 0.25, 0.25, 0.5, 1.0));
// Index into our array using gl_VertexID
gl_Position = vertices[gl_VertexID] - offset;
游戏.cpp
#include "Game.h"
void Game::init()
GLuint vertex_shader = getIO().loadShader("opengl2_vert.glsl", ShaderType::VERTEX);
GLuint fragment_shader = getIO().loadShader("opengl2_frag.glsl", ShaderType::FRAGMENT);
// Create program, attach shaders to it, and link it
program = glCreateProgram();
glAttachShader(program, vertex_shader);
glAttachShader(program, fragment_shader);
glLinkProgram(program);
GLint isLinked = GL_FALSE;
glGetProgramiv(program, GL_LINK_STATUS, &isLinked);
// Logging
GLint maxLength = 255;
GLint rLength = 0;
GLchar* err = new char[maxLength];
// Vertex shader
glGetShaderInfoLog(vertex_shader, maxLength, &rLength, err);
DEBUGSTR((char*)err);
// Fragment shader
glGetShaderInfoLog(vertex_shader, maxLength, &rLength, err);
DEBUGSTR((char*)err);
// Program
glGetProgramInfoLog(vertex_shader, maxLength, &rLength, err);
DEBUGSTR((char*)err);
delete [] err;
ASSERT(isLinked == GL_TRUE);
// Delete the shaders as the program has them now
glDeleteShader(vertex_shader);
glDeleteShader(fragment_shader);
glUseProgram(program);
// VAO
glGenVertexArrays(1, &vertex_array_object); // Creates a VAO
glBindVertexArray(vertex_array_object); // Attaches VAO to rendering context
void Game::render(double dt)
//DEBUG("FPS %i", static_cast<int>(1/dt));
static bool seizure = false;
seizure = !seizure;
//(seizure)?getScreen().setBackgroundColor(0.333f, 0.003f, 0.082f):getScreen().setBackgroundColor(0.803f, 0.753f, 0.573f);
static float angle = 0;
angle += dt;
//DEBUG("ANGLE %f %f", cos(angle)/2.0f, sin(angle)/2.0f);
// Use the program object we created earlier for rendering
GLfloat attrib[] = cos(angle)/2.0f, sin(angle)/2.0f, 0.0f, 0.0f;
glVertexAttrib4fv(glGetAttribLocation(program, "offset"), attrib);
// Draw one point
glDrawArrays(GL_TRIANGLES, 0, 3);
void Game::shutdown()
glDeleteProgram(program);
glDeleteVertexArrays(1, &vertex_array_object);
IO.cpp
#include "IO.h"
GLuint IO::loadShader(const char* fileName, ShaderType shaderType)
std::ifstream f(fileName, std::ifstream::binary);
ASSERT(fileName);
f.seekg(0, std::ios::end);
int length = (int)f.tellg();
f.seekg(0, std::ios::beg);
char* buffer = new char[length+1];
f.read(buffer, length);
buffer[length] = 0;
f.close();
const GLchar* in = (const GLchar *)buffer;
GLuint shader;
switch(shaderType)
case VERTEX:
shader = glCreateShader(GL_VERTEX_SHADER);
break;
case FRAGMENT:
shader = glCreateShader(GL_FRAGMENT_SHADER);
break;
glShaderSource(shader, 1, &in, NULL);
glCompileShader(shader);
// Logging
GLint maxLength = 255;
GLint rLength = 0;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &maxLength);
GLchar* err = new char[maxLength];
glGetShaderInfoLog(shader, maxLength, &rLength, err);
DEBUGSTR((char*)err);
delete [] err;
delete [] buffer;
GLint isCompiled = 0;
glGetShaderiv(shader, GL_COMPILE_STATUS, &isCompiled);
ASSERT(isCompiled == GL_TRUE);
return shader;
入口点/游戏循环
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR szCmdLine, int iCmdShow)
// Creating dummy window
HWND hWnd = getDummyWindow();
HDC hdc = GetDC(hWnd);
PIXELFORMATDESCRIPTOR pfd = getWindowsPixelFormatStruct();
int chosenPixelFormat = ChoosePixelFormat( hdc, &pfd );
ASSERT(chosenPixelFormat != 0);
int result = SetPixelFormat(hdc, chosenPixelFormat, &pfd );
ASSERT(result != NULL);
// Creating rendering context
HGLRC hglrc = wglCreateContext(hdc);
wglMakeCurrent(hdc, hglrc);
// Getting supported OpenGL version
DEBUG("System OpenGL version: %s", (char*)glGetString(GL_VERSION));
DEBUG("Windows pixel format: %i", chosenPixelFormat);
GLint major_version = 1;
GLint minor_version = 1;
glGetIntegerv(GL_MAJOR_VERSION, &major_version);
glGetIntegerv(GL_MINOR_VERSION, &minor_version);
GLenum err = glewInit();
ASSERT(GLEW_OK == err);
// Getting OpenGL pixel format
int nPixCount = 0;
// Specify the important attributes we care about
int pixAttribs[] =
WGL_SUPPORT_OPENGL_ARB, 1, // Must support OGL rendering
WGL_DRAW_TO_WINDOW_ARB, 1, // pf that can run a window
WGL_RED_BITS_ARB, 8, // At least 8 bits of red
WGL_GREEN_BITS_ARB, 8, // At least 8 bits of green
WGL_BLUE_BITS_ARB, 8, // At least 8 bits of blue
WGL_DEPTH_BITS_ARB, 16, // At least 16 bits of depth
WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB, // Must be HW accelerated
WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB, // pf should be RGBA type
WGL_DOUBLE_BUFFER_ARB, GL_TRUE,
0 ; // Zero termination
// Ask OpenGL to find the most relevant format matching our attribs
// Only get one format back.
wglChoosePixelFormatARB(hdc,
&pixAttribs[0],
NULL,
1,
&chosenPixelFormat,
(UINT*)&nPixCount);
ASSERT(chosenPixelFormat != -1);
DEBUG("OpenGL pixel format: %i", chosenPixelFormat);
// Clean up dummies
wglDeleteContext(hglrc);
ReleaseDC(hWnd, hdc);
DestroyWindow(hWnd);
// Create window
hWnd = getWindow(hInstance, TEXT("OpenGL Window"), iCmdShow);
hdc = GetDC(hWnd);
result = SetPixelFormat(hdc, chosenPixelFormat, &pfd );
ASSERT(result != NULL);
// Creating OpenGL rendering context
GLint attribs[] =
WGL_CONTEXT_MAJOR_VERSION_ARB, major_version,
WGL_CONTEXT_MINOR_VERSION_ARB, minor_version,
WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB,
0
;
DEBUG("Using OpenGL version %i.%i", major_version, minor_version);
hglrc = wglCreateContextAttribsARB(hdc, 0, attribs);
wglMakeCurrent(hdc, hglrc);
// Getting rendering dimensions
RECT rc_dimensions;
GetClientRect(hWnd, &rc_dimensions);
glViewport(0, 0, rc_dimensions.left-1, rc_dimensions.bottom-1); // set viewport
// Setting up game
Game game;
game.getScreen().setWidth(rc_dimensions.left-1);
game.getScreen().setHeight(rc_dimensions.bottom-1);
game.getScreen().setFrameCap(59.0f);
game.init();
game._getGameTimer().elapsed_time();
// Starting game loop
MSG msg;
float accum_time = 0.0f;
while(true)
if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
if(msg.message == WM_QUIT)
break;
TranslateMessage(&msg);
DispatchMessage(&msg);
accum_time += game._getGameTimer().elapsed_time();
if(accum_time > game.getScreen()._getSPF())
game.render(game.getScreen()._getSPF());
// Post render
SwapBuffers(hdc);
game.getScreen().clearBuffer();
accum_time -= game.getScreen()._getSPF();
// Cleaning up before shutdown
game.shutdown();
wglDeleteContext(hglrc);
ReleaseDC(hWnd, hdc);
DestroyWindow(hWnd);
UnregisterClass(TEXT("OPENGL"), hInstance);
return 0;
OpenGL 支持
Renderer: Intel(R) HD Graphics 3000
Vendor: Intel
Memory: 2108 MB
Version: 3.1.0 - Build 9.17.10.3347
Shading language version: 1.40 - Intel Build 9.17.10.3347
Max texture size: 8192 x 8192
Max vertex texture image units: 16
Max texture image units: 16
Max geometry texture units: 0
Max anisotropic filtering value: 16
Max viewport size: 8192 x 8192
Max Clip Distances: 6
Max samples: 4
Extensions: 129
GL_3DFX_texture_compression_FXT1
GL_ARB_color_buffer_float
GL_ARB_compatibility
GL_ARB_copy_buffer
GL_ARB_depth_buffer_float
GL_ARB_depth_clamp
GL_ARB_depth_texture
GL_ARB_draw_buffers
GL_ARB_draw_buffers_blend
GL_ARB_draw_elements_base_vertex
GL_ARB_draw_instanced
GL_ARB_explicit_attrib_location
GL_ARB_fragment_coord_conventions
GL_ARB_fragment_program
GL_ARB_fragment_program_shadow
GL_ARB_fragment_shader
GL_ARB_framebuffer_object
GL_ARB_framebuffer_sRGB
GL_ARB_half_float_pixel
GL_ARB_half_float_vertex
GL_ARB_instanced_arrays
GL_ARB_map_buffer_range
GL_ARB_multisample
GL_ARB_multitexture
GL_ARB_occlusion_query
GL_ARB_occlusion_query2
GL_ARB_pixel_buffer_object
GL_ARB_point_parameters
GL_ARB_point_sprite
GL_ARB_provoking_vertex
GL_ARB_sampler_objects
GL_ARB_seamless_cube_map
GL_ARB_shader_bit_encoding
GL_ARB_shader_objects
GL_ARB_shading_language_100
GL_ARB_shadow
GL_ARB_sync
GL_ARB_texture_border_clamp
GL_ARB_texture_buffer_object_rgb32
GL_ARB_texture_compression
GL_ARB_texture_compression_rgtc
GL_ARB_texture_cube_map
GL_ARB_texture_env_add
GL_ARB_texture_env_combine
GL_ARB_texture_env_crossbar
GL_ARB_texture_env_dot3
GL_ARB_texture_float
GL_ARB_texture_non_power_of_two
GL_ARB_texture_query_lod
GL_ARB_texture_rectangle
GL_ARB_texture_rg
GL_ARB_texture_rgb10_a2ui
GL_ARB_timer_query
GL_ARB_transpose_matrix
GL_ARB_uniform_buffer_object
GL_ARB_vertex_array_bgra
GL_ARB_vertex_array_object
GL_ARB_vertex_buffer_object
GL_ARB_vertex_program
GL_ARB_vertex_shader
GL_ARB_vertex_type_2_10_10_10_rev
GL_ARB_window_pos
GL_ATI_separate_stencil
GL_EXT_abgr
GL_EXT_bgra
GL_EXT_blend_color
GL_EXT_blend_equation_separate
GL_EXT_blend_func_separate
GL_EXT_blend_minmax
GL_EXT_blend_subtract
GL_EXT_clip_volume_hint
GL_EXT_compiled_vertex_array
GL_EXT_draw_buffers2
GL_EXT_draw_range_elements
GL_EXT_fog_coord
GL_EXT_framebuffer_blit
GL_EXT_framebuffer_multisample
GL_EXT_framebuffer_object
GL_EXT_gpu_program_parameters
GL_EXT_multi_draw_arrays
GL_EXT_packed_depth_stencil
GL_EXT_packed_float
GL_EXT_packed_pixels
GL_EXT_rescale_normal
GL_EXT_secondary_color
GL_EXT_separate_specular_color
GL_EXT_shadow_funcs
GL_EXT_stencil_two_side
GL_EXT_stencil_wrap
GL_EXT_texture3D
GL_EXT_texture_array
GL_EXT_texture_compression_s3tc
GL_EXT_texture_edge_clamp
GL_EXT_texture_env_add
GL_EXT_texture_env_combine
GL_EXT_texture_filter_anisotropic
GL_EXT_texture_integer
GL_EXT_texture_lod_bias
GL_EXT_texture_rectangle
GL_EXT_texture_shared_exponent
GL_EXT_texture_snorm
GL_EXT_texture_sRGB
GL_EXT_texture_swizzle
GL_EXT_transform_feedback
GL_IBM_texture_mirrored_repeat
GL_INTEL_map_texture
GL_INTEL_performance_queries
GL_NV_blend_square
GL_NV_conditional_render
GL_NV_primitive_restart
GL_NV_texgen_reflection
GL_SGIS_generate_mipmap
GL_SGIS_texture_edge_clamp
GL_SGIS_texture_lod
GL_WIN_swap_hint
WGL_ARB_buffer_region
WGL_ARB_create_context
WGL_ARB_extensions_string
WGL_ARB_framebuffer_sRGB
WGL_ARB_make_current_read
WGL_ARB_multisample
WGL_ARB_pbuffer
WGL_ARB_pixel_format
WGL_ARB_pixel_format_float
WGL_EXT_depth_float
WGL_EXT_extensions_string
WGL_EXT_pixel_format_packed_float
WGL_EXT_swap_control
WGL_EXT_swap_control_tear
Core features
v3.0 (100 % - 23/23)
v3.1 (100 % - 8/8)
v3.2 (70 % - 7/10)
v3.3 (70 % - 7/10)
v4.0 (21 % - 3/14)
v4.1 (0 % - 0/7)
v4.2 (0 % - 0/12)
v4.3 (0 % - 0/18)
v4.4 (0 % - 0/10)
OpenGL driver version check (Current: 3.1.0 - Build 9.17.10.3347, Latest known: 9.17.10.3347):
Outdated version of display drivers detected
According the database, you are might be not using the latest version of display drivers for your video card.
No ICD registry entry
The current OpenGL driver doesn't expose the SOFTWARE/Microsoft/Windows (NT)/CurrentVersion/OpenGLDrivers registry entry. Unable to detect the driver version, driver revision name and filename.
Extension verification:
GL_EXT_color_subtable was not found, but has the entry point glColorSubTableEXT
GL_EXT_paletted_texture was not found, but has the entry point glColorTableEXT
GL_EXT_paletted_texture was not found, but has the entry point glGetColorTableEXT
GL_EXT_paletted_texture was not found, but has the entry point glGetColorTableParameterfvEXT
GL_EXT_paletted_texture was not found, but has the entry point glGetColorTableParameterivEXT
【问题讨论】:
根据安东的建议编辑。日志输出中未发现错误。仍然有同样的问题,只是内存泄漏更少=P。 我会避免每次绘制时都获取属性位置。此功能要求您使用字符串按名称搜索(这使得它比大多数glGet...
功能更昂贵),并且在您重新链接程序之前位置永远不会改变。您应该养成在链接程序后查询这些位置并将它们存储在某处以避免这种情况的习惯。
另外,我不知道game.getScreen()._getSPF()
是如何实现的,但看起来它可能会返回一个常量值......如果它是像 2 * pi 或足够接近 0.0,那么您将有效地将相同的值传递给偏移量。
好的!我开始工作了!多亏了科尔曼先生。谢谢你。一旦我在链接程序之前添加了 glBindAttribLocation 并保存了我绑定的位置,它就开始像它应该的那样旋转。 =D
glBindAttribLocation 似乎只喜欢 1 到 15 之间的数字 >.> 如果我给它 0 它只会每 3 秒更新一次。
【参考方案1】:
有一些问题需要解决,虽然我不知道它们是否能解决你的问题。
不能保证in vec4 offset
将被分配给顶点属性位置0。您应该使用glBindAttribLocation (...)
将其位置(链接前)绑定到0,或使用@ 查询名称(链接后)的位置987654322@ 而不是盲目地使用魔数 0。属性位置在程序链接后分配,并且仅分配给程序执行时实际主动使用的顶点属性(就像制服一样)。所以不能假设属性是从0开始按顺序分配的,实际上需要告诉GL给它什么位置,或者链接后查询。
但事情变得非常有趣...#version 140 core
。在 OpenGL 3.2 (GLSL 1.50) 之前,core 这个词确实没有任何意义。我很惊讶你的 GLSL 编译器没有抱怨这个。事实上,GLSL 1.40 规范定义的#version
指令仅限于一个数字,仅此而已,在 1.50 中添加了一个可选的配置文件名称。即使是成功编译的着色器,您也应该检查着色器信息日志,因为它们可能包含诸如此类的警告。
此外,关于信息日志的主题……链接器也会生成一个。您在编译着色器时正在检查编译状态,但没有检查链接状态的代码。
更新:
我注意到您用来查询着色器信息日志的代码也存在一些问题:
假设DEBUGSTR (...)
没有删除它传递的指针,那么当你的着色器编译失败时,你将会泄漏内存。
如果编译器生成长度 >= 255 个字符的着色器信息日志,您将超出分配的内存。
将这个:GLchar* err = new char[255];
改写成这个:GLchar* err = new char[maxLength];
。
【讨论】:
非常有帮助。我会改变这些东西,看看我能找到什么! 谢谢!仍然有同样的问题,但现在代码更好了。 谢谢,这帮助我解决了我的顶点着色器中的“0”错误。我在 glVertexAttrib4fv 中使用 1 而不是 0 并且它起作用了。该问题出现在OpenGL superbible book 6th edition Listing 3.2中以上是关于将属性传递给 OpenGL 顶点着色器的行为很奇怪的主要内容,如果未能解决你的问题,请参考以下文章