Example #1
0
 def _do_flip(self):
     """Draw the canvas to the screen."""
     sdl2.SDL_FillRect(self.work_surface, None, self.border_attr)
     if self.composite_artifacts:
         self.work_pixels[:] = video_graphical.apply_composite_artifacts(
             self.pixels[self.vpagenum], 4 // self.bitsperpixel)
         sdl2.SDL_SetSurfacePalette(self.work_surface,
                                    self.composite_palette)
     else:
         self.work_pixels[:] = self.pixels[self.vpagenum]
         sdl2.SDL_SetSurfacePalette(self.work_surface,
                                    self.show_palette[self.blink_state])
     # apply cursor to work surface
     self._show_cursor(True)
     # convert 8-bit work surface to (usually) 32-bit display surface format
     pixelformat = self.display_surface.contents.format
     conv = sdl2.SDL_ConvertSurface(self.work_surface, pixelformat, 0)
     # scale converted surface and blit onto display
     if not self.smooth:
         sdl2.SDL_BlitScaled(conv, None, self.display_surface, None)
     else:
         # smooth-scale converted surface
         w, h = self.window_width, self.window_height
         zoomx = ctypes.c_double(w / (self.size[0] + 2.0 * self.border_x))
         zoomy = ctypes.c_double(h / (self.size[1] + 2.0 * self.border_y))
         # only free the surface just before zoomSurface needs to re-allocate
         # so that the memory block is highly likely to be easily available
         # this seems to avoid unpredictable delays
         sdl2.SDL_FreeSurface(self.zoomed)
         self.zoomed = sdl2.sdlgfx.zoomSurface(conv, zoomx, zoomy,
                                               sdl2.sdlgfx.SMOOTHING_ON)
         # blit onto display
         sdl2.SDL_BlitSurface(self.zoomed, None, self.display_surface, None)
     # create clipboard feedback
     if self.clipboard.active():
         rects = (sdl2.SDL_Rect(r[0] + self.border_x, r[1] + self.border_y,
                                r[2], r[3])
                  for r in self.clipboard.selection_rect)
         sdl_rects = (sdl2.SDL_Rect *
                      len(self.clipboard.selection_rect))(*rects)
         sdl2.SDL_FillRect(
             self.overlay, None,
             sdl2.SDL_MapRGBA(self.overlay.contents.format, 0, 0, 0, 0))
         sdl2.SDL_FillRects(
             self.overlay, sdl_rects, len(sdl_rects),
             sdl2.SDL_MapRGBA(self.overlay.contents.format, 128, 0, 128, 0))
         sdl2.SDL_BlitScaled(self.overlay, None, self.display_surface, None)
     # flip the display
     sdl2.SDL_UpdateWindowSurface(self.display)
     # destroy the temporary surface
     sdl2.SDL_FreeSurface(conv)
Example #2
0
 def screencapture(self, filename):
     format = sdl2.SDL_PIXELFORMAT_ARGB8888
     surface = sdl2.SDL_CreateRGBSurfaceWithFormat(0, 800, 600, 32, format)
     sdl2.SDL_RenderReadPixels(self.wrapped_object.renderer, None, format,
                               surface.pixels, surface.pitch)
     sdl2.SDL_SaveBMP(surface, filename)
     sdl2.SDL_FreeSurface(surface)
Example #3
0
    def _create_texture_from_pict(self, pict):
        print(f'Initializing pict: {pict.stringname}')

        width = 128
        height = 64
        pixelsize = 3
        bytecount = width * height * pixelsize
        assert len(pict.image_bits) * pixelsize >= bytecount

        # create memory for pixel data
        new_p = (ctypes.c_uint8 * bytecount)()
        ref_p = ctypes.byref(new_p)

        # set pixels
        m = memoryview(new_p).cast('B')
        i = 0
        j = pixelsize
        for pixel in pict.image_bits[:width * height]:
            if pixel:
                m[i:j] = b'\x10\x10\x10'
            else:
                m[i:j] = b'\xee\xe8\xe8'
            i += pixelsize
            j += pixelsize

        new_surface = sdl2.SDL_CreateRGBSurfaceWithFormatFrom(
            ref_p, width, height, 8 * pixelsize, width * pixelsize,
            sdl2.SDL_PIXELFORMAT_BGR24)
        texture = sdl2.SDL_CreateTextureFromSurface(self.renderer, new_surface)
        sdl2.SDL_FreeSurface(new_surface)
        return texture
Example #4
0
    def _create_inverted_texture(self, surface):
        # copy the pixels in
        sdl2.SDL_LockSurface(surface)
        surface_p = ctypes.c_void_p.from_address(surface.contents.pixels)
        pixelsize = surface.contents.format.contents.BytesPerPixel
        assert pixelsize == 3
        bytecount = surface.contents.w * surface.contents.h * pixelsize
        # create memory for copy of pixel data
        new_p = (ctypes.c_uint8 * bytecount)()
        ref_p = ctypes.byref(new_p)
        ctypes.memmove(ref_p, ctypes.byref(surface_p), bytecount)
        sdl2.SDL_UnlockSurface(surface)

        # swap pixels
        m = memoryview(new_p).cast('B')
        i = 0
        j = pixelsize
        while j < bytecount:
            if m[i:j] == b'\xee\xe8\xe8':
                m[i:j] = b'\x10\x10\x10'
            else:
                m[i:j] = b'\xee\xe8\xe8'
            i += pixelsize
            j += pixelsize

        new_surface = sdl2.SDL_CreateRGBSurfaceWithFormatFrom(
            ref_p, surface.contents.w, surface.contents.h,
            surface.contents.format.contents.BitsPerPixel,
            surface.contents.pitch, surface.contents.format.contents.format)
        texture = sdl2.SDL_CreateTextureFromSurface(self.renderer, new_surface)
        sdl2.SDL_FreeSurface(new_surface)
        return texture
 def renderall(self, snake, br, g):
     '''
     a function which calls all other functions 
     to render the objects in the game
     '''
     self.__renderblockrows(br)
     self.rendersnake(snake)
     self.rendergoodies(g)
     if self.mode == gameinfo.BLOCK_IN_MOTION:
         self.mode = br.advance(snake)
         for gd in g:
             gd.pos += snake.s
             if gd.pos > gameinfo.WINDOW_HEIGHT:
                 g.remove(gd)
     else:
         self.mode = snake.advance(br)
     texttodisplay = "score:"
     texttodisplay += "%8d" % snake.score
     texttodisplay = texttodisplay.encode()
     sur = ttf.TTF_RenderText_Solid(self.t, texttodisplay, self.YELLOW)
     tex = sdl2.SDL_CreateTextureFromSurface(self.sdlrenderer, sur)
     sdl2.SDL_RenderCopy(self.sdlrenderer, tex, self.Rscore, self.Rscore)
     sdl2.SDL_FreeSurface(sur)
     sdl2.SDL_DestroyTexture(tex)
     snake.adjust()
Example #6
0
 def generate(self) -> None:
     if self.font and len(self.text) and self.color:
         surface = sdl2.sdlttf.TTF_RenderText_Solid(self.font, self.text,
                                                    self.color)
         self.renderObject = RenderObject.render_object_from_surface(
             self.context.renderer, surface)
         sdl2.SDL_FreeSurface(surface)
 def __renderblock(self, number, val, y):
     '''drawing blocks of color according the strength of blocks'''
     if 0 < val < 10:
         self.color = gameinfo.COLOR_GRID["white-green"]
     elif 9 < val < 20:
         self.color = gameinfo.COLOR_GRID["green"]
     elif 19 < val < 30:
         self.color = gameinfo.COLOR_GRID["blue-green"]
     elif 29 < val < 40:
         self.color = gameinfo.COLOR_GRID["blue"]
     else:
         self.color = gameinfo.COLOR_GRID["red"]
     sx = gameinfo.BLOCKSTART[number]
     self.fill((sx, y - gameinfo.BLOCKSIZE, gameinfo.BLOCKSIZE,
                gameinfo.BLOCKSIZE))
     texttodisplay = "%2d" % val
     sur = ttf.TTF_RenderText_Solid(self.t, texttodisplay.encode(),
                                    self.BLACK)
     tex = sdl2.SDL_CreateTextureFromSurface(self.sdlrenderer, sur)
     Rblock = sdl2.SDL_Rect(sx + gameinfo.RECTSTART_X,
                            y - gameinfo.RECTSTART_Y, gameinfo.RECTWIDTH,
                            gameinfo.RECTHEIGHT)
     sdl2.SDL_RenderCopy(self.sdlrenderer, tex, None, Rblock)
     sdl2.SDL_FreeSurface(sur)
     sdl2.SDL_DestroyTexture(tex)
Example #8
0
    def LoadTexture(self, filepath):
        surface = sdl2.sdlimage.IMG_Load(filepath)
        texture = sdl2.SDL_CreateTextureFromSurface(self.sdl_renderer, surface)
        sdl2.SDL_FreeSurface(surface)
        self.loaded_textures[filepath] = texture

        return texture
Example #9
0
def run():
    sdl2.SDL_Init(sdl2.SDL_INIT_VIDEO)
    window = sdl2.SDL_CreateWindow(b"Hello World", sdl2.SDL_WINDOWPOS_CENTERED,
                                   sdl2.SDL_WINDOWPOS_CENTERED, 592, 460,
                                   sdl2.SDL_WINDOW_SHOWN)
    fname = os.path.join(os.path.dirname(os.path.abspath(__file__)),
                         "resources", "hello.bmp")
    image = sdl2.SDL_LoadBMP(fname.encode("utf-8"))
    windowsurface = sdl2.SDL_GetWindowSurface(window)
    sdl2.SDL_BlitSurface(image, None, windowsurface, None)
    sdl2.SDL_UpdateWindowSurface(window)
    sdl2.SDL_FreeSurface(image)

    running = True
    event = sdl2.SDL_Event()
    while running:
        while sdl2.SDL_PollEvent(ctypes.byref(event)) != 0:
            if event.type == sdl2.SDL_QUIT:
                running = False
                break
        sdl2.SDL_Delay(10)

    sdl2.SDL_DestroyWindow(window)
    sdl2.SDL_Quit()
    return 0
Example #10
0
    def create_text(self, renderer, font):
        # Create font surface
        meters_surface = sdl2.sdlttf.TTF_RenderText_Solid(
            font, str.encode(self.meters_text), self.text_color)
        time_surface = sdl2.sdlttf.TTF_RenderText_Solid(
            font, str.encode(self.time_text), self.text_color)

        # Create texture from surface
        self.meters_texture = sdl2.SDL_CreateTextureFromSurface(
            renderer, meters_surface)
        self.time_texture = sdl2.SDL_CreateTextureFromSurface(
            renderer, time_surface)

        # Free surface
        sdl2.SDL_FreeSurface(meters_surface)
        sdl2.SDL_FreeSurface(time_surface)
Example #11
0
 def close(self):
     """ Close the SDL2 interface. """
     video.VideoPlugin.close(self)
     if sdl2 and numpy:
         # free windows
         sdl2.SDL_DestroyWindow(self.display)
         # free surfaces
         for s in self.canvas:
             sdl2.SDL_FreeSurface(s)
         sdl2.SDL_FreeSurface(self.work_surface)
         sdl2.SDL_FreeSurface(self.overlay)
         # free palettes
         for p in self.show_palette:
             sdl2.SDL_FreePalette(p)
         sdl2.SDL_FreePalette(self.composite_palette)
         # close SDL2
         sdl2.SDL_Quit()
Example #12
0
 def free(self):
     """
     Free the image's data. Should be called when it is not needed anymore.
     """
     if self.surface != None:
         sdl2.SDL_FreeSurface(self.surface)
     if self.texture != None:
         sdl2.SDL_DestroyTexture(self.texture)
Example #13
0
 def _load_texture(self, filename):
     filepath = path_join(dirname(__file__), filename).encode()
     surface = sdl2.SDL_LoadBMP(filepath)
     texture = sdl2.SDL_CreateTextureFromSurface(self.renderer, surface)
     # create a copy of inverted pixels
     inverted_texture = self._create_inverted_texture(surface)
     # free the surface
     sdl2.SDL_FreeSurface(surface)
     return texture, inverted_texture
Example #14
0
 def set_mode(self, mode_info):
     """Initialise a given text or graphics mode."""
     self.text_mode = mode_info.is_text_mode
     # unpack mode info struct
     self.font_height = mode_info.font_height
     self.font_width = mode_info.font_width
     # prebuilt glyphs
     # NOTE: [x][y] format - change this if we change pixels2d
     self.glyph_dict = {
         u'\0': numpy.zeros((self.font_width, self.font_height))
     }
     self.num_pages = mode_info.num_pages
     self.mode_has_blink = mode_info.has_blink
     self.mode_has_artifacts = False
     if not self.text_mode:
         self.bitsperpixel = mode_info.bitsperpixel
         self.mode_has_artifacts = mode_info.supports_artifacts
     # logical size
     self.size = (mode_info.pixel_width, mode_info.pixel_height)
     self._resize_display(*self._find_display_size(
         self.size[0], self.size[1], self.border_width))
     # set standard cursor
     self.set_cursor_shape(self.font_width, self.font_height, 0,
                           self.font_height)
     # screen pages
     canvas_width, canvas_height = self.size
     self.canvas = [
         sdl2.SDL_CreateRGBSurface(0, canvas_width, canvas_height, 8, 0, 0,
                                   0, 0) for _ in range(self.num_pages)
     ]
     self.pixels = [pixels2d(canvas.contents) for canvas in self.canvas]
     # create work surface for border and composite
     self.border_x = int(canvas_width * self.border_width // 200)
     self.border_y = int(canvas_height * self.border_width // 200)
     work_width = canvas_width + 2 * self.border_x
     work_height = canvas_height + 2 * self.border_y
     sdl2.SDL_FreeSurface(self.work_surface)
     self.work_surface = sdl2.SDL_CreateRGBSurface(0, work_width,
                                                   work_height, 8, 0, 0, 0,
                                                   0)
     self.work_pixels = pixels2d(
         self.work_surface.contents)[self.border_x:work_width -
                                     self.border_x,
                                     self.border_y:work_height -
                                     self.border_y]
     # create overlay for clipboard selection feedback
     # use convertsurface to create a copy of the display surface format
     pixelformat = self.display_surface.contents.format
     self.overlay = sdl2.SDL_ConvertSurface(self.work_surface, pixelformat,
                                            0)
     sdl2.SDL_SetSurfaceBlendMode(self.overlay, sdl2.SDL_BLENDMODE_ADD)
     # initialise clipboard
     self.clipboard = video_graphical.ClipboardInterface(
         self, mode_info.width, mode_info.height)
     self.screen_changed = True
     self._has_window = True
Example #15
0
 def __exit__(self, type, value, traceback):
     """Close the SDL2 interface."""
     base.VideoPlugin.__exit__(self, type, value, traceback)
     if sdl2 and numpy and self._has_window:
         # free windows
         sdl2.SDL_DestroyWindow(self.display)
         # free surfaces
         for s in self.canvas:
             sdl2.SDL_FreeSurface(s)
         sdl2.SDL_FreeSurface(self.work_surface)
         sdl2.SDL_FreeSurface(self.overlay)
         # free palettes
         for p in self.show_palette:
             sdl2.SDL_FreePalette(p)
         sdl2.SDL_FreePalette(self.composite_palette)
         # close IME
         sdl2.SDL_StopTextInput()
         # close SDL2
         sdl2.SDL_Quit()
Example #16
0
 def refresh(self, image):
     bytes_io = io.BytesIO()
     size = image.size
     image.resize((size[0] * self.scale, size[1] * self.scale)).save(bytes_io, "PPM")
     image_bytes = bytes_io.getvalue()
     rw_ops = sdl2.SDL_RWFromMem(image_bytes, len(image_bytes))
     sdl_image = sdl2.sdlimage.IMG_Load_RW(rw_ops, 1)
     sdl2.SDL_BlitSurface(sdl_image, None, self.window_surface, None)
     sdl2.SDL_UpdateWindowSurface(self.window)
     sdl2.SDL_FreeSurface(sdl_image)
Example #17
0
    def render_object_from_file(cls, renderer: sdl2.SDL_Renderer,
                                path: bytes) -> RenderObject:
        surface = sdl2.sdlimage.IMG_Load(path)
        if not surface:
            raise RuntimeError("Unable to load image " + str(path) +
                               "! SDL_image Error: " +
                               str(sdl2.sdlimage.IMG_GetError()))

        render_object = cls.render_object_from_surface(renderer, surface)
        sdl2.SDL_FreeSurface(surface)
        return render_object
Example #18
0
    def RenderDebug(self, world, render_dt):
        '''
        This probably doesn't belong here... Should move into a subsystem elsewhere.
        This is an easy light way of having a quick debugger that can print the hero's
        stats.
        Move this elsewhere later on.
        Tutorial: https://egdev.wordpress.com/2014/03/14/python-sdl2-ttf-test/
        '''

        # Open font
        font = sdl2.sdlttf.TTF_OpenFont(
            '/home/prestonh/Desktop/Programming/gamedev/shoot/shoot/resources/fonts/computer_modern/cmunsx.ttf',
            12)
        color = sdl2.SDL_Color(40, 255, 40)

        # Create debug text
        entity = world.entity_manager.entities['hero_0']
        debug_lines = []
        debug_lines.append('fps:' + str(round(1. / render_dt)))
        debug_lines.append('(x,y):' + str(round(entity.kinematics.x, 3)) +
                           ',  ' + str(round(entity.kinematics.y, 3)))
        debug_lines.append('(vx,vy):' + str(round(entity.kinematics.vx, 3)) +
                           ',  ' + str(round(entity.kinematics.vy, 3)))

        debug_text = ''
        for debug_line in debug_lines:
            debug_text += debug_line + '\n'

        # Render the debug text

        # Create surface and texture
        debug_width = 200
        text_surface = sdl2.sdlttf.TTF_RenderText_Blended_Wrapped(
            font, debug_text, color, debug_width)
        text_texture = sdl2.SDL_CreateTextureFromSurface(
            self.sdl_renderer, text_surface)

        # Render surface and texture
        window_rect = self.GetWindowRect()
        w = ctypes.pointer(ctypes.c_int(0))
        h = ctypes.pointer(ctypes.c_int(0))
        sdl2.SDL_QueryTexture(text_texture, None, None, w, h)
        x = window_rect.w - debug_width
        y = 50  #window_rect.h - h.contents.value
        debug_rect = sdl2.SDL_Rect(x, y, w.contents.value, h.contents.value)

        sdl2.SDL_RenderCopy(self.sdl_renderer, text_texture, None, debug_rect)

        # Free resources
        sdl2.SDL_FreeSurface(text_surface)
        sdl2.sdlttf.TTF_CloseFont(font)

        pass
Example #19
0
    def update(self):
        # If we're using software rendering, do rotation using sdlgfx.
        if RENDERER == "software":
            surface = sdl2.sdlgfx.rotozoomSurface(self.sprite_original.surface,
                                                  self.body.angle, 1.0,
                                                  1).contents
            sdl2.SDL_FreeSurface(self.sprite.surface)
            self.sprite.surface = surface

        self.sprite.angle = self.body.angle
        self.sprite.x = int(self.body.position[0]) - (self.sprite.size[0] / 2)
        self.sprite.y = int(self.body.position[1]) - (self.sprite.size[1] / 2)
Example #20
0
 def _set_icon(self):
     """Set the icon on the SDL window."""
     mask = numpy.array(self.icon).T.repeat(2, 0).repeat(2, 1)
     icon = sdl2.SDL_CreateRGBSurface(0, mask.shape[0], mask.shape[1], 8, 0, 0, 0, 0)
     pixels2d(icon.contents)[:] = mask
     # icon palette (black & white)
     icon_palette = sdl2.SDL_AllocPalette(256)
     icon_colors = [ sdl2.SDL_Color(x, x, x, 255) for x in [0, 255] + [255]*254 ]
     sdl2.SDL_SetPaletteColors(icon_palette, (sdl2.SDL_Color * 256)(*icon_colors), 0, 2)
     sdl2.SDL_SetSurfacePalette(icon, icon_palette)
     sdl2.SDL_SetWindowIcon(self.display, icon)
     sdl2.SDL_FreeSurface(icon)
     sdl2.SDL_FreePalette(icon_palette)
Example #21
0
 def glyph(self, renderer, ch):
     assert isinstance(ch, int)
     if ch not in self.glyphs:
         # Pop the surface out of the cache and load it into a texture and the glyph cache.
         surface, size = self.surfaces.pop(ch, (None, None))
         if surface is None:
             surface = TTF_RenderGlyph_Blended(
                 self.font, ch, sdl2.SDL_Color(255, 255, 255))
             size = Size(surface.contents.w, surface.contents.h)
         self.glyphs[ch] = (sdl2.SDL_CreateTextureFromSurface(
             renderer, surface), size)
         sdl2.SDL_FreeSurface(surface)
     return self.glyphs[ch]
Example #22
0
 def refresh(self):
     """
     Refreshes the graphical representation of stored text.
     """
     surface = ttf.TTF_RenderUTF8_Blended(
         self.font.handle, bytes(self._text, "utf8"),
         sdl2.SDL_Color(255, 255, 255, 255))
     if not surface:
         self.surface_size = (0, 0)
         return
     self.surface_size = (surface.contents.w, surface.contents.h)
     self.texture = sdl2.SDL_CreateTextureFromSurface(
         self.canvas.renderer, surface)
     sdl2.SDL_SetTextureBlendMode(self.texture, sdl2.SDL_BLENDMODE_BLEND)
     sdl2.SDL_FreeSurface(surface)
Example #23
0
def loadImageFile(imageFile, renderer):
    # Load into a surface
    surf = sdl2.sdlimage.IMG_Load(imageFile)

    if surf is None:
        print "IMG_Load failed"
        return None

    # Create a texture from the surface with the image
    texture = sdl2.SDL_CreateTextureFromSurface(renderer, surf)
    if texture is None:
        print "SDL_CreateTextureFromSurface failed"

    # Clean up the surface
    sdl2.SDL_FreeSurface(surf)
    return texture
Example #24
0
    def write_snapshot(self, filename):
        """Take a snapshot of the view and write it as a BMP image.

        Parameters
        ----------
        filename : str
            Destination filename.
        """
        pixel_size = 4
        pixels = self._renderer.read_pixels()
        surface = sdl2.SDL_CreateRGBSurfaceFrom(
            pixels.data, pixels.width, pixels.height,
            8 * pixel_size, pixels.width * pixel_size,
            _RGB_MASKS.red, _RGB_MASKS.green, _RGB_MASKS.blue, 0)
        sdl2.SDL_SaveBMP(surface, filename)
        sdl2.SDL_FreeSurface(surface)
 def rendersnake(self, snake):
     '''drawing snake object'''
     if snake.l > 0:
         self.color = gameinfo.COLOR_GRID["red-blue"]
         for i in range(0, len(snake.a)):
             self.__rendercircle(snake.a[i][0], snake.a[i][1])
             if i > ob.Snake.SHOWABLE:
                 break
         sur = ttf.TTF_RenderText_Solid(self.t,
                                        snake.l.__str__().encode(),
                                        self.WHITE)
         tex = sdl2.SDL_CreateTextureFromSurface(self.sdlrenderer, sur)
         Rsnake = sdl2.SDL_Rect(snake.head[0] - gameinfo.TSPACE_X,
                                snake.head[1] - gameinfo.TSPACE_Y,
                                gameinfo.TWIDTH, gameinfo.THEIGHT)
         sdl2.SDL_RenderCopy(self.sdlrenderer, tex, None, Rsnake)
         sdl2.SDL_FreeSurface(sur)
         sdl2.SDL_DestroyTexture(tex)
Example #26
0
def renderText(message, font, color, renderer):
    # Render to a surface
    surf = sdl2.sdlttf.TTF_RenderUTF8_Blended(font, message.encode('utf8'),
                                              color)

    if surf is None:
        sdl2.sdlttf.TTF_CloseFont(font)
        print "TTF_RenderText failed"
        return None

    # Create a texture from the surface with the text
    texture = sdl2.SDL_CreateTextureFromSurface(renderer, surf)
    if texture is None:
        print "SDL_CreateTextureFromSurface failed"

    # Clean up the surface
    sdl2.SDL_FreeSurface(surf)
    return texture
Example #27
0
def renderText(message, font, renderer, color, size=10, bgcolor=sdl2.SDL_Color(0,0,0) ):
	#We need to first render to a surface as that's what TTF_RenderText
	#returns, then load that surface into a texture
	surf = sdl2.sdlttf.TTF_RenderUTF8_Solid(font, message.encode('utf-8'), color)

	sdl2.sdlttf.TTF_CloseFont(font)
	if surf is None:
		print("TTF_RenderText")
		return None
	texture = sdl2.SDL_CreateTextureFromSurface(renderer.sdlrenderer, surf)
	if texture is None:
		print("CreateTexture")
	#Clean up the surface and font
	width = surf.contents.w
	height = surf.contents.h
	sdl2.SDL_FreeSurface(surf)
	# sdl2.sdlttf.TTF_CloseFont(font)
	return texture,width,height
Example #28
0
    def render(self, renderer):
        i = 0
        for game in self.currentState.roms:
            currentColor = WHITE
            if self.currentState.getCurrentRom() == game:
                currentColor = RED

            surf = sdl2.sdlttf.TTF_RenderText_Blended(
                self.font, game.name.encode("utf-8"), currentColor).contents
            text = sdl2.SDL_CreateTextureFromSurface(renderer, surf)
            sdl2.SDL_SetTextureBlendMode(text, sdl2.SDL_BLENDMODE_BLEND)
            sdl2.SDL_FreeSurface(surf)

            w, h = c_int(), c_int()
            sdl2.SDL_QueryTexture(text, None, None, byref(w), byref(h))
            sdl2.SDL_RenderCopy(renderer, text, None,
                                sdl2.SDL_Rect(50, 50 + (i * 40), w, h))

            i += 1
Example #29
0
def set_window_icon(icon: PathLike, bytes_per_pixel: int = 4):
    """
    Lets you set a custom window icon for pyxel. you can call this after pyxel.init
    """

    if not has_pil:
        RuntimeWarning('You need Pillow/PIL in order to use pyxelext.system.set_window_icon')
        return

    current_window = sdl2.SDL_GL_GetCurrentWindow()
    img = Image.open(icon)
    x, y = img.size
    rmask = 0x000000ff
    gmask = 0x0000ff00
    bmask = 0x00ff0000
    amask = 0 if bytes_per_pixel == 3 else 0xff000000
    icon_surface = sdl2.SDL_CreateRGBSurfaceFrom(img.tobytes(), x, y, bytes_per_pixel*8, bytes_per_pixel*x, rmask, gmask, bmask, amask)

    sdl2.SDL_SetWindowIcon(current_window, icon_surface)
    sdl2.SDL_FreeSurface(icon_surface)
Example #30
0
def loadTexture(path, type, clamp, mipmap=False):
    img = sdl2.SDL_LoadBMP(path)
    if not img:
        print('Unable to load bitmap :', sdl2.SDL_GetError())
        return 0

    width = img.contents.w
    height = img.contents.h

    # converts from BGR to RGB
    if (type == gl.GL_RGB) or (type == gl.GL_RGBA):
        if type == gl.GL_RGB:
            offset = 3
        else:
            offset = 4
        imagesize = width * height * offset
        b = ctypes.cast(img.contents.pixels, ctypes.POINTER(ctypes.c_byte))
        for i in range(0, imagesize, offset):
            b[i], b[i + 2] = b[i + 2], b[i]  # slow...

    index = int(gl.glGenTextures(1))
    gl.glBindTexture(gl.GL_TEXTURE_2D, index)
    gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, clamp)
    gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, clamp)
    gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER,
                       gl.GL_LINEAR)

    if mipmap:
        gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER,
                           gl.GL_LINEAR_MIPMAP_LINEAR)
        bytes = ctypes.cast(img.contents.pixels, ctypes.POINTER(ctypes.c_byte))
        glu.gluBuild2DMipmaps(gl.GL_TEXTURE_2D, type, width, height, type,
                              gl.GL_UNSIGNED_BYTE, bytes)
    else:
        gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER,
                           gl.GL_LINEAR)
        bytes = ctypes.cast(img.contents.pixels, ctypes.POINTER(ctypes.c_byte))
        gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, type, width, height, 0, type,
                        gl.GL_UNSIGNED_BYTE, bytes)
    sdl2.SDL_FreeSurface(img)
    return index