
import OpenGL.GL as gl

import glitch

class Cached(glitch.Node):
    def _make_display_list(self, ctx):
        id = gl.glGenLists(1)
        gl.glNewList(id, gl.GL_COMPILE)
        self.draw(ctx)
        gl.glEndList()
        return id

    def _cached_draw(self, ctx, key):
        lists = ctx.setdefault('display_lists', {})

        if key in lists:
            list_id = lists[key]
        else:
            list_id = lists[key] = self._make_display_list(ctx)

        gl.glCallList(list_id)

    def render(self, ctx):
        self._cached_draw(ctx, key=self.__class__)

        for c in self.children:
            c.render(ctx)

