Example #1
0
def save_jpg(surf, filename):
    if (surf.format.BytesPerPixel == 3
            and not (surf.flags & sdl.SDL_SRCALPHA)
            and surf.format.Rshift == 0):
        ss_surf = surf
    else:
        if get_sdl_byteorder() == sdl.SDL_LIL_ENDIAN:
            rmask, gmask, bmask, amask = 0xff, 0xff00, 0xff0000, 0xff000000
        else:
            rmask, gmask, bmask, amask = 0xff00, 0xff, 0xff0000, 0xff000000
        ss_surf = sdl.SDL_CreateRGBSurface(sdl.SDL_SWSURFACE, surf.w, surf.h,
                                           24, rmask, gmask, bmask, amask)
        if not ss_surf:
            return -1
        rect = ffi.new('SDL_Rect*')
        rect.w = surf.w
        rect.h = surf.h
        sdl.SDL_BlitSurface(surf, rect, ss_surf, ffi.NULL)

    ss_rows = ffi.new('unsigned char*[]', surf.h)
    ss_pixels = ffi.cast('unsigned char*', ss_surf.pixels)
    for i in range(surf.h):
        ss_rows[i] = ss_pixels + i * ss_surf.pitch
    err_msg = ffi.new('char**')
    result = jpglib.write_jpeg(filename, ss_rows, surf.w, surf.h, 85, err_msg)

    if ss_surf is not surf:
        sdl.SDL_FreeSurface(ss_surf)
    if result == -1:
        raise IOError("JPGError: %s" % ffi.string(err_msg[0]))
    return result
Example #2
0
def save_png(surf, filename):
    alpha = bool(surf.format.Amask)
    if get_sdl_byteorder() == sdl.SDL_LIL_ENDIAN:
        rmask, gmask, bmask, amask = 0xff, 0xff00, 0xff0000, 0xff000000
    else:
        rmask, gmask, bmask, amask = 0xff00, 0xff0000, 0xff, 0x000000ff
    ss_surf = sdl.SDL_CreateRGBSurface(sdl.SDL_SWSURFACE | sdl.SDL_SRCALPHA,
                                       surf.w, surf.h, 32 if alpha else 24,
                                       rmask, gmask, bmask, amask)
    if not ss_surf:
        return -1
    with opaque(surf):
        rect = ffi.new('SDL_Rect*')
        rect.w = surf.w
        rect.h = surf.h
        sdl.SDL_BlitSurface(surf, rect, ss_surf, ffi.NULL)

    ss_rows = ffi.new('unsigned char*[]', surf.h)
    ss_pixels = ffi.cast('unsigned char*', ss_surf.pixels)
    for i in range(surf.h):
        ss_rows[i] = ss_pixels + i * ss_surf.pitch
    err_msg = ffi.new('char**')
    result = pnglib.write_png(filename, ss_rows, surf.w, surf.h,
                              (pnglib.PNG_COLOR_TYPE_RGB_ALPHA if alpha else
                               pnglib.PNG_COLOR_TYPE_RGB), 8, err_msg)

    sdl.SDL_FreeSurface(ss_surf)
    if result == -1:
        raise IOError("PNGError: %s" % ffi.string(err_msg[0]))
    return result
