Discussion:
[PyOpenGL-Users] glGetUniformLocation causes segmentation faults
richard hawkins
2009-06-25 14:03:20 UTC
Permalink
Hello all,

I am having some trouble with a simple test application. I am mixing
one of the nehe tutorials with the brick example from the OpenGL
orange book.

Here is my problem, all calls to glGetUniformLocation result in a
segmentation fault. I removed all calls to glGetUniformLocation, and
played around with guessing the appropriate values. Doing this I was
able to get the shader to render correctly, but is not a good way to
do things.

I am running Ubuntu 9.04 64bit

uname -a output: Linux starscream 2.6.28-11-generic #42-Ubuntu SMP Fri
Apr 17 01:58:03 UTC 2009 x86_64 GNU/Linux

Below I have listed the output from calling glGetString on my box, I
have also included my version of the program.

Any assistance would be appreciated.

Thanks,
Richard


GL_VENDOR: Tungsten Graphics, Inc
GL_RENDERER: Mesa DRI Intel(R) 965GM GEM 20090326 2009Q1 RC2
GL_VERSION: 2.0 Mesa 7.4
GL_EXTENSIONS: GL_ARB_depth_texture GL_ARB_draw_buffers
GL_ARB_fragment_program GL_ARB_fragment_program_shadow
GL_ARB_fragment_shader GL_ARB_multisample GL_ARB_multitexture
GL_ARB_occlusion_query GL_ARB_pixel_buffer_object
GL_ARB_point_parameters GL_ARB_point_sprite GL_ARB_shader_objects
GL_ARB_shading_language_100 GL_ARB_shadow GL_ARB_texture_border_clamp
GL_ARB_texture_compression 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_mirrored_repeat GL_ARB_texture_non_power_of_two
GL_ARB_texture_rectangle GL_ARB_transpose_matrix
GL_ARB_vertex_buffer_object GL_ARB_vertex_program GL_ARB_vertex_shader
GL_ARB_window_pos GL_EXT_abgr GL_EXT_bgra GL_EXT_blend_color
GL_EXT_blend_equation_separate GL_EXT_blend_func_separate
GL_EXT_blend_logic_op GL_EXT_blend_minmax GL_EXT_blend_subtract
GL_EXT_clip_volume_hint GL_EXT_cull_vertex
GL_EXT_compiled_vertex_array GL_EXT_copy_texture
GL_EXT_draw_range_elements GL_EXT_framebuffer_object GL_EXT_fog_coord
GL_EXT_multi_draw_arrays GL_EXT_packed_depth_stencil
GL_EXT_packed_pixels GL_EXT_pixel_buffer_object
GL_EXT_point_parameters GL_EXT_polygon_offset GL_EXT_rescale_normal
GL_EXT_secondary_color GL_EXT_separate_specular_color
GL_EXT_shadow_funcs GL_EXT_stencil_wrap GL_EXT_subtexture
GL_EXT_texture GL_EXT_texture3D GL_EXT_texture_edge_clamp
GL_EXT_texture_env_add GL_EXT_texture_env_combine
GL_EXT_texture_env_dot3 GL_EXT_texture_filter_anisotropic
GL_EXT_texture_lod_bias GL_EXT_texture_object GL_EXT_texture_rectangle
GL_EXT_texture_sRGB GL_EXT_vertex_array
GL_3DFX_texture_compression_FXT1 GL_APPLE_client_storage
GL_APPLE_packed_pixels GL_ATI_blend_equation_separate
GL_ATI_texture_env_combine3 GL_ATI_separate_stencil
GL_IBM_rasterpos_clip GL_IBM_texture_mirrored_repeat
GL_INGR_blend_func_separate GL_MESA_pack_invert GL_MESA_ycbcr_texture
GL_MESA_window_pos GL_NV_blend_square GL_NV_light_max_exponent
GL_NV_point_sprite GL_NV_texture_rectangle GL_NV_texgen_reflection
GL_NV_vertex_program GL_NV_vertex_program1_1 GL_OES_read_format
GL_SGIS_generate_mipmap GL_SGIS_texture_border_clamp
GL_SGIS_texture_edge_clamp GL_SGIS_texture_lod GL_SGIX_depth_texture
GL_SUN_multi_draw_arrays

#--- pysqr.py ---------------------------
#!/usr/bin/python

import wx
from wx import glcanvas

from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *

from OpenGL.GL.ARB.shader_objects import *
from OpenGL.GL.ARB.vertex_shader import *
from OpenGL.GL.ARB.fragment_shader import *

class GLFrame(wx.Frame):
"""A simple class for using OpenGL with wxPython."""

vert_src = """
uniform vec3 LightPosition;

const float SpecularContribution = 0.3;
const float DiffuseContribution = 1.0 - SpecularContribution;

varying float LightIntensity;
varying vec2 MCposition;

void main(void)
{
vec3 ecPosition = vec3 (gl_ModelViewMatrix * gl_Vertex);
vec3 tnorm = normalize(gl_NormalMatrix * gl_Normal);
vec3 lightVec = normalize(LightPosition - ecPosition);
vec3 reflectVec = reflect(-lightVec, tnorm);
vec3 viewVec = normalize(-ecPosition);
float diffuse = max(dot(lightVec, tnorm), 0.0);
float spec = 0.0;

if (diffuse > 0.0)
{
spec = max(dot(reflectVec, viewVec), 0.0);
spec = pow(spec, 16.0);
}

LightIntensity = DiffuseContribution * diffuse +
SpecularContribution * spec;

MCposition = gl_Vertex.xy;
gl_Position = ftransform();
}"""

frag_src = """
uniform vec3 BrickColor, MortarColor;
uniform vec2 BrickSize;
uniform vec2 BrickPct;

varying vec2 MCposition;
varying float LightIntensity;

void main(void)
{
vec3 color;
vec2 position, useBrick;

position = MCposition / BrickSize;

if (fract(position.y * 0.5) > 0.5)
position.x += 0.5;

position = fract(position);

useBrick = step(position, BrickPct);

color = mix(MortarColor, BrickColor, useBrick.x * useBrick.y);
color *= LightIntensity;
gl_FragColor = vec4 (color, 1.0);
}"""

def __init__(self, parent, id, title, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE,
name='frame'):
#
# Forcing a specific style on the window.
# Should this include styles passed?
style = wx.DEFAULT_FRAME_STYLE | wx.NO_FULL_REPAINT_ON_RESIZE

super(GLFrame, self).__init__(parent, id, title, pos, size, style, name)

self.GLinitialized = False
attribList = (glcanvas.WX_GL_RGBA, # RGBA
glcanvas.WX_GL_DOUBLEBUFFER, # Double Buffered
glcanvas.WX_GL_DEPTH_SIZE, 24) # 24 bit

#
# Create the canvas
self.canvas = glcanvas.GLCanvas(self, attribList=attribList)

#
# Set the event handlers.
self.canvas.Bind(wx.EVT_ERASE_BACKGROUND,
self.processEraseBackgroundEvent)
self.canvas.Bind(wx.EVT_SIZE, self.processSizeEvent)
self.canvas.Bind(wx.EVT_PAINT, self.processPaintEvent)

#
# Canvas Proxy Methods

def GetGLExtents(self):
"""Get the extents of the OpenGL canvas."""
return self.canvas.GetClientSize()

def SwapBuffers(self):
"""Swap the OpenGL buffers."""
self.canvas.SwapBuffers()

#
# wxPython Window Handlers

def processEraseBackgroundEvent(self, event):
"""Process the erase background event."""
pass # Do nothing, to avoid flashing on MSWin

def processSizeEvent(self, event):
"""Process the resize event."""
if self.canvas.GetContext():
# Make sure the frame is shown before calling SetCurrent.
self.Show()
self.canvas.SetCurrent()

size = self.GetGLExtents()
self.OnReshape(size.width, size.height)
self.canvas.Refresh(False)
event.Skip()

def processPaintEvent(self, event):
"""Process the drawing event."""
self.canvas.SetCurrent()

# This is a 'perfect' time to initialize OpenGL ... only if we need to
if not self.GLinitialized:
self.OnInitGL()
self.GLinitialized = True

self.OnDraw()
event.Skip()

#
# GLFrame OpenGL Event Handlers
def getUniLoc(self, program, name):
loc = glGetUniformLocation(program, name);
if (loc == -1):
print "No such uniform named ", name
return loc

def OnInitGL(self):
"""Initialize OpenGL for use in the window."""
print "GL_VENDOR: ", glGetString(GL_VENDOR)
print "GL_RENDERER: ", glGetString(GL_RENDERER)
print "GL_VERSION: ", glGetString(GL_VERSION)
print "GL_EXTENSIONS: ", glGetString(GL_EXTENSIONS)

glClearColor(0.0, 0.0, 0.0, 0.0)

glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0)

glMatrixMode( GL_MODELVIEW )
glLoadIdentity()

vert = glCreateShader(GL_VERTEX_SHADER)
frag = glCreateShader(GL_FRAGMENT_SHADER)

glShaderSource(vert, self.vert_src)
glShaderSource(frag, self.frag_src)

glCompileShader(vert)
glCompileShader(frag)

program = glCreateProgram()
glAttachShader(program, vert)
glAttachShader(program, frag)

glValidateProgram(program)
glLinkProgram(program)
glUseProgram(program)

# Any of the following will cause a segmentation
# fault. (due to the call to glGetUniformLocation)
glUniform3f(self.getUniLoc(program, "BrickColor"), 1.0, 0.3, 0.2)
glUniform3f(self.getUniLoc(program, "MortarColor"), 0.85, 0.86, 0.84)
glUniform2f(self.getUniLoc(program, "BrickSize"), 0.30, 0.15)
glUniform2f(self.getUniLoc(program, "BrickPct"), 0.90, 0.85)
glUniform3f(self.getUniLoc(program, "LightPosition"), 0.0, 0.0, 4.0)

# These cause the shader to be rendered properly, but obviously is
# not the right way to do things. ;)
#glUniform3f(1, 1.0, 0.3, 0.2)
#glUniform3f(2, 0.85, 0.86, 0.84)
#glUniform2f(3, 0.30, 0.15)
#glUniform2f(4, 0.90, 0.85)
#glUniform3f(0, 0.0, 0.0, 4.0)

def OnReshape(self, width, height):
"""Reshape the OpenGL viewport based on the dimensions of the window."""
glViewport(0, 0, width, height)

def OnDraw(self, *args, **kwargs):
"Draw the window."
glClear(GL_COLOR_BUFFER_BIT)

glColor3f(1.0, 1.0, 1.0);
glBegin(GL_POLYGON);
glVertex2f(-0.5, -0.5);
glVertex2f(-0.5, 0.5);
glVertex2f(0.5, 0.5);
glVertex2f(0.5, -0.5);
glEnd();

self.SwapBuffers()

def main():
app = wx.App()

frame = GLFrame(None, -1, 'GL Window')
frame.Show()

app.MainLoop()
app.Destroy()

if __name__ == "__main__":
main()
# --- end of pysqr.py ------------------------
Mike C. Fletcher
2009-06-25 15:24:10 UTC
Permalink
Post by richard hawkins
Hello all,
I am having some trouble with a simple test application. I am mixing
one of the nehe tutorials with the brick example from the OpenGL
orange book.
Here is my problem, all calls to glGetUniformLocation result in a
segmentation fault. I removed all calls to glGetUniformLocation, and
played around with guessing the appropriate values. Doing this I was
able to get the shader to render correctly, but is not a good way to
do things.
Interesting, my machine bombs out (not a segfault, just an invalid
operation) when trying to do glUseProgram. I'd suspect that something
is failing during compilation and you just aren't retrieving a
compilation error message to see the failure? Don't have time to track
it down this morning (already late for meeting). (Tested on an Ubuntu
9.04 64-bit with AMD Radeon, btw).

Good luck,
Mike
--
________________________________________________
Mike C. Fletcher
Designer, VR Plumber, Coder
http://www.vrplumber.com
http://blog.vrplumber.com
richard hawkins
2009-06-25 16:14:34 UTC
Permalink
I moved over to my desktop which has a GeForce GTX 260, and is also
running 64 bit Ubuntu 9.04. This machine also segfaults when I call
glGetUniformLocation. As I expected, the enumeration of the uniform
resources changed between my Intel card and this GeForce. The GeForce
enumerates as follows for me:

glUniform3f(0, 1.0, 0.3, 0.2)
glUniform3f(4, 0.85, 0.86, 0.84)
glUniform2f(2, 0.30, 0.15)
glUniform2f(1, 0.90, 0.85)
glUniform3f(3, 0.0, 0.0, 4.0)

Also I installed pyopengl using the python-opengl package in apt if
that might help at all.

I also added calls to glGetError, but it appears that nothing is
failing. Below is an excerpt of my changes:

------------------------------------
...
vert = glCreateShader(GL_VERTEX_SHADER)
print "glGetError - glCreateShader: ", glGetError()
frag = glCreateShader(GL_FRAGMENT_SHADER)
print "glGetError - glCreateShader: ", glGetError()

glShaderSource(vert, self.vert_src)
print "glGetError - glShaderSource: ", glGetError()
glShaderSource(frag, self.frag_src)
print "glGetError - glShaderSource: ", glGetError()

glCompileShader(vert)
print "glGetError - glCompileShader: ", glGetError()
glCompileShader(frag)
print "glGetError - glCompileShader: ", glGetError()

program = glCreateProgram()
print "glGetError - glCreateProgram: ", glGetError()
glAttachShader(program, vert)
print "glGetError - glAttachShader: ", glGetError()
glAttachShader(program, frag)
print "glGetError - glAttachShader: ", glGetError()

glValidateProgram(program)
print "glGetError - glValidateProgram: ", glGetError()
glLinkProgram(program)
print "glGetError - glLinkProgram: ", glGetError()
glUseProgram(program)
print "glGetError - glUseProgram: ", glGetError()

# Any of the following will cause a segmentation
# fault. (due to the call to glGetUniformLocation)
glUniform3f(self.getUniLoc(program, "BrickColor"), 1.0, 0.3, 0.2)
...
------------------------------------

which now gives me the output:
GL_VENDOR: NVIDIA Corporation
GL_RENDERER: GeForce GTX 260/PCI/SSE2
GL_VERSION: 3.0.0 NVIDIA 180.44
...
glGetError - glCreateShader: 0
glGetError - glCreateShader: 0
glGetError - glShaderSource: 0
glGetError - glShaderSource: 0
glGetError - glCompileShader: 0
glGetError - glCompileShader: 0
glGetError - glCreateProgram: 0
glGetError - glAttachShader: 0
glGetError - glAttachShader: 0
glGetError - glValidateProgram: 0
glGetError - glLinkProgram: 0
glGetError - glUseProgram: 0
Segmentation fault

Thanks for the help,
Richard

On Thu, Jun 25, 2009 at 10:24 AM, Mike C.
Post by Mike C. Fletcher
Post by richard hawkins
Hello all,
I am having some trouble with a simple test application.  I am mixing
one of the nehe tutorials with the brick example from the OpenGL
orange book.
Here is my problem, all calls to glGetUniformLocation result in a
segmentation fault.  I removed all calls to glGetUniformLocation, and
played around with guessing the appropriate values.  Doing this I was
able to get the shader to render correctly, but is not a good way to
do things.
Interesting, my machine bombs out (not a segfault, just an invalid
operation) when trying to do glUseProgram.  I'd suspect that something
is failing during compilation and you just aren't retrieving a
compilation error message to see the failure?  Don't have time to track
it down this morning (already late for meeting).  (Tested on an Ubuntu
9.04 64-bit with AMD Radeon, btw).
Good luck,
Mike
--
________________________________________________
 Mike C. Fletcher
 Designer, VR Plumber, Coder
 http://www.vrplumber.com
 http://blog.vrplumber.com
--
"People who think they know everything really annoy those of us who
know we don't" - Bjarne Stroustrup
Ian Mallett
2009-06-25 18:17:08 UTC
Permalink
Hello,

If you haven't already, try:

glGetProgramInfoLog(program)
glGetInfoLogARB(program)

Also, wx might be confounding your results. If you're just trying to learn
shaders, I recommend
http://bazaar.launchpad.net/~mcfletch/pyopengl-demo/trunk/annotate/2?file_id=shader_test.py-20080923005140-67c17kywpwxa2usj-25<http://bazaar.launchpad.net/%7Emcfletch/pyopengl-demo/trunk/annotate/2?file_id=shader_test.py-20080923005140-67c17kywpwxa2usj-25>

This might be a good time to bring up a long standing issue. Personally,
I'm getting null function errors--the only way I've gotten shaders to work
is with ARB, and I'm not sure why.

Ian
Mike C. Fletcher
2009-07-05 19:39:46 UTC
Permalink
Post by Ian Mallett
This might be a good time to bring up a long standing issue.
Personally, I'm getting null function errors--the only way I've gotten
shaders to work is with ARB, and I'm not sure why.
Missed this.

Can you give more details and/or a test-case? When I run against
PyOpenGL trunk and enable INFO level logging in the extensions module I
get this:

