def main(): sdl2.sdl2_load( ctypes.util.find_library('SDL2')) # '/usr/local/lib/libSDL2.dylib' sdl2.SDL_Init(sdl2.SDL_INIT_EVERYTHING) WINDOW_W = 320 WINDOW_H = 240 window = sdl2.SDL_CreateWindow(b"1st SDL Window via Python-SDL2", 0, 0, WINDOW_W, WINDOW_H, 0) fpsdelay = 100 count = 0 event = sdl2.SDL_Event() done = False while not done: while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0: # 'type' and 'timestamp' are common members for all SDL Event structs. event_type = event.common.type event_timestamp = event.common.timestamp print("Event : type=0x%s, timestamp=%s" % (event_type, event_timestamp)) if event_type == sdl2.SDL_KEYDOWN: if event.key.keysym.sym == sdl2.SDLK_ESCAPE: print("\tSPACE key pressed.") count += 1 if count >= 100: done = True sdl2.SDL_Delay(fpsdelay) sdl2.SDL_Quit()
def run(): sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) window = sdl2.SDL_CreateWindow(b"Hello World", sdl2.SDL_WINDOWPOS_CENTERED, sdl2.SDL_WINDOWPOS_CENTERED, 592, 460, sdl2.SDL_WINDOW_SHOWN) fname = os.path.join(os.path.dirname(os.path.abspath(__file__)), "resources", "hello.bmp") image = sdl2.SDL_LoadBMP(fname.encode("utf-8")) windowsurface = sdl2.SDL_GetWindowSurface(window) sdl2.SDL_BlitSurface(image, None, windowsurface, None) sdl2.SDL_UpdateWindowSurface(window) sdl2.SDL_FreeSurface(image) running = True event = sdl2.SDL_Event() while running: while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0: if event.type == sdl2.SDL_QUIT: running = False break sdl2.SDL_Delay(10) sdl2.SDL_DestroyWindow(window) sdl2.SDL_Quit() return 0
def main(): sdl2.sdl2_load(ctypes.util.find_library('SDL2')) # '/usr/local/lib/libSDL2.dylib' sdl2.SDL_Init(sdl2.SDL_INIT_EVERYTHING) fpsdelay = 100 count = 0 event = sdl2.SDL_Event() done = False while not done: while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0: # 'type' and 'timestamp' are common members for all SDL Event structs. event_type = event.common.type event_timestamp = event.common.timestamp print("Event : type=0x%s, timestamp=%s" % (event_type, event_timestamp) ) if event_type == sdl2.SDL_KEYDOWN: if event.key.keysym.sym == sdl2.SDLK_ESCAPE: done = True count += 1 if count >= 100: done = True sdl2.SDL_Delay(fpsdelay) sdl2.SDL_Quit()
def main(): window_size = (DEFAULT_WINDOW_WIDTH, DEFAULT_WINDOW_HEIGHT) sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) window = sdl2.SDL_CreateWindow( b"Lab 1 - Cardioid", sdl2.SDL_WINDOWPOS_CENTERED, sdl2.SDL_WINDOWPOS_CENTERED, window_size[0], window_size[1], sdl2.SDL_WINDOW_SHOWN | sdl2.SDL_WINDOW_RESIZABLE) # CREATE !!! renderer = sdl2.SDL_CreateRenderer(window, -1, sdl2.SDL_RENDERER_ACCELERATED) running = True event = sdl2.SDL_Event() while running: while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0: if event.type == sdl2.SDL_QUIT: running = False break elif event.type == sdl2.SDL_WINDOWEVENT: if event.window.event == sdl2.SDL_WINDOWEVENT_SIZE_CHANGED: new_width = event.window.data1 new_height = event.window.data2 print("Window {} resized to {}x{}".format( event.window.windowID, new_width, new_height)) window_size = (new_width, new_height) draw(renderer, window_size) sdl2.SDL_DestroyWindow(window) sdl2.SDL_Quit() return 0
def __init__( self, width: int, height: int, fft_bins: int # Number of bins in a FFT spectrum. ): # The object creates interacts with Window Manager of the OS. # And displays the rendered pixel data in Window. # Width and Height are dynamic (must overflow the Display size). self.window = sdl2.SDL_CreateWindow(b'', sdl2.SDL_WINDOWPOS_CENTERED, sdl2.SDL_WINDOWPOS_CENTERED, width, height, sdl2.SDL_RENDERER_ACCELERATED) # Renderer draws rasterizes the data to pixels to be # displayed on the screen. (Doesn't support Float precision). self.renderer = sdl2.SDL_CreateRenderer(self.window, 0, sdl2.SDL_RENDERER_ACCELERATED) # Stores severeal information about events get emitted # in SDL2. Mainly required to detect "Window Close". self.event = sdl2.SDL_Event() # Create several SDL_Point objects which store the coordinates # of the path. self.data_points = pointer((sdl2.SDL_Point * fft_bins)()) self.bar_width = width / fft_bins self.viewport = {'width': width, 'height': height} self.fft_bins = fft_bins
def loop(window, renderer, inputfoo, renderfoo, choke_ms = 100): while True: loopstart = sdl2.SDL_GetTicks() while True: event = sdl2.SDL_Event() rv = sdl2.SDL_PollEvent(ctypes.byref(event)) if rv == 0: break elif event.type == sdl2.SDL_QUIT: return elif event.type == sdl2.SDL_KEYUP: if event.key.keysym.sym == sdl2.SDLK_ESCAPE: if inputfoo(): return elif event.type == sdl2.SDL_WINDOWEVENT: if event.window.event == sdl2.SDL_WINDOWEVENT_RESIZED: sz = Size2(event.window.data1, event.window.data2) sdl2.SDL_GetWindowSize(window, ctypes.byref(w_w), ctypes.byref(w_h)) elif sdl2.SDL_WINDOWEVENT_CLOSE: inputfoo() else: continue print(event.window.event) elif event.type == sdl2.SDL_MOUSEBUTTONDOWN: inputfoo() elapsed = sdl2.SDL_GetTicks() - loopstart if choke_ms > elapsed: sdl2.SDL_Delay(choke_ms - elapsed) renderfoo(window, renderer)
def event_loop(self): assert not self.event_loop_is_running self._next_axes_tick = 0 self._axes_throttle_delay_timer_set = False self._get_axis_pos = sdl2.SDL_GameControllerGetAxis if self.device_is_game_controller else sdl2.SDL_JoystickGetAxis self.event_loop_is_running = True try: assert SDL_INITED assert self.device self.init_handlers() self._last_axes_positions = { axis_idx: None for axis_idx in self._axis_movement_handlers.keys() } try: while not self.quit_event_posted: event = sdl2.SDL_Event() # If there is no event for an entire second, we iterate, giving CPython an opportunity to # raise KeyboardInterrupt. if sdl2.SDL_WaitEventTimeout(ctypes.byref(event), 1000): self._event_handlers.get( event.type, self._on_unhandled_event)(event) except KeyboardInterrupt: pass finally: self.event_loop_is_running = False self._halt_stage(only_axes_with_nonzero_last_command_velocity=True)
def run(self, screen, draw_func, update_func, fps=DEFAULT_FPS): self._screen = screen self._running = True self._fps = fps self._frame_time_ms = 1000 / fps event = sdl2.SDL_Event() time_accumulator_ms = 0 old_time = sdl2.SDL_GetPerformanceCounter() timer_resolution = sdl2.SDL_GetPerformanceFrequency() / 1000 # ms while self._running: while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0: if event.type == sdl2.SDL_QUIT: self._running = False # Adjust the loop speed based on the time passed current_time = sdl2.SDL_GetPerformanceCounter() delta_time_ms = (current_time - old_time) / timer_resolution time_accumulator_ms += delta_time_ms while time_accumulator_ms > self._frame_time_ms: update_func(delta_time_ms) time_accumulator_ms -= self._frame_time_ms old_time = current_time # Update the screen screen.begin_update() draw_func(screen) screen.end_update() self.stop()
def exit_event_loop(self): '''The exit_event_loop method is thread safe and is safe to call even if the event loop is not running. Calling exit_event_loop pushes a quit request onto the SDL event queue, causing self.event_loop() to exit gracefully (IE, return) if it is running.''' event = sdl2.SDL_Event() event.type = sdl2.SDL_QUIT sdl2.SDL_PushEvent(ctypes.byref(event))
def refresh(self): event = sdl2.SDL_Event() self.update_data(self.lidar.get_image()) while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0: if event.type == sdl2.SDL_QUIT: self.running = False break elif event.type == sdl2.SDL_KEYDOWN: if event.key.keysym.sym == sdl2.SDLK_ESCAPE: self.running = False elif event.key.keysym.sym == sdl2.SDLK_1: self.mode = RAW elif event.key.keysym.sym == sdl2.SDLK_2: self.mode = POLAR elif event.key.keysym.sym == sdl2.SDLK_3: self.mode = EUCLID_3D elif event.key.keysym.sym == sdl2.SDLK_4: self.mode = PRETTY_POLAR elif event.key.keysym.sym == sdl2.SDLK_5: self.mode = PRETTY_3D if self.mode == RAW: self.draw_raw() elif self.mode == POLAR: self.draw_polar() elif self.mode == EUCLID_3D: self.draw_3D() elif self.mode == PRETTY_POLAR: self.draw_pretty_polar() elif self.mode == PRETTY_3D: self.draw_pretty_3D() self.window.refresh()
def event_handler(data, event_ptr): if self.running: # SDL2 seems to re-use SDL_Event structures, so we need to make a copy. event = sdl2.SDL_Event() ctypes.pointer(event)[0] = event_ptr.contents self.dispatch(event) return 0
def run(self) -> None: e = sdl2.SDL_Event() while not self.context.quit: while sdl2.SDL_PollEvent(ctypes.byref(e)) != 0: if e.type == sdl2.SDL_QUIT: self.context.quit = True self.world.handle_event(e) self.world.handle_keyboard(sdl2.SDL_GetKeyboardState(None)) self.world.clean() self.world.process_physics() self.world.detect_collisions() self.world.animate() sdl2.SDL_SetRenderDrawColor(self.context.renderer, 0xff, 0xff, 0xff, 0xff) sdl2.SDL_RenderClear(self.context.renderer) self.world.render(self.world.frame.center, self.world.camera.global_position(), self.world.camera.frame.size) self.ui.render(self.ui.frame.center, Vector2D(), self.world.camera.originalSize) sdl2.SDL_RenderPresent(self.context.renderer) self.exit()
def _mainLoop(self): # Main loop running = True event = sdl2.SDL_Event() logging.info('SDL2 Main Loop: Executing.') #sdl2.SDL_ShowWindow(self.vulkan_window) while running: # Poll sdl2 window for currently pending events. while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0: if event.type == sdl2.SDL_QUIT: logging.info('Leaving SDL2 Main Loop: sdl2.SDL_QUIT.') running = False break if event.type == sdl2.SDL_WINDOWEVENT: if event.window.event == sdl2.SDL_WINDOWEVENT_SIZE_CHANGED: newWidth, newHeight = self.vulkan_window.getWindowSize() self.vulkan_base._recreateSwapChain() break # Renderer: Present Vulkan images onto sdl2 window. self.vulkan_base._drawFrame() vkDeviceWaitIdle( self.vulkan_base.logical_device ) logging.info('Checked all outstanding queue operations for all' ' queues in Logical Device have ceased.') return 0
def __init__(self, window): self._event_dispatcher = EventDispatcher(self, window) self._running = False rotate_event = sdl2.SDL_Event() rotate_event.type = EventDispatcher.ROTATE_EVENT self._window = window self._rotate_event_pointer = ctypes.byref(rotate_event)
def click(button='right', loc=(0, 0), release=False): etype = sdl2.SDL_MOUSEBUTTONUP if release else sdl2.SDL_MOUSEBUTTONDOWN e = sdl2.SDL_Event() e.type = etype e.button.type = etype e.button.x, e.button.y = loc e.button.button = _mousebutton_flag(button) return e
def keyup(key, mod=None): keycode, modval = _keysym_attrs(key, mod) e = sdl2.SDL_Event() e.type = sdl2.SDL_KEYUP e.key.type = sdl2.SDL_KEYUP e.key.keysym.sym = keycode e.key.keysym.mod = modval return e
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)
def run(small=False): """SDL2 back end.""" target_board = board.Board(192, 32) # initialise renderer if small: target_renderer = renderer.SdlRendererActualSize() else: target_renderer = renderer.SdlRendererLarge() target_renderer.initialise((192, 32)) board_lock = threading.RLock() end_event = threading.Event() # initialise board animator animator_thread = animator.BoardAnimator( board=target_board, renderer=target_renderer, time_step_in_s=0.05, board_lock=board_lock, end_event=end_event, ) # initialise board updater (also initialises board with 3 rows) target_board_updater = ( board_updater.BoardUpdater_192_32_3_Rows_From_ProtocolBuffers( target_board=target_board, board_lock=board_lock)) # initialise gRPC server server = grpc.server(futures.ThreadPoolExecutor(max_workers=3)) departure_pb2_grpc.add_BoardManagerServicer_to_server( BoardManagerServicer(target_board_updater), server) server.add_insecure_port("[::]:50051") # start gRPC server and board animator animator_thread.start() server.start() running = True event = sdl2.SDL_Event() try: while running: if (sdl2.SDL_PollEvent(ctypes.byref(event)) != 0 and event.type == sdl2.SDL_QUIT): logger.info("received SDL QUIT event") running = False break end_event.wait(0.5) except KeyboardInterrupt: logger.info("received keyboard interrupt") end_event.set() server.stop(0) animator_thread.join() target_renderer.terminate()
def main(): sdl2.sdl2_load(ctypes.util.find_library('SDL2'), # '/usr/local/lib/libSDL2.dylib' ttf_libpath = ctypes.util.find_library('SDL2_ttf'), img_libpath = ctypes.util.find_library('SDL2_image') ) sdl2.SDL_Init(sdl2.SDL_INIT_EVERYTHING) WINDOW_W = 640 WINDOW_H = 360 window = sdl2.SDL_CreateWindow(b"Minimal SDL_Image Test via python-sdl2", 0, 0, WINDOW_W, WINDOW_H, sdl2.SDL_WINDOW_OPENGL) renderer = sdl2.SDL_CreateRenderer(window, -1, 0) sdl2.IMG_Init(sdl2.IMG_INIT_JPG|sdl2.IMG_INIT_PNG|sdl2.IMG_INIT_TIF|sdl2.IMG_INIT_WEBP) rwops_ptr = sdl2.SDL_RWFromFile(bytes(sys.argv[1], 'utf-8'), b"rb") print("PNG?: %s" % ('true' if sdl2.IMG_isPNG(rwops_ptr) else 'false')) texture = sdl2.IMG_LoadTexture_RW(renderer, rwops_ptr, 1) wh = 300 pos = sdl2.SDL_Rect() pos.x = int((WINDOW_W - wh) / 2) pos.y = int((WINDOW_H - wh) / 2) pos.w = wh pos.h = wh sdl2.SDL_RenderCopy(renderer, texture, None, ctypes.byref(pos)) sdl2.SDL_RenderPresent(renderer) fpsdelay = 100 count = 0 event = sdl2.SDL_Event() done = False while not done: while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0: # 'type' and 'timestamp' are common members for all SDL Event structs. event_type = event.common.type event_timestamp = event.common.timestamp # print("Event : type=0x%s, timestamp=%s" % (event_type, event_timestamp) ) if event_type == sdl2.SDL_KEYDOWN: if event.key.keysym.sym == sdl2.SDLK_ESCAPE: done = True sdl2.SDL_SetRenderDrawColor(renderer, 0xA0, 0xA0, 0xA0, 0xFF) sdl2.SDL_RenderClear(renderer) sdl2.SDL_RenderCopy(renderer, texture, None, ctypes.byref(pos)) sdl2.SDL_RenderPresent(renderer) sdl2.SDL_Delay(fpsdelay) sdl2.IMG_Quit() sdl2.SDL_DestroyRenderer(renderer) sdl2.SDL_DestroyWindow(window) sdl2.SDL_Quit()
def run(self): event = sdl2.SDL_Event() while self.running: while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0: self.onEvent(event) # sdl2.SDL_Delay(10) # uncomment this if you want to save CPU resources self.onLoop() self.onCleanup() sdl2.SDL_Quit()
def main_loop(self, draw_frame): running = True event = sdl2.SDL_Event() while running: while sdl2.SDL_PollEvent(ctypes.byref(event)): if event.type == sdl2.SDL_QUIT: running = False draw_frame() sdl2.SDL_Delay(160)
def emit(self, code: int = 0, data: typing.Any = None) -> sdl2.SDL_Event: event = sdl2.SDL_Event() sdl2.SDL_memset(ctypes.byref(event), 0, ctypes.sizeof(sdl2.SDL_Event)) event.type = self.type event.user.code = code event.user.data1 = ctypes.cast(ctypes.pointer(ctypes.py_object(data)), ctypes.c_void_p) if sdl2.SDL_PushEvent(event) != 1: raise sdl2.ext.SDLError() return event
def pump(self, world): # TODO: optimize eventloop to use more efficient functions like PeepEvents? event = sdl2.SDL_Event() while sdl2.SDL_PollEvent(event): for event_handler in event_handlers.get(event.type, ()): event_handler(event, world) if not self.keepRunning: break if not self.keepRunning: break
def run(self): 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 self.render()
def stop_event_wait(): """Post an event to break out of the event loop wait.""" try: user_event = sdl2.SDL_Event() user_event.type = sdl2.SDL_USEREVENT user_event.user.code = 2 user_event.user.data1 = None user_event.user.data2 = None sdl2.SDL_PushEvent(ctypes.byref(user_event)) except: pass
def main(): init() joy = sdl2.SDL_JoystickOpen(0) print('Name: {}'.format(sdl2.SDL_JoystickName(joy))) print('Axes: {}'.format(sdl2.SDL_JoystickNumAxes(joy))) state = ControllerState() evt = sdl2.SDL_Event() running = True conn = SerialConnection( sys.argv[1] if len(sys.argv) >= 2 else '/dev/ttyACM0') # set to mode 1 so it will not attack conn.call(MD49_MODE, (0x00, 0x34, 0x01)) while running: while sdl2.SDL_PollEvent(ctypes.byref(evt)) != 0: if evt.type == sdl2.SDL_QUIT: running = False break elif evt.type == sdl2.SDL_JOYAXISMOTION: jaxis = evt.jaxis # print(state, jaxis.axis, jaxis.value) state.axis_state[jaxis.axis] = jaxis.value handle_axis_motion(conn, state, jaxis.axis, jaxis.value) elif evt.type == sdl2.SDL_JOYBUTTONUP: button = evt.jbutton if button.button == 0: # A: toggle independent state.ind = not state.ind print('Independent: {}'.format(state.ind)) elif button.button == 8: # B: log encoders print(conn.md49_get_encoders()) log_encoders(conn) elif button.button == 3: # Y: reset encoders conn.call(MD49_MODE, ( 0x00, 0x35, )) elif button.button == 4: # left shoulder: reverse state.r_rev = not state.r_rev print('Right reverse: {}'.format(state.r_rev)) elif button.button == 5: # right shoulder: reverse state.l_rev = not state.l_rev print('Left reverse: {}'.format(state.l_rev)) else: print('Button', button.button) time.sleep(0.01) sdl2.SDL_Quit()
def poll_events(): ''' 1) checks for window quit events ''' event = sdl2.SDL_Event() if sdl2.SDL_PollEvent(ctypes.byref(event)): # check for escape key press if (event.type == sdl2.SDL_KEYDOWN and event.key.keysym.sym == sdl2.SDLK_ESCAPE): return False # check for other forms of quit if (event.type == sdl2.SDL_QUIT): return False return True
def pushPesEvent(eventType, data1="", data2=""): global EVENT_TYPE if EVENT_TYPE == None: logging.error("pushPesEvent: PES Event Type has not been registered!") return False pesEvent = sdl2.SDL_Event() pesEvent.type = EVENT_TYPE pesEvent.user.code = eventType pesEvent.user.data1 = cast(c_char_p(data1), c_void_p) pesEvent.user.data2 = cast(c_char_p(data2), c_void_p) logging.debug("pushPesEvent: pushing event (%d, %s, %s)" % (eventType, data1, data2)) sdl2.SDL_PushEvent(pesEvent) return True
def InitializeSDL(self): # SDL sub systems sdl2.SDL_Init(sdl2.SDL_INIT_EVERYTHING) # Video sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) # Window self.window = sdl2.SDL_CreateWindow("shoot 0.0.1",\ sdl2.SDL_WINDOWPOS_UNDEFINED,\ sdl2.SDL_WINDOWPOS_UNDEFINED, 640,\ 480,\ sdl2.SDL_WINDOW_SHOWN) # renderer self.sdl_renderer = sdl2.SDL_CreateRenderer(self.window, -1,\ sdl2.SDL_RENDERER_ACCELERATED) sdl2.SDL_SetRenderDrawColor(self.sdl_renderer, 255, 255, 255, 0) # Sound (from tutorial: http://lazyfoo.net/SDL_tutorials/lesson11/index.php ) # Initialize sdl mixer # Mix_OpenAudio args # First arg (22050) is sound frequency (recommended according to multiple tutorials, # but look into this) # Second arg is sound format # Third arg is number of channels we plan to use (e.g., 2 for stereo sound) # Fourth arg is the sample size (should be 4096) # Audio #sdl2.SDL_Init(sdl2.SDL_INIT_AUDIO) # If using SDL sound; shouldn't do this sdl2.sdlmixer.Mix_Init(sdl2.sdlmixer.MIX_INIT_MOD) # Insert the file formats you wish to allow here, e.g. OGG sdl2.sdlmixer.Mix_OpenAudio(22050, sdl2.sdlmixer.MIX_DEFAULT_FORMAT, 2, 4096) # TTF sdl2.sdlttf.TTF_Init() # Joystick sdl2.SDL_Init(sdl2.SDL_INIT_JOYSTICK) self.joystick = sdl2.SDL_JoystickOpen(0) # Event self.input = sdl2.SDL_Event()
def run(args): sdl2.ext.init() window = sdl2.ext.Window( "Live scan", (800, 600), flags=(sdl2.SDL_WINDOW_SHOWN | sdl2.SDL_WINDOW_RESIZABLE), ) scanner_event_type = sdl2.SDL_RegisterEvents(1) if scanner_event_type == -1: raise RuntimeError() scanner_event = sdl2.SDL_Event() scanner_event.type = scanner_event_type factory = sdl2.ext.SpriteFactory(sdl2.ext.SOFTWARE) scanner = Scanner(args, scanner_event, factory) scanner.start() renderer = sdl2.ext.Renderer(window, logical_size=scanner.sprite.size) window.size = renderer.logical_size[0] * 20, renderer.logical_size[1] * 20 running = True tex = None while running: for event in sdl2.ext.get_events(): if event.type == sdl2.SDL_QUIT: running = False break if event.type == scanner_event_type: tex = sdl2.SDL_CreateTextureFromSurface( renderer.sdlrenderer, scanner.sprite.surface).contents renderer.copy(tex) renderer.present() if event.type == sdl2.SDL_WINDOWEVENT: win_ev = event.window if win_ev.event == sdl2.SDL_WINDOWEVENT_SIZE_CHANGED: renderer.clear() if tex is not None: renderer.copy(tex) renderer.present() if event.type == sdl2.SDL_KEYDOWN: if event.key.keysym.sym == sdl2.SDLK_s: im = contrast_enhance( surface_to_pil(scanner.completed_part.surface), args.contrast) im.save(args.image_out) window.refresh() scanner.join()