user1123936
user1123936

Reputation: 181

How can I queue up custom Pyglet events while keeping input and graphics events at highest priority?

Ok, so there's a very very long list of low priority function calls which have to be made. I would like the keyboard triggered events to continue executing right on time, and I would like the display to continue updating on time, but, when neither of these two things need to be done, I would like all remaining CPU time to be used to continue to walk down the list of low priority function calls, making them one by one.

I tried to implement this behavior by recursively calling dispatch_event in the last line of the event handler that handles the low priority events. This call is recursive because the type of event being dispatched is another of the same type of low priority events. The code in the body of this event handler simply pops a function call off of the long list, and executes it.

However, this doesn't work, because it turns out that dispatch_event actually fires the event's event handler pronto, as opposed to adding it to a queue. So, the result is that execution becomes stuck in a recursive loop, resulting in a stack overflow.

So... what should I do instead?

Upvotes: 0

Views: 674

Answers (1)

Torxed
Torxed

Reputation: 23480

#!/usr/bin/python
import pyglet
from time import time, sleep

class Window(pyglet.window.Window):
    def __init__(self, refreshrate):
        super(Window, self).__init__(vsync = False)
        self.frames = 0
        self.framerate = pyglet.text.Label(text='Unknown', font_name='Verdana', font_size=8, x=10, y=10, color=(255,255,255,255))
        self.last = time()
        self.alive = 1
        self.refreshrate = refreshrate

    def on_draw(self):
        self.render()

    def render(self):
        self.clear()
        if time() - self.last >= 1:
            self.framerate.text = str(self.frames)
            self.frames = 0
            self.last = time()
        else:
            self.frames += 1
        self.framerate.draw()
        self.flip()

    def on_close(self):
        self.alive = 0

    def on_key_release(self, symbol, modkey):
            print(symbol, modkey)

    def on_mouse_motion(x, y, dx, dy):
        print('Mouse from:',x,y,'moved:',dx,dy)

    def run(self):
        while self.alive:
            self.render()
            event = self.dispatch_events() # <-- This is the event queue
            sleep(1.0/self.refreshrate)

win = Window(23) # set the fps
win.run()

This takes care of mouse and keyborad while not clogging up any event queues. Generate events or listen to events in the event dispatcher or do the rendering you need to do in def render().

Upvotes: 1

Related Questions