def destroy(self): """ Gracefully close the window """ sdl2.SDL_GL_DeleteContext(self.context) sdl2.SDL_DestroyWindow(self.window) sdl2.SDL_Quit()
def shutdown(self): """Shut down the renderer.""" renderer_shutdown() sdl.SDL_GL_DeleteContext(self.ctx) self.ctx = None sdl.SDL_DestroyWindow(self.win) self.win = None
def terminate(self): """Cleanup the GUI resources.""" self._renderer.cleanup() if hienoi.renderer.get_info().api == GraphicsAPI.OPENGL: sdl2.SDL_GL_DeleteContext(self._handles.renderer.context) sdl2.SDL_DestroyWindow(self._handles.window) sdl2.SDL_Quit()
def clear(self): # release resources if self.context: sdl2.SDL_GL_DeleteContext(self.context) self.context = None if self.window: sdl2.SDL_DestroyWindow(self.window) self.window = None
def dispose(self): if self._window is not None: sdl2.SDL_HideWindow(self._window) if self._timer is not None: self._loop.destroy_timer(self._timer) self._timer = None if self._window is not None: sdl2.SDL_DestroyWindow(self._window) self._window = None if self._glcontext is not None: sdl2.SDL_GL_DeleteContext(self._glcontext) self._glcontext = None
def run(): if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0: print(sdl2.SDL_GetError()) return -1 window = sdl2.SDL_CreateWindow(b"OpenGL demo", sdl2.SDL_WINDOWPOS_UNDEFINED, sdl2.SDL_WINDOWPOS_UNDEFINED, 800, 600, sdl2.SDL_WINDOW_OPENGL) if not window: print(sdl2.SDL_GetError()) return -1 context = sdl2.SDL_GL_CreateContext(window) GL.glMatrixMode(GL.GL_PROJECTION | GL.GL_MODELVIEW) GL.glLoadIdentity() GL.glOrtho(-400, 400, 300, -300, 0, 1) x = 0.0 y = 30.0 event = sdl2.SDL_Event() running = True while running: while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0: if event.type == sdl2.SDL_QUIT: running = False GL.glClearColor(0, 0, 0, 1) GL.glClear(GL.GL_COLOR_BUFFER_BIT) GL.glRotatef(10.0, 0.0, 0.0, 1.0) GL.glBegin(GL.GL_TRIANGLES) GL.glColor3f(1.0, 0.0, 0.0) GL.glVertex2f(x, y + 90.0) GL.glColor3f(0.0, 1.0, 0.0) GL.glVertex2f(x + 90.0, y - 90.0) GL.glColor3f(0.0, 0.0, 1.0) GL.glVertex2f(x - 90.0, y - 90.0) GL.glEnd() sdl2.SDL_GL_SwapWindow(window) sdl2.SDL_Delay(10) sdl2.SDL_GL_DeleteContext(context) sdl2.SDL_DestroyWindow(window) sdl2.SDL_Quit() return 0
def main(): global rend if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0: print(sdl2.SDL_GetError()) return 0 x, y = 0, 0 # window = sdl2.ext.Window("ekkek", 600,600, sdl2.SDL_WINDOW_OPENGL) window = sdl2.SDL_CreateWindow(TITLE, sdl2.SDL_WINDOWPOS_UNDEFINED, sdl2.SDL_WINDOWPOS_UNDEFINED, 600, 600, sdl2.SDL_WINDOW_OPENGL) context = sdl2.SDL_GL_CreateContext(window) rend = Renderer() time = sdl2.SDL_GetTicks() prev_time = sdl2.SDL_GetTicks() frame_time = 0 e = ioproc(sdl2.SDL_Event()) dt = 1000. / 60. #while sdl2.SDL_WaitEvent(ctypes.byref(sdl2.SDL_QUIT)): while e.checkEvents(): # time = sdl2.SDL_GetTicks() # frame_time = time - prev_time # prev_time = time # while sdl2.SDL_PollEvent(ctypes.byref(e)) !=0: # if(e.type == sdl2.SDL_QUIT): # running = False time += dt frame_time = time - sdl2.SDL_GetTicks() if (frame_time <= 0): frame_time = 1 tms.sleep(frame_time / 1000.) # update shit here # ... rend.doShit() rend.draw() sdl2.SDL_GL_SwapWindow(window) # rend.unload() #Unload assimp imports sdl2.SDL_GL_DeleteContext(context) sdl2.SDL_Quit()
def run(): if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0: print(sdl2.SDL_GetError()) return -1 window = sdl2.SDL_CreateWindow(b"OpenGL demo", sdl2.SDL_WINDOWPOS_UNDEFINED, sdl2.SDL_WINDOWPOS_UNDEFINED, 800, 600, sdl2.SDL_WINDOW_OPENGL) if not window: print(sdl2.SDL_GetError()) return -1 # Force OpenGL 3.3 'core' context. # Must set *before* creating GL context! video.SDL_GL_SetAttribute(video.SDL_GL_CONTEXT_MAJOR_VERSION, 3) video.SDL_GL_SetAttribute(video.SDL_GL_CONTEXT_MINOR_VERSION, 3) video.SDL_GL_SetAttribute(video.SDL_GL_CONTEXT_PROFILE_MASK, video.SDL_GL_CONTEXT_PROFILE_CORE) context = sdl2.SDL_GL_CreateContext(window) # Setup GL shaders, data, etc. initialize() event = sdl2.SDL_Event() running = True while running: while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0: if event.type == sdl2.SDL_QUIT: running = False elif (event.type == sdl2.SDL_KEYDOWN and event.key.keysym.sym == sdl2.SDLK_ESCAPE): running = False render() sdl2.SDL_GL_SwapWindow(window) sdl2.SDL_Delay(10) sdl2.SDL_GL_DeleteContext(context) sdl2.SDL_DestroyWindow(window) sdl2.SDL_Quit() return 0
def __del__(self): sdl2.SDL_GL_DeleteContext(self._context) sdl2.SDL_DestroyWindow(self.window) sdl2.SDL_Quit()
def run(): if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0: print(sdl2.SDL_GetError()) return -1 window = sdl2.SDL_CreateWindow(b"OpenGL demo", sdl2.SDL_WINDOWPOS_UNDEFINED, sdl2.SDL_WINDOWPOS_UNDEFINED, 800, 600, sdl2.SDL_WINDOW_OPENGL) if not window: print(sdl2.SDL_GetError()) return -1 # Force OpenGL 3.3 'core' context. # Must set *before* creating GL context! video.SDL_GL_SetAttribute(video.SDL_GL_CONTEXT_MAJOR_VERSION, 3) video.SDL_GL_SetAttribute(video.SDL_GL_CONTEXT_MINOR_VERSION, 3) video.SDL_GL_SetAttribute(video.SDL_GL_CONTEXT_PROFILE_MASK, video.SDL_GL_CONTEXT_PROFILE_CORE) context = sdl2.SDL_GL_CreateContext(window) quad = [ -0.5, -0.5, 0.0, 1.0, 0.0, 0.0, 0.5, -0.5, 0.0, 0.0, 1.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0, -0.5, 0.5, 0.0, 1.0, 1.0, 1.0 ] quad = numpy.array(quad, dtype=numpy.float32) indices = [0, 1, 2, 2, 3, 0] indices = numpy.array(indices, dtype=numpy.uint32) # Setup GL shaders, data, etc. vertex_shader = shaders.compileShader( """ #version 330 in vec3 position; in vec3 color; out vec3 newColor; void main() { gl_Position = vec4(position, 1.0f); newColor = color; } """, GL.GL_VERTEX_SHADER) fragment_shader = shaders.compileShader( """ #version 330 in vec3 newColor; out vec4 outColor; void main() { outColor = vec4(newColor, 1.0f); } """, GL.GL_FRAGMENT_SHADER) shaderProgram = shaders.compileProgram(vertex_shader, fragment_shader) GL.glUseProgram(shaderProgram) VAO = GL.glGenVertexArrays(1) GL.glBindVertexArray(VAO) # Need VBO for triangle vertices and colours VBO = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, VBO) GL.glBufferData(GL.GL_ARRAY_BUFFER, 96, quad, GL.GL_STATIC_DRAW) EBO = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, EBO) GL.glBufferData(GL.GL_ELEMENT_ARRAY_BUFFER, 24, indices, GL.GL_STATIC_DRAW) position = GL.glGetAttribLocation(shaderProgram, "position") GL.glVertexAttribPointer(position, 3, GL.GL_FLOAT, GL.GL_FALSE, 24, ctypes.c_void_p(0)) GL.glEnableVertexAttribArray(position) color = GL.glGetAttribLocation(shaderProgram, "color") GL.glVertexAttribPointer(color, 3, GL.GL_FLOAT, GL.GL_FALSE, 24, ctypes.c_void_p(12)) GL.glEnableVertexAttribArray(color) event = sdl2.SDL_Event() running = True GL.glClearColor(0, 0, 0, 1) while running: while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0: if event.type == sdl2.SDL_QUIT: running = False try: GL.glClear(GL.GL_COLOR_BUFFER_BIT) GL.glDrawElements(GL.GL_TRIANGLES, 6, GL.GL_UNSIGNED_INT, None) finally: GL.glUseProgram(0) sdl2.SDL_GL_SwapWindow(window) sdl2.SDL_Delay(10) sdl2.SDL_GL_DeleteContext(context) sdl2.SDL_DestroyWindow(window) sdl2.SDL_Quit() return 0
def quit(self): sdl2.SDL_GL_DeleteContext(self.context) sdl2.SDL_DestroyWindow(self.window) sdl2.SDL_Quit() gc.collect()
def main(): ######################## class Opts(object): pass opts = Opts() opts.verbose = True opts.windowed = True opts.vsync = False ######################## if opts.verbose: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) logger.info("Initializing") sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) dm = sdl2.SDL_DisplayMode() sdl2.SDL_GetDesktopDisplayMode(0, dm) if not opts.windowed: width = dm.w height = dm.h else: width = round(dm.w * .8) height = round(dm.h * .8) sdl2.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_PROFILE_MASK, sdl2.SDL_GL_CONTEXT_PROFILE_ES) sdl2.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_MAJOR_VERSION, 3) sdl2.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_MINOR_VERSION, 0) window_flags = sdl2.SDL_WINDOW_OPENGL | (sdl2.SDL_WINDOW_FULLSCREEN if not opts.windowed else 0) window = sdl2.SDL_CreateWindow(TITLE.encode('utf-8'), sdl2.SDL_WINDOWPOS_UNDEFINED, sdl2.SDL_WINDOWPOS_UNDEFINED, width, height, window_flags) context = sdl2.SDL_GL_CreateContext(window) fbo = None # fbo = gllib.framebuffer.MultisampledFramebuffer(8, (width, height)) if opts.vsync: if sdl2.SDL_GL_SetSwapInterval(-1) == -1: logger.warning("Adaptive vsync not available") sdl2.SDL_GL_SetSwapInterval(1) else: sdl2.SDL_GL_SetSwapInterval(0) main_scene = scene.Scene((width, height)) frames = 0 frame_count_time = time.monotonic() ev = sdl2.SDL_Event() running = True while running: while True: if (sdl2.SDL_PollEvent(ev) == 0): break if ev.type == sdl2.SDL_QUIT: running = False elif ev.type == sdl2.SDL_KEYUP and ev.key.keysym.sym == sdl2.SDLK_ESCAPE: running = False main_scene.update() if fbo is not None: with fbo: main_scene.render() fbo.activate_for_read() fbo.blit() else: main_scene.render() sdl2.SDL_GL_SwapWindow(window) frames += 1 now = time.monotonic() if now - frame_count_time > FPS_PRINT_TIME: fps = frames / (now - frame_count_time) frames = 0 frame_count_time = now logger.debug("%.3f FPS", fps) main_scene.shutdown() sdl2.SDL_GL_DeleteContext(context) sdl2.SDL_DestroyWindow(window) sdl2.SDL_Quit()
def __del__(self): """Shut down the App.""" sdl2.SDL_GL_DeleteContext(self._gl_context) sdl2.ext.quit()
def run(self) -> int: """ Run scene. This is a complex function and needs some refactoring. Here is the logic and flow behind this function: 1. Initialize SDL 2. Create SDL window with given parameters enabling OpenGL Pipeline 3. Create and set active context as OpenGL Context 4. Set running flag. 5. Fix aspect ratios of observers *aka cameras* in the scene. 6. Start scene loop. 1. Poll for SDL events 2. React to SDL events *(quit, key press, key up, mouse motion etc)* 3. Render scene, turn to step 6.1 if not quit 7. Destroy objects and clear memory. 8. Destroy window and such. """ if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0: return -1 sdl2.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_MAJOR_VERSION, 3) sdl2.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_MINOR_VERSION, 3) sdl2.SDL_GL_SetAttribute(sdl2.SDL_GL_CONTEXT_PROFILE_MASK, sdl2.SDL_GL_CONTEXT_PROFILE_CORE) sdl2.SDL_GL_SetAttribute(sdl2.SDL_GL_MULTISAMPLEBUFFERS, 1) sdl2.SDL_GL_SetAttribute(sdl2.SDL_GL_MULTISAMPLESAMPLES, 16) self.window = sdl2.SDL_CreateWindow( b"Payton Scene", sdl2.SDL_WINDOWPOS_UNDEFINED, sdl2.SDL_WINDOWPOS_UNDEFINED, int(self.window_width), int(self.window_height), sdl2.SDL_WINDOW_OPENGL, ) # type: ignore if not self.window: return -1 self._context = sdl2.SDL_GL_CreateContext(self.window) self.event = sdl2.SDL_Event() self.running = True # Fix aspect ratios of observers for observer in self.observers: observer.aspect_ratio = (self.window_width / self.window_height * 1.0) for clock in self.clocks: self.clocks[clock].start() while self.running: while sdl2.SDL_PollEvent(ctypes.byref(self.event)) != 0: self.controller.keyboard(self.event, self) self.controller.mouse(self.event, self) self._render() sdl2.SDL_GL_SwapWindow(self.window) sdl2.SDL_Delay(1) for obj in self.objects: self.objects[obj].destroy() for clock in self.clocks: self.clocks[clock].kill() sdl2.SDL_GL_DeleteContext(self._context) sdl2.SDL_DestroyWindow(self.window) self.window = None sdl2.SDL_Quit() return 0
def cleanup(self): sdl.SDL_GL_DeleteContext(self.glcontext) sdl.SDL_DestroyWindow(self.window) sdl.SDL_Quit()
def close(self): sdl2.SDL_GL_DeleteContext(self._context) self._context = None sdl2.SDL_DestroyWindow(self._window) self._window = None
def terminate(self): sdl2.SDL_GL_DeleteContext(self.context) sdl2.SDL_DestroyWindow(self.window) sdl2.SDL_Quit()
def main(): if len(sys.argv) != 2: print("usage: 3dwf.py REMOTE_ADDRESS", file=sys.stderr) sys.exit(1) nbins = 256 overlap = 192 rem_address = (sys.argv[1], 3731) conn = socket.create_connection(rem_address) sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO | sdl2.SDL_INIT_AUDIO) window = sdl2.SDL_CreateWindow(b"3D Waterfall", sdl2.SDL_WINDOWPOS_CENTERED, sdl2.SDL_WINDOWPOS_CENTERED, 800, 600, sdl2.SDL_WINDOW_RESIZABLE | sdl2.SDL_WINDOW_OPENGL) context = sdl2.SDL_GL_CreateContext(window) wf = WFViewer(nbins) wf.init(800, 600) wf.shift = 0 filt = interp_fir_filter(lowpass(np.pi / 4, 512) * np.hamming(512), 4) freqx = freq_translator((0.8/8.0) * np.pi) headlen = max(filt.nhistory, overlap) ringbuf = RingBuf(headlen, np.zeros(headlen + (nbins - overlap) * 512, dtype=np.complex64)) # FIXME global audio_edge audio_edge = 0 def callback(unused, buf, buflen): global audio_edge bufbuf = pybuf_from_memory(buf, buflen, 0x200) # PyBUF_WRITE array = np.frombuffer(bufbuf, np.float32) assert len(array) % filt.interp == 0 # TODO nreqframes = len(array) // filt.interp loc_ringbuf_edge = ringbuf.fill_edge if loc_ringbuf_edge < 0 or (loc_ringbuf_edge - audio_edge) % len(ringbuf) < nreqframes: print("audio underrun", file=sys.stderr) array.fill(0) return # TODO if audio_edge + nreqframes > len(ringbuf): audio_edge = 0 slic = ringbuf.slice(audio_edge - filt.nhistory, audio_edge + nreqframes) array[:] = np.real(freqx(filt(slic))) * wf.volume audio_edge += nreqframes sdl2.SDL_PushEvent(UPDATE_EVENT) audio_spec = sdl2.SDL_AudioSpec(8000, sdl2.AUDIO_F32, 1, 512, sdl2.SDL_AudioCallback(callback)) audio_dev = sdl2.SDL_OpenAudioDevice(None, 0, audio_spec, None, 0) if audio_dev == 0: raise Error('could not open audio device') err_queue = queue.Queue() def readfunc(nbytes): bytes = b'' while len(bytes) < nbytes: ret = conn.recv(nbytes - len(bytes)) if not ret: raise Exception('end of stream') bytes += ret return bytes def thread_target(): try: input_thread(readfunc, ringbuf, nbins, overlap, wf) except Exception as e: err_queue.put(e) event = sdl2.SDL_Event() event.type = sdl2.SDL_QUIT sdl2.SDL_PushEvent(event) other_thread = threading.Thread(target=thread_target) other_thread.setDaemon(True) other_thread.start() sdl2.SDL_PauseAudioDevice(audio_dev, 0) running = True event = sdl2.SDL_Event() while running: sdl2.SDL_WaitEvent(ctypes.byref(event)) while True: if event.type == sdl2.SDL_QUIT: running = False break wf.event(event) if sdl2.SDL_PollEvent(ctypes.byref(event)) == 0: break # FIXME wf.shift = ((ringbuf.fill_edge - audio_edge) % len(ringbuf)) / (nbins - overlap) wf.draw() sdl2.SDL_GL_SwapWindow(window) try: for exc in iter(err_queue.get_nowait, None): sdl2.SDL_ShowSimpleMessageBox(sdl2.SDL_MESSAGEBOX_ERROR, b"Exception", str(exc).encode("ascii"), None) except queue.Empty: pass sdl2.SDL_CloseAudioDevice(audio_dev) sdl2.SDL_GL_DeleteContext(context) sdl2.SDL_DestroyWindow(window) sdl2.SDL_Quit()
def main(): args = argparse.ArgumentParser(description="Run " + TITLE) args.add_argument('-i', '--midi-input', help="connect to specified MIDI input port") args.add_argument('-o', '--midi-output', help="connect to specified MIDI output port") args.add_argument('-c', '--debug-camera', action='store_true', help="use a controllable camera") args.add_argument('-s', '--vsync', action='store_true', help="use vsync") args.add_argument('-v', '--verbose', action='store_true', help="increase verbosity") args.add_argument('-w', '--windowed', action='store_true', help="run in a window") args.add_argument('-3', '--stereoscopy', choices=[scene.STEREOSCOPY_OFF, scene.STEREOSCOPY_ANAGLYPH], help="stereoscopy mode") args.add_argument('-e', '--eye-separation', type=float, help="stereoscopic eye separation") opts = args.parse_args(sys.argv[1:]) if opts.verbose: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) logger.info("Initializing") sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) dm = sdl2.SDL_DisplayMode() sdl2.SDL_GetDesktopDisplayMode(0, dm) if not opts.windowed: width = dm.w height = dm.h else: width = round(dm.w * .8) height = round(dm.h * .8) window_flags = sdl2.SDL_WINDOW_OPENGL | (sdl2.SDL_WINDOW_FULLSCREEN if not opts.windowed else 0) window = sdl2.SDL_CreateWindow(TITLE.encode('utf-8'), sdl2.SDL_WINDOWPOS_UNDEFINED, sdl2.SDL_WINDOWPOS_UNDEFINED, width, height, window_flags) context = sdl2.SDL_GL_CreateContext(window) fbo = create_multisampled_fbo(width, height, 0) if opts.vsync: if sdl2.SDL_GL_SetSwapInterval(-1) == -1: logger.warning("Adaptive vsync not available") sdl2.SDL_GL_SetSwapInterval(1) else: sdl2.SDL_GL_SetSwapInterval(0) midi_handler = midi.MidiHandler(opts.midi_input, opts.midi_output) main_scene = scene.Scene((width, height), midi_handler, debug_camera=opts.debug_camera) if opts.stereoscopy is not None: main_scene.set_stereoscopy(opts.stereoscopy) if opts.eye_separation is not None: main_scene.stereoscopy_eye_separation = opts.eye_separation frames = 0 frame_count_time = time.monotonic() ev = sdl2.SDL_Event() running = True while running: while True: if (sdl2.SDL_PollEvent(ev) == 0): break if ev.type == sdl2.SDL_QUIT: running = False elif ev.type == sdl2.SDL_KEYUP and ev.key.keysym.sym == sdl2.SDLK_ESCAPE: running = False elif ev.type == sdl2.SDL_KEYDOWN and ev.key.repeat == 0: main_scene.key_down(sdl2.SDL_GetKeyName(ev.key.keysym.sym).decode('ascii').lower()) elif ev.type == sdl2.SDL_KEYUP and ev.key.repeat == 0: main_scene.key_up(sdl2.SDL_GetKeyName(ev.key.keysym.sym).decode('ascii').lower()) elif ev.type == sdl2.SDL_MOUSEBUTTONDOWN: main_scene.mouse_down(ev.button.button, (ev.button.x / width, ev.button.y / height)) elif ev.type == sdl2.SDL_MOUSEBUTTONUP: main_scene.mouse_up(ev.button.button, (ev.button.x / width, ev.button.y / height)) main_scene.update() main_scene.render() blit_multisampled_fbo(width, height, fbo) sdl2.SDL_GL_SwapWindow(window) frames += 1 now = time.monotonic() if now - frame_count_time > FPS_PRINT_TIME: fps = frames / (now - frame_count_time) frames = 0 frame_count_time = now logger.debug("%.3f FPS", fps) main_scene.shutdown() sdl2.SDL_GL_DeleteContext(context) sdl2.SDL_DestroyWindow(window) sdl2.SDL_Quit()
video.SDL_GL_CONTEXT_PROFILE_CORE) context = sdl2.SDL_GL_CreateContext(window) glClearColor(0.5, 0.5, 0.5, 1.0) glEnable(GL_DEPTH_TEST) glViewport(0, 0, 800, 600) shader = OpenGL.GL.shaders.compileProgram( shaders.compileShader(vertex_shader, GL_VERTEX_SHADER), shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER)) vertex_array_object, vertex_buffer = create_vbo(shader) event = sdl2.SDL_Event() running = True while running: while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0: if event.type == sdl2.SDL_QUIT: running = False elif (event.type == sdl2.SDL_KEYDOWN and event.key.keysym.sym == sdl2.SDLK_ESCAPE): running = False render() sdl2.SDL_GL_SwapWindow(window) sdl2.SDL_Delay(10) sdl2.SDL_GL_DeleteContext(context) sdl2.SDL_DestroyWindow(window) sdl2.SDL_Quit()
def __exit__(self, *args): sdl2.SDL_GL_DeleteContext(self.context) sdl2.SDL_DestroyWindow(self.window) sdl2.SDL_Quit()
def cleanup(self): self.renderDelegate.cleanup() sdl2.SDL_GL_DeleteContext(self.glcontext) sdl2.SDL_DestroyWindow(self.window) sdl2.SDL_Quit()
def run(): if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0: print(sdl2.SDL_GetError()) return -1 verts, tris = dc.dual_contour(test_f, test_df, 16) print verts print tris window = sdl2.SDL_CreateWindow(b"OpenGL demo", sdl2.SDL_WINDOWPOS_UNDEFINED, sdl2.SDL_WINDOWPOS_UNDEFINED, 800, 600, sdl2.SDL_WINDOW_OPENGL) if not window: print(sdl2.SDL_GetError()) return -1 # Force OpenGL 3.3 'core' context. # Must set *before* creating GL context! video.SDL_GL_SetAttribute(video.SDL_GL_CONTEXT_MAJOR_VERSION, 3) video.SDL_GL_SetAttribute(video.SDL_GL_CONTEXT_MINOR_VERSION, 3) video.SDL_GL_SetAttribute(video.SDL_GL_CONTEXT_PROFILE_MASK, video.SDL_GL_CONTEXT_PROFILE_CORE) context = sdl2.SDL_GL_CreateContext(window) i = 0 array = [] array_tris = [] normals = [] vertex_struct_array = [] for v in verts: vv = vertex() vv.vertex = v vertex_struct_array.append(vv) array.extend(v) if i == 0: array.extend([1.0, 0.0, 0.0]) elif i == 1: array.extend([0.0, 1.0, 0.0]) elif i == 2: array.extend([0.0, 0.0, 1.0]) if i < 2: i += 1 else: i = 0 for t in tris: normal = calculate_normal(t, verts) normals.append(normal) array_tris.extend(t) quad = [ -0.5, -0.5, 0.0, 1.0, 0.0, 0.0, 0.5, -0.5, 0.0, 0.0, 1.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0, -0.5, 0.5, 0.0, 1.0, 1.0, 1.0 ] quad = numpy.array(array, dtype=numpy.float32) indices = [0, 1, 2, 2, 3, 0] indices = numpy.array(array_tris, dtype=numpy.uint32) # Setup GL shaders, data, etc. vertex_shader = shaders.compileShader( """ #version 330 in vec3 position; in vec3 color; out vec3 newColor; void main() { gl_Position = vec4(position.xyz / 10.0 - vec3(1.0), 1.0f); newColor = color; } """, GL.GL_VERTEX_SHADER) fragment_shader = shaders.compileShader( """ #version 330 in vec3 newColor; out vec4 outColor; void main() { outColor = vec4(newColor, 1.0f); } """, GL.GL_FRAGMENT_SHADER) shaderProgram = shaders.compileProgram(vertex_shader, fragment_shader) GL.glUseProgram(shaderProgram) VAO = GL.glGenVertexArrays(1) GL.glBindVertexArray(VAO) # Need VBO for triangle vertices and colours VBO = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ARRAY_BUFFER, VBO) GL.glBufferData(GL.GL_ARRAY_BUFFER, quad.nbytes, quad, GL.GL_STATIC_DRAW) EBO = GL.glGenBuffers(1) GL.glBindBuffer(GL.GL_ELEMENT_ARRAY_BUFFER, EBO) GL.glBufferData(GL.GL_ELEMENT_ARRAY_BUFFER, indices.nbytes, indices, GL.GL_STATIC_DRAW) position = GL.glGetAttribLocation(shaderProgram, "position") GL.glVertexAttribPointer(position, 3, GL.GL_FLOAT, GL.GL_FALSE, 24, ctypes.c_void_p(0)) GL.glEnableVertexAttribArray(position) color = GL.glGetAttribLocation(shaderProgram, "color") GL.glVertexAttribPointer(color, 3, GL.GL_FLOAT, GL.GL_FALSE, 24, ctypes.c_void_p(12)) GL.glEnableVertexAttribArray(color) event = sdl2.SDL_Event() running = True GL.glClearColor(0, 0, 0, 1) GL.glEnable(GL.GL_DEPTH_TEST) GL.glEnable(GL.GL_CULL_FACE) GL.glCullFace(GL.GL_FRONT) while running: while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0: if event.type == sdl2.SDL_QUIT: running = False if event.type == sdl2.events.SDL_KEYDOWN: print "SDL_KEYDOWN" if event.key.keysym.sym == sdl2.SDLK_ESCAPE: running = False GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT) GL.glDrawElements(GL.GL_TRIANGLES, len(indices), GL.GL_UNSIGNED_INT, None) sdl2.SDL_GL_SwapWindow(window) #sdl2.SDL_Delay(10) sdl2.SDL_GL_DeleteContext(context) sdl2.SDL_DestroyWindow(window) sdl2.SDL_Quit() return 0
def run(): global shaderProgram global rot global projection global translation global view global lightVec if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0: print(sdl2.SDL_GetError()) return -1 window = sdl2.SDL_CreateWindow(b"OpenGL demo", sdl2.SDL_WINDOWPOS_UNDEFINED, sdl2.SDL_WINDOWPOS_UNDEFINED, windowwidth, windowheight, sdl2.SDL_WINDOW_OPENGL) if not window: print(sdl2.SDL_GetError()) return -1 video.SDL_GL_SetAttribute(video.SDL_GL_CONTEXT_MAJOR_VERSION, 3) video.SDL_GL_SetAttribute(video.SDL_GL_CONTEXT_MINOR_VERSION, 3) video.SDL_GL_SetAttribute(video.SDL_GL_CONTEXT_PROFILE_MASK, video.SDL_GL_CONTEXT_PROFILE_CORE) context = sdl2.SDL_GL_CreateContext(window) # Setup GL shaders, data, etc. initialize() event = sdl2.SDL_Event() running = True # Initial position animated = 1 init_t = glm.vec3(0.0, 0.0, -4.0) rot = glm.mat4(1.0) rot = glm.rotate(rot, glm.radians(45), glm.vec3(0.0, 1.0, 0.0)) rot = glm.rotate(rot, glm.radians(20), glm.vec3(1.0, 0.0, 0.0)) rot = glm.rotate(rot, glm.radians(20), glm.vec3(0.0, 0.0, 1.0)) step = 0.5 translation = glm.mat4(1.0) translation = glm.translate(translation, init_t) projection = glm.perspective(glm.radians(45.0), windowwidth / windowheight, 1.0, 10.0) cameraPos = glm.vec3(0.0, 0.0, 1.0) cameraFront = glm.vec3(0.0, 0.0, -1.0) cameraUp = glm.vec3(0.0, 1.0, 0.0) view = glm.lookAt(cameraPos, cameraPos + cameraFront, cameraUp) while running: while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0: if event.type == sdl2.SDL_QUIT: running = False elif (event.type == sdl2.SDL_KEYDOWN and event.key.keysym.sym == sdl2.SDLK_ESCAPE): running = False # Animation elif (event.type == sdl2.SDL_KEYDOWN and event.key.keysym.sym == sdl2.SDLK_s): if animated == 1: animated = 0 else: animated = 1 # Rotation elif (event.type == sdl2.SDL_KEYDOWN and event.key.keysym.sym == sdl2.SDLK_RIGHT): rot = glm.rotate(rot, glm.radians(step), glm.vec3(0.0, 0.0, 1.0)) elif (event.type == sdl2.SDL_KEYDOWN and event.key.keysym.sym == sdl2.SDLK_LEFT): rot = glm.rotate(rot, glm.radians(-step), glm.vec3(0.0, 0.0, 1.0)) elif (event.type == sdl2.SDL_KEYDOWN and event.key.keysym.sym == sdl2.SDLK_q): rot = glm.rotate(rot, glm.radians(step), glm.vec3(0.0, 1.0, 0.0)) elif (event.type == sdl2.SDL_KEYDOWN and event.key.keysym.sym == sdl2.SDLK_a): rot = glm.rotate(rot, glm.radians(-step), glm.vec3(0.0, 1.0, 0.0)) elif (event.type == sdl2.SDL_KEYDOWN and event.key.keysym.sym == sdl2.SDLK_UP): rot = glm.rotate(rot, glm.radians(step), glm.vec3(1.0, 0.0, 0.0)) elif (event.type == sdl2.SDL_KEYDOWN and event.key.keysym.sym == sdl2.SDLK_DOWN): rot = glm.rotate(rot, glm.radians(-step), glm.vec3(1.0, 0.0, 0.0)) render() if animated == 1: rot = glm.rotate(rot, glm.radians(step), glm.vec3(0.0, 1.0, 0.0)) sdl2.SDL_GL_SwapWindow(window) sdl2.SDL_Delay(10) sdl2.SDL_GL_DeleteContext(context) sdl2.SDL_DestroyWindow(window) sdl2.SDL_Quit() return 0
def cleanup(self): sdl2.SDL_GL_DeleteContext(self.context) sdl2.SDL_DestroyWindow(self.window) sdl2.SDL_Quit() sys.exit(0)
def run(): if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0: print(sdl2.SDL_GetError()) return window = sdl2.SDL_CreateWindow( b"Example 1", sdl2.SDL_WINDOWPOS_UNDEFINED, sdl2.SDL_WINDOWPOS_UNDEFINED, 640, 480, sdl2.SDL_WINDOW_OPENGL) context = sdl2.SDL_GL_CreateContext(window) # get Vertex Array Object name vao = GL.glGenVertexArrays(1) # set this new VAO to the active one GL.glBindVertexArray(vao) # vertex data for one triangle triangle_vertices = [0.0, 0.5, 0.5, -0.5, -0.5, -0.5] # convert to ctypes c_float array triangle_array = ((ctypes.c_float * len(triangle_vertices)) (*triangle_vertices)) # get a VBO name from the graphics card vbo = GL.glGenBuffers(1) # bind our vbo name to the GL_ARRAY_BUFFER target GL.glBindBuffer(GL.GL_ARRAY_BUFFER, vbo) # move the vertex data to a new data store associated with our vbo GL.glBufferData(GL.GL_ARRAY_BUFFER, ctypes.sizeof(triangle_array), triangle_array, GL.GL_STATIC_DRAW) # vertex shader vertexShaderProgram = """#version 100 in vec2 position; void main() { gl_Position = vec4(position, 0.0, 1.0); }""" vertexShader = GL.glCreateShader(GL.GL_VERTEX_SHADER) GL.glShaderSource(vertexShader, vertexShaderProgram) GL.glCompileShader(vertexShader) # fragment shader fragmentShaderProgram = """#version 100 out vec4 outColor; void main() { outColor = vec4(1.0, 1.0, 1.0, 1.0); }""" fragmentShader = GL.glCreateShader(GL.GL_FRAGMENT_SHADER) GL.glShaderSource(fragmentShader, fragmentShaderProgram) GL.glCompileShader(fragmentShader) # shader program shaderProgram = GL.glCreateProgram() GL.glAttachShader(shaderProgram, vertexShader) GL.glAttachShader(shaderProgram, fragmentShader) # color output buffer assignment GL.glBindFragDataLocation(shaderProgram, 0, b"outColor") # link the program GL.glLinkProgram(shaderProgram) # validate the program GL.glValidateProgram(shaderProgram) # activate the program GL.glUseProgram(shaderProgram) # specify the layout of our vertex data posAttrib = GL.glGetAttribLocation(shaderProgram, b"position") GL.glEnableVertexAttribArray(posAttrib) GL.glVertexAttribPointer(posAttrib, 2, GL.GL_FLOAT, False, 0, ctypes.c_voidp(0)) # do the actual drawing GL.glClearColor(1.0, 0.5, 0.0, 1.0) GL.glClear(GL.GL_COLOR_BUFFER_BIT) GL.glDrawArrays(GL.GL_TRIANGLES, 0, int(len(triangle_vertices) / 2)) # show the back buffer sdl2.SDL_GL_SwapWindow(window) # wait for somebody to close the window event = sdl2.SDL_Event() while sdl2.SDL_WaitEvent(ctypes.byref(event)): if event.type == sdl2.SDL_QUIT: break # cleanup GL.glDisableVertexAttribArray(posAttrib) GL.glDeleteProgram(shaderProgram) GL.glDeleteShader(fragmentShader) GL.glDeleteShader(vertexShader) GL.glDeleteBuffers(1, [vbo]) GL.glDeleteVertexArrays(1, [vao]) sdl2.SDL_GL_DeleteContext(context) sdl2.SDL_Quit()