Hi Everybody! I hope you are all doing well today.
Today I started exploring pyglet again after a considerable time away, and I ran into a curious problem. I could not get pyglet to call "on_draw" in even the most simple of applications!
Here's a demonstration:
================
import pyglet
window = pyglet.window.Window()
draw_count = 0
@window.event
def on_draw():
global draw_count
window.clear()
draw_count += 1
print "drawing {}".format(draw_count)
pyglet.app.run()
================
If you're using the latest hg repository pyglet (revision 2632 as of this post), and you're running Windows like me, you'll probably see just this:
C:\Users\cseebach>python pyglet_draw_demo.py
drawing 1
If you minimize and restore (hide and unhide) the window, you'll see a few more draw reports.
If you're anything like me, you panicked! This is basically what the "Hello, World!" tutorial in the docs says to do. What on Earth is going on?
You're about to see that this behavior is actually a feature, and not a bug.
I've changed the code slightly to add an update() method which does nothing, called approximately once every 1/60th of a second.
================
import pyglet
window = pyglet.window.Window()
draw_count = 0
@window.event
def on_draw():
global draw_count
window.clear()
draw_count += 1
print "drawing {}".format(draw_count)
def update(dt):
pass
pyglet.clock.schedule_interval(update, 1/60.0)
pyglet.app.run()
================
Try running that sucker!
C:\Users\cseebach>python pyglet_draw_demo_2.py
drawing 1
drawing 2
drawing 3
...
drawing
3242562461 #(no, I didn't actually run it for 15,000 hours, but you get the point)
etc...
Here's my theory, which I hope will be supported and elucidated by somebody more familiar with the win32 event loop code in pyglet:
pyglet only calls "on_draw" when there are other events to be dispatched. Previously, there were no events in our loop to dispatch! Now that we've scheduled update() for 60 times a second, our loop is no longer empty, and pyglet will happily draw our stuff! This minimizes the cpu and gpu usage of your application, which I believe is more important than always calling on_draw.
Hope this saves somebody a little time and frustration when learning pyglet.
--Cam