Fix plot initialization, improve frame titles
[ctsim.git] / libctgraphics / bresenham.cpp
1 /*****************************************************************************
2 **  This is part of the CTSim program
3 **  Copyright (c) 1983-2009 Kevin Rosenberg
4 **
5 **  This program is free software; you can redistribute it and/or modify
6 **  it under the terms of the GNU General Public License (version 2) as
7 **  published by the Free Software Foundation.
8 **
9 **  This program is distributed in the hope that it will be useful,
10 **  but WITHOUT ANY WARRANTY; without even the implied warranty of
11 **  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 **  GNU General Public License for more details.
13 **
14 **  You should have received a copy of the GNU General Public License
15 **  along with this program; if not, write to the Free Software
16 **  Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
17 ******************************************************************************/
18
19 // REFERENCES FOR BRESENHAM'S ALGORITHM
20 // Newman & Sproll, "Principals of Interactive Computer Graphics",  page 25.
21 // Foley & van Dam, "Fundementals of Interactive Computer Graphics", page 433
22
23
24
25 void
26 bresenham (int x1, int y1, int x2, int y2)
27 {
28   int delta_x = x2 - x1;
29   int dx_abs = (delta_x >= 0 ? delta_x : -delta_x);
30
31   int delta_y = y2 - y1;
32   int dy_abs = (delta_y >= 0 ? delta_y : -delta_y);
33
34   // draws a line when abs(dx) >= abs(dy)
35   if (dx_abs > dy_abs) {
36     int count = dx_abs + 1;
37     int major_inc = (x1 <= x2 ? 1 : -1);
38     int min_inc = (delta_y >= 0 ? 1 : -1);     // determine direction of minor axis
39
40     int d = dy_abs * 2 - dx_abs;      // Put decision variable in d
41     int dinc1 = (dy_abs - dx_abs) * 2;
42     int dinc2 = 2 * dy_abs;
43
44     bresx (x1, y1, major_inc, d, d1, d2);
45   } else {    //For plotting lines with abs(dy) > abs(sx)
46     int count = dy_abs + 1;
47
48     int major_inc = (y1 <= y2 ? 1 : -1);
49     int min_inc = (delta_x >= 0 ? 1 : -1);      // check direction of minor axis
50
51     int d = dx_abs * 2 - dy_abs;
52     dinc1 = (dx_abs - dy_abs) * 2;
53     dinc2 = 2 * dx_abs;
54
55     bresy (x1, y1, major_inc, min_inc, count, d, d1, d2);
56   }
57 }
58
59
60 static void
61 bresx (int x, int y, int majorinc, int minorinc, int count, int d, int d1, int d2)
62 {
63   do {
64     setpixel();
65     x += majorinc;
66
67     if (d < 0)
68       d += dinc2;
69     else {
70       d += dinc1;
71       y += min_inc;
72     }
73   } while (--count > 0);
74 }
75
76
77 static void
78 bresy (int x, int y, int majorinc, int minorinc, int count, int d, int d1, int d2)
79 {
80   do {
81     setpixel();
82     y += majorinc;
83
84     if (d < 0)
85       d += dinc2;
86     else {
87       d += dinc1;
88       x += min_inc;
89     }
90   } while (--count > 0);
91 }
92
93