Ruby and OpenGL

[ LiB ]

Ruby and OpenGL

I discussed OpenGL first in Chapter 4, where I introduced PyOpenGL. To briefly summarize, OpenGL is a platform-independent API for creating graphics. Ruby's OpenGL extension module was developed by Yoshiyuki Kusano. It provides an interface to the basic OpenGL, GLU, and GLUT APIs.

As of this writing, the extension is at Version 0.32b and can be found at Yohshiyukani Kusabo's homepage, at

GLU is a high-level library that partners with OpenGL. It provides additional functionality that would otherwise be fairly difficult to code in just OpenGL. GLUT is another OpenGL additionit's a toolkit for designing OpenGL programs. Together these two build an API that allows Ruby to easily access OpenGL commands.

A simple example of OpenGL is drawing a geometric shape. Step 1 is including the OpenGL, GLU, and GLUT libraries if they are necessary. Posix systems may also need the Ruby paththat is, #!/usr/local/bin/ruby :

 #!/usr/local/bin/ruby require "opengl" require "glut" 

Using the OpenGL Proc function and its new method will declare a new function, called MyTriangle , that can draw a geometric shape:

 MyTriangle = { 

In order to draw the shape, the GL buffer must be cleared, and a new GL object of type TRIANGLE must be created:


Then you can set, with GL. Color , the RGB values that you'll use when drawing:

 GL.Color(1.0, 1.0, 1.0) 

And then you need to set the vertices of the three points of the triangle in 2D space:

 GL.Color(1.0, 1.0, 1.0) GL.Vertex(0, 0) GL.Vertex(10, 10) GL.Vertex(10, 50) 

The OpenGL buffer must be flushed with GL.Flush and the calls to OpenGL ended.

The whole MyTriangle function looks like this:

 MyTriangle = {   GL.Clear(GL::COLOR_BUFFER_BIT)   GL.Begin(GL::TRIANGLES)     GL.Color(1.0, 1.0, 1.0)     GL.Vertex(0, 0)     GL.Vertex(10, 10)     GL.Vertex(10, 50)   GL.End   GL.Flush 

In order to use the function, you must create a window ( MyWindow ) for display. The window can be built using GLUT's CreateWindow method after GLUT is initialized :

 GLUT.Init MyWindow =  GLUT.CreateWindow("OpenGL Triangle") 

The final steps for actually running this short Ruby OpenGL sample are to use GLUT's DisplayFunc method to display MyTriangle , and then call MainLoop to get it all started:

 GLUT.DisplayFunc(MyTriangle) GLUT.MainLoop 

The standard Ruby install comes with many OpenGL samples located in the Ruby\Samples\OpenGL directory. These include examples showing how to draw two-dimensional and three-dimensional shapes , play with colors, and rotate objects in three-dimensional space.

[ LiB ]

Game Programming with Pyton, Lua and Ruby
Game Programming with Pyton, Lua and Ruby
Year: 2005
Pages: 133 © 2008-2017.
If you may any questions please contact us: