Context

Slut's reliance on OpenGL calls for an easy way to set up and tear down predefined OpenGL states. Almost any aspect of OpenGL requires that OpenGL's state machine is first put into the right state--line color line thickness, fill color, material of surface, lights, etc--prior to drawing a specific shape. After this object has been drawn another state is set up for the next shape.

glColor4f(1.0, 1.0, 1.0, 1.0)
drawFirstShape()

glColor4f(0.0, 1.0, 0.0, 1.0)
glLineWidth(3)
drawSecondShape()
<world>.Context(context)
<tag>.addContext(context)
<sprite>.addContext(context)
  • context ... an object that has been instanced from a Context class

<world>.removeContext(context)
<tag>.removeContext(context)
<sprite>.removeContext(context)
  • context ... an object that has been instanced from a Context class

Relevant examples: context.py , ALL

In cases when all shapes of an element (tag or sprite) share the same OpenGL "context" one may find it convenient to define such a context in a custom context class. Moving the setup (onPreDraw()) and tear-down (onPostDraw()) of an OpenGL state into a context class is particularly useful when the same OpenGL context is needed multiple times.

from slut import *

class Atlantis(World):
    def onSetup(self):
        Sphere(self, 'sph1')
        redContext = ColorContext('redctxt')
        asphere = Sphere(self, 'sph2')
        asphere.addContext(redContext)
        asphere.moveBy(0.5, 0.0, 0.0)
        anothersphere = Sphere(self, 'sph3')
        anothersphere.addContext(redContext)
        anothersphere.moveBy(1.0, 0.0, 0.0)
        

class Sphere(Sprite):
    def onDraw(self):
        primitives.sphere()


class ColorContext(Context):
    def onPreDraw(self):
        glPushAttrib(GL_CURRENT_BIT)
        glColor4f(1.0, 1.0, 1.0, 1.0)

    def onPostDraw(self):
        glPopAttrib()
        

atlantis = Atlantis()
atlantis.run()

As onPreDraw() and onPostDraw() suggest, they are called before and after an element is drawn. While onPreDraw() is run just before the element's onDraw(), onPostDraw() is only run after all the sub-elements have been drawn. Not surprisingly, contexts affect the content of the element as well as the content of all the element's sub-elements.

Initiated by Stephan Hechenberger
Thanks to CADRE's 103