GRASS GIS 8 Programmer's Manual  8.5.0dev(2024)-36359e2344
bres_line.c
Go to the documentation of this file.
1 /*
2  * \file lib/gis/bres_line.c
3  *
4  * \brief GIS Library - Bresenham line routines.
5  *
6  * (C) 2001-2014 by the GRASS Development Team
7  *
8  * This program is free software under the GNU General Public License
9  * (>=v2). Read the file COPYING that comes with GRASS for details.
10  *
11  * \author Original author CERL
12  */
13 
14 #include <grass/gis.h>
15 
16 /*!
17  * \brief Bresenham line algorithm.
18  *
19  * Draws a line from <i>x1,y1</i> to <i>x2,y2</i> using Bresenham's
20  * algorithm. A routine to plot points must be provided, as is defined
21  * as: point(x, y) plot a point at x,y.
22  *
23  * This routine does not require a previous call to G_setup_plot() to
24  * function correctly, and is independent of all following routines.
25  *
26  * \param x0,y0 first point
27  * \param x1,y1 end point
28  * \param point pointer to point plotting function
29  */
30 void G_bresenham_line(int x0, int y0, int x1, int y1, int (*point)(int, int))
31 {
32  int dx, dy;
33  int xinc, yinc;
34 
35  int res1;
36  int res2;
37 
38  xinc = 1;
39  yinc = 1;
40  if ((dx = x1 - x0) < 0) {
41  xinc = -1;
42  dx = -dx;
43  }
44 
45  if ((dy = y1 - y0) < 0) {
46  yinc = -1;
47  dy = -dy;
48  }
49  res1 = 0;
50  res2 = 0;
51 
52  if (dx > dy) {
53  while (x0 != x1) {
54  point(x0, y0);
55  if (res1 > res2) {
56  res2 += dx - res1;
57  res1 = 0;
58  y0 += yinc;
59  }
60  res1 += dy;
61  x0 += xinc;
62  }
63  }
64  else if (dx < dy) {
65  while (y0 != y1) {
66  point(x0, y0);
67  if (res1 > res2) {
68  res2 += dy - res1;
69  res1 = 0;
70  x0 += xinc;
71  }
72  res1 += dx;
73  y0 += yinc;
74  }
75  }
76  else {
77  while (x0 != x1) {
78  point(x0, y0);
79  y0 += yinc;
80  x0 += xinc;
81  }
82  }
83 
84  point(x1, y1);
85 }
void G_bresenham_line(int x0, int y0, int x1, int y1, int(*point)(int, int))
Bresenham line algorithm.
Definition: bres_line.c:30