Search code examples
openglstate-machineautomata-theory

Is OpenGL a "state machine"?


OpenGL is usually described as a "state machine" because, as far as I know, it consists of global variables which can be set through its API and they change/define its behavior. For example it is possible to set current color or transformation matrix. Many of state variables have continuous value range.

However, as far as I understand, a "state machine" or "finite state machine" in computer science is defined as a directed graph of states (as nodes) and transitions (as directed edges).

Is the "state machine" term used to describe OpenGL the same as the "state machine" which is defined in general computer science.


Solution

  • Many of state variables have continuous value range.

    A GLfloat, much like a regular float, has a fixed size in bits. A 32-bit IEEE-754 has only 32-bits of storage. Therefore, it can only assume 2^32 distinct values (though quite a few of these values will be considered identical or incomparable). And while 2^32 is large, it is still very much finite.

    An OpenGL context has a well-specified and finite set of state values. And each state value can take on a finite set of discrete values. So it is possible to model the OpenGL context as a finite state machine, with changing values in state simply being making state transitions (though OpenGL objects, particularly program objects, complicate this view somewhat).


    All that being said, the main point of the "OpenGL is a state machine" statement really has nothing to do with an actual finite state machine. The statement is usually said as a reminder that:

    1. OpenGL will remember the state that was last set into the context, even if you forgot what you last set it to.

    2. OpenGL will remember the state that was last set into the context, even if you forgot what you last set it to.

    OpenGL is a state machine because it remembers its state. Unless you explicitly perform a transition, it remains in the state that it was in.

    Basically, it's a reminder to either keep track of what the current state is, or just set all of the state at the beginning of your render loop to make sure that it is what you think it is.