Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add draw.aapolygon #3126

Draft
wants to merge 9 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions buildconfig/stubs/pygame/draw.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@ def polygon(
points: SequenceLike[Coordinate],
width: int = 0,
) -> Rect: ...
def aapolygon(
surface: Surface,
color: ColorLike,
points: SequenceLike[Coordinate],
filled: bool = True,
) -> Rect: ...
def circle(
surface: Surface,
color: ColorLike,
Expand Down
Binary file modified docs/reST/ref/code_examples/draw_module_example.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
9 changes: 8 additions & 1 deletion docs/reST/ref/code_examples/draw_module_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,9 +65,16 @@
# Draw an solid ellipse, using a rectangle as the outside boundaries
pygame.draw.ellipse(screen, "red", [300, 10, 50, 20])

# This draws a triangle using the polygon command
# Draw a triangle using the polygon command
pygame.draw.polygon(screen, "black", [[100, 100], [0, 200], [200, 200]], 5)

# Draw an antialiased polygon
pygame.draw.aapolygon(
screen,
"black",
[[100, 40], [150, 75], [110, 60], [70, 70]]
)

# Draw an arc as part of an ellipse.
# Use radians to determine what angle to draw.
pygame.draw.arc(screen, "black", [210, 75, 150, 125], 0, pi / 2, 2)
Expand Down
40 changes: 40 additions & 0 deletions docs/reST/ref/draw.rst
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,46 @@ object around the draw calls (see :func:`pygame.Surface.lock` and

.. ## pygame.draw.polygon ##

.. function:: aapolygon

| :sl:`draw an antialiased polygon`
| :sg:`aapolygon(surface, color, points) -> Rect`
| :sg:`aapolygon(surface, color, points, filled=True) -> Rect`

Draws an antialiased polygon on the given surface.

:param Surface surface: surface to draw on
:param color: color to draw with, the alpha value is optional if using a
tuple ``(RGB[A])``
:type color: Color or string (for :doc:`color_list`) or int or tuple(int, int, int, [int])
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Here it would be interesting to refer to ColorLike from pygame.typing, using a link to its paragraph in the docs.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It would be better to add this to all functions in docs at once, in one separate PR. Like just one find-and-replace.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why it should be in a different PR when it concerns directly aapolygon ?

:param points: a sequence of 3 or more (x, y) coordinates that make up the
bilhox marked this conversation as resolved.
Show resolved Hide resolved
vertices of the polygon, each *coordinate* in the sequence must be a
tuple/list/:class:`pygame.math.Vector2` of 2 ints/floats,
e.g. ``[(x1, y1), (x2, y2), (x3, y3)]``
:type points: tuple(coordinate) or list(coordinate)
:param int filled: (optional) used to indicate that the polygon is to be filled

| if filled == True, (default) fill the polygon
| if filled == False, don't fill the polygon
|

:returns: a rect bounding the changed pixels, if nothing is drawn the
bounding rect's position will be the position of the first point in the
``points`` parameter (float values will be truncated) and its width and
height will be 0
:rtype: Rect

:raises ValueError: if ``len(points) < 3`` (must have at least 3 points)
damusss marked this conversation as resolved.
Show resolved Hide resolved
:raises TypeError: if ``points`` is not a sequence or ``points`` does not
contain number pairs

.. note::
For an aapolygon, use :func:`aalines()` with ``closed=True``.
mzivic7 marked this conversation as resolved.
Show resolved Hide resolved

.. versionadded:: 2.6.0

.. ## pygame.draw.aapolygon ##

.. function:: circle

| :sl:`draw a circle`
Expand Down
1 change: 1 addition & 0 deletions src_c/doc/draw_doc.h
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
#define DOC_DRAW "pygame module for drawing shapes"
#define DOC_DRAW_RECT "rect(surface, color, rect) -> Rect\nrect(surface, color, rect, width=0, border_radius=0, border_top_left_radius=-1, border_top_right_radius=-1, border_bottom_left_radius=-1, border_bottom_right_radius=-1) -> Rect\ndraw a rectangle"
#define DOC_DRAW_POLYGON "polygon(surface, color, points) -> Rect\npolygon(surface, color, points, width=0) -> Rect\ndraw a polygon"
#define DOC_DRAW_AAPOLYGON "aapolygon(surface, color, points) -> Rect\naapolygon(surface, color, points, filled=True) -> Rect\ndraw an antialiased polygon"
#define DOC_DRAW_CIRCLE "circle(surface, color, center, radius) -> Rect\ncircle(surface, color, center, radius, width=0, draw_top_right=None, draw_top_left=None, draw_bottom_left=None, draw_bottom_right=None) -> Rect\ndraw a circle"
#define DOC_DRAW_AACIRCLE "aacircle(surface, color, center, radius) -> Rect\naacircle(surface, color, center, radius, width=0, draw_top_right=None, draw_top_left=None, draw_bottom_left=None, draw_bottom_right=None) -> Rect\ndraw an antialiased circle"
#define DOC_DRAW_ELLIPSE "ellipse(surface, color, rect) -> Rect\nellipse(surface, color, rect, width=0) -> Rect\ndraw an ellipse"
Expand Down
194 changes: 167 additions & 27 deletions src_c/draw.c
Original file line number Diff line number Diff line change
Expand Up @@ -81,10 +81,10 @@ draw_ellipse_thickness(SDL_Surface *surf, int x0, int y0, int width,
int *drawn_area);
static void
draw_fillpoly(SDL_Surface *surf, int *vx, int *vy, Py_ssize_t n, Uint32 color,
int *drawn_area);
int *drawn_area, int aapolygon_fix);
static int
draw_filltri(SDL_Surface *surf, int *xlist, int *ylist, Uint32 color,
int *drawn_area);
int *drawn_area, int aapolygon_fix);
static void
draw_rect(SDL_Surface *surf, int x1, int y1, int x2, int y2, int width,
Uint32 color);
Expand Down Expand Up @@ -960,10 +960,10 @@ polygon(PyObject *self, PyObject *arg, PyObject *kwargs)
}

