File: draw.py

package info (click to toggle)
pysdl2 0.9.9%2Bdfsg1-6
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 3,276 kB
  • sloc: python: 18,592; makefile: 148; sh: 40
file content (211 lines) | stat: -rw-r--r-- 7,583 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
"""Drawing routines for software surfaces."""
import ctypes
from .compat import isiterable, UnsupportedError
from .array import to_ctypes
from .color import convert_to_color
from .. import surface, pixels, rect
from .algorithms import clipline
from .sprite import SoftwareSprite

__all__ = ["prepare_color", "fill", "line"]


def _get_target_surface(target, argname="target"):
    """Gets the SDL_surface from the passed target."""
    if isinstance(target, surface.SDL_Surface):
        rtarget = target
    elif isinstance(target, SoftwareSprite):
        rtarget = target.surface
    elif "SDL_Surface" in str(type(target)):
        rtarget = target.contents
    else:
        raise TypeError("{0} must be a Sprite or SDL_Surface".format(argname))
    return rtarget


def prepare_color(color, target):
    """Prepares a given color for a specific target.

    Colors can be provided in any form supported by
    :func:`sdl2.ext.convert_to_color`.
    
    Args:
        color (:obj:`sdl2.ext.Color`): The color to prepare for the pixel format
            of the given target.
        target (:obj:`~sdl2.SDL_PixelFormat`, :obj:`~sdl2.SDL_Surface`,
            :obj:`~sdl2.ext.SoftwareSprite`): The target pixel format, surface,
            or sprite for which the color should be prepared.
    
    Returns:
        int: An integer approximating the given color in the target's pixel
            format.

"""
    color = convert_to_color(color)
    pformat = None
    # Software surfaces
    if isinstance(target, pixels.SDL_PixelFormat):
        pformat = target
    else:
        surf = _get_target_surface(target)
        pformat = surf.format.contents
    if pformat.Amask != 0:
        # Target has an alpha mask
        return pixels.SDL_MapRGBA(pformat, color.r, color.g, color.b, color.a)
    return pixels.SDL_MapRGB(pformat, color.r, color.g, color.b)


def fill(target, color, area=None):
    """Fills one or more rectangular areas on a surface with a given color.

    Fill areas can be specified as 4-item (x, y, w, h) tuples,
    :obj:`~sdl2.rect.SDL_Rect` objects, or a list containing multiple areas to
    fill in either format. If no area is provided, the entire target will be
    filled with the provided color.

    The fill color can be provided in any format supported by
    :func:`~sdl2.ext.color.convert_to_color`.

    Args:
        target (:obj:`~sdl2.SDL_Surface`, :obj:`~sdl2.ext.SoftwareSprite`): The
            target surface or sprite to modify.
        color (:obj:`sdl2.ext.Color`): The color with which to fill the
            specified region(s) of the target.
        area (tuple, :obj:`~sdl2.SDL_Rect`, list, optional): The rectangular
            region (or regions) of the target surface to fill with the given
            colour. If no regions are specified (the default), the whole surface
            of the target will be filled.

    """
    color = prepare_color(color, target)
    rtarget = _get_target_surface(target)

    err_msg = (
        "Fill areas must be specified as either (x, y, w, h) tuples or "
        "SDL_Rect objects (Got unsupported format '{0}')"
    )

    rects = []
    if area:
        if not isiterable(area) or not isiterable(area[0]):
            area = [area]
        for r in area:
            if isinstance(r, rect.SDL_Rect):
                rects.append(r)
            else:
                try:
                    new_rect = rect.SDL_Rect(
                        int(r[0]), int(r[1]), int(r[2]), int(r[3])
                    )
                    rects.append(new_rect)
                except (TypeError, ValueError, IndexError):
                    raise ValueError(err_msg.format(str(r)))

    if len(rects) > 2:
        rects, count = to_ctypes(rects, rect.SDL_Rect)
        rects = ctypes.cast(rects, ctypes.POINTER(rect.SDL_Rect))
        surface.SDL_FillRects(rtarget, rects, count, color)
    elif len(rects) == 1:
        surface.SDL_FillRect(rtarget, rects[0], color)
    else:
        surface.SDL_FillRect(rtarget, None, color)


def line(target, color, dline, width=1):
    """Draws one or lines on a surface in a given color.

    The fill color can be provided in any format supported by
    :func:`~sdl2.ext.color.convert_to_color`.

    Args:
        target (:obj:`~sdl2.SDL_Surface`, :obj:`~sdl2.ext.SoftwareSprite`): The
            target surface or sprite to modify.
        color (:obj:`sdl2.ext.Color`): The color with which to draw lines.
        dline (tuple, list): The (x1, y1, x2, y2) integer coordinates of a line
            to draw, or a list of multiple sets of (x1, y1, x2, y2) coordinates
            for multiple lines.
        width (int, optional): The width of the line(s) in pixels. Defaults to
            1 if not specified.

    """
    if width < 1:
        raise ValueError("width must be greater than 0")
    color = prepare_color(color, target)
    rtarget = _get_target_surface(target)

    # If first item is iterable, assume multiple lines in (x1, y1, x2, y2) form
    if isiterable(dline[0]):
        flattened = []
        for line in dline:
            flattened += list(line)
        dline = flattened

    # line: (x1, y1, x2, y2) OR (x1, y1, x2, y2, ...)
    if (len(dline) % 4) != 0:
        raise ValueError("line does not contain a valid set of points")
    pcount = len(dline)
    SDLRect = rect.SDL_Rect
    fillrect = surface.SDL_FillRect

    pitch = rtarget.pitch
    bpp = rtarget.format.contents.BytesPerPixel
    frac = pitch / bpp
    clip_rect = rtarget.clip_rect
    left, right = clip_rect.x, clip_rect.x + clip_rect.w - 1
    top, bottom = clip_rect.y, clip_rect.y + clip_rect.h - 1

    if bpp == 3:
        raise UnsupportedError(line, "24bpp are currently not supported")
    if bpp == 2:
        pxbuf = ctypes.cast(rtarget.pixels, ctypes.POINTER(ctypes.c_uint16))
    elif bpp == 4:
        pxbuf = ctypes.cast(rtarget.pixels, ctypes.POINTER(ctypes.c_uint32))
    else:
        pxbuf = rtarget.pixels  # byte-wise access.

    for idx in range(0, pcount, 4):
        x1, y1, x2, y2 = dline[idx:idx + 4]
        if x1 == x2:
            # Vertical line
            if y1 < y2:
                varea = SDLRect(x1 - width // 2, y1, width, y2 - y1)
            else:
                varea = SDLRect(x1 - width // 2, y2, width, y1 - y2)
            fillrect(rtarget, varea, color)
            continue
        if y1 == y2:
            # Horizontal line
            if x1 < x2:
                varea = SDLRect(x1, y1 - width // 2, x2 - x1, width)
            else:
                varea = SDLRect(x2, y1 - width // 2, x1 - x2, width)
            fillrect(rtarget, varea, color)
            continue
        if width != 1:
            raise UnsupportedError(line, "width > 1 is not supported")
        if width == 1:
            # Bresenham
            x1, y1, x2, y2 = clipline(left, top, right, bottom, x1, y1, x2, y2)
            x1, y1, x2, y2 = int(x1), int(y1), int(x2), int(y2)
            if x1 is None:
                # not to be drawn
                continue
            dx = abs(x2 - x1)
            dy = -abs(y2 - y1)
            err = dx + dy
            sx, sy = 1, 1
            if x1 > x2:
                sx = -sx
            if y1 > y2:
                sy = -sy
            while True:
                pxbuf[int(y1 * frac + x1)] = color
                if x1 == x2 and y1 == y2:
                    break
                e2 = err * 2
                if e2 > dy:
                    err += dy
                    x1 += sx
                if e2 < dx:
                    err += dx
                    y1 += sy