INFO:OpenGL.extensions:OpenGL Version: 2.1.8575 FireGL
INFO:OpenGL.extensions:Chose alternate: glCreateProgram from
glCreateProgram, glCreateProgramObjectARB
INFO:OpenGL.extensions:Chose alternate: glCreateShader from
glCreateShader, glCreateShaderObjectARB
INFO:OpenGL.extensions:Chose alternate: glShaderSource from
glShaderSource, glShaderSourceARB
INFO:OpenGL.extensions:Chose alternate: glCompileShader from
glCompileShader, glCompileShaderARB
INFO:OpenGL.extensions:Chose alternate: glAttachShader from
glAttachShader, glAttachObjectARB
INFO:OpenGL.extensions:Chose alternate: glValidateProgram from
glValidateProgram, glValidateProgramARB
INFO:OpenGL.extensions:Chose alternate: glLinkProgram from
glLinkProgram, glLinkProgramARB
INFO:OpenGL.extensions:Chose alternate: glDeleteShader from
glDeleteShader, glDeleteObjectARB
INFO:OpenGL.extensions:Chose alternate: glGetAttribLocation from
glGetAttribLocation, glGetAttribLocationARB
INFO:OpenGL.extensions:GL Extension GL_ARB_occlusion_query available
INFO:OpenGL.extensions:GL Extension GL_ARB_point_parameters available
INFO:OpenGL.extensions:Chose alternate: glUseProgram from glUseProgram,
glUseProgramObjectARB
INFO:OpenGL.extensions:GL Extension GL_ARB_vertex_buffer_object available
INFO:OpenGL.extensions:Chose alternate: glVertexAttribPointer from
glVertexAttribPointer, glVertexAttribPointerARB

when running a shader-using sample. That is, it appears to properly
choose the core rather than ARB extension versions (and the core
functions are non-null).

Good luck,
Mike
--
________________________________________________
Mike C. Fletcher
Designer, VR Plumber, Coder
http://www.vrplumber.com
http://blog.vrplumber.com
Ian Mallett
2009-07-05 19:52:53 UTC
Permalink
Post by Mike C. Fletcher
Post by Ian Mallett
This might be a good time to bring up a long standing issue.
Personally, I'm getting null function errors--the only way I've gotten
shaders to work is with ARB, and I'm not sure why.
Missed this.
Can you give more details and/or a test-case?
Well, this <http://www.pygame.org/wiki/GLSLExample?parent=CookBook> didn't
work...
Post by Mike C. Fletcher
Post by Ian Mallett
Post by richard hawkins
from OpenGL.GL import *
glCreateShader
<OpenGL.platform.baseplatform.glCreateShader object at 0x02C03090>
Post by Mike C. Fletcher
Post by Ian Mallett
Post by richard hawkins
glCreateShader()
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
glCreateShader()
File "C:\dev\Python25\Lib\site-packages\OpenGL\platform\baseplatform.py",
line 299, in __call__
self.__name__, self.__name__,
NullFunctionError: Attempt to call an undefined function glCreateShader,
check for bool(glCreateShader) before calling

Simply missing something?

Ian
Mike C. Fletcher
2009-07-05 20:57:55 UTC
Permalink
On Sun, Jul 5, 2009 at 12:39 PM, Mike C. Fletcher
Post by Ian Mallett
This might be a good time to bring up a long standing issue.
Personally, I'm getting null function errors--the only way I've
gotten
Post by Ian Mallett
shaders to work is with ARB, and I'm not sure why.
Missed this.
Can you give more details and/or a test-case?
Well, this <http://www.pygame.org/wiki/GLSLExample?parent=CookBook>
didn't work...
Post by Ian Mallett
Post by richard hawkins
from OpenGL.GL import *
glCreateShader
<OpenGL.platform.baseplatform.glCreateShader object at 0x02C03090>
Post by Ian Mallett
Post by richard hawkins
glCreateShader()
File "<pyshell#2>", line 1, in <module>
glCreateShader()
File
"C:\dev\Python25\Lib\site-packages\OpenGL\platform\baseplatform.py",
line 299, in __call__
self.__name__, self.__name__,
NullFunctionError: Attempt to call an undefined function
glCreateShader, check for bool(glCreateShader) before calling
Simply missing something?
You don't have a valid OpenGL context at this point, without that many
of the newer GL implementations will return NULL pointers when you try
to get the pointer. Some will even silently return NULL values (without
raising errors!) when there's no active context. That's all reasonably
spec-compliant, but a bit of a PITA IMO.

Maybe I'm missing something, though. You do *way* more work with
PyOpenGL than me, so I could quite easily have missed a common failure-case.
Mike
--
________________________________________________
Mike C. Fletcher
Designer, VR Plumber, Coder
http://www.vrplumber.com
http://blog.vrplumber.com
Ian Mallett
2009-07-05 22:27:33 UTC
Permalink
Post by Mike C. Fletcher
You don't have a valid OpenGL context at this point, without that many
of the newer GL implementations will return NULL pointers when you try
to get the pointer. Some will even silently return NULL values (without
raising errors!) when there's no active context. That's all reasonably
spec-compliant, but a bit of a PITA IMO.
Thought it might be the context. Attached is a simple example that crashes.
Ian
Mike C. Fletcher
2009-07-06 04:00:34 UTC
Permalink
On Sun, Jul 5, 2009 at 1:57 PM, Mike C. Fletcher
You don't have a valid OpenGL context at this point, without that many
of the newer GL implementations will return NULL pointers when you try
to get the pointer. Some will even silently return NULL values (without
raising errors!) when there's no active context. That's all reasonably
spec-compliant, but a bit of a PITA IMO.
Thought it might be the context. Attached is a simple example that crashes.
Ian
Hmm, no problem over here (AMD64 Linux with fglrx ATI drivers (OpenGL
2.1)). You're sure your card supports an actual OpenGL 2.x driver, and
doesn't just have extensions on top of a 1.x driver?

Clueless is me,
Mike
--
________________________________________________
Mike C. Fletcher
Designer, VR Plumber, Coder
http://www.vrplumber.com
http://blog.vrplumber.com
Ian Mallett
2009-07-06 04:05:35 UTC
Permalink
I don't know, but I've had this problem on two systems.

My newer (current) is a NVidia GeForce 8400M GS
According to here<http://en.kioskea.net/guide/692632-nvidia-geforce-6800-gs-256-mo-gddr3>,
it has "Graphics Support: DirectX 9.0, OpenGL 2.0"

richard hawkins
2009-06-25 05:38:49 UTC
Permalink
Hello all,

I am having some trouble with a simple test application. I am mixing
one of the nehe tutorials with the brick example from the OpenGL
orange book.

Here is my problem, all calls to glGetUniformLocation result in a
segmentation fault. I removed all calls to glGetUniformLocation, and
played around with guessing the appropriate values. Doing this I was
able to get the shader to render correctly, but is not a good way to
do things.

I am running Ubuntu 9.04 64bit

uname -a output: Linux starscream 2.6.28-11-generic #42-Ubuntu SMP Fri
Apr 17 01:58:03 UTC 2009 x86_64 GNU/Linux

Below I have listed the output from calling glGetString on my box, I
have also included my version of the program.

Any assistance would be appreciated.

Thanks,
Richard


GL_VENDOR: Tungsten Graphics, Inc
GL_RENDERER: Mesa DRI Intel(R) 965GM GEM 20090326 2009Q1 RC2
GL_VERSION: 2.0 Mesa 7.4
GL_EXTENSIONS: GL_ARB_depth_texture GL_ARB_draw_buffers
GL_ARB_fragment_program GL_ARB_fragment_program_shadow
GL_ARB_fragment_shader GL_ARB_multisample GL_ARB_multitexture
GL_ARB_occlusion_query GL_ARB_pixel_buffer_object
GL_ARB_point_parameters GL_ARB_point_sprite GL_ARB_shader_objects
GL_ARB_shading_language_100 GL_ARB_shadow GL_ARB_texture_border_clamp
GL_ARB_texture_compression 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_mirrored_repeat GL_ARB_texture_non_power_of_two
GL_ARB_texture_rectangle GL_ARB_transpose_matrix
GL_ARB_vertex_buffer_object GL_ARB_vertex_program GL_ARB_vertex_shader
GL_ARB_window_pos GL_EXT_abgr GL_EXT_bgra GL_EXT_blend_color
GL_EXT_blend_equation_separate GL_EXT_blend_func_separate
GL_EXT_blend_logic_op GL_EXT_blend_minmax GL_EXT_blend_subtract
GL_EXT_clip_volume_hint GL_EXT_cull_vertex
GL_EXT_compiled_vertex_array GL_EXT_copy_texture
GL_EXT_draw_range_elements GL_EXT_framebuffer_object GL_EXT_fog_coord
GL_EXT_multi_draw_arrays GL_EXT_packed_depth_stencil
GL_EXT_packed_pixels GL_EXT_pixel_buffer_object
GL_EXT_point_parameters GL_EXT_polygon_offset GL_EXT_rescale_normal
GL_EXT_secondary_color GL_EXT_separate_specular_color
GL_EXT_shadow_funcs GL_EXT_stencil_wrap GL_EXT_subtexture
GL_EXT_texture GL_EXT_texture3D GL_EXT_texture_edge_clamp
GL_EXT_texture_env_add GL_EXT_texture_env_combine
GL_EXT_texture_env_dot3 GL_EXT_texture_filter_anisotropic
GL_EXT_texture_lod_bias GL_EXT_texture_object GL_EXT_texture_rectangle
GL_EXT_texture_sRGB GL_EXT_vertex_array
GL_3DFX_texture_compression_FXT1 GL_APPLE_client_storage
GL_APPLE_packed_pixels GL_ATI_blend_equation_separate
GL_ATI_texture_env_combine3 GL_ATI_separate_stencil
GL_IBM_rasterpos_clip GL_IBM_texture_mirrored_repeat
GL_INGR_blend_func_separate GL_MESA_pack_invert GL_MESA_ycbcr_texture
GL_MESA_window_pos GL_NV_blend_square GL_NV_light_max_exponent
GL_NV_point_sprite GL_NV_texture_rectangle GL_NV_texgen_reflection
GL_NV_vertex_program GL_NV_vertex_program1_1 GL_OES_read_format
GL_SGIS_generate_mipmap GL_SGIS_texture_border_clamp
GL_SGIS_texture_edge_clamp GL_SGIS_texture_lod GL_SGIX_depth_texture
GL_SUN_multi_draw_arrays

