How to fix "segmentation fault" when using PyOpenGL on Mac

46 Views Asked by At

My script worked initially, displaying a window as expected. However, subsequent runs result in a segmentation fault (zsh: segmentation fault /usr/local/bin/python3) without any Python errors. I tested another Python program (fibonacci) and it worked fine. Can anyone assist?

Here's my script:

import pygame as pg
from OpenGL.GL import *

class App():
    def __init__(self):
        # init python 
        pg.init()
        self.clock = pg.time.Clock()
        # init opengl
        glClearColor(0.1, 0.2, 0.2, 1)
        self.mainLoop()
    
    def mainLoop(self):
        running = True
        while running:
            # check events
            for event in pg.event.get():
                if event.type == pg.QUIT:
                    running = False
            
            # refresh
            glClear(GL_COLOR_BUFFER_BIT)
            pg.display

            # timing
            self.clock.tick(60)
        self.quit()
    
    def quit(self):
        pg.quit()

if __name__ == "__main__":
    myApp = App()
1

There are 1 best solutions below

0
Rabbid76 On

You have to create an OpenGL display with pygame.display.set_mode using the pygame.OPENGL flag:

import pygame as pg
from OpenGL.GL import *

class App():
    def __init__(self):
        pg.init()
        pg.display.set_mode((800, 600), pg.OPENGL) # create OpenGL display
        self.clock = pg.time.Clock()
        
        glClearColor(0.1, 0.2, 0.2, 1)
        self.mainLoop()
    
    def mainLoop(self):
        running = True
        while running:
            for event in pg.event.get():
                if event.type == pg.QUIT:
                    running = False

            # draw 
            glClear(GL_COLOR_BUFFER_BIT)
            # [...]

            # update display
            pg.display.flip()
            self.clock.tick(60)
        self.quit()
    
    def quit(self):
        pg.quit()

if __name__ == "__main__":
    myApp = App()