def set_palette(palette=None): """ set_palette(palette=None) -> None Set the display color palette for indexed displays """ check_video() screen = sdl.SDL_GetVideoSurface() if not screen: raise SDLError("Display mode not set") if palette and not hasattr(palette, '__iter__'): raise TypeError("Argument must be a sequence type") default_pal = screen.format.palette if screen.format.BytesPerPixel != 1 or default_pal is None: raise SDLError("Display mode is not colormapped") if palette is None: sdl.SDL_SetPalette(screen, sdl.SDL_PHYSPAL, default_pal.colors, 0, default_pal.ncolors) else: ncolors = min(default_pal.ncolors, len(palette)) colors = ffi.new('SDL_Color[]', ncolors) for i in range(ncolors): try: r, g, b = palette[i] except (ValueError, TypeError): raise TypeError("takes a sequence of sequence of RGB") try: colors[i].r = r colors[i].g = g colors[i].b = b except: raise TypeError("RGB sequence must contain numeric values") sdl.SDL_SetPalette(screen, sdl.SDL_PHYSPAL, colors, 0, ncolors)
def check_opengl(): screen = sdl.SDL_GetVideoSurface() if not screen: raise SDLError("Display mode not set") if not (screen.flags & sdl.SDL_OPENGL): raise SDLError("Not an OPENGL display")
def new_surface_from_surface(c_surface, w, h): if 4 < c_surface.format.BytesPerPixel <= 0: raise ValueError("unsupported Surface bit depth for transform") format = c_surface.format newsurf = sdl.SDL_CreateRGBSurface(c_surface.flags, w, h, format.BitsPerPixel, format.Rmask, format.Gmask, format.Bmask, format.Amask) if not newsurf: SDLError.from_sdl_error() if format.BytesPerPixel == 1 and format.palette: sdl.SDL_SetColors(newsurf, format.palette.colors, 0, format.palette.ncolors) if c_surface.flags & sdl.SDL_SRCCOLORKEY: sdl.SDL_SetColorKey(newsurf, (c_surface.flags & sdl.SDL_RLEACCEL) | sdl.SDL_SRCCOLORKEY, format.colorkey) if c_surface.flags & sdl.SDL_SRCALPHA: result = sdl.SDL_SetAlpha(newsurf, c_surface.flags, format.alpha) if result == -1: raise SDLError.from_sdl_error() return newsurf
def set_palette(self, colors): """ set_palette([RGB, RGB, RGB, ...]) -> None set the color palette for an 8bit Surface """ palette = self._format.palette if not palette: raise SDLError("Surface has no palette") if not hasattr(colors, '__iter__'): raise ValueError("Argument must be a sequence type") if not sdl.SDL_WasInit(sdl.SDL_INIT_VIDEO): raise SDLError( "cannot set palette without pygame.display initialized") length = min(palette.ncolors, len(colors)) c_colors = ffi.new('SDL_Color[]', length) for i in range(length): rgb = colors[i] if (not hasattr(rgb, '__iter__')) or len(rgb) < 3 or len(rgb) > 4: raise ValueError("takes a sequence of integers of RGB") c_colors[i].r = rgb[0] c_colors[i].g = rgb[1] c_colors[i].b = rgb[2] if len(rgb) == 4 and rgb[3] != 255: raise ValueError("takes an alpha value of 255") sdl.SDL_SetColors(self._c_surface, c_colors, 0, length)
def play(loops=0, startpos=0.0): """play(loops=0, start=0.0): return None Start the playback of the music stream""" global _current_music, _music_pos, _music_pos_time, \ _music_frequency, _music_format, _music_channels check_mixer() if not _current_music: raise SDLError("music not loaded") sdl.Mix_HookMusicFinished(_endmusic_callback) sdl.Mix_SetPostMix(_mixmusic_callback, ffi.NULL) frequency, format, channels = (ffi.new('int*'), ffi.new('uint16_t*'), ffi.new('int*')) sdl.Mix_QuerySpec(frequency, format, channels) _music_pos = 0 _music_pos_time = sdl.SDL_GetTicks() _music_frequency = frequency[0] _music_format = format[0] _music_channels = channels[0] volume = sdl.Mix_VolumeMusic(-1) val = sdl.Mix_FadeInMusicPos(_current_music, loops, 0, startpos) sdl.Mix_VolumeMusic(volume) if val == -1: raise SDLError.from_sdl_error()
def rwops_encode_file_path(filepath): if isinstance(filepath, unicode_): filepath = filesystem_encode(filepath) if isinstance(filepath, bytes_): if b'\x00' in filepath: raise SDLError("File path '%.1024s' contains null " "characters" % filepath) return filepath raise SDLError("filepath argument needs to be a unicode or str value")
def update(rectangle=None): """ update(rectangle=None) -> None update(rectangle_list) -> None Update portions of the screen for software displays """ check_video() screen = sdl.SDL_GetVideoSurface() if not screen: raise SDLError("Display mode not set") if (screen.flags & sdl.SDL_OPENGL): raise SDLError("Cannot update an OPENGL display") if not rectangle: sdl.SDL_UpdateRect(screen, 0, 0, 0, 0) return try: if hasattr(rectangle, '__iter__'): # it can either be a rect style 4-tuple or # a sequence of rects or rect styles try: int(rectangle[0]) rects = (rectangle, ) except (ValueError, TypeError): rects = rectangle else: rects = (rectangle, ) if len(rects) == 1: rect = game_rect_from_obj(rects[0]) if screen_crop_rect(rect, screen.w, screen.h): sdl.SDL_UpdateRect(screen, rect.x, rect.y, rect.w, rect.h) return rect_array = ffi.new('SDL_Rect[]', len(rects)) count = 0 for obj in rects: if not obj: continue rect = game_rect_from_obj(obj) if screen_crop_rect(rect, screen.w, screen.h): sdlrect = rect_array[count] sdlrect.x = rect.x sdlrect.y = rect.y sdlrect.w = rect.w sdlrect.h = rect.h count += 1 sdl.SDL_UpdateRects(screen, count, rect_array) except (NotImplementedError, TypeError): raise ValueError( "update requires a rectstyle or sequence of recstyles")
def set_mode(resolution=(0, 0), flags=0, depth=0): """ set_mode(resolution=(0,0), flags=0, depth=0) -> Surface Initialize a window or screen for display """ w, h = unpack_rect(resolution) if w < 0 or h < 0: raise SDLError("Cannot set negative sized display mode") if flags == 0: flags = sdl.SDL_SWSURFACE if not get_init(): init() # depth and double buffering attributes need to be set specially for OpenGL if flags & sdl.SDL_OPENGL: if flags & sdl.SDL_DOUBLEBUF: gl_set_attribute(sdl.SDL_GL_DOUBLEBUFFER, 1) else: gl_set_attribute(sdl.SDL_GL_DOUBLEBUFFER, 0) if depth: gl_set_attribute(sdl.SDL_GL_DEPTH_SIZE, depth) c_surface = sdl.SDL_SetVideoMode(w, h, depth, flags) if c_surface and gl_get_attribute(sdl.SDL_GL_DOUBLEBUFFER): c_surface.flags |= sdl.SDL_DOUBLEBUF else: if depth == 0: flags |= sdl.SDL_ANYFORMAT c_surface = sdl.SDL_SetVideoMode(w, h, depth, flags) if not c_surface: raise SDLError.from_sdl_error() title = ffi.new("char*[1]") icon = ffi.new("char*[1]") sdl.SDL_WM_GetCaption(title, icon) if not title: sdl.SDL_WM_SetCaption("pygame window", "pygame") # pygame does this, so it's possibly a good idea sdl.SDL_PumpEvents() global _display_surface _display_surface = SurfaceNoFree._from_sdl_surface(c_surface) # TODO: set icon stuff return _display_surface
def set_clip(self, rect): """ set_clip(rect) -> None set the current clipping area of the Surface """ if not self._c_surface: raise SDLError("display Surface quit") if rect: sdlrect = ffi.new('SDL_Rect*') sdlrect.x, sdlrect.y, sdlrect.w, sdlrect.h = \ rect_vals_from_obj(rect) res = sdl.SDL_SetClipRect(self._c_surface, sdlrect) else: res = sdl.SDL_SetClipRect(self._c_surface, ffi.NULL) if res == -1: raise SDLError.from_sdl_error()
def save(surface, filename): """ save(Surface, filename) -> None save an image to disk """ surf = surface._c_surface if surf.flags & sdl.SDL_OPENGL: raise NotImplementedError() if not isinstance(filename, string_types): raise TypeError("Expected a string for the file arugment: got %s" % type(filename).__name__) filename = rwops_encode_file_path(filename) fn_normalized = filename.lower() result = 0 # TODO: prep/unprep surface if fn_normalized.endswith(b'bmp'): # save as BMP result = sdl.SDL_SaveBMP(surf, filename) elif (fn_normalized.endswith(b'jpg') or fn_normalized.endswith(b'jpeg')): # save as JPEG result = save_jpg(surf, filename) elif fn_normalized.endswith(b'png'): # save as PNG result = save_png(surf, filename) else: # save as TGA result = save_tga(surf, filename, True) if result == -1: raise SDLError.from_sdl_error()
def set_cursor(size, hotspot, xormasks, andmasks): """ set_cursor(size, hotspot, xormasks, andmasks) -> None set the image for the system mouse cursor """ check_video() spotx, spoty = int(hotspot[0]), int(hotspot[1]) w, h = int(size[0]), int(size[1]) if w % 8 != 0: raise ValueError("Cursor width must be divisible by 8") if not hasattr(xormasks, '__iter__') or not hasattr(andmasks, '__iter__'): raise TypeError("xormask and andmask must be sequences") if len(xormasks) != w * h / 8.0 or len(andmasks) != w * h / 8.0: raise ValueError("bitmasks must be sized width*height/8") try: xordata = ffi.new('uint8_t[]', [int(m) for m in xormasks]) anddata = ffi.new('uint8_t[]', [int(andmasks[i]) for i in range(len(xormasks))]) except (ValueError, TypeError): raise TypeError("Invalid number in mask array") except OverflowError: raise TypeError("Number in mask array is larger than 8 bits") cursor = sdl.SDL_CreateCursor(xordata, anddata, w, h, spotx, spoty) if not cursor: raise SDLError.from_sdl_error() lastcursor = sdl.SDL_GetCursor() sdl.SDL_SetCursor(cursor) sdl.SDL_FreeCursor(lastcursor)
def fill(self, color, rect=None, special_flags=0): """ fill(color, rect=None, special_flags=0) -> Rect fill Surface with a solid color """ self.check_opengl() c_color = create_color(color, self._format) sdlrect = ffi.new('SDL_Rect*') if rect is not None: sdlrect.x, sdlrect.y, sdlrect.w, sdlrect.h = rect_vals_from_obj( rect) else: sdlrect.w = self._w sdlrect.h = self._h if self.crop_to_surface(sdlrect): if special_flags: res = sdl.surface_fill_blend(self._c_surface, sdlrect, c_color, special_flags) else: with locked(self._c_surface): # TODO: prep/unprep res = sdl.SDL_FillRect(self._c_surface, sdlrect, c_color) if res == -1: raise SDLError.from_sdl_error() return Rect._from4(sdlrect.x, sdlrect.y, sdlrect.w, sdlrect.h)
def load(filename, namehint=""): try: filename = rwops_encode_file_path(filename) c_surface = sdl.IMG_Load(filename) except SDLError: # filename is not a string, try as file object try: rwops = rwops_from_file(filename) if namehint: name, ext = path.splitext(namehint) elif hasattr(filename, 'name'): name, ext = path.splitext(filename.name) else: # No name info, so we pass an empty extension to # SDL to indicate we can only load files with # suitable magic format markers in the file. name, ext = '', '' if len(ext) == 0: ext = name ext = rwops_encode_file_path(ext) c_surface = sdl.IMG_LoadTyped_RW(rwops, 1, ext) except TypeError: raise TypeError("file argument must be a valid path " "string or file object") if not c_surface: raise SDLError(ffi.string(sdl.IMG_GetError())) return Surface._from_sdl_surface(c_surface)
def fill(self, color, rect=None, special_flags=0): """ fill(color, rect=None, special_flags=0) -> Rect fill Surface with a solid color """ self.check_opengl() c_color = create_color(color, self._format) sdlrect = ffi.new('SDL_Rect*') if rect is not None: sdlrect.x, sdlrect.y, sdlrect.w, sdlrect.h = rect_vals_from_obj(rect) else: sdlrect.w = self._w sdlrect.h = self._h if self.crop_to_surface(sdlrect): if special_flags: res = sdl.surface_fill_blend(self._c_surface, sdlrect, c_color, special_flags) else: with locked(self._c_surface): # TODO: prep/unprep res = sdl.SDL_FillRect(self._c_surface, sdlrect, c_color) if res == -1: raise SDLError.from_sdl_error() return Rect._from4(sdlrect.x, sdlrect.y, sdlrect.w, sdlrect.h)
def get_pitch(self): """ get_pitch() -> int get the number of bytes used per Surface row """ if not self._c_surface: raise SDLError("display Surface quit") return self._c_surface.flags
def get_view(self, kind): """ get_view(<kind>='2') -> BufferProxy return a buffer view of the Surface's pixels. """ if not self._c_surface: raise SDLError("display Surface quit") raise NotImplementedError
def get_buffer(self): """ get_buffer() -> BufferProxy acquires a buffer object for the pixels of the Surface. """ if not self._c_surface: raise SDLError("display Surface quit") raise NotImplementedError
def get_flags(self): """ get_flags() -> int get the additional flags used for the Surface """ if not self._c_surface: raise SDLError("display Surface quit") return self._c_surface.flags
def play(loops=0, startpos=0.0): """play(loops=0, start=0.0): return None Start the playback of the music stream""" global _current_music, _music_pos, _music_pos_time, \ _music_frequency, _music_format, _music_channels check_mixer() if not _current_music: raise SDLError("music not loaded") sdl.Mix_HookMusicFinished(sdl._endmusic_callback) sdl.Mix_SetPostMix(sdl._mixmusic_callback, ffi.NULL) frequency, format, channels = (ffi.new('int*'), ffi.new('uint16_t*'), ffi.new('int*')) sdl.Mix_QuerySpec(frequency, format, channels) _music_pos = 0 _music_pos_time = sdl.SDL_GetTicks() _music_frequency = frequency[0] _music_format = format[0] _music_channels = channels[0] volume = sdl.Mix_VolumeMusic(-1) val = sdl.Mix_FadeInMusicPos(_current_music, loops, 0, startpos) sdl.Mix_VolumeMusic(volume) if val == -1: raise SDLError.from_sdl_error()
def get_button(self, i): """ get_button(button) -> bool get the current button state """ joydata = self._joydata if i < 0 or i >= sdl.SDL_JoystickNumButtons(joydata): raise SDLError("Invalid joystick button") return sdl.SDL_JoystickGetButton(joydata, i)
def _win_rwops_from_file(fileobj): """Windows compatible implementation of rwops_from_file.""" # sdl.SDL_RWFromFP doesn't setup the correct handlers on # windows, so we fall back to our helpers rwops = _lib_rwops_from_file(fileobj) if not rwops: raise SDLError.from_sdl_error() return rwops
def set_pos(pos): """ set_pos(pos) -> None set position to play from """ check_mixer() pos = float(pos) if sdl.Mix_SetMusicPosition(pos) == -1: raise SDLError("set_pos unsupported for this codec")
def init(): """ init() -> None Initialize the display module """ if not video_autoinit(): raise SDLError.from_sdl_error() if not autoinit(): raise RuntimeError("autoinit failed")
def get_shifts(self): """ get_shifts() -> (R, G, B, A) the bit shifts needed to convert between a color and a mapped integer """ if not self._c_surface: raise SDLError("display Surface quit") format = self._format return (format.Rshift, format.Gshift, format.Bshift, format.Ashift)
def wait(): """ wait() -> EventType instance wait for a single event from the queue """ event = ffi.new('SDL_Event*') if not sdl.SDL_WaitEvent(event): raise SDLError.from_sdl_error() return EventType(event[0])
def set_volume(self, lvolume, rvolume=None): check_mixer() # This logic differs a bit from pygames because we can use a better # sentinal value if rvolume is None: # No Panning if sdl.Mix_SetPanning(self.chan, 255, 255) == 0: raise SDLError.from_sdl_error() volume = int(lvolume * 128) else: # Panning left = int(lvolume * 255) right = int(rvolume * 255) if sdl.Mix_SetPanning(self.chan, left, right) == 0: raise SDLError.from_sdl_error() volume = 128 sdl.Mix_Volume(self.chan, volume)
def get_masks(self): """ get_masks() -> (R, G, B, A) the bitmasks needed to convert between a color and a mapped integer """ if not self._c_surface: raise SDLError("display Surface quit") format = self._format return (format.Rmask, format.Gmask, format.Bmask, format.Amask)
def get_losses(self): """ get_losses() -> (R, G, B, A) the significant bits used to convert between a color and a mapped integer """ if not self._c_surface: raise SDLError("display Surface quit") format = self._format return (format.Rloss, format.Gloss, format.Bloss, format.Aloss)
def get_clip(self): """ get_clip() -> Rect get the current clipping area of the Surface """ if not self._c_surface: raise SDLError("display Surface quit") c_rect = self._c_surface.clip_rect return Rect._from4(c_rect.x, c_rect.y, c_rect.w, c_rect.h)
def init(self): """ init() -> None initialize the Joystick """ if self._id not in self._OPEN_JOYSTICKS: joydata = sdl.SDL_JoystickOpen(self._id) if not joydata: raise SDLError.from_sdl_error() self._OPEN_JOYSTICKS[self._id] = joydata
def flip(): """ flip() -> None Update the full display Surface to the screen """ check_video() screen = sdl.SDL_GetVideoSurface() if not screen: raise SDLError("Display mode not set") if screen.flags & sdl.SDL_OPENGL: sdl.SDL_GL_SwapBuffers() status = 0 else: status = sdl.SDL_Flip(screen) if status == -1: raise SDLError.from_sdl_error()
def set_repeat(delay=0, interval=0): """ set_repeat() -> None control how held keys are repeated """ check_video() if delay and not interval: interval = delay if sdl.SDL_EnableKeyRepeat(delay, interval) == -1: raise SDLError.from_sdl_error()
def set_colorkey(self, color=None, flags=0): self.check_opengl() c_color = 0 if color is not None: c_color = create_color(color, self._format) flags |= sdl.SDL_SRCCOLORKEY with locked(self._c_surface): if sdl.SDL_SetColorKey(self._c_surface, flags, c_color) == -1: raise SDLError.from_sdl_error()
def gl_set_attribute(flag, value): """ gl_set_attribute(flag, value) -> None Request an OpenGL display attribute for the display mode """ check_video() # check_opengl() if flag == -1: return None if sdl.SDL_GL_SetAttribute(flag, value) == -1: raise SDLError.from_sdl_error()
def _unix_rwops_from_file(fileobj): """Non-windows implementation of rwops_from_file.""" try: # We try use the SDL helper first, since # it's the simplest code path rwops = sdl.SDL_RWFromFP(fileobj, 0) except (TypeError, IOError): # Construct a suitable rwops object rwops = _lib_rwops_from_file(fileobj) if not rwops: raise SDLError.from_sdl_error() return rwops
def gl_get_attribute(flag): """ gl_get_attribute(flag) -> value Get the value for an OpenGL flag for the current display """ check_video() # pygame seg faults instead of doing this # check_opengl() value = ffi.new('int *') if sdl.SDL_GL_GetAttribute(flag, value) == -1: raise SDLError.from_sdl_error() return value[0]
def set_timer(eventid, milliseconds): """set_timer(eventid, milliseconds) -> None repeatedly create an event on the event queue" """ if eventid <= sdl.SDL_NOEVENT or eventid >= sdl.SDL_NUMEVENTS: raise ValueError("Event id must be between NOEVENT(0) and" " NUMEVENTS(32)") old_event = _event_timers.pop(eventid, None) if old_event: sdl.SDL_RemoveTimer(old_event) if milliseconds <= 0: return _try_init() handle = ffi.cast("void *", eventid) newtimer = sdl.SDL_AddTimer(milliseconds, _timer_callback, handle) if not newtimer: SDLError.from_sdl_error() _event_timers[eventid] = newtimer
def set_clip(self, rect): """ set_clip(rect) -> None set the current clipping area of the Surface """ self.check_surface() if rect: sdlrect = ffi.new('SDL_Rect*') sdlrect.x, sdlrect.y, sdlrect.w, sdlrect.h = \ rect_vals_from_obj(rect) res = sdl.SDL_SetClipRect(self._c_surface, sdlrect) else: res = sdl.SDL_SetClipRect(self._c_surface, ffi.NULL) if res == -1: raise SDLError.from_sdl_error()
def init(): """ init() -> (numpass, numfail) initialize all imported pygame modules """ # check that the SDL version is supported # TODO: preserve backwards compatibility in mixer, RWops, etc major, minor, patch = get_sdl_version() try: assert major == 1 assert minor == 2 assert patch >= 9 except AssertionError: raise RuntimeError("Current version of SDL is %i.%i.%i. Only SDL " "versions >= 1.2.9, < 2.0.0 are supported." % (major, minor, patch)) global _sdl_was_init if not platform.system().startswith('Windows') and _with_thread: _sdl_was_init = sdl.SDL_Init(sdl.SDL_INIT_TIMER | sdl.SDL_INIT_NOPARACHUTE | sdl.SDL_INIT_EVENTTHREAD) else: _sdl_was_init = sdl.SDL_Init(sdl.SDL_INIT_TIMER | sdl.SDL_INIT_NOPARACHUTE) if _sdl_was_init == -1: raise SDLError.from_sdl_error() # initialize all the things! success, fail = 0, 0 if video_autoinit(): success += 1 else: fail += 1 # pygame inspects sys.modules and finds all __PYGAMEinit__ functions. # We look for autoinit and only consider submodules of pygame. # pygame normally initializes 6 modules. # We are at 4 modules: cdrom and joystick are missing modules = [v for k, v in sys.modules.iteritems() if k.startswith('pygame.') and v is not None and v != sys.modules[__name__]] for module in modules: init_call = getattr(module, 'autoinit', None) if hasattr(init_call, '__call__'): if init_call(): success += 1 else: fail += 1 return success, fail
def get_cursor(): """ get_cursor() -> (size, hotspot, xormasks, andmasks) get the image for the system mouse cursor """ check_video() cursor = sdl.SDL_GetCursor() if not cursor: raise SDLError.from_sdl_error() w = cursor.area.w h = cursor.area.h size = w * h / 8 xordata = [int(cursor.data[i]) for i in range(size)] anddata = [int(cursor.mask[i]) for i in range(size)] return (w, h), (cursor.hot_x, cursor.hot_y), xordata, anddata
def rwops_from_file(fileobj): try: # We try use the SDL helper first, since # it's the simplest code path rwops = sdl.SDL_RWFromFP(fileobj, 0) except (TypeError, IOError): # Construct a suitable rwops object rwops = sdl.SDL_AllocRW() rwops.hidden.unknown.data1 = ffi.new_handle(fileobj) rwops.seek = obj_seek rwops.read = obj_read rwops.write = obj_write rwops.close = obj_close if not rwops: raise SDLError.from_sdl_error() return rwops
def queue(filename): """ queue(filename) -> None queue a music file to follow the current """ check_mixer() global _queue_music try: filename = rwops_encode_file_path(filename) _queue_music = sdl.Mix_LoadMUS(filename) except SDLError: # try as file object rwops = rwops_from_file(filename) _queue_music = sdl.Mix_LoadMUS_RW(rwops) if not _queue_music: raise SDLError.from_sdl_error()
def post(event): """post(Event): return None place a new event on the queue""" # SDL requires video to be initialised before PushEvent does the right thing check_video() is_blocked = sdl.SDL_EventState(event.type, sdl.SDL_QUERY) == sdl.SDL_IGNORE if is_blocked: raise RuntimeError("event post blocked for %s" % event_name(event.type)) sdl_event = ffi.new("SDL_Event *") sdl_event.type = event.type sdl_event.user.code = _USEROBJECT_CHECK1 sdl_event.user.data1 = _USEROBJECT_CHECK2 sdl_event.user.data2 = ffi.cast("void*", sdl_event) _user_events[sdl_event] = event if sdl.SDL_PushEvent(sdl_event) == -1: raise SDLError.from_sdl_error()
def set_alpha(self, value=None, flags=0): """ set_alpha(value, flags=0) -> None set the alpha value for the full Surface image """ if value is not None: value = int(value) if value > 255: value = 255 if value < 0: value = 0 flags |= sdl.SDL_SRCALPHA else: value = 255 with locked(self._c_surface): if sdl.SDL_SetAlpha(self._c_surface, flags, value) == -1: raise SDLError.from_sdl_error()
def post(event): """post(Event): return None place a new event on the queue""" # SDL requires video to be initialised before PushEvent does the right thing check_video() is_blocked = sdl.SDL_EventState(event.type, sdl.SDL_QUERY) == sdl.SDL_IGNORE if is_blocked: # Silently drop blocked events, since that's what pygame does # (maybe worth logging somehow?) return None sdl_event = ffi.new("SDL_Event *") sdl_event.type = event.type sdl_event.user.code = _USEROBJECT_CHECK1 sdl_event.user.data1 = _USEROBJECT_CHECK2 sdl_event.user.data2 = ffi.cast("void*", sdl_event) _user_events[sdl_event] = event if sdl.SDL_PushEvent(sdl_event) == -1: raise SDLError.from_sdl_error()
def subsurface(self, *rect): self.check_opengl() try: if hasattr(rect[0], '__iter__'): rect = game_rect_from_obj(rect[0]) else: rect = game_rect_from_obj(rect) except TypeError: raise ValueError("not a valid rect style object") if (rect.x < 0 or rect.x + rect.w > self._c_surface.w or rect.y < 0 or rect.y + rect.h > self._c_surface.h): raise ValueError("subsurface rectangle outside surface area") with locked(self._c_surface): format = self._format pixeloffset = (rect.x * format.BytesPerPixel + rect.y * self._c_surface.pitch) startpixel = ffi.cast("char*", self._c_surface.pixels) + pixeloffset surf = self._c_surface sub = sdl.SDL_CreateRGBSurfaceFrom(startpixel, rect.w, rect.h, format.BitsPerPixel, surf.pitch, format.Rmask, format.Gmask, format.Bmask, format.Amask) if not sub: raise SDLError.from_sdl_error() if format.BytesPerPixel == 1 and format.palette: sdl.SDL_SetPalette(sub, sdl.SDL_LOGPAL, format.palette.colors, 0, format.palette.ncolors); if surf.flags & sdl.SDL_SRCALPHA: sdl.SDL_SetAlpha(sub, surf.flags & sdl.SDL_SRCALPHA, format.alpha); if surf.flags & sdl.SDL_SRCCOLORKEY: sdl.SDL_SetColorKey(sub, surf.flags & (sdl.SDL_SRCCOLORKEY | sdl.SDL_RLEACCEL), format.colorkey) subsurface = Surface._from_sdl_surface(sub) data = SubSurfaceData(self, pixeloffset, rect.x, rect.y) subsurface.subsurfacedata = data return subsurface
def __init__(self, font, fontsize): check_font() if not isinstance(fontsize, int): raise TypeError("expected an integer, but got %r" % type(fontsize)) if fontsize < 1: fontsize = 1 file_obj = None if font is None or font == _font_defaultname: file_obj = getResource(_font_defaultname) self._font_file = file_obj # Scaling as from pygame/src/font.c fontsize = int(fontsize * 0.6875) if fontsize < 1: fontsize = 1 elif isinstance(font, (bytes_, unicode_)): filepath = rwops_encode_file_path(font) # According to the pygame comments, we need to ensure the # file exists and is readable before calling out to SDL f = open(filepath, 'r') # pygame raises IOError if this fails, so we don't catch the # exception f.close() self._sdl_font = sdl.TTF_OpenFont(filepath, fontsize) else: file_obj = font if file_obj: # Get a new handle on the file to load the font from. # Otherwise, if the file handle is closed elsewhere, font # rendering will segfault. if self._font_file is None: file_obj = open(os.path.abspath(file_obj.name)) self._font_file = file_obj rwops = rwops_from_file(file_obj) self._sdl_font = sdl.TTF_OpenFontRW(rwops, 1, fontsize) if not self._sdl_font: raise SDLError.from_sdl_error()
def load(obj): """load(filename): return None load(object): return None Load a music file for playback""" check_mixer() global _current_music, _queue_music if isinstance(obj, (bytes_, unicode_)): filename = rwops_encode_file_path(obj) new_music = sdl.Mix_LoadMUS(filename) else: rwops = rwops_from_file(obj) new_music = sdl.Mix_LoadMUS_RW(rwops) if not new_music: raise SDLError.from_sdl_error() # Cleanup if _current_music: sdl.Mix_FreeMusic(_current_music) if _queue_music: sdl.Mix_FreeMusic(_queue_music) _queue_music = None _current_music = new_music
def init(): """ init() -> None Initialize the joystick module. """ if not autoinit(): SDLError.from_sdl_error()