bres_line.c 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /*
  2. * \file bres_line.c
  3. *
  4. * \brief GIS Library - Bresenham line routines.
  5. *
  6. * (C) 2001-2008 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 GRASS GIS Development Team
  12. *
  13. * \date 1999-2008
  14. */
  15. #include <grass/gis.h>
  16. /**
  17. * \brief Bresenham line algorithm.
  18. *
  19. * Draws a line from <b>x1,y1</b> to <b>x2,y2</b> 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
  24. * <i>G_setup_plot()</i> to function correctly, and is independent of
  25. * all following routines.
  26. *
  27. * \param[in] x0
  28. * \param[in] y0
  29. * \param[in] x1
  30. * \param[in] y1
  31. * \param[in] point pointer to point plotting function
  32. * \return
  33. */
  34. void G_bresenham_line(int x0, int y0, int x1, int y1, int (*point) (int, int))
  35. {
  36. int dx, dy;
  37. int xinc, yinc;
  38. int res1;
  39. int res2;
  40. xinc = 1;
  41. yinc = 1;
  42. if ((dx = x1 - x0) < 0) {
  43. xinc = -1;
  44. dx = -dx;
  45. }
  46. if ((dy = y1 - y0) < 0) {
  47. yinc = -1;
  48. dy = -dy;
  49. }
  50. res1 = 0;
  51. res2 = 0;
  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. point(x1, y1);
  84. }