Example #3
0
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)
Example #4
0
def save_png(surf, filename):
    alpha = bool(surf.format.Amask)
    if get_sdl_byteorder() == sdl.SDL_LIL_ENDIAN:
        rmask, gmask, bmask, amask = 0xff, 0xff00, 0xff0000, 0xff000000
    else:
        rmask, gmask, bmask, amask = 0xff00, 0xff0000, 0xff, 0x000000ff
    ss_surf = sdl.SDL_CreateRGBSurface(sdl.SDL_SWSURFACE | sdl.SDL_SRCALPHA,
                                       surf.w, surf.h, 32 if alpha else 24,
                                       rmask, gmask, bmask, amask)
    if not ss_surf:
        return -1
    with opaque(surf):
        rect = ffi.new('SDL_Rect*')
        rect.w = surf.w
        rect.h = surf.h
        sdl.SDL_BlitSurface(surf, rect, ss_surf, ffi.NULL)

    ss_rows = ffi.new('unsigned char*[]', surf.h)
    ss_pixels = ffi.cast('unsigned char*', ss_surf.pixels)
    for i in range(surf.h):
        ss_rows[i] = ss_pixels + i * ss_surf.pitch
    err_msg = ffi.new('char**')
    result = pnglib.write_png(filename, ss_rows, surf.w, surf.h,
                              (pnglib.PNG_COLOR_TYPE_RGB_ALPHA if alpha else
                               pnglib.PNG_COLOR_TYPE_RGB), 8, err_msg)

    sdl.SDL_FreeSurface(ss_surf)
    if result == -1:
        raise IOError("PNGError: %s" % ffi.string(err_msg[0]))
    return result
Example #5
0
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()
Example #6
0
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)
Example #7
0
def save_jpg(surf, filename):
    if (surf.format.BytesPerPixel == 3 and not (surf.flags & sdl.SDL_SRCALPHA)
            and surf.format.Rshift == 0):
        ss_surf = surf
    else:
        if get_sdl_byteorder() == sdl.SDL_LIL_ENDIAN:
            rmask, gmask, bmask, amask = 0xff, 0xff00, 0xff0000, 0xff000000
        else:
            rmask, gmask, bmask, amask = 0xff00, 0xff, 0xff0000, 0xff000000
        ss_surf = sdl.SDL_CreateRGBSurface(sdl.SDL_SWSURFACE, surf.w, surf.h,
                                           24, rmask, gmask, bmask, amask)
        if not ss_surf:
            return -1
        rect = ffi.new('SDL_Rect*')
        rect.w = surf.w
        rect.h = surf.h
        sdl.SDL_BlitSurface(surf, rect, ss_surf, ffi.NULL)

    ss_rows = ffi.new('unsigned char*[]', surf.h)
    ss_pixels = ffi.cast('unsigned char*', ss_surf.pixels)
    for i in range(surf.h):
        ss_rows[i] = ss_pixels + i * ss_surf.pitch
    err_msg = ffi.new('char**')
    result = jpglib.write_jpeg(filename, ss_rows, surf.w, surf.h, 85, err_msg)

    if ss_surf is not surf:
        sdl.SDL_FreeSurface(ss_surf)
    if result == -1:
        raise IOError("JPGError: %s" % ffi.string(err_msg[0]))
    return result
Example #8
0
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()
Example #9
0
def get_repeat():
    """ get_repeat() -> (delay, interval)
    see how held keys are repeated
    """
    check_video()
    delay, interval = ffi.new('int*'), ffi.new('int*')
    sdl.SDL_GetKeyRepeat(delay, interval)
    return (delay[0], interval[0])
Example #10
0
def get_rel():
    """ get_rel() -> (x, y)
    get the amount of mouse movement
    """
    check_video()
    x, y = ffi.new('int*'), ffi.new('int*')
    sdl.SDL_GetRelativeMouseState(x, y)
    return x[0], y[0]
Example #11
0
def get_rel():
    """ get_rel() -> (x, y)
    get the amount of mouse movement
    """
    check_video()
    x, y = ffi.new('int*'), ffi.new('int*')
    sdl.SDL_GetRelativeMouseState(x, y)
    return x[0], y[0]
Example #12
0
    def render(self, text, antialias, color, background=None):
        """Font.render(text, antialias, color, background=None): return Surface
           draw text on a new Surface"""
        color = Color(color)
        fg = ffi.new("SDL_Color [1]")
        bg = ffi.new("SDL_Color [1]")
        fg[0].r = color.r
        fg[0].g = color.g
        fg[0].b = color.b
        if background:
            try:
                background = Color(background)
                bg[0].r = background.r
                bg[0].g = background.g
                bg[0].b = background.b
            except (TypeError, ValueError):
                # Same error behaviour as pygame
                bg[0].r = 0
                bg[0].g = 0
                bg[0].b = 0
        else:
            bg[0].r = 0
            bg[0].g = 0
            bg[0].b = 0

        if text is None or text == "":
            # Just return a surface of width 1 x font height
            height = sdl.TTF_FontHeight(self._sdl_font)
            surf = Surface((1, height))
            if background and isinstance(background, Color):
                surf.fill(background)
            else:
                # clear the colorkey
                surf.set_colorkey(flags=sdl.SDL_SRCCOLORKEY)
            return surf

        if not isinstance(text, basestring):
            raise TypeError("text must be a string or unicode")
        if "\x00" in text:
            raise ValueError("A null character was found in the text")
        if isinstance(text, unicode):
            text = text.encode("utf-8", "replace")
            if utf_8_needs_UCS_4(text):
                raise UnicodeError("A Unicode character above '\\uFFFF' was found;" " not supported")
        if antialias:
            if background is None:
                sdl_surf = sdl.TTF_RenderUTF8_Blended(self._sdl_font, text, fg[0])
            else:
                sdl_surf = sdl.TTF_RenderUTF8_Shaded(self._sdl_font, text, fg[0], bg[0])
        else:
            sdl_surf = sdl.TTF_RenderUTF8_Solid(self._sdl_font, text, fg[0])
        if not sdl_surf:
            raise SDLError(ffi.string(sdl.TTF_GetError()))
        surf = Surface._from_sdl_surface(sdl_surf)
        if not antialias and background is not None:
            surf.set_colorkey()
            surf.set_palette([(bg[0].r, bg[0].g, bg[0].b)])
        return surf
Example #13
0
def get_caption():
    """ get_caption() -> (title, icontitle)
    Get the current window caption
    """
    title = ffi.new("char*[1]")
    icon = ffi.new("char*[1]")

    sdl.SDL_WM_GetCaption(title, icon)
    return ffi.string(title[0]), ffi.string(icon[0])
Example #14
0
def get_caption():
    """ get_caption() -> (title, icontitle)
    Get the current window caption
    """
    title = ffi.new("char*[1]")
    icon = ffi.new("char*[1]")

    sdl.SDL_WM_GetCaption(title, icon)
    return ffi.string(title[0]), ffi.string(icon[0])
Example #15
0
    def get_ball(self, i):
        """ get_ball(ball_number) -> x, y
        get the relative position of a trackball
        """
        joydata = self._joydata
        if i < 0 or i >= sdl.SDL_JoystickNumBalls(joydata):
            raise SDLError("Invalid joystick trackball")

        dx, dy = ffi.new('int*'), ffi.new('int*')
        sdl.SDL_JoystickGetBall(joydata, i, dx, dy)
        return (dx[0], dy[0])
Example #16
0
    def get_colorkey(self):
        self.check_opengl()

        if not self._c_surface.flags & sdl.SDL_SRCCOLORKEY:
            return None
        r = ffi.new("uint8_t[1]")
        g = ffi.new("uint8_t[1]")
        b = ffi.new("uint8_t[1]")
        a = ffi.new("uint8_t[1]")
        sdl.SDL_GetRGBA(self._format.colorkey, self._format, r, g, b, a)
        return (r[0], g[0], b[0], a[0])
Example #17
0
    def get_colorkey(self):
        self.check_opengl()

        if not self._c_surface.flags & sdl.SDL_SRCCOLORKEY:
            return None
        r = ffi.new("uint8_t[1]")
        g = ffi.new("uint8_t[1]")
        b = ffi.new("uint8_t[1]")
        a = ffi.new("uint8_t[1]")
        sdl.SDL_GetRGBA(self._format.colorkey, self._format, r, g, b, a)
        return (r[0], g[0], b[0], a[0])
Example #18
0
    def overlap(self, othermask, offset):
        """overlap(othermask, offset) -> x,y

           Returns the point of intersection if the masks overlap with
           the given offset - or None if it does not overlap."""
        x, y = offset
        xp = ffi.new('int[1]')
        yp = ffi.new('int[1]')
        val = sdl.bitmask_overlap_pos(self._mask, othermask._mask,
                                      x, y, xp, yp)
        if val:
            return (xp[0], yp[0])
        return None
Example #19
0
    def overlap(self, othermask, offset):
        """overlap(othermask, offset) -> x,y

           Returns the point of intersection if the masks overlap with
           the given offset - or None if it does not overlap."""
        x, y = offset
        xp = ffi.new('int[1]')
        yp = ffi.new('int[1]')
        val = sdl.bitmask_overlap_pos(self._mask, othermask._mask, x, y, xp,
                                      yp)
        if val:
            return (xp[0], yp[0])
        return None
Example #20
0
    def size(self, text):
        """Font.size(text): return (width, height)
           determine the amount of space needed to render text"""
        if not isinstance(text, (bytes_, unicode_)):
            raise TypeError("text must be a string or unicode")
        if isinstance(text, unicode_):
            text = text.encode('utf-8', 'replace')
        w = ffi.new("int*")
        h = ffi.new("int*")
        ecode = sdl.TTF_SizeUTF8(self._sdl_font, text, w, h)
        if ecode == -1:
            raise SDLError(ffi.string(sdl.TTF_GetError()))

        return int(w[0]), int(h[0])
Example #21
0
 def get_length(self):
     """ get_length() -> seconds
     get the length of the Sound
     """
     check_mixer()
     frequency, format, channels = (ffi.new('int*'), ffi.new('uint16_t*'),
                                    ffi.new('int*'))
     sdl.Mix_QuerySpec(frequency, format, channels)
     if format == sdl.AUDIO_S8 or format == sdl.AUDIO_U8:
         mixerbytes = 1.0
     else:
         mixerbytes = 2.0
     numsamples = self.chunk.alen / mixerbytes / channels[0]
     return numsamples / frequency[0]
Example #22
0
    def size(self, text):
        """Font.size(text): return (width, height)
           determine the amount of space needed to render text"""
        if not isinstance(text, (bytes_, unicode_)):
            raise TypeError("text must be a string or unicode")
        if isinstance(text, unicode_):
            text = text.encode('utf-8', 'replace')
        w = ffi.new("int*")
        h = ffi.new("int*")
        ecode = sdl.TTF_SizeUTF8(self._sdl_font, text, w, h)
        if ecode == -1:
            raise SDLError(ffi.string(sdl.TTF_GetError()))

        return int(w[0]), int(h[0])
Example #23
0
 def get_length(self):
     """ get_length() -> seconds
     get the length of the Sound
     """
     check_mixer()
     frequency, format, channels = (ffi.new('int*'), ffi.new('uint16_t*'),
                                    ffi.new('int*'))
     sdl.Mix_QuerySpec(frequency, format, channels)
     if format == sdl.AUDIO_S8 or format == sdl.AUDIO_U8:
         mixerbytes = 1.0
     else:
         mixerbytes = 2.0
     numsamples = self.chunk.alen / mixerbytes / channels[0]
     return numsamples / frequency[0]
Example #24
0
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
Example #25
0
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
Example #26
0
    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)
Example #27
0
    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)
Example #28
0
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)
Example #29
0
    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)
Example #30
0
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)
Example #31
0
def peek(types=None):
    """ peek(type) -> bool
    test if event types are waiting on the queue
    """
    mask = 0
    if not types:
        mask = sdl.SDL_ALLEVENTS
    elif isinstance(types, int):
        mask |= event_mask(types) 
    elif hasattr(types, '__iter__'):
        try:
            for t in types:
                mask |= event_mask(int(t))
        except (ValueError, TypeError):
            raise TypeError("type sequence must contain valid event types")
    else:
        raise TypeError("peek type must be numeric or a sequence")

    sdl.SDL_PumpEvents()
    event = ffi.new('SDL_Event*')
    result = sdl.SDL_PeepEvents(event, 1, sdl.SDL_PEEKEVENT, mask)

    if not types:
        return EventType(event[0])
    return result == 1
Example #32
0
def peek(types=None):
    """ peek(type) -> bool
    test if event types are waiting on the queue
    """
    mask = 0
    if not types:
        mask = sdl.SDL_ALLEVENTS
    elif isinstance(types, int):
        mask |= event_mask(types) 
    elif hasattr(types, '__iter__'):
        try:
            for t in types:
                mask |= event_mask(int(t))
        except (ValueError, TypeError):
            raise TypeError("type sequence must contain valid event types")
    else:
        raise TypeError("peek type must be numeric or a sequence")

    sdl.SDL_PumpEvents()
    event = ffi.new('SDL_Event*')
    result = sdl.SDL_PeepEvents(event, 1, sdl.SDL_PEEKEVENT, mask)

    if not types:
        return EventType(event[0])
    return result == 1
Example #33
0
def _timer_callback(interval, param):
    if sdl.SDL_WasInit(sdl.SDL_INIT_VIDEO):
        event = ffi.new("SDL_Event*")
        event.type = ffi.cast("intptr_t", param)
        # SDL will make a copy of the event while handling SDL_PushEvent,
        # so we don't need to hold the allocated memory after this call.
        sdl.SDL_PushEvent(event)
    return interval
Example #34
0
def get_init():
    """get_init(): return (frequency, format, channels)

       test if the mixer is initialized"""
    if not sdl.SDL_WasInit(sdl.SDL_INIT_AUDIO):
        return None

    freq = ffi.new("int *")
    audioformat = ffi.new("uint16_t *")
    chan = ffi.new("int *")
    if not sdl.Mix_QuerySpec(freq, audioformat, chan):
        return None
    if audioformat[0] & ~0xff:
        format_in_bits = -(audioformat[0] & 0xff)
    else:
        format_in_bits = audioformat[0] & 0xff
    return (int(freq[0]), format_in_bits, int(chan[0]))
Example #35
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])
Example #36
0
def get_init():
    """get_init(): return (frequency, format, channels)

       test if the mixer is initialized"""
    if not sdl.SDL_WasInit(sdl.SDL_INIT_AUDIO):
        return None

    freq = ffi.new("int *")
    audioformat = ffi.new("uint16_t *")
    chan = ffi.new("int *")
    if not sdl.Mix_QuerySpec(freq, audioformat, chan):
        return None
    if audioformat[0] & ~0xff:
        format_in_bits = -(audioformat[0] & 0xff)
    else:
        format_in_bits = audioformat[0] & 0xff
    return (int(freq[0]), format_in_bits, int(chan[0]))
Example #37
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])
Example #38
0
def _timer_callback(interval, param):
    if sdl.SDL_WasInit(sdl.SDL_INIT_VIDEO):
        event = ffi.new("SDL_Event*")
        event.type = ffi.cast("intptr_t", param)
        # SDL will make a copy of the event while handling SDL_PushEvent,
        # so we don't need to hold the allocated memory after this call.
        sdl.SDL_PushEvent(event)
    return interval
Example #39
0
 def unmap_rgb(self, mapped_int):
     """ unmap_rgb(mapped_int) -> Color
     convert a mapped integer color value into a Color
     """
     self.check_surface()
     mapped_int = ffi.cast('uint32_t', mapped_int)
     r, g, b, a = [ffi.new('uint8_t*') for i in range(4)]
     sdl.SDL_GetRGBA(mapped_int, self._format, r, g, b, a)
     return Color(r[0], g[0], b[0], a[0])
Example #40
0
 def unmap_rgb(self, mapped_int):
     """ unmap_rgb(mapped_int) -> Color
     convert a mapped integer color value into a Color
     """
     self.check_surface()
     mapped_int = ffi.cast('uint32_t', mapped_int)
     r, g, b, a = [ffi.new('uint8_t*') for i in range(4)]
     sdl.SDL_GetRGBA(mapped_int, self._format, r, g, b, a)
     return Color(r[0], g[0], b[0], a[0])
Example #41
0
    def get_bounding_rects(self):
        """get_bounding_rects() -> Rects

           Returns a list of bounding rects of regions of set pixels."""
        num_bounding_boxes = ffi.new('int[1]')
        regions = ffi.new('SDL_Rect**')
        r = sdl.internal_get_bounding_rects(self._mask, num_bounding_boxes,
                                            regions)
        # internal_get_bounding_rects returns -2 on memory errors, 0 otherwise
        if r == -2:
            raise MemoryError("Not enough memory to get bounding rects.")
        rects = []
        # The C code creates an array indexed from 1.
        # This turns out to be surprisingly hard to figure out.
        for i in range(1, num_bounding_boxes[0] + 1):
            region = regions[0][i]
            rects.append(Rect((region.x, region.y, region.w, region.h)))
        return rects
Example #42
0
def _drawhorizline(surface, c_color, start_x, end_x, y):
    """Draw a horizontal line using SDL_FillRect"""
    sdlrect = ffi.new('SDL_Rect*')
    if start_x > end_x:
        end_x, start_x = start_x, end_x
    sdlrect.x = ffi.cast("int16_t", start_x)
    sdlrect.y = ffi.cast("int16_t", y)
    sdlrect.w = ffi.cast("uint16_t", end_x - start_x + 1)
    sdlrect.h = 1
    sdl.SDL_FillRect(surface._c_surface, sdlrect, c_color)
Example #43
0
 def unmap_rgb(self, mapped_int):
     """ unmap_rgb(mapped_int) -> Color
     convert a mapped integer color value into a Color
     """
     if not self._c_surface:
         raise SDLError("display Surface quit")
     mapped_int = ffi.cast('uint32_t', mapped_int)
     r, g, b, a = [ffi.new('uint8_t*') for i in range(4)]
     sdl.SDL_GetRGBA(mapped_int, self._format, r, g, b, a)
     return Color(r[0], g[0], b[0], a[0])
Example #44
0
def _drawhorizline(surface, c_color, start_x, end_x, y):
    """Draw a horizontal line using SDL_FillRect"""
    sdlrect = ffi.new('SDL_Rect*')
    if start_x > end_x:
        end_x, start_x = start_x, end_x
    sdlrect.x = ffi.cast("int16_t", start_x)
    sdlrect.y = ffi.cast("int16_t", y)
    sdlrect.w = ffi.cast("uint16_t", end_x - start_x + 1)
    sdlrect.h = 1
    sdl.SDL_FillRect(surface._c_surface, sdlrect, c_color)
Example #45
0
def _drawvertline(surface, c_color, start_y, end_y, x):
    """Draw a vertical line using SDL_FillRect"""
    sdlrect = ffi.new("SDL_Rect*")
    if start_y > end_y:
        end_y, start_y = start_y, end_y
    sdlrect.x = x
    sdlrect.y = start_y
    sdlrect.w = 1
    sdlrect.h = end_y - start_y + 1
    sdl.SDL_FillRect(surface._c_surface, sdlrect, c_color)
Example #46
0
def _drawvertline(surface, c_color, start_y, end_y, x):
    """Draw a vertical line using SDL_FillRect"""
    sdlrect = ffi.new('SDL_Rect*')
    if start_y > end_y:
        end_y, start_y = start_y, end_y
    sdlrect.x = ffi.cast("int16_t", x)
    sdlrect.y = ffi.cast("int16_t", start_y)
    sdlrect.w = 1
    sdlrect.h = ffi.cast("uint16_t", end_y - start_y + 1)
    sdl.SDL_FillRect(surface._c_surface, sdlrect, c_color)
Example #47
0
def clear(event_filter=None):
    if event_filter is None:
        # unfiltered list of events
        mask = sdl.SDL_ALLEVENTS
    else:
        raise NotImplementedError("Implement me")
    sdl.SDL_PumpEvents()
    event = ffi.new("SDL_Event *")
    while sdl.SDL_PeepEvents(event, 1, sdl.SDL_GETEVENT, mask) == 1:
        pass
Example #48
0
def clear(event_filter=None):
    if event_filter is None:
        # unfiltered list of events
        mask = sdl.SDL_ALLEVENTS
    else:
        raise NotImplementedError("Implement me")
    sdl.SDL_PumpEvents()
    event = ffi.new("SDL_Event *")
    while sdl.SDL_PeepEvents(event, 1, sdl.SDL_GETEVENT, mask) == 1:
        pass
Example #49
0
def _drawhorizline(surface, c_color, start_x, end_x, y):
    """Draw a horizontal line using SDL_FillRect"""
    sdlrect = ffi.new("SDL_Rect*")
    if start_x > end_x:
        end_x, start_x = start_x, end_x
    sdlrect.x = start_x
    sdlrect.y = y
    sdlrect.w = end_x - start_x + 1
    sdlrect.h = 1
    sdl.SDL_FillRect(surface._c_surface, sdlrect, c_color)
Example #50
0
def _drawvertline(surface, c_color, start_y, end_y, x):
    """Draw a vertical line using SDL_FillRect"""
    sdlrect = ffi.new('SDL_Rect*')
    if start_y > end_y:
        end_y, start_y = start_y, end_y
    sdlrect.x = ffi.cast("int16_t", x)
    sdlrect.y = ffi.cast("int16_t", start_y)
    sdlrect.w = 1
    sdlrect.h = ffi.cast("uint16_t", end_y - start_y + 1)
    sdl.SDL_FillRect(surface._c_surface, sdlrect, c_color)
Example #51
0
    def get_bounding_rects(self):
        """get_bounding_rects() -> Rects

           Returns a list of bounding rects of regions of set pixels."""
        num_bounding_boxes = ffi.new('int[1]')
        regions = ffi.new('SDL_Rect**')
        r = sdl.internal_get_bounding_rects(self._mask,
                                            num_bounding_boxes, regions)
        # internal_get_bounding_rects returns -2 on memory errors, 0 otherwise
        if r == -2:
            raise MemoryError("Not enough memory to get bounding rects.")
        rects = []
        # The C code creates an array indexed from 1.
        # This turns out to be surprisingly hard to figure out.
        for i in range(1, num_bounding_boxes[0] + 1):
            region = regions[0][i]
            rects.append(Rect((region.x, region.y,
                               region.w, region.h)))
        return rects
Example #52
0
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")
Example #53
0
def get_driver():
    """ get_driver() -> name
    Get the name of the pygame display backend
    """
    check_video()

    buffer_len = 256
    buf = ffi.new('char[]', buffer_len)
    if not sdl.SDL_VideoDriverName(buf, buffer_len):
        return None
    return ffi.string(buf)
Example #54
0
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")
Example #55
0
def get_driver():
    """ get_driver() -> name
    Get the name of the pygame display backend
    """
    check_video()

    buffer_len = 256
    buf = ffi.new('char[]', buffer_len)
    if not sdl.SDL_VideoDriverName(buf, buffer_len):
        return None
    return ffi.string(buf)
Example #56
0
def get_pressed():
    """ get_pressed() -> bools
    get the state of all keyboard buttons
    """
    check_video()
    num_keys = ffi.new('int*')
    key_state = sdl.SDL_GetKeyState(num_keys)
    num_keys = num_keys[0]
    if not key_state or not num_keys:
        return None
    return [key_state[i] for i in range(num_keys)]
Example #57
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]