#--- pysqr.py ---------------------------
#!/usr/bin/python

import wx
from wx import glcanvas

from OpenGL.GL import *
from OpenGL.GLU import *
from OpenGL.GLUT import *

from OpenGL.GL.ARB.shader_objects import *
from OpenGL.GL.ARB.vertex_shader import *
from OpenGL.GL.ARB.fragment_shader import *

class GLFrame(wx.Frame):
"""A simple class for using OpenGL with wxPython."""

vert_src = """
uniform vec3 LightPosition;

const float SpecularContribution = 0.3;
const float DiffuseContribution = 1.0 - SpecularContribution;

varying float LightIntensity;
varying vec2 MCposition;

void main(void)
{
vec3 ecPosition = vec3 (gl_ModelViewMatrix * gl_Vertex);
vec3 tnorm = normalize(gl_NormalMatrix * gl_Normal);
vec3 lightVec = normalize(LightPosition - ecPosition);
vec3 reflectVec = reflect(-lightVec, tnorm);
vec3 viewVec = normalize(-ecPosition);
float diffuse = max(dot(lightVec, tnorm), 0.0);
float spec = 0.0;

if (diffuse > 0.0)
{
spec = max(dot(reflectVec, viewVec), 0.0);
spec = pow(spec, 16.0);
}

LightIntensity = DiffuseContribution * diffuse +
SpecularContribution * spec;

MCposition = gl_Vertex.xy;
gl_Position = ftransform();
}"""

frag_src = """
uniform vec3 BrickColor, MortarColor;
uniform vec2 BrickSize;
uniform vec2 BrickPct;

varying vec2 MCposition;
varying float LightIntensity;

void main(void)
{
vec3 color;
vec2 position, useBrick;

position = MCposition / BrickSize;

if (fract(position.y * 0.5) > 0.5)
position.x += 0.5;

position = fract(position);

useBrick = step(position, BrickPct);

color = mix(MortarColor, BrickColor, useBrick.x * useBrick.y);
color *= LightIntensity;
gl_FragColor = vec4 (color, 1.0);
}"""

def __init__(self, parent, id, title, pos=wx.DefaultPosition,
size=wx.DefaultSize, style=wx.DEFAULT_FRAME_STYLE,
name='frame'):
#
# Forcing a specific style on the window.
# Should this include styles passed?
style = wx.DEFAULT_FRAME_STYLE | wx.NO_FULL_REPAINT_ON_RESIZE

super(GLFrame, self).__init__(parent, id, title, pos, size, style, name)

self.GLinitialized = False
attribList = (glcanvas.WX_GL_RGBA, # RGBA
glcanvas.WX_GL_DOUBLEBUFFER, # Double Buffered
glcanvas.WX_GL_DEPTH_SIZE, 24) # 24 bit

#
# Create the canvas
self.canvas = glcanvas.GLCanvas(self, attribList=attribList)

#
# Set the event handlers.
self.canvas.Bind(wx.EVT_ERASE_BACKGROUND,
self.processEraseBackgroundEvent)
self.canvas.Bind(wx.EVT_SIZE, self.processSizeEvent)
self.canvas.Bind(wx.EVT_PAINT, self.processPaintEvent)

#
# Canvas Proxy Methods

def GetGLExtents(self):
"""Get the extents of the OpenGL canvas."""
return self.canvas.GetClientSize()

def SwapBuffers(self):
"""Swap the OpenGL buffers."""
self.canvas.SwapBuffers()

#
# wxPython Window Handlers

