How to Use a GLSL Program




GLSL Hacker - How to Use a GLSL Program

Let’s suppose you just found this cool GLSL program somewhere on the Net:

Vertex shader:

#version 120
void main()
{
  gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}

Pixel shader:

#version 120
void main()
{
  gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}

Now, let’s suppose you want to test it with a mesh torus. The first thing to do is to create a XML node for the GLSL program in the main XML file.

In GLSL Hacker, a GLSL program is simply called GPU program:


  
  

This piece of code is enough for GLSL Hacker to load and compile the GPU program. Even if you won’t use this GLSL code, it’s compiled and eventual errors are displayed in the log file and, for the Win64 version of GLSL Hacker, in the output window (CTRL+L).

Now, let’s look at how to use this GPU program in Lua (or Python, the syntax is the same).

Here is how to get the GPU program handle:

simple_prog = gh_node.getid("simple_prog")

For GLSL Hacker, a GPU program is node. A texture, a camera or a mesh are also nodes. The gh_node library exposes several functions to deal with nodes.

Let’s create a camera (with gh_camera) as well as a torus (with gh_mesh):

camera = gh_camera.create_persp(60, winW/winH, 0.1, 1000.0)
gh_camera.set_viewport(camera, 0, 0, winW, winH)
gh_camera.set_position(camera, 0, 10, 20)
gh_camera.set_lookat(camera, 0, 0, 0, 1)
gh_camera.setupvec(camera, 0, 1, 0, 0)

torus = gh_mesh.create_torus(10, 2, 20)

Now we have a camera, a GPU program and a mesh. We have everything we need to draw something on the screen.

First we bind the camera (we make it active) and we clear the color and depth buffers:

gh_camera.bind(camera)
gh_renderer.clear_color_depth_buffers(0.2, 0.2, 0.2, 1.0, 1.0)

Then we bind the GPU program using the gh_gpu_program.php lib:

gh_gpu_program.bind(simple_prog)

The binding of a GPU program does the linking if necessary and makes it current.

Now all following drawing functions will use the current GPU program. Then to draw the torus, we just need this line:

gh_object.render(torus)


OpenGL 2 demo - red torus

You can play and hack the demo available in the code sample pack
(host_api/GLSL_Simple_OpenGL_21_32_42/demo_torus_gl2.xml).





Leave a Comment

Your email address will not be published. Required fields are marked *