if (length != 3) {
draw_fillpoly(surf, xlist, ylist, length, color, drawn_area);
draw_fillpoly(surf, xlist, ylist, length, color, drawn_area, 0);
}
else {
draw_filltri(surf, xlist, ylist, color, drawn_area);
draw_filltri(surf, xlist, ylist, color, drawn_area, 0);
}
PyMem_Free(xlist);
PyMem_Free(ylist);
Expand All @@ -981,6 +981,123 @@ polygon(PyObject *self, PyObject *arg, PyObject *kwargs)
return pgRect_New4(l, t, 0, 0);
}

static PyObject *
aapolygon(PyObject *self, PyObject *arg, PyObject *kwargs)
{
pgSurfaceObject *surfobj;
PyObject *colorobj, *points, *item = NULL;
SDL_Surface *surf = NULL;
Uint32 color;
int *xlist = NULL, *ylist = NULL;
int filled = 1; /* filled by default */
int x, y, result;
int drawn_area[4] = {INT_MAX, INT_MAX, INT_MIN,
INT_MIN}; /* Used to store bounding box values */
Py_ssize_t loop, length;
static char *keywords[] = {"surface", "color", "points", "filled", NULL};

if (!PyArg_ParseTupleAndKeywords(arg, kwargs, "O!OO|p", keywords,
&pgSurface_Type, &surfobj, &colorobj,
&points, &filled)) {
return NULL; /* Exception already set. */
}

length = PySequence_Length(points);

if (!PySequence_Check(points)) {
return RAISE(PyExc_TypeError,
"points argument must be a sequence of number pairs");
}

// always check this because aalines accepts 2 points
if (length < 3) {
return RAISE(PyExc_ValueError,
"points argument must contain more than 2 points");
}

if (filled == 0) {
PyObject *ret = NULL;
PyObject *args = Py_BuildValue("(OOiO)", surfobj, colorobj, 1, points);

if (!args) {
return NULL; /* Exception already set. */
}

ret = aalines(NULL, args, NULL);
Py_DECREF(args);
return ret;
}

surf = pgSurface_AsSurface(surfobj);
SURF_INIT_CHECK(surf)

if (PG_SURF_BytesPerPixel(surf) <= 0 || PG_SURF_BytesPerPixel(surf) > 4) {
return PyErr_Format(PyExc_ValueError,
"unsupported surface bit depth (%d) for drawing",
PG_SURF_BytesPerPixel(surf));
}

CHECK_LOAD_COLOR(colorobj)

xlist = PyMem_New(int, length);
ylist = PyMem_New(int, length);

if (NULL == xlist || NULL == ylist) {
if (xlist) {
PyMem_Free(xlist);
}
if (ylist) {
PyMem_Free(ylist);
}
return RAISE(PyExc_MemoryError,
"cannot allocate memory to draw polygon");
}

for (loop = 0; loop < length; ++loop) {
item = PySequence_GetItem(points, loop);
result = pg_TwoIntsFromObj(item, &x, &y);
Py_DECREF(item);

if (!result) {
PyMem_Free(xlist);
PyMem_Free(ylist);
return RAISE(PyExc_TypeError, "points must be number pairs");
}

xlist[loop] = x;
ylist[loop] = y;
}

if (!pgSurface_Lock(surfobj)) {
PyMem_Free(xlist);
PyMem_Free(ylist);
return RAISE(PyExc_RuntimeError, "error locking surface");
}

if (length != 3) {
draw_fillpoly(surf, xlist, ylist, length, color, drawn_area, 1);
}
else {
draw_filltri(surf, xlist, ylist, color, drawn_area, 1);
}
PyMem_Free(xlist);
PyMem_Free(ylist);

// aalines for antialiasing
PyObject *ret = NULL;
PyObject *args = Py_BuildValue("(OOiO)", surfobj, colorobj, 1, points);
if (!args) {
return NULL; /* Exception already set. */
}
ret = aalines(NULL, args, NULL);
Py_DECREF(args);

if (!pgSurface_Unlock(surfobj)) {
return RAISE(PyExc_RuntimeError, "error unlocking surface");
}
return ret; // already calculated return rect in aalines
}

static PyObject *
rect(PyObject *self, PyObject *args, PyObject *kwargs)
{
Expand Down Expand Up @@ -1613,7 +1730,7 @@ swap_coordinates(int *x1, int *y1, int *x2, int *y2)

static int
draw_filltri(SDL_Surface *surf, int *xlist, int *ylist, Uint32 color,
int *draw_area)
int *drawn_area, int aapolygon_fix)
{
int p0x, p0y, p1x, p1y, p2x, p2y;

Expand Down Expand Up @@ -1644,16 +1761,37 @@ draw_filltri(SDL_Surface *surf, int *xlist, int *ylist, Uint32 color,
float d2 = (float)((p1x - p0x) / ((p1y - p0y) + 1e-17));
float d3 = (float)((p2x - p1x) / ((p2y - p1y) + 1e-17));
int y;
for (y = p0y; y <= p2y; y++) {
int x1 = p0x + (int)((y - p0y) * d1);
if (aapolygon_fix) {
for (y = p0y; y <= p2y; y++) {
int x1 = p0x + (int)((y - p0y) * d1) + 1;

int x2;
if (y < p1y)
x2 = p0x + (int)((y - p0y) * d2);
else
x2 = p1x + (int)((y - p1y) * d3) - 1;
if (x1 > x2) {
if (x1 - x2 != 1) {
set_and_check_rect(surf, x1 - 1, y, color, drawn_area);
}
}
else {
drawhorzlineclipbounding(surf, color, x1, y, x2, drawn_area);
}
}
}
else {
for (y = p0y; y <= p2y; y++) {
int x1 = p0x + (int)((y - p0y) * d1);

int x2;
if (y < p1y)
x2 = p0x + (int)((y - p0y) * d2);
else
x2 = p1x + (int)((y - p1y) * d3);
int x2;
if (y < p1y)
x2 = p0x + (int)((y - p0y) * d2);
else
x2 = p1x + (int)((y - p1y) * d3);

drawhorzlineclipbounding(surf, color, x1, y, x2, draw_area);
drawhorzlineclipbounding(surf, color, x1, y, x2, drawn_area);
}
}

return 0;
Expand Down Expand Up @@ -2871,36 +3009,32 @@ draw_ellipse_thickness(SDL_Surface *surf, int x0, int y0, int width,

static void
draw_fillpoly(SDL_Surface *surf, int *point_x, int *point_y,
Py_ssize_t num_points, Uint32 color, int *drawn_area)
Py_ssize_t num_points, Uint32 color, int *drawn_area,
int aapolygon_fix)
{
/* point_x : x coordinates of the points
* point-y : the y coordinates of the points
* num_points : the number of points
*/
Py_ssize_t i, i_previous; // i_previous is the index of the point before i
Py_ssize_t i, i_previous; // index of the point before i
int y, miny, maxy;
int x1, y1;
int x2, y2;
float intersect;
/* x_intersect are the x-coordinates of intersections of the polygon
* with some horizontal line */
/* x-coordinate of intersections of the polygon with some
horizontal line */
int *x_intersect = PyMem_New(int, num_points);
if (x_intersect == NULL) {
PyErr_NoMemory();
return;
}

/* Determine Y maxima */
/* Determine Y bounds */
miny = point_y[0];
maxy = point_y[0];
for (i = 1; (i < num_points); i++) {
miny = MIN(miny, point_y[i]);
maxy = MAX(maxy, point_y[i]);
}

/* Special case: polygon only 1 pixel high. */
if (miny == maxy) {
/* Special case: polygon only 1 pixel high. */

/* Determine X bounds */
int minx = point_x[0];
int maxx = point_x[0];
Expand Down Expand Up @@ -2949,7 +3083,8 @@ draw_fillpoly(SDL_Surface *surf, int *point_x, int *point_y,
// end), or when we are on the lowest line (maxy)
intersect = (y - y1) * (x2 - x1) / (float)(y2 - y1);
if (n_intersections % 2 == 0) {
intersect = (float)floor(intersect);
// for aapolygon, 1 is added so lower half is moved right
intersect = (float)floor(intersect) + aapolygon_fix;
}
else
intersect = (float)ceil(intersect);
Expand All @@ -2958,8 +3093,11 @@ draw_fillpoly(SDL_Surface *surf, int *point_x, int *point_y,
}
qsort(x_intersect, n_intersections, sizeof(int), compare_int);
for (i = 0; (i < n_intersections); i += 2) {
// for aapolygon, 1 is subtracted, so right x coordinate is moved
// left
drawhorzlineclipbounding(surf, color, x_intersect[i], y,
x_intersect[i + 1], drawn_area);
x_intersect[i + 1] - aapolygon_fix,
drawn_area);
}
}

Expand Down Expand Up @@ -3045,7 +3183,7 @@ draw_round_rect(SDL_Surface *surf, int x1, int y1, int x2, int y2, int radius,
pts[13] = y2;
pts[14] = y2;
pts[15] = y2 - bottom_left;
draw_fillpoly(surf, pts, pts + 8, 8, color, drawn_area);
draw_fillpoly(surf, pts, pts + 8, 8, color, drawn_area, 0);
draw_circle_quadrant(surf, x2 - top_right + 1, y1 + top_right,
top_right, 0, color, 1, 0, 0, 0, drawn_area);
draw_circle_quadrant(surf, x1 + top_left, y1 + top_left, top_left, 0,
Expand Down Expand Up @@ -3137,6 +3275,8 @@ static PyMethodDef _draw_methods[] = {
DOC_DRAW_AACIRCLE},
{"polygon", (PyCFunction)polygon, METH_VARARGS | METH_KEYWORDS,
DOC_DRAW_POLYGON},
{"aapolygon", (PyCFunction)aapolygon, METH_VARARGS | METH_KEYWORDS,
DOC_DRAW_AAPOLYGON},
{"rect", (PyCFunction)rect, METH_VARARGS | METH_KEYWORDS, DOC_DRAW_RECT},

{NULL, NULL, 0, NULL}};
Expand Down
Loading
Loading