def processEraseBackgroundEvent(self, event):
"""Process the erase background event."""
pass # Do nothing, to avoid flashing on MSWin

def processSizeEvent(self, event):
"""Process the resize event."""
if self.canvas.GetContext():
# Make sure the frame is shown before calling SetCurrent.
self.Show()
self.canvas.SetCurrent()

size = self.GetGLExtents()
self.OnReshape(size.width, size.height)
self.canvas.Refresh(False)
event.Skip()

def processPaintEvent(self, event):
"""Process the drawing event."""
self.canvas.SetCurrent()

# This is a 'perfect' time to initialize OpenGL ... only if we need to
if not self.GLinitialized:
self.OnInitGL()
self.GLinitialized = True

self.OnDraw()
event.Skip()

#
# GLFrame OpenGL Event Handlers
def getUniLoc(self, program, name):
loc = glGetUniformLocation(program, name);
if (loc == -1):
print "No such uniform named ", name
return loc

def OnInitGL(self):
"""Initialize OpenGL for use in the window."""
print "GL_VENDOR: ", glGetString(GL_VENDOR)
print "GL_RENDERER: ", glGetString(GL_RENDERER)
print "GL_VERSION: ", glGetString(GL_VERSION)
print "GL_EXTENSIONS: ", glGetString(GL_EXTENSIONS)

glClearColor(0.0, 0.0, 0.0, 0.0)

glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0)

glMatrixMode( GL_MODELVIEW )
glLoadIdentity()

vert = glCreateShader(GL_VERTEX_SHADER)
frag = glCreateShader(GL_FRAGMENT_SHADER)

glShaderSource(vert, self.vert_src)
glShaderSource(frag, self.frag_src)

glCompileShader(vert)
glCompileShader(frag)

program = glCreateProgram()
glAttachShader(program, vert)
glAttachShader(program, frag)

glValidateProgram(program)
glLinkProgram(program)
glUseProgram(program)

# Any of the following will cause a segmentation
# fault. (due to the call to glGetUniformLocation)
glUniform3f(self.getUniLoc(program, "BrickColor"), 1.0, 0.3, 0.2)
glUniform3f(self.getUniLoc(program, "MortarColor"), 0.85, 0.86, 0.84)
glUniform2f(self.getUniLoc(program, "BrickSize"), 0.30, 0.15)
glUniform2f(self.getUniLoc(program, "BrickPct"), 0.90, 0.85)
glUniform3f(self.getUniLoc(program, "LightPosition"), 0.0, 0.0, 4.0)

# These cause the shader to be rendered properly, but obviously is
# not the right way to do things. ;)
#glUniform3f(1, 1.0, 0.3, 0.2)
#glUniform3f(2, 0.85, 0.86, 0.84)
#glUniform2f(3, 0.30, 0.15)
#glUniform2f(4, 0.90, 0.85)
#glUniform3f(0, 0.0, 0.0, 4.0)

def OnReshape(self, width, height):
"""Reshape the OpenGL viewport based on the dimensions of the window."""
glViewport(0, 0, width, height)

def OnDraw(self, *args, **kwargs):
"Draw the window."
glClear(GL_COLOR_BUFFER_BIT)

glColor3f(1.0, 1.0, 1.0);
glBegin(GL_POLYGON);
glVertex2f(-0.5, -0.5);
glVertex2f(-0.5, 0.5);
glVertex2f(0.5, 0.5);
glVertex2f(0.5, -0.5);
glEnd();

self.SwapBuffers()

def main():
app = wx.App()

frame = GLFrame(None, -1, 'GL Window')
frame.Show()

app.MainLoop()
app.Destroy()

if __name__ == "__main__":
main()
# --- end of pysqr.py ------------------------
Ian Mallett
2009-07-01 21:08:45 UTC
Permalink
As a wild guess that may not work, it looks like you're using ARB
extensions. You could try creating the shader like so:

program = glCreateProgramObjectARB()

vert = glCreateShaderObjectARB(GL_VERTEX_SHADER_ARB)
frag = glCreateShaderObjectARB(GL_FRAGMENT_SHADER_ARB)

glShaderSourceARB(vert,[self.vert_src])
glShaderSourceARB(frag,[self.frag_src])

glCompileShaderARB(vert)
glCompileShaderARB(frag)

glAttachObjectARB(program,vert)
glAttachObjectARB(program,frag)

glDeleteObjectARB(vert)
glDeleteObjectARB(frag)

glValidateProgramARB(program)
glLinkProgramARB(program)

glUseShader(program)

Ian
Loading...