Skip to content

Instantly share code, notes, and snippets.

@qxcv
Created October 25, 2018 03:43
Show Gist options
  • Save qxcv/08fd00b380e76dcc1aaef98af0c0bf67 to your computer and use it in GitHub Desktop.
Save qxcv/08fd00b380e76dcc1aaef98af0c0bf67 to your computer and use it in GitHub Desktop.
FreeGLUT non-blocking drawing demo
#!/usr/bin/env python3
# Shows us to use non-blocking event loop from FreeGLUT. Original code from
# https://code.activestate.com/recipes/325391-open-a-glut-window-and-draw-a-sphere-using-pythono/
from OpenGL.GLUT import *
from OpenGL.GLU import *
from OpenGL.GL import *
import sys
import threading
import time
name = 'ball_glut'
closed = False
def on_close():
global closed
closed = True
def glut_init():
print('Starting glut_init()')
glutInit(sys.argv)
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH)
glutInitWindowSize(400,400)
glutCreateWindow(name)
freeglut.glutSetOption(freeglut.GLUT_ACTION_ON_WINDOW_CLOSE,
freeglut.GLUT_ACTION_GLUTMAINLOOP_RETURNS)
freeglut.glutCloseFunc(on_close)
glClearColor(0.,0.,0.,1.)
glShadeModel(GL_SMOOTH)
glEnable(GL_CULL_FACE)
glEnable(GL_DEPTH_TEST)
glEnable(GL_LIGHTING)
lightZeroPosition = [10.,4.,10.,1.]
lightZeroColor = [0.8,1.0,0.8,1.0] #green tinged
glLightfv(GL_LIGHT0, GL_POSITION, lightZeroPosition)
glLightfv(GL_LIGHT0, GL_DIFFUSE, lightZeroColor)
glLightf(GL_LIGHT0, GL_CONSTANT_ATTENUATION, 0.1)
glLightf(GL_LIGHT0, GL_LINEAR_ATTENUATION, 0.05)
glEnable(GL_LIGHT0)
glutDisplayFunc(display)
glMatrixMode(GL_PROJECTION)
gluPerspective(40.,1.,1.,40.)
glMatrixMode(GL_MODELVIEW)
gluLookAt(0,0,10,
0,0,0,
0,1,0)
glPushMatrix()
def display():
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)
glPushMatrix()
color = [1.0,0.,0.,1.]
glMaterialfv(GL_FRONT,GL_DIFFUSE,color)
glutSolidSphere(2,20,20)
glPopMatrix()
glutSwapBuffers()
def main():
glut_init()
print('Starting to render stuff')
try:
while not closed:
print('Running render')
freeglut.glutMainLoopEvent()
print('Waiting 0.1s')
time.sleep(0.1)
finally:
print('Done, killing window')
# Sometimes (e.g when ctrl+c-ing) this will lead to an illegal
# instruction error, but I have no idea how to fix that.
freeglut.glutLeaveMainLoop()
print('Program will exit now (hopefully!)')
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment