How To Render a Reference Grid


GLSL Hacker - reference grid

GLSL Hacker has a handy object called a grid. A grid is more or less just a collection of lines but that info is not really important. You can use a grid as a reference object when there’s no ground plane in the scene.

To use a grid, you need a grid (obviously), a vertex color GPU program and a camera (a perspective in our code snippet).

The following code shows the initialization of a 100×100 units grid made up of 20×20 segments:

grid = gh_utils.grid_create()
gh_utils.grid_set_geometry_params(grid, 100, 100, 20, 20)
gh_utils.grid_set_lines_color(grid, 0.7, 0.7, 0.7, 1.0)
gh_utils.grid_set_main_lines_color(grid, 1.0, 1.0, 0.0, 1.0)
gh_utils.grid_set_main_x_axis_color(grid, 1.0, 0.0, 0.0, 1.0)
gh_utils.grid_set_main_z_axis_color(grid, 0.0, 0.0, 1.0, 1.0)
local display_main_lines = 1
local display_lines = 1
gh_utils.grid_set_display_lines_options(grid, display_main_lines, display_lines)

For the vertex color GLSL program, you can use this one (OpenGL 2 style):


  
  

Or this one, in OpenGL 3 style:


  
  

We can retrieve the gpu program handle with this code:

color_prog = gh_node.getid("color_prog")

The perspective camera:

winW, winH = gh_window.getsize(0)

local aspect = winW / winH
camera = gh_camera.create_persp(60, aspect, 1.0, 1000.0)
gh_camera.set_viewport(camera, 0, 0, winW, winH)
gh_camera.set_position(camera, 20, 20, 80)
gh_camera.set_lookat(camera, 0, 0, 0, 1)
gh_camera.setupvec(camera, 0, 1, 0, 0)

Now we can render the reference grid:

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

gh_gpu_program.bind(color_prog)
gh_object.render(grid)