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 init(self, hide_window): self._ticks = sdl2.SDL_GetTicks() # Should be less... https://wiki.libsdl.org/SDL_Init sdl2.SDL_Init(sdl2.SDL_INIT_EVERYTHING) self._window = sdl2.SDL_CreateWindow(b"PyBoy", sdl2.SDL_WINDOWPOS_CENTERED, sdl2.SDL_WINDOWPOS_CENTERED, self._scaledresolution[0], self._scaledresolution[1], sdl2.SDL_WINDOW_RESIZABLE) self._sdlrenderer = sdl2.SDL_CreateRenderer( self._window, -1, sdl2.SDL_RENDERER_ACCELERATED) self._sdltexturebuffer = sdl2.SDL_CreateTexture( self._sdlrenderer, sdl2.SDL_PIXELFORMAT_RGBA32, sdl2.SDL_TEXTUREACCESS_STATIC, COLS, ROWS) self.blank_screen() if hide_window: sdl2.SDL_HideWindow(self._window) else: sdl2.SDL_ShowWindow(self._window)
def initialize(self): if os.name == "nt": ctypes.windll.shcore.SetProcessDpiAwareness(1) sdl2.SDL_Init(sdl2.SDL_INIT_EVERYTHING) IMG_Init(IMG_INIT_PNG) # Ugly hack to determine resolution scaling factor as early as possible. win = sdl2.SDL_CreateWindow( "ResolutionTest".encode("utf-8"), sdl2.SDL_WINDOWPOS_UNDEFINED, sdl2.SDL_WINDOWPOS_UNDEFINED, 100, 100, sdl2.SDL_WINDOW_HIDDEN | sdl2.SDL_WINDOW_ALLOW_HIGHDPI, ) rend = sdl2.SDL_CreateRenderer(win, -1, sdl2.SDL_RENDERER_ACCELERATED) win_w = ctypes.c_int() rend_w = ctypes.c_int() sdl2.SDL_GetWindowSize(win, ctypes.byref(win_w), None) sdl2.SDL_GetRendererOutputSize(rend, ctypes.byref(rend_w), None) # Windows HiDPI is silly like this. You get back different window sizes than you put in. self.win_scale = win_w.value / 100.0 Environment.scale.default = rend_w.value / 100.0 sdl2.SDL_DestroyRenderer(rend) sdl2.SDL_DestroyWindow(win) # Initialize our font cache and calculate DPI scaling. Font.initialize()
def __init__(self, lcd, w, h, scale, title, pos=(sdl2.SDL_WINDOWPOS_CENTERED, sdl2.SDL_WINDOWPOS_CENTERED)): self.lcd = lcd self.width = w self.height = h self.mouse_hover_x = -1 self.mouse_hover_y = -1 self.mouse_x = -1 self.mouse_y = -1 self.scale = scale self.window = sdl2.SDL_CreateWindow(title, pos[0], pos[1], w * scale, h * scale, sdl2.SDL_WINDOW_RESIZABLE) self.buf, self.buf0, self.buf_p = make_buffer(w, h) self.sdlrenderer = sdl2.SDL_CreateRenderer( self.window, -1, sdl2.SDL_RENDERER_ACCELERATED) self.sdl_texture_buffer = sdl2.SDL_CreateTexture( self.sdlrenderer, sdl2.SDL_PIXELFORMAT_RGBA32, sdl2.SDL_TEXTUREACCESS_STATIC, w, h) sdl2.SDL_ShowWindow(self.window)
def __init__(self, display_scale: int = 10): self._display_scale = display_scale self._width = self._display_scale * Display._original_width self._height = self._display_scale * Display._original_height self._pixels = np.zeros(Display._original_width * Display._original_height, dtype=np.uint32) if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) < 0: raise sdl2.ext.SDLError() self._window = sdl2.SDL_CreateWindow(b'pychip8', sdl2.SDL_WINDOWPOS_UNDEFINED, sdl2.SDL_WINDOWPOS_UNDEFINED, self._width, self._height, sdl2.SDL_WINDOW_SHOWN) if not self._window: raise sdl2.ext.SDLError() self._renderer = sdl2.SDL_CreateRenderer(self._window, -1, sdl2.SDL_RENDERER_ACCELERATED) if not self._renderer: raise sdl2.ext.SDLError() self._texture = sdl2.SDL_CreateTexture( self._renderer, sdl2.SDL_PIXELFORMAT_ARGB8888, sdl2.SDL_TEXTUREACCESS_STREAMING, Display._original_width, Display._original_height) if not self._texture: raise sdl2.ext.SDLError() sdl2.SDL_RenderClear(self._renderer) sdl2.SDL_RenderPresent(self._renderer)
def __init__(self, window): self.window = window self.world = sdl2.ext.World() self.sdl_renderer = sdl2.SDL_CreateRenderer( window, -1, sdl2.SDL_RENDERER_ACCELERATED) sdl2.SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN_DESKTOP) sdl2.SDL_GL_SetSwapInterval(1)
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 __init__(self): window = sdl2.SDL_CreateWindow( bytes("haxima2", "utf-8"), sdl2.SDL_WINDOWPOS_UNDEFINED, sdl2.SDL_WINDOWPOS_UNDEFINED, 640 * 2, 480 * 2, sdl2.SDL_WINDOW_SHOWN | sdl2.SDL_WINDOW_OPENGL, ) self._renderer = sdl2.SDL_CreateRenderer(window, -1, 0)
def init_sdl2(game, window_name): global cell_size sdl2.ext.init() wsize = cell_size * game.size window = sdl2.SDL_CreateWindow(bytes(window_name, 'utf-8'), sdl2.SDL_WINDOWPOS_UNDEFINED, sdl2.SDL_WINDOWPOS_UNDEFINED, wsize, wsize, sdl2.SDL_WINDOW_SHOWN) renderer = sdl2.SDL_CreateRenderer(window, -1, sdl2.SDL_RENDERER_ACCELERATED) return window, renderer
def setupWindow(self, width, height): self.window = sdl2.SDL_CreateWindow( "%s: %s" % (config.sdl_window_caption, self.clientName), sdl2.SDL_WINDOWPOS_CENTERED, sdl2.SDL_WINDOWPOS_CENTERED, width, height, sdl2.SDL_WINDOW_SHOWN) self.renderer = sdl2.SDL_CreateRenderer( self.window, -1, sdl2.SDL_RENDERER_ACCELERATED) self.texture = sdl2.SDL_CreateTexture( self.renderer, sdl2.SDL_PIXELFORMAT_YV12, sdl2.SDL_TEXTUREACCESS_STREAMING, width, height)
def initialise(self, size): # pylint: disable=arguments-differ sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) self.window = sdl2.SDL_CreateWindow( b"Departure board", sdl2.SDL_WINDOWPOS_CENTERED, sdl2.SDL_WINDOWPOS_CENTERED, *size, sdl2.SDL_WINDOW_SHOWN ) self.renderer = sdl2.SDL_CreateRenderer( self.window, -1, sdl2.SDL_RENDERER_ACCELERATED )
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 init(self): import sdl2 import sdl2.sdlgfx as gfx self._window = sdl2.SDL_CreateWindow(b"FGAme App", sld2.SDL_WINDOWPOS_CENTERED, sld2.SDL_WINDOWPOS_CENTERED, width, height, sld2.SDL_WINDOW_SHOWN) self._renderer = sdl2.SDL_CreateRenderer(self._window, -1, sld2.SDL_RENDERER_ACCELERATED | sld2.SDL_RENDERER_PRESENTVSYNC) self._screen_rect = sdl2.SDL_Rect(x=0, y=0, w=width, h=height) R, G, B = self.background self._bg_color = (R << 24) + (G << 16) + (B << 8) + 255 self.sdl2 = sdl2 self.gfx = gfx self._LP_short = aapolygonRGBA.argtypes[1]
def prepare(): App.running = True App.num_displays = sdl2.SDL_GetNumVideoDisplays() logger.info(f"Number of displays: {App.num_displays}") for display in range(0, App.num_displays): rect = sdl2.SDL_Rect() sdl2.SDL_GetDisplayBounds(display, rect) border_width = rect.w * App.BORDER_WIDTH_PERCENT / 100 border_height = rect.h * App.BORDER_WIDTH_PERCENT / 100 window = sdl2.SDL_CreateWindow( f"{display}".encode("ascii"), 0, 0, int(rect.w - 2 * border_width), int(rect.h - 2 * border_height), int(sdl2.SDL_WINDOW_BORDERLESS), ) window_id = sdl2.SDL_GetWindowID(window) renderer = sdl2.SDL_CreateRenderer(window, -1, 0) sdl2.SDL_SetRenderDrawColor(renderer, 30, 30, 30, 255) sdl2.SDL_ShowWindow(window) sdl2.SDL_SetWindowPosition(window, int(rect.x + border_width), int(rect.y + border_height)) scale_factor = (100 - 2 * App.BORDER_WIDTH_PERCENT) / 100 internal_rect = sdl2.SDL_Rect( int(rect.x * scale_factor), int(rect.y * scale_factor), int(rect.w * scale_factor), int(rect.h * scale_factor), ) App.windows.append({ "rect": rect, "internal_rect": internal_rect, "window_id": window_id, "window": window, "renderer": renderer, }) Events.add_listener(*App.handle_window_leave) Events.add_listener(*App.handle_window_close) Events.add_listener(*App.handle_q)
def __init__(self, pyboy, mb, pyboy_argv, *, scale, title, width, height, pos_x, pos_y): super().__init__(pyboy, mb, pyboy_argv) self.scale = scale self.width, self.height = width, height self.base_title = title self.hover_x = -1 self.hover_y = -1 self._window = sdl2.SDL_CreateWindow( self.base_title.encode("utf8"), pos_x, pos_y, width * scale, height * scale, sdl2.SDL_WINDOW_RESIZABLE ) self.window_id = sdl2.SDL_GetWindowID(self._window) self.buf, self.buf0, self.buf_p = make_buffer(width, height) self._sdlrenderer = sdl2.SDL_CreateRenderer(self._window, -1, sdl2.SDL_RENDERER_ACCELERATED) self._sdltexturebuffer = sdl2.SDL_CreateTexture( self._sdlrenderer, sdl2.SDL_PIXELFORMAT_RGBA8888, sdl2.SDL_TEXTUREACCESS_STATIC, width, height )
def __init__(self, pyboy, mb, pyboy_argv): super().__init__(pyboy, mb, pyboy_argv) if not self.enabled(): return sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) self._ftime = 0.0 self._window = sdl2.SDL_CreateWindow( b"PyBoy", sdl2.SDL_WINDOWPOS_CENTERED, sdl2.SDL_WINDOWPOS_CENTERED, self._scaledresolution[0], self._scaledresolution[1], sdl2.SDL_WINDOW_RESIZABLE ) self._sdlrenderer = sdl2.SDL_CreateRenderer(self._window, -1, sdl2.SDL_RENDERER_ACCELERATED) self._sdltexturebuffer = sdl2.SDL_CreateTexture( self._sdlrenderer, sdl2.SDL_PIXELFORMAT_RGBA8888, sdl2.SDL_TEXTUREACCESS_STATIC, COLS, ROWS ) sdl2.SDL_ShowWindow(self._window)
def __init__(self, width, height, title="Better Pygame", x=sdl2.SDL_WINDOWPOS_CENTERED, y=sdl2.SDL_WINDOWPOS_CENTERED): """ Initialise a display with a title, width and height. """ title = title.encode() global _displays if not _displays: self.window = sdl2.SDL_CreateWindow(title, x, y, width, height, 0) self.renderer = sdl2.SDL_CreateRenderer(self.window, -1, 0) _displays += 1 else: raise DisplayError("A display is already initialised. ")
def __init__(self): # Auto size window for screen root = Tk() self.screen_width = root.winfo_screenwidth() - 10 self.screen_height = root.winfo_screenheight() - 100 sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) sdl2.sdlttf.TTF_Init() self.window = sdl2.SDL_CreateWindow(b'COVID Simulator', sdl2.SDL_WINDOWPOS_UNDEFINED, sdl2.SDL_WINDOWPOS_UNDEFINED, self.screen_width, self.screen_height, sdl2.SDL_WINDOW_SHOWN) sdl2.SDL_SetWindowResizable(self.window, sdl2.SDL_TRUE) self.sdl_renderer = sdl2.SDL_CreateRenderer( self.window, -1, sdl2.SDL_RENDERER_ACCELERATED) sdl2.SDL_RenderSetIntegerScale(self.sdl_renderer, sdl2.SDL_FALSE) sdl2.SDL_SetHint(sdl2.SDL_HINT_RENDER_SCALE_QUALITY, b'0') self.camera = Camera()
def run(): db.connect() db.create_tables([Rom, System, Asset], safe=True) window = sdl2.SDL_CreateWindow(b"Nostalgo", sdl2.SDL_WINDOWPOS_UNDEFINED, sdl2.SDL_WINDOWPOS_UNDEFINED, 1280, 720, sdl2.SDL_WINDOW_SHOWN) renderer = sdl2.SDL_CreateRenderer(window, -1, sdl2.SDL_RENDERER_ACCELERATED | sdl2.SDL_RENDERER_PRESENTVSYNC) sdl2.SDL_SetRenderDrawBlendMode(renderer, sdl2.SDL_BLENDMODE_BLEND) currentState = CurrentState(window=window, db=db) backdrop = Backdrop(currentState) gameList = GameList(currentState) running = True while running: events = sdl2.ext.get_events() for event in events: if event.type == sdl2.SDL_QUIT: running = False break elif event.type == sdl2.SDL_KEYDOWN: if event.key.keysym.sym in [sdl2.SDLK_RETURN]: EmulatorRunner(currentState.getCurrentSystem(), currentState.getCurrentRom()).run() elif event.key.keysym.sym in [sdl2.SDLK_RIGHT, sdl2.SDLK_n]: currentState.incrementSystem() elif event.key.keysym.sym in [sdl2.SDLK_LEFT, sdl2.SDLK_p]: currentState.decrementSystem() elif event.key.keysym.sym in [sdl2.SDLK_UP, sdl2.SDLK_k]: currentState.decrementRom() elif event.key.keysym.sym in [sdl2.SDLK_DOWN, sdl2.SDLK_j]: currentState.incrementRom() elif event.key.keysym.sym in [sdl2.SDLK_ESCAPE, sdl2.SDLK_q]: running = False break sdl2.SDL_Delay(20) sdl2.SDL_RenderClear(renderer) backdrop.render(renderer) gameList.render(renderer) sdl2.SDL_RenderPresent(renderer)
def _initialize_sdl2(self): sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) self.window = sdl2.SDL_CreateWindow( b'CASINT: CASIO Basic Interpreter', sdl2.SDL_WINDOWPOS_CENTERED, sdl2.SDL_WINDOWPOS_CENTERED, 512, 256, sdl2.SDL_WINDOW_SHOWN | sdl2.SDL_WINDOW_RESIZABLE) self.renderer = sdl2.SDL_CreateRenderer(self.window, -1, sdl2.SDL_RENDERER_ACCELERATED) sdl2.SDL_RenderSetLogicalSize(self.renderer, 128, 64) self.texture_graph = sdl2.SDL_CreateTexture( self.renderer, sdl2.SDL_PIXELFORMAT_RGBA8888, sdl2.SDL_TEXTUREACCESS_TARGET, 128, 64) self.texture_text = sdl2.SDL_CreateTexture( self.renderer, sdl2.SDL_PIXELFORMAT_RGBA8888, sdl2.SDL_TEXTUREACCESS_TARGET, 128, 64) # for scrolling the text screen self.texture_scroll = sdl2.SDL_CreateTexture( self.renderer, sdl2.SDL_PIXELFORMAT_RGBA8888, sdl2.SDL_TEXTUREACCESS_TARGET, 128, 64) # init with a clear screen self._render_begin(self.texture_graph) self._clear_screen() self._render_end() self._render_begin(self.texture_text) self._clear_screen() self._render_end() self.font_graph, self.font_graph_inverted = self._load_texture( 'img/font_graph.bmp') self.font_text, self.font_text_inverted = self._load_texture( 'img/font_text.bmp')
def main(): sdl2.sdl2_load( ctypes.util.find_library('SDL2')) # '/usr/local/lib/libSDL2.dylib' sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) WINDOW_W = 640 WINDOW_H = 360 window = sdl2.SDL_CreateWindow( b"RenderDrawPoint/RenderDrawLine/RenderFillRect", 0, 0, WINDOW_W, WINDOW_H, sdl2.SDL_WINDOW_OPENGL) renderer = sdl2.SDL_CreateRenderer(window, -1, 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) draw_points(renderer) draw_lines(renderer) draw_rects(renderer) sdl2.SDL_RenderPresent(renderer) sdl2.SDL_Quit()
def __init__(self, width, height, title="Pythons", borders=True): self.width, self.height = width, height self.show_borders = borders self.title = title.encode() if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0: print(sdl2.SDL_GetError()) return -1 sdl2.sdlttf.TTF_Init() sdl2.sdlimg.IMG_Init(sdl2img.IMG_INIT_PNG) self.window = sdl2.SDL_CreateWindow(self.title, sdl2.SDL_WINDOWPOS_UNDEFINED, sdl2.SDL_WINDOWPOS_UNDEFINED, self.width, self.height, sdl2.SDL_WINDOW_OPENGL) sdl2.SDL_SetWindowBordered(self.window, self.show_borders) if not self.window: print(sdl2.SDL_GetError()) return -1 self.renderer = sdl2.SDL_CreateRenderer( self.window, -1, sdl2.SDL_RENDERER_ACCELERATED | sdl2.SDL_RENDERER_PRESENTVSYNC)
def __init__(self, window): self._window = window self.sdl_renderer = sdl2.SDL_CreateRenderer( self._window.sdl_window, -1, sdl2.SDL_RENDERER_ACCELERATED) self._viewport = Polygon(self.sdl_renderer, Renderer.VIEWPORT_POINTS) rectangle = Polygon(self.sdl_renderer, Renderer.INITIAL_RECTANGLE_POINTS, is_point_visible=self._viewport.contains) circle = Circle( self.sdl_renderer, *Renderer.INITIAL_CIRCLE_PARAMETERS, lambda point: self._viewport.contains(point) and not self._shapes[ 0].contains(point)) triangle = Polygon( self.sdl_renderer, Renderer.INITIAL_TRIANGLE_POINTS, lambda point: self._viewport.contains(point) and not self._shapes[ 0].contains(point) and not self._shapes[2].contains(point)) self._shapes = [ rectangle, triangle, circle, ]
def show(self): # Init video global HAS_INIT_SDL_VIDEO if not HAS_INIT_SDL_VIDEO: self._no_error(sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO)) else: HAS_INIT_SDL_VIDEO = True # Create window self._window = self._no_null( sdl2.SDL_CreateWindow(b"FGAme Game", sdl2.SDL_WINDOWPOS_CENTERED, sdl2.SDL_WINDOWPOS_CENTERED, self.width, self.height, sdl2.SDL_WINDOW_SHOWN)) self._surface = sdl2.SDL_GetWindowSurface(self._window) # Create a renderer # flags = sdl2.SDL_RENDERER_SOFTWARE # flags = sdl2.SDL_RENDERER_ACCELERATED # flags = sdl2.SDL_RENDERER_PRESENTVSYNC flags = sdl2.SDL_RENDERER_ACCELERATED | sdl2.SDL_RENDERER_PRESENTVSYNC self._renderer = self._no_null( sdl2.SDL_CreateRenderer(self._window, -1, flags)) # Create a rect instance that stores the window shape self._screen_rect = self._no_null( sdl2.SDL_Rect(x=0, y=0, w=self.width, h=self.height)) # Saves background color if self.background is not None: R, B, G, A = Color(self.background) self._bg_color = (R << 24) + (G << 16) + (B << 8) + A else: self._bg_color = None self._LP_short = gfx.aapolygonRGBA.argtypes[1] # Flip image self.flip()
def createWindow(self): # Create the window context if sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) != 0: print(sdl2.SDL_GetError()) return -1 sdl2ttf.TTF_Init() sdl2img.IMG_Init(sdl2img.IMG_INIT_PNG) self.window = sdl2.SDL_CreateWindow(self.params["title"].encode(), sdl2.SDL_WINDOWPOS_UNDEFINED, sdl2.SDL_WINDOWPOS_UNDEFINED, self.window_width, self.window_height, sdl2.SDL_WINDOW_OPENGL) sdl2.SDL_SetWindowBordered(self.window, self.show_borders) if not self.window: print(sdl2.SDL_GetError()) return -1 # Renderer self.renderer = sdl2.SDL_CreateRenderer( self.window, -1, sdl2.SDL_RENDERER_ACCELERATED | sdl2.SDL_RENDERER_PRESENTVSYNC) # Build the GUI self.buildElements() # onStart handler if self.onStart is not None: if self.onStart[1] is None: self.onStart[0]() else: self.onStart[0](self.onStart[1]) # look for events self._loopForEvents()
def main(): parser = argparse.ArgumentParser( description='PySDL2 / cefpython example', add_help=True ) parser.add_argument( '-v', '--verbose', help='Turn on debug info', dest='verbose', action='store_true' ) parser.add_argument( '-r', '--renderer', help='Specify hardware or software rendering', default='software', dest='renderer', choices=['software', 'hardware'] ) args = parser.parse_args() logLevel = logging.INFO if args.verbose: logLevel = logging.DEBUG logging.basicConfig( format='[%(filename)s %(levelname)s]: %(message)s', level=logLevel ) logging.info("Using PySDL2 %s" % sdl2.__version__) version = sdl2.SDL_version() sdl2.SDL_GetVersion(version) logging.info( "Using SDL2 %s.%s.%s" % (version.major, version.minor, version.patch) ) # The following variables control the dimensions of the window # and browser display area width = 800 height = 600 # headerHeight is useful for leaving space for controls # at the top of the window (future implementation?) headerHeight = 0 browserHeight = height - headerHeight browserWidth = width # Mouse wheel fudge to enhance scrolling scrollEnhance = 40 # desired frame rate frameRate = 100 # Initialise CEF for offscreen rendering sys.excepthook = cef.ExceptHook switches = { # Tweaking OSR performance by setting the same Chromium flags # as in upstream cefclient (Issue #240). "disable-surfaces": "", "disable-gpu": "", "disable-gpu-compositing": "", "enable-begin-frame-scheduling": "", } browser_settings = { # Tweaking OSR performance (Issue #240) "windowless_frame_rate": frameRate } cef.Initialize(settings={"windowless_rendering_enabled": True}, switches=switches) logging.debug("cef initialised") window_info = cef.WindowInfo() window_info.SetAsOffscreen(0) # Initialise SDL2 for video (add other init constants if you # require other SDL2 functionality e.g. mixer, # TTF, joystick etc. sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) logging.debug("SDL2 initialised") # Create the window window = sdl2.video.SDL_CreateWindow( 'cefpython3 SDL2 Demo', sdl2.video.SDL_WINDOWPOS_UNDEFINED, sdl2.video.SDL_WINDOWPOS_UNDEFINED, width, height, 0 ) # Define default background colour (black in this case) backgroundColour = sdl2.SDL_Color(0, 0, 0) renderer = None if args.renderer == 'hardware': # Create the renderer using hardware acceleration logging.info("Using hardware rendering") renderer = sdl2.SDL_CreateRenderer( window, -1, sdl2.render.SDL_RENDERER_ACCELERATED ) else: # Create the renderer using software acceleration logging.info("Using software rendering") renderer = sdl2.SDL_CreateRenderer( window, -1, sdl2.render.SDL_RENDERER_SOFTWARE ) # Set-up the RenderHandler, passing in the SDL2 renderer renderHandler = RenderHandler(renderer, width, height - headerHeight) # Create the browser instance browser = cef.CreateBrowserSync(window_info, url="https://www.google.com/", settings=browser_settings) browser.SetClientHandler(LoadHandler()) browser.SetClientHandler(renderHandler) # Must call WasResized at least once to let know CEF that # viewport size is available and that OnPaint may be called. browser.SendFocusEvent(True) browser.WasResized() # Begin the main rendering loop running = True # FPS debug variables frames = 0 logging.debug("beginning rendering loop") resetFpsTime = True fpsTime = 0 while running: # record when we started drawing this frame startTime = sdl2.timer.SDL_GetTicks() if resetFpsTime: fpsTime = sdl2.timer.SDL_GetTicks() resetFpsTime = False # Convert SDL2 events into CEF events (where appropriate) events = sdl2.ext.get_events() for event in events: if (event.type == sdl2.SDL_QUIT or (event.type == sdl2.SDL_KEYDOWN and event.key.keysym.sym == sdl2.SDLK_ESCAPE)): running = False logging.debug("SDL2 QUIT event") break if event.type == sdl2.SDL_MOUSEBUTTONDOWN: if event.button.button == sdl2.SDL_BUTTON_LEFT: if event.button.y > headerHeight: logging.debug( "SDL2 MOUSEBUTTONDOWN event (left button)" ) # Mouse click triggered in browser region browser.SendMouseClickEvent( event.button.x, event.button.y - headerHeight, cef.MOUSEBUTTON_LEFT, False, 1 ) elif event.type == sdl2.SDL_MOUSEBUTTONUP: if event.button.button == sdl2.SDL_BUTTON_LEFT: if event.button.y > headerHeight: logging.debug("SDL2 MOUSEBUTTONUP event (left button)") # Mouse click triggered in browser region browser.SendMouseClickEvent( event.button.x, event.button.y - headerHeight, cef.MOUSEBUTTON_LEFT, True, 1 ) elif event.type == sdl2.SDL_MOUSEMOTION: if event.motion.y > headerHeight: # Mouse move triggered in browser region browser.SendMouseMoveEvent(event.motion.x, event.motion.y - headerHeight, False) elif event.type == sdl2.SDL_MOUSEWHEEL: logging.debug("SDL2 MOUSEWHEEL event") # Mouse wheel event x = event.wheel.x if x < 0: x -= scrollEnhance else: x += scrollEnhance y = event.wheel.y if y < 0: y -= scrollEnhance else: y += scrollEnhance browser.SendMouseWheelEvent(0, 0, x, y) elif event.type == sdl2.SDL_TEXTINPUT: # Handle text events to get actual characters typed rather # than the key pressed. logging.debug("SDL2 TEXTINPUT event: %s" % event.text.text) keycode = ord(event.text.text) key_event = { "type": cef.KEYEVENT_CHAR, "windows_key_code": keycode, "character": keycode, "unmodified_character": keycode, "modifiers": cef.EVENTFLAG_NONE } browser.SendKeyEvent(key_event) key_event = { "type": cef.KEYEVENT_KEYUP, "windows_key_code": keycode, "character": keycode, "unmodified_character": keycode, "modifiers": cef.EVENTFLAG_NONE } browser.SendKeyEvent(key_event) elif event.type == sdl2.SDL_KEYDOWN: # Handle key down events for non-text keys logging.debug("SDL2 KEYDOWN event") if event.key.keysym.sym == sdl2.SDLK_RETURN: keycode = event.key.keysym.sym key_event = { "type": cef.KEYEVENT_CHAR, "windows_key_code": keycode, "character": keycode, "unmodified_character": keycode, "modifiers": cef.EVENTFLAG_NONE } browser.SendKeyEvent(key_event) elif event.key.keysym.sym in [ sdl2.SDLK_BACKSPACE, sdl2.SDLK_DELETE, sdl2.SDLK_LEFT, sdl2.SDLK_RIGHT, sdl2.SDLK_UP, sdl2.SDLK_DOWN, sdl2.SDLK_HOME, sdl2.SDLK_END ]: keycode = get_key_code(event.key.keysym.sym) if keycode is not None: key_event = { "type": cef.KEYEVENT_RAWKEYDOWN, "windows_key_code": keycode, "character": keycode, "unmodified_character": keycode, "modifiers": cef.EVENTFLAG_NONE } browser.SendKeyEvent(key_event) elif event.type == sdl2.SDL_KEYUP: # Handle key up events for non-text keys logging.debug("SDL2 KEYUP event") if event.key.keysym.sym in [ sdl2.SDLK_RETURN, sdl2.SDLK_BACKSPACE, sdl2.SDLK_DELETE, sdl2.SDLK_LEFT, sdl2.SDLK_RIGHT, sdl2.SDLK_UP, sdl2.SDLK_DOWN, sdl2.SDLK_HOME, sdl2.SDLK_END ]: keycode = get_key_code(event.key.keysym.sym) if keycode is not None: key_event = { "type": cef.KEYEVENT_KEYUP, "windows_key_code": keycode, "character": keycode, "unmodified_character": keycode, "modifiers": cef.EVENTFLAG_NONE } browser.SendKeyEvent(key_event) # Clear the renderer sdl2.SDL_SetRenderDrawColor( renderer, backgroundColour.r, backgroundColour.g, backgroundColour.b, 255 ) sdl2.SDL_RenderClear(renderer) # Tell CEF to update which will trigger the OnPaint # method of the RenderHandler instance cef.MessageLoopWork() # Update display sdl2.SDL_RenderCopy( renderer, renderHandler.texture, None, sdl2.SDL_Rect(0, headerHeight, browserWidth, browserHeight) ) sdl2.SDL_RenderPresent(renderer) # FPS debug code frames += 1 if sdl2.timer.SDL_GetTicks() - fpsTime > 1000: logging.debug("FPS: %d" % frames) frames = 0 resetFpsTime = True # regulate frame rate if sdl2.timer.SDL_GetTicks() - startTime < 1000.0 / frameRate: sdl2.timer.SDL_Delay( (1000 / frameRate) - (sdl2.timer.SDL_GetTicks() - startTime) ) # User exited exit_app()
# Initialize Subsystems sdl2.SDL_Init(sdl2.SDL_INIT_EVERYTHING) # Window Parameters winName = b"Fuu Flappy Bird" win_width = 600 win_height = 600 window = sdl2.SDL_CreateWindow(winName, sdl2.SDL_WINDOWPOS_CENTERED, sdl2.SDL_WINDOWPOS_CENTERED, win_width, win_height, sdl2.SDL_WINDOW_SHOWN) renderer = sdl2.SDL_CreateRenderer(window, -1, sdl2.SDL_RENDERER_ACCELERATED | sdl2.SDL_RENDERER_PRESENTVSYNC) # Instantiate Scenes gameScene = scene() gameScene.init_as_game(renderer) menuScene = scene() menuScene.init_as_menu(renderer) sceneList = [gameScene, menuScene] # Scene Indexes game_scene_index = 0 menu_scene_index = 1 current_scene_index = menu_scene_index sceneList[current_scene_index].Pause = False
def run_raw(): global renderer, bg_texture, maze, vmp, walls_texture sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO) window = sdl2.SDL_CreateWindow(b"Eye of the Beholder 2", sdl2.SDL_WINDOWPOS_CENTERED, sdl2.SDL_WINDOWPOS_CENTERED, 800, 600, sdl2.SDL_WINDOW_SHOWN | sdl2.SDL_WINDOW_RESIZABLE) renderer = sdl2.SDL_CreateRenderer(window, -1, sdl2.SDL_RENDERER_ACCELERATED + sdl2.SDL_RENDERER_TARGETTEXTURE + sdl2.SDL_RENDERER_PRESENTVSYNC) sdl2.SDL_SetRenderDrawBlendMode(renderer, sdl2.SDL_BLENDMODE_BLEND) render_target = sdl2.SDL_CreateTexture(renderer, sdl2.SDL_PIXELFORMAT_RGB888, sdl2.SDL_TEXTUREACCESS_TARGET, VP_WIDTH_PIXELS, VP_HEIGHT_PIXELS) sdl2.SDL_SetTextureBlendMode(render_target, sdl2.SDL_BLENDMODE_BLEND) sdl2.sdlimage.IMG_Init(sdl2.sdlimage.IMG_INIT_PNG) maze = load_maze('build/level1.maz') vmp = load_vmp('build/dung.vmp.json') bg_texture = get_vmp_bg_texture() walls_texture = get_vmp_wall_texture() party_position = (5, 28) party_direction = Direction.North running = True event = sdl2.SDL_Event() while running: while sdl2.SDL_PollEvent(byref(event)) != 0: if event.type == sdl2.SDL_QUIT: running = False break elif event.type == sdl2.SDL_KEYDOWN: if event.key.keysym.sym == KEY_W: party_position = party_direction.update_pos(party_position) elif event.key.keysym.sym == KEY_S: party_position = party_direction.opposite().update_pos(party_position) elif event.key.keysym.sym == KEY_A: party_position = party_direction.previous_dir().update_pos(party_position) elif event.key.keysym.sym == KEY_D: party_position = party_direction.next_dir().update_pos(party_position) elif event.key.keysym.sym == KEY_Q: party_direction = party_direction.previous_dir() elif event.key.keysym.sym == KEY_E: party_direction = party_direction.next_dir() print(f'position: {party_position[0]}, {party_position[1]}, direction: {party_direction.symbol}') sdl2.SDL_SetRenderTarget(renderer, render_target) sdl2.SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255) sdl2.SDL_RenderClear(renderer) draw_bg() draw_walls(party_position, party_direction) sdl2.SDL_SetRenderTarget(renderer, None) sdl2.SDL_RenderCopy(renderer, render_target, None, None) sdl2.SDL_RenderPresent(renderer) sdl2.SDL_DestroyWindow(window) sdl2.SDL_Quit() return 0
def __init__(self, scale=1): self._scale = scale if self._scale != 1: logger.warn("Scaling set to %s. The implementation is temporary, which means scaling above 1 will impact performance." % self._scale) super(self.__class__, self).__init__(scale) # http://pysdl2.readthedocs.org/en/latest/tutorial/pong.html # https://wiki.libsdl.org/SDL_Scancode#Related_Enumerations self.windowEventsDown = { sdl2.SDLK_UP: WindowEvent.PressArrowUp, sdl2.SDLK_DOWN: WindowEvent.PressArrowDown, sdl2.SDLK_RIGHT: WindowEvent.PressArrowRight, sdl2.SDLK_LEFT: WindowEvent.PressArrowLeft, sdl2.SDLK_a: WindowEvent.PressButtonA, sdl2.SDLK_s: WindowEvent.PressButtonB, sdl2.SDLK_RETURN: WindowEvent.PressButtonStart, sdl2.SDLK_BACKSPACE: WindowEvent.PressButtonSelect, sdl2.SDLK_ESCAPE: WindowEvent.Quit, # sdl2.SDLK_e: self.debug = True sdl2.SDLK_d: WindowEvent.DebugToggle, sdl2.SDLK_SPACE: WindowEvent.PressSpeedUp, } self.windowEventsUp = { sdl2.SDLK_UP: WindowEvent.ReleaseArrowUp, sdl2.SDLK_DOWN: WindowEvent.ReleaseArrowDown, sdl2.SDLK_RIGHT: WindowEvent.ReleaseArrowRight, sdl2.SDLK_LEFT: WindowEvent.ReleaseArrowLeft, sdl2.SDLK_a: WindowEvent.ReleaseButtonA, sdl2.SDLK_s: WindowEvent.ReleaseButtonB, sdl2.SDLK_RETURN: WindowEvent.ReleaseButtonStart, sdl2.SDLK_BACKSPACE: WindowEvent.ReleaseButtonSelect, sdl2.SDLK_z: WindowEvent.SaveState, sdl2.SDLK_x: WindowEvent.LoadState, sdl2.SDLK_SPACE: WindowEvent.ReleaseSpeedUp, } self.debug = False CoreDump.windowHandle = self logger.debug("SDL initialization") sdl2.ext.init() self._scaledResolution = tuple(x * self._scale for x in gameboyResolution) logger.debug('Scale: x%s %s' % (self._scale, self._scaledResolution)) self._window = sdl2.ext.Window("PyBoy", size=self._scaledResolution) self._windowSurface = self._window.get_surface() if self._scale == 1: self._screenBuffer = SimpleFrameBuffer(pixels2dWithoutWarning(self._windowSurface)) else: self._screenBuffer = ScaledFrameBuffer(pixels2dWithoutWarning(self._windowSurface), self._scale) self._screenBuffer.fill(0x00558822) self._window.show() # Only used for VSYNC self.win = sdl2.SDL_CreateWindow(b"", 0, 0, 0, 0, 0) # Hack doesn't work, if hidden # sdl2.SDL_WINDOW_HIDDEN) self.renderer = sdl2.SDL_CreateRenderer(self.win, -1, sdl2.SDL_RENDERER_PRESENTVSYNC) self.scanlineParameters = np.ndarray(shape=(gameboyResolution[0], 4), dtype='uint8') if __debug__: self.__setDebug()