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 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 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 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 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 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 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 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 _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 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 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 _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_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 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 init(): """ init() -> None Initialize the display module """ if not video_autoinit(): raise SDLError.from_sdl_error() if not autoinit(): raise RuntimeError("autoinit failed")
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 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 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 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 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 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 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 _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 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 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 5 modules: cdrom is missing modules = [ v for k, v in sys.modules.items() 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 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 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 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 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 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 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 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 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 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 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 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: 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 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 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 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 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 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 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 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 __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 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 _try_init(): if not _get_init(): if sdl.SDL_InitSubSystem(sdl.SDL_INIT_TIMER): raise SDLError.from_sdl_error()
def init(): """ init() -> None Initialize the joystick module. """ if not autoinit(): SDLError.from_sdl_error()