bres_line.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. #include <grass/gis.h>
  14. /*!
  15. * \brief Bresenham line algorithm.
  16. *
  17. * Draws a line from <i>x1,y1</i> to <i>x2,y2</i> using Bresenham's
  18. * algorithm. A routine to plot points must be provided, as is defined
  19. * as: point(x, y) plot a point at x,y.
  20. *
  21. * This routine does not require a previous call to G_setup_plot() to
  22. * function correctly, and is independent of all following routines.
  23. *
  24. * \param x0,y0 first point
  25. * \param x1,y1 end point
  26. * \param point pointer to point plotting function
  27. */
  28. void G_bresenham_line(int x0, int y0, int x1, int y1, int (*point) (int, int))
  29. {
  30. int dx, dy;
  31. int xinc, yinc;
  32. int res1;
  33. int res2;
  34. xinc = 1;
  35. yinc = 1;
  36. if ((dx = x1 - x0) < 0) {
  37. xinc = -1;
  38. dx = -dx;
  39. }
  40. if ((dy = y1 - y0) < 0) {
  41. yinc = -1;
  42. dy = -dy;
  43. }
  44. res1 = 0;
  45. res2 = 0;
  46. if (dx > dy) {
  47. while (x0 != x1) {
  48. point(x0, y0);
  49. if (res1 > res2) {
  50. res2 += dx - res1;
  51. res1 = 0;
  52. y0 += yinc;
  53. }
  54. res1 += dy;
  55. x0 += xinc;
  56. }
  57. }
  58. else if (dx < dy) {
  59. while (y0 != y1) {
  60. point(x0, y0);
  61. if (res1 > res2) {
  62. res2 += dy - res1;
  63. res1 = 0;
  64. x0 += xinc;
  65. }
  66. res1 += dx;
  67. y0 += yinc;
  68. }
  69. }
  70. else {
  71. while (x0 != x1) {
  72. point(x0, y0);
  73. y0 += yinc;
  74. x0 += xinc;
  75. }
  76. }
  77. point(x1, y1);
  78. }