Bresenham's line algorithm

Bresenham's line algorithm is a line drawing algorithm that determines the points of an n-dimensional raster that should be selected in order to form a close approximation to a straight line between two points. It is commonly used to draw line primitives in a bitmap image (e.g. on a computer screen), as it uses only integer addition, subtraction, and bit shifting, all of which are very cheap operations in historically common computer architectures. It is an incremental error algorithm, and one of the earliest algorithms developed in the field of computer graphics. An extension to the original algorithm called the midpoint circle algorithm may be used for drawing circles.

While algorithms such as Wu's algorithm are also frequently used in modern computer graphics because they can support antialiasing, Bresenham's line algorithm is still important because of its speed and simplicity. The algorithm is used in hardware such as plotters and in the graphics chips of modern graphics cards. It can also be found in many software graphics libraries. Because the algorithm is very simple, it is often implemented in either the firmware or the graphics hardware of modern graphics cards.

The label "Bresenham" is used today for a family of algorithms extending or modifying Bresenham's original algorithm.

History

Bresenham's line algorithm is named after Jack Elton Bresenham who developed it in 1962 at IBM. In 2001 Bresenham wrote:[1]

I was working in the computation lab at IBM's San Jose development lab. A Calcomp plotter had been attached to an IBM 1401 via the 1407 typewriter console. [The algorithm] was in production use by summer 1962, possibly a month or so earlier. Programs in those days were freely exchanged among corporations so Calcomp (Jim Newland and Calvin Hefte) had copies. When I returned to Stanford in Fall 1962, I put a copy in the Stanford comp center library. A description of the line drawing routine was accepted for presentation at the 1963 ACM national convention in Denver, Colorado. It was a year in which no proceedings were published, only the agenda of speakers and topics in an issue of Communications of the ACM. A person from the IBM Systems Journal asked me after I made my presentation if they could publish the paper. I happily agreed, and they printed it in 1965.

Method

Illustration of the result of Bresenham's line algorithm. (0,0) is at the top left corner of the grid, (1,1) is at the top left end of the line and (11, 5) is at the bottom right end of the line.

The following conventions will be utilized:

  • the top-left is (0,0) such that pixel coordinates increase in the right and down directions (e.g. that the pixel at (7,4) is directly above the pixel at (7,5)), and
  • the pixel centers have integer coordinates.

The endpoints of the line are the pixels at and , where the first coordinate of the pair is the column and the second is the row.

The algorithm will be initially presented only for the octant in which the segment goes down and to the right ( and ), and its horizontal projection is longer than the vertical projection (the line has a positive slope less than 1). In this octant, for each column x between and , there is exactly one row y (computed by the algorithm) containing a pixel of the line, while each row between and may contain multiple rasterized pixels.

Bresenham's algorithm chooses the integer y corresponding to the pixel center that is closest to the ideal (fractional) y for the same x; on successive columns y can remain the same or increase by 1. The general equation of the line through the endpoints is given by:

.

Since we know the column, x, the pixel's row, y, is given by rounding this quantity to the nearest integer:

.

The slope depends on the endpoint coordinates only and can be precomputed, and the ideal y for successive integer values of x can be computed starting from and repeatedly adding the slope.

In practice, the algorithm does not keep track of the y coordinate, which increases by m = ∆y/∆x each time the x increases by one; it keeps an error bound at each stage, which represents the negative of the distance from (a) the point where the line exits the pixel to (b) the top edge of the pixel. This value is first set to (due to using the pixel's center coordinates), and is incremented by m each time the x coordinate is incremented by one. If the error becomes greater than 0.5, we know that the line has moved upwards one pixel, and that we must increment our y coordinate and readjust the error to represent the distance from the top of the new pixel – which is done by subtracting one from error.[2]

Derivation

To derive Bresenham's algorithm, two steps must be taken. The first step is transforming the equation of a line from the typical slope-intercept form into something different; and then using this new equation to draw a line based on the idea of accumulation of error.

Line equation

y=f(x)=.5x+1 or f(x,y)=x-2y+2=0
Positive and negative half-planes

The slope-intercept form of a line is written as

where is the slope and is the y-intercept. Because this is a function of only , it can't represent a vertical line. Therefore, it would be useful to make this equation written as a function of both and , to be able to draw lines at any angle. The angle (or slope) of a line can be stated as "rise over run", or . Then, using algebraic manipulation,

Letting this last equation be a function of and , it can be written as

where the constants are

The line is then defined for some constants , , and anywhere . That is, for any not on the line, . This form involves only integers if and are integers, since the constants , , and are defined as integers.

As an example, the line then this could be written as . The point (2,2) is on the line

and the point (2,3) is not on the line

and neither is the point (2,1)

Notice that the points (2,1) and (2,3) are on opposite sides of the line and evaluates to positive or negative. A line splits a plane into halves and the half-plane that has a negative can be called the negative half-plane, and the other half can be called the positive half-plane. This observation is very important in the remainder of the derivation.

Algorithm

The starting point is on the line

only because the line is defined to start and end on integer coordinates (though it is entirely reasonable to want to draw a line with non-integer end points).

Candidate point (2,2) in blue and two candidate points in green (3,2) and (3,3)

Keeping in mind that the slope is at most , the problem now presents itself as to whether the next point should be at or . Perhaps intuitively, the point should be chosen based upon which is closer to the line at . If it is closer to the former then include the former point on the line, if the latter then the latter. To answer this, evaluate the line function at the midpoint between these two points:

If the value of this is positive then the ideal line is below the midpoint and closer to the candidate point ; i.e. the y coordinate should increase. Otherwise, the ideal line passes through or above the midpoint, and the y coordinate should stay the same; in which case the point is chosen. The value of the line function at this midpoint is the sole determinant of which point should be chosen.

The adjacent image shows the blue point (2,2) chosen to be on the line with two candidate points in green (3,2) and (3,3). The black point (3, 2.5) is the midpoint between the two candidate points.

Algorithm for integer arithmetic

Alternatively, the difference between points can be used instead of evaluating f(x,y) at midpoints. This alternative method allows for integer-only arithmetic, which is generally faster than using floating-point arithmetic. To derive the other method, define the difference to be as follows:

For the first decision, this formulation is equivalent to the midpoint method since at the starting point. Simplifying this expression yields:

Just as with the midpoint method, if is positive, then choose , otherwise choose .

If is chosen, the change in will be:

If is chosen the change in will be:

If the new D is positive then is chosen, otherwise . This decision can be generalized by accumulating the error on each subsequent point.

Plotting the line from (0,1) to (6,4) showing a plot of grid lines and pixels

All of the derivation for the algorithm is done. One performance issue is the 1/2 factor in the initial value of D. Since all of this is about the sign of the accumulated difference, then everything can be multiplied by 2 with no consequence.

This results in an algorithm that uses only integer arithmetic.

plotLine(x0, y0, x1, y1)
    dx = x1 - x0
    dy = y1 - y0
    D = 2*dy - dx
    y = y0

    for x from x0 to x1
        plot(x, y)
        if D > 0
            y = y + 1
            D = D - 2*dx
        end if
        D = D + 2*dy

Running this algorithm for from (0,1) to (6,4) yields the following differences with dx=6 and dy=3:

D=2*3-6=0
Loop from 0 to 6
 * x=0: plot(0, 1), D≤0: D=0+6=6
 * x=1: plot(1, 1), D>0: D=6-12=-6, y=1+1=2, D=-6+6=0
 * x=2: plot(2, 2), D≤0: D=0+6=6
 * x=3: plot(3, 2), D>0: D=6-12=-6, y=2+1=3, D=-6+6=0
 * x=4: plot(4, 3), D≤0: D=0+6=6
 * x=5: plot(5, 3), D>0: D=6-12=-6, y=3+1=4, D=-6+6=0
 * x=6: plot(6, 4), D≤0: D=0+6=6

The result of this plot is shown to the right. The plotting can be viewed by plotting at the intersection of lines (blue circles) or filling in pixel boxes (yellow squares). Regardless, the plotting is the same.

All cases

However, as mentioned above this only works for octant zero, that is lines starting at the origin with a slope between 0 and 1 where x increases by exactly 1 per iteration and y increases by 0 or 1.

The algorithm can be extended to cover slopes between 0 and -1 by checking whether y needs to increase or decrease (i.e. dy < 0)

plotLineLow(x0, y0, x1, y1)
    dx = x1 - x0
    dy = y1 - y0
    yi = 1
    if dy < 0
        yi = -1
        dy = -dy
    end if
    D = (2 * dy) - dx
    y = y0

    for x from x0 to x1
        plot(x, y)
        if D > 0
            y = y + yi
            D = D + (2 * (dy - dx))
        else
            D = D + 2*dy
        end if

By switching the x and y axis an implementation for positive or negative steep slopes can be written as

plotLineHigh(x0, y0, x1, y1)
    dx = x1 - x0
    dy = y1 - y0
    xi = 1
    if dx < 0
        xi = -1
        dx = -dx
    end if
    D = (2 * dx) - dy
    x = x0

    for y from y0 to y1
        plot(x, y)
        if D > 0
            x = x + xi
            D = D + (2 * (dx - dy))
        else
            D = D + 2*dx
        end if

A complete solution would need to detect whether x1 > x0 or y1 > y0 and reverse the input coordinates before drawing, thus

plotLine(x0, y0, x1, y1)
    if abs(y1 - y0) < abs(x1 - x0)
        if x0 > x1
            plotLineLow(x1, y1, x0, y0)
        else
            plotLineLow(x0, y0, x1, y1)
        end if
    else
        if y0 > y1
            plotLineHigh(x1, y1, x0, y0)
        else
            plotLineHigh(x0, y0, x1, y1)
        end if
    end if

In low level implementations which access the video memory directly, it would be typical for the special cases of vertical and horizontal lines to be handled separately as they can be highly optimized.

Some versions use Bresenham's principles of integer incremental error to perform all octant line draws, balancing the positive and negative error between the x and y coordinates.[3]

plotLine(x0, y0, x1, y1)
    dx = abs(x1 - x0)
    sx = x0 < x1 ? 1 : -1
    dy = -abs(y1 - y0)
    sy = y0 < y1 ? 1 : -1
    error = dx + dy
    
    while true
        plot(x0, y0)
        if x0 == x1 && y0 == y1 break
        e2 = 2 * error
        if e2 >= dy
            error = error + dy
            x0 = x0 + sx
        end if
        if e2 <= dx
            error = error + dx
            y0 = y0 + sy
        end if
    end while

Similar algorithms

The Bresenham algorithm can be interpreted as slightly modified digital differential analyzer (using 0.5 as error threshold instead of 0, which is required for non-overlapping polygon rasterizing).

The principle of using an incremental error in place of division operations has other applications in graphics. It is possible to use this technique to calculate the U,V co-ordinates during raster scan of texture mapped polygons.[4] The voxel heightmap software-rendering engines seen in some PC games also used this principle.

Bresenham also published a Run-Slice computational algorithm: while the above described Run-Length algorithm runs the loop on the major axis, the Run-Slice variation loops the other way.[5] This method has been represented in a number of US patents:

5,815,163 Method and apparatus to draw line slices during calculation
5,740,345 Method and apparatus for displaying computer graphics data stored in a compressed format with an efficient color indexing system
5,657,435 Run slice line draw engine with non-linear scaling capabilities
5,627,957 Run slice line draw engine with enhanced processing capabilities
5,627,956 Run slice line draw engine with stretching capabilities
5,617,524 Run slice line draw engine with shading capabilities
5,611,029 Run slice line draw engine with non-linear shading capabilities
5,604,852 Method and apparatus for displaying a parametric curve on a video display
5,600,769 Run slice line draw engine with enhanced clipping techniques

The algorithm has been extended to:

  • Draw lines of arbitrary thickness, an algorithm created by Alan Murphy at IBM.[6]
  • Draw multiple kinds curves (circles, ellipses, cubic, quadratic, and rational bezier curves) and antialiased lines and curves; a set of algorithms by Alois Zingl.[3]

See also

Notes

  1. ^ Paul E. Black. Dictionary of Algorithms and Data Structures, NIST. https://xlinux.nist.gov/dads/HTML/bresenham.html
  2. ^ Joy, Kenneth. "Bresenham's Algorithm" (PDF). Visualization and Graphics Research Group, Department of Computer Science, University of California, Davis. Retrieved 20 December 2016.
  3. ^ a b Zingl, Alois (2012). A Rasterizing Algorithm for Drawing Curves (PDF) (Report).
    HTML abstract and demo: Zingl, Alois (2016). "Bresenham". members.chello.at.
  4. ^ US 5739818, Spackman, John Neil, "Apparatus and method for performing perspectively correct interpolation in computer graphics", published 1998-04-14, assigned to Canon KK 
  5. ^ "Michael Abrash's Graphics Programming Black Book Special Edition: The Good, the Bad, and the Run-Sliced". www.phatcode.net. Retrieved 13 February 2024.;
  6. ^ "Murphy's Modified Bresenham Line Algorithm". homepages.enterprise.net. Retrieved 2018-06-09. ('Line Thickening by Modification to Bresenham's Algorithm' in the IBM Technical Disclosure Bulletin Vol. 20 No. 12 May 1978 pages 5358-5366.)

References

Further reading

  • Patrick-Gillesbanda Thesis, containing an extension of the Bresenham line drawing algorithm to perform 3D hidden lines removal
    • also published in MICAD '87 proceedings on CAD/CAM and Computer Graphics, page 591 - ISBN 2-86601-084-1.
  • Line Thickening by Modification To Bresenham's Algorithm, A.S. Murphy, IBM Technical Disclosure Bulletin, Vol. 20, No. 12, May 1978.
  • Bresenham, Jack (February 1977). "A linear algorithm for incremental digital display of circular arcs". Communications of the ACM. 20 (2): 100–106. doi:10.1145/359423.359432. – also Technical Report 1964 Jan-27 -11- Circle Algorithm TR-02-286 IBM San Jose Lab

Read other articles:

  لمعانٍ أخرى، طالع الترجي الرياضي التونسي (توضيح). الترجي الرياضي التونسي اللقب شيخ الأندية التونسية، المكشّخة، غول إفريقيا، الدم والذهب شعار النادي أحنا الترجي[1] الاسم المختصر EST الألوان  الترجي الرياضي                أحمر، أصفر وأسو

Para los accesorios de moda, véase Complemento (ropa). Batería eléctrica, un accesorio para los automóviles. Se suele llamar accesorio a todo aquel elemento que forma parte de un sistema o de una máquina, una vez definida esta como producto o subproducto básico. Sirve para que la misma ejecute o no la función para la que se prepara. También se define como aquel complemento de un sistema predeterminado (tienen que ser compatibles) y necesario para realizar funciones ejecutadas por medi...

Округ Ларжантьєр фр. Largentière[1]фр. arrondissement de Largentière[1] Адм. центр Ларжантьєр Країна  Франція[2] Регіон Овернь-Рона-Альпи Департамент Ардеш Населення  - повне 103 089 осіб (1 січня 2019)[3] Площа  - повна 2511 км² Округ Ларжантьєр (фр. Arrondissement de Largentière) — о

Кубайчук Віктор Павлович Народився 5 листопада 1946(1946-11-05)Київ, Українська РСР, СРСРПомер 27 січня 2018(2018-01-27) (71 рік)Київ, УкраїнаКраїна  УкраїнаДіяльність фізик, мовознавецьAlma mater фізичний факультет Київського національного університету імені Тараса Шевченка (1972)Галузь

1957 studio album by Stan GetzAward Winner: Stan GetzStudio album by Stan GetzReleased1957RecordedAugust 1957StudioHollywoodGenreJazzLength74:16LabelVerve[1]ProducerNorman GranzStan Getz chronology The Soft Swing(1957) Award Winner: Stan Getz(1957) Stan Getz and the Oscar Peterson Trio(1957) Professional ratingsReview scoresSourceRatingAllMusic[2]The Penguin Guide to Jazz Recordings[3] Award Winner: Stan Getz is a 1957 album by Stan Getz.[4] Track listi...

Anhui Daftar provinsi Republik Rakyat Tiongkok Tempat Negara berdaulatRepublik Rakyat Tiongkok NegaraRepublik Rakyat Tiongkok Ibu kotaHefei Pembagian administratifHefei Wuhu Bengbu Huainan Ma'anshan Huaibei Tongling Anqing, Tiongkok Huangshan Chuzhou Fuyang Suzhou, Anhui Lu'an Bozhou Chizhou Xuancheng PendudukTotal61.027.171  (2020 )Bahasa resmiHuizhou Chinese (en) , Bahasa Gan dan bahasa Wu GeografiLuas wilayah139.000 km² [convert: unit tak dikenal]Titik tertinggiLianhua Peak (en)...

Southern part of Manhattan, New York City Central business district in New York, United StatesLower Manhattan Downtown Manhattan, Downtown New York CityCentral business districtLower Manhattan, including Wall Street, the world's principal financial center, and One World Trade Center, the tallest skyscraper in the United States[1]Country United StatesState New YorkCity New YorkBorough ManhattanSettled1626Population (2010) • Total382,654ZIP Codes10004, 10...

1991 studio album by Rocket from the CryptPaint as a FragranceStudio album by Rocket from the CryptReleasedFebruary 8, 1991Recorded1990Genre Punk rock[1][2] pop-punk[3] Length27:59LabelCargo/HeadhunterProducerJohn ReisRocket from the Crypt chronology Paint as a Fragrance(1991) Circa: Now!(1992) Professional ratingsReview scoresSourceRatingAllMusic[1]The Encyclopedia of Popular Music[4]MusicHound Rock: The Essential Album Guide[5] Paint a...

Park in Shibuya, Tokyo, Japan Yoyogi ParkLocationShibuya, Tokyo, JapanCoordinates35°40′19″N 139°41′52″E / 35.671975°N 139.69768536°E / 35.671975; 139.69768536Area54.1 ha (134 acres)Created1967Public transit accessHarajuku Station, Yoyogi-Koen Station, Meiji-jingumae Station Yoyogi Park (代々木公園, Yoyogi kōen) is a park in Shibuya, Tokyo, Japan. It is located adjacent to Harajuku Station and Meiji Shrine in Yoyogikamizonochō. The park is a popu...

2019 studio album by Dermot KennedyWithout FearStudio album by Dermot KennedyReleased4 October 2019GenreFolk-pop[1]Length50:31LabelRigginsInterscopeIslandProducerScott HarrisCharlie HugallKozSir NolanJonah ShaiStarsmithCarey WillettsDermot Kennedy chronology Dermot Kennedy(2019) Without Fear(2019) Sonder(2022) Singles from Without Fear Moments PassedReleased: 19 September 2017 Power Over MeReleased: 16 October 2018 LostReleased: 6 February 2019 OutnumberedReleased: 14 June 201...

World ParaVolleyFormation1981 - 1994 (WOVD) - 2014 (World ParaVolley)TypeSports federationHeadquartersLoughborough, EnglandMembership 66 membersOfficial language EnglishPresidentPhil AllenWebsitehttps://www.worldparavolley.org/ World ParaVolley, formerly the World Organization Volleyball for Disabled (WOVD), is an international organization that is for people with physical disabilities. It is affiliated with the International Paralympic Committee(IPC). The World Organization Volleyball for Di...

Teritorial Utara Pulau-pulau dipersengketakanNama lain: Kepulauan Kuril Selatan Empat pulau Teritorial Utara: A. Kepulauan Habomai, B. Shikotan, C. Kunashiri (Kunashir), D. Etorofu (Iturup)1. Desa Shikotan, 2. Desa Tomari, 3. Desa Ruyobetsu, 4. Desa Rubetsu, 5. Desa Shana, 6. Desa Shibetoro Geografi Lokasi Samudra Pasifik Kepulauan Kepulauan Kuril Total pulau 4 pulau utama Pulau utama Etorofu (Iturup), Kunashiri (Kunashir), Shikotan, Habomai (Khabomai) Wilayah 5.036 km2 Titik tertinggi Chacha...

Royal Rumble (1989) Девиз Нет партнеров... 30 соперников Промоушн World Wrestling Federation Дата 15 января 1989 года Город Хьюстон, Техас, США Арена Саммит Арена Посещаемость 19000 зрителей Хронология премиальных шоу или PPV ← ПредыдущееSurvivor Series (1988) Следующее → WrestleMania V Xронология Royal Rumble ← П...

В Википедии есть статьи о других людях с фамилией Пуассон. Симеон Дени Пуассонфр. Siméon Denis Poisson Дата рождения 21 июня 1781(1781-06-21) Место рождения Питивье, Франция Дата смерти 25 апреля 1840(1840-04-25) (58 лет) Место смерти Со (О-де-Сен), Франция Страна  Франция Научная сфера математик...

For the sculpture in New York City, see Bust of George Floyd. 2021 statue in Newark, New Jersey, United States Statue of George FloydThe statue in 2021ArtistStanley WattsYear2021 (2021)MediumBronzeSubjectGeorge FloydWeight700 pounds (320 kg)LocationNewark, New Jersey, U.S.Coordinates40°43′54″N 74°10′26″W / 40.7318°N 74.1740°W / 40.7318; -74.1740 A bronze statue of George Floyd (1973–2020), an African-American man who was murdered by police in Mi...

1908 novel by Baroness Orczy The Elusive Pimpernel 1908 First EditionAuthorBaroness OrczyCountryUnited KingdomLanguageEnglishGenreAdventure, HistoricalPublisherHutchinson & Co, LondonPublication date1908Pages352Preceded byI Will Repay Followed byLord Tony's Wife  First published in 1908, The Elusive Pimpernel by Baroness Orczy is the 4th book in the classic adventure series about the Scarlet Pimpernel. A French-language version, translated and adapted by Charlotte and ...

Early Christian hymn of praise Ambrosian Hymn redirects here. For hymns written by Ambrose, see Ambrosian hymns. Te Deum stained glass window by Christopher Whall at St Mary's church, Ware, Hertfordshire The Te Deum (/teɪ ˈdeɪəm/ or /tiː ˈdiːəm/,[1][2] Latin: [te ˈde.um]; from its incipit, Te Deum laudamus (Latin for 'Thee, O God, we praise') is a Latin Christian hymn traditionally ascribed to AD 387 authorship, but with antecedents that place it ...

ChurchSt Olaf's ChurchThe church, viewed from the west, in 2018St Olaf's Church57°25′10″N 1°53′03″W / 57.419416°N 1.884093°W / 57.419416; -1.884093DenominationChurch of ScotlandWebsitehttp://www.crudenchurch.org.uk/ St Olaf's Church (also known as Old Parish Church)[1] is a Category B listed building in Cruden, Aberdeenshire, Scotland, dating to 1776.[2] It is of Church of Scotland denomination.[3] The church's twin, conically roofed...

American radio network This article is about the current radio network in its second incarnation. For the defunct network formerly known as ABC Radio, see Cumulus Media Networks. ABC AudioCountryUnited StatesOwnershipOwnerABC News(Disney Entertainment)Key peopleStacia Philips Deshishku(vice president and general manager)HistoryFoundedAugust 7, 2014 (2014-08-07)Former namesABC Radio (2015-2019)CoverageAvailabilityAvailable on select radio affiliatesLinksWebsiteabcaudio.com ABC A...

1894 | Motorsportjahr 1895 | 1896 | 1897 | 1898 | 1899 | ► | ►► Weitere Sportereignisse Die Apperson-Brüder mit der Haynes Motor Carriage, an der sie mitgebaut hatten. In Chicago, während der Anfahrt zum Rennen, verunfallte Elwood Haynes mit diesem Fahrzeug und konnte nicht am Chicago Times-Herald contest teilnehmen. Nach dem Eklat um den vorenthaltenen Siegespreis für Albert de Dion nach dem Auto-Rennen Paris-Rouen 1894 begann dieser mit einem kle...