[Haskell-cafe] Correct way to record state in OpenGL?

Casey McCann syntaxglitch at gmail.com
Sun Apr 4 11:14:04 EDT 2010

On Sun, Apr 4, 2010 at 5:03 AM, Mark Spezzano
<mark.spezzano at chariot.net.au> wrote:
> What is the correct way to record "custom" state when using OpenGL?
> By this, I refer to, say, properties of a square--say it's x,y coordinates as it moves across the screen. This requires that the program keep track of the object's state as it moves. These coordinates are _not_ part of the OpenGL state machine, so is the correct way to use the State monad?

The State monad effectively just adds an extra argument and result to
each function and connects them together for you; the type of a
function (a -> State s b) translates into (a -> s -> (b, s)). There's
nothing magic in there, and nothing truly stateful in the sense of
OpenGL's "it's turtles all the way down" approach to mutable state,
but any state-keeping you could reasonably do by adding more
arguments/results to pure functions can usually be done more elegantly
with State. Of course you can't really do much with OpenGL outside of
IO, so you'd probably want a StateT transformer on top of the IO

The "downside" is that code outside of the transformed monad can't
change the state, and can't access it except as an explicit argument.
Normally this is a good thing, but it means that any main event loop
in the application must be in the transformed monad, and thus under
your control--which isn't the case if you're using GLUT.

> If so--or if not so--how would I proceed to keep track of the state of my objects as they move about the screen? Maybe the HOpenGL implementation comes with such state-tracking devices?

HOpenGL does use the StateVar package to provide a consistent
interface to mutable references, but that doesn't provide any special
implementation of such. Using Data.IORef is probably the simplest
choice, and optionally using StateVar if you want to use the same
syntax for both IORefs and OpenGL state.

On the other hand, if you're getting a GL context from something
else--such as SDL or a GUI library--that requires you to manage an
explicit event loop, feel free to use StateT instead.

- C.

More information about the Haskell-Cafe mailing list