Midpoint circle algorithm

Last updated
Rasterizing a circle of radius 23 with the Bresenham midpoint circle algorithm. Only the green octant is actually calculated, it's simply mirrored eight times to form the other seven octants. Midpoint circle algorithm animation (radius 23).gif
Rasterizing a circle of radius 23 with the Bresenham midpoint circle algorithm. Only the green octant is actually calculated, it's simply mirrored eight times to form the other seven octants.
A circle of radius 23 drawn by the Bresenham algorithm Midpoint circle algorithm, radius 23.png
A circle of radius 23 drawn by the Bresenham algorithm

In computer graphics, the midpoint circle algorithm is an algorithm used to determine the points needed for rasterizing a circle. It's a generalization of Bresenham's line algorithm. The algorithm can be further generalized to conic sections. [1] [2] [3]

Contents

Summary

This algorithm draws all eight octants simultaneously, starting from each cardinal direction (0°, 90°, 180°, 270°) and extends both ways to reach the nearest multiple of 45° (45°, 135°, 225°, 315°). It can determine where to stop because when y = x, it has reached 45°. The reason for using these angles is shown in the above picture: As x increases, it neither skips nor repeats any x value until reaching 45°. So during the while loop, x increments by 1 each iteration, and y decrements by 1 on occasion, never exceeding 1 in one iteration. This changes at 45° because that is the point where the tangent is rise=run. Whereas rise>run before and rise<run after.

The second part of the problem, the determinant, is far trickier. This determines when to decrement y. It usually comes after drawing the pixels in each iteration, because it never goes below the radius on the first pixel. Because in a continuous function, the function for a sphere is the function for a circle with the radius dependent on z (or whatever the third variable is), it stands to reason that the algorithm for a discrete(voxel) sphere would also rely on this Midpoint circle algorithm. But when looking at a sphere, the integer radius of some adjacent circles is the same, but it is not expected to have the same exact circle adjacent to itself in the same hemisphere. Instead, a circle of the same radius needs a different determinant, to allow the curve to come in slightly closer to the center or extend out farther.

Algorithm

The objective of the algorithm is to approximate a circle, more formally put, to approximate the curve using pixels; in layman's terms every pixel should be approximately the same distance from the center, as is the definition of a circle. At each step, the path is extended by choosing the adjacent pixel which satisfies but maximizes . Since the candidate pixels are adjacent, the arithmetic to calculate the latter expression is simplified, requiring only bit shifts and additions. But a simplification can be done in order to understand the bitshift. Keep in mind that a left bitshift of a binary number is the same as multiplying with 2. Ergo, a left bitshift of the radius only produces the diameter which is defined as radius times two.

This algorithm starts with the circle equation. For simplicity, assume the center of the circle is at . To start with, consider the first octant only, and draw a curve which starts at point and proceeds counterclockwise, reaching the angle of 45°.

The fast direction here (the basis vector with the greater increase in value) is the direction (see Differentiation of trigonometric functions). The algorithm always takes a step in the positive direction (upwards), and occasionally takes a step in the slow direction (the negative direction).

From the circle equation is obtained the transformed equation , where is computed only once during initialization.

Let the points on the circle be a sequence of coordinates of the vector to the point (in the usual basis). Points are numbered according to the order in which drawn, with assigned to the first point .

For each point, the following holds:

This can be rearranged thus:

And likewise for the next point:

Since for the first octant the next point will always be at least 1 pixel higher than the last (but also at most 1 pixel higher to maintain continuity), it is true that:

So, rework the next-point-equation into a recursive one by substituting :

Because of the continuity of a circle and because the maxima along both axes is the same, clearly it will not be skipping x points as it advances in the sequence. Usually it stays on the same x coordinate, and sometimes advances by one to the left.

The resulting coordinate is then translated by adding midpoint coordinates. These frequent integer additions do not limit the performance much, as those square (root) computations can be spared in the inner loop in turn. Again, the zero in the transformed circle equation is replaced by the error term.

The initialization of the error term is derived from an offset of ½ pixel at the start. Until the intersection with the perpendicular line, this leads to an accumulated value of in the error term, so that this value is used for initialization.

The frequent computations of squares in the circle equation, trigonometric expressions and square roots can again be avoided by dissolving everything into single steps and using recursive computation of the quadratic terms from the preceding iterations.

Variant with integer-based arithmetic

Just as with Bresenham's line algorithm, this algorithm can be optimized for integer-based math. Because of symmetry, if an algorithm can be found that only computes the pixels for one octant, the pixels can be reflected to get the whole circle.

We start by defining the radius error as the difference between the exact representation of the circle and the center point of each pixel (or any other arbitrary mathematical point on the pixel, so long as it's consistent across all pixels). For any pixel with a center at , the radius error is defined as:

For clarity, this formula for a circle is derived at the origin, but the algorithm can be modified for any location. It is useful to start with the point on the positive X-axis. Because the radius will be a whole number of pixels, clearly the radius error will be zero:

Because it starts in the first counter-clockwise positive octant, it will step in the direction with the greatest travel, the Y direction, so it is clear that . Also, because it concerns this octant only, the X values have only 2 options: to stay the same as the prior iteration, or decrease by 1. A decision variable can be created that determines if the following is true:

If this inequality holds, then plot ; if not, then plot . So, how to determine if this inequality holds? Start with a definition of radius error:

The absolute value function does not help, so square both sides, since a square is always positive:

Since x > 0, the term , so dividing gets:

Thus, the decision criterion changes from using floating-point operations to simple integer addition, subtraction, and bit shifting (for the multiply by 2 operations). If , then decrement the x value. If , then keep the same x value. Again, by reflecting these points in all the octants, a full circle results.

We may reduce computation by only calculating the delta between the values of this decision formula from its value at the previous step. We start by assigning as which is the initial value of the formula at , then as above at each step if we update it as (and decrement X), otherwise thence increment Y as usual.

Jesko's Method

The algorithm has already been explained to a large extent, but there are further optimizations.

The new presented method [4] gets along with only 5 arithmetic operations per step (for 8 pixels) and is thus best suitable for low-performate systems. In the "if" operation, only the sign is checked (positive? Yes or No) and there is a variable assignment, which is also not considered an arithmetic operation. The initialization in the first line (shifting by 4 bits to the right) is only due to beauty and not really necessary.

So we get countable operations within main-loop:

  1. The comparison x >= y (is counted as a substraction: x - y >= 0 )
  2. y=y+1 [y++]
  3. t1 + y
  4. t1 - x
    1. The comparison t2 >= 0 is NOT counted as no real arithmetic takes place. In Two's-complement representation of the vars only the sign bit has to be checked.
  5. x=x-1 [x--]

Operations: 5

t1 = r / 16 x = r y = 0 Repeat Untilx < y     Pixel (x, y) and all symmetric pixels are colored (8 times)     y = y + 1     t1 = t1 + yt2 = t1 - xIft2 >= 0         t1 = t2x = x - 1

Drawing incomplete octants

The implementations above always draw only complete octants or circles. To draw only a certain arc from an angle to an angle , the algorithm needs first to calculate the and coordinates of these end points, where it is necessary to resort to trigonometric or square root computations (see Methods of computing square roots). Then the Bresenham algorithm is run over the complete octant or circle and sets the pixels only if they fall into the wanted interval. After finishing this arc, the algorithm can be ended prematurely.

If the angles are given as slopes, then no trigonometry or square roots are necessary: simply check that is between the desired slopes.

Generalizations

It is also possible to use the same concept to rasterize a parabola, ellipse, or any other two-dimensional curve. [5]

Related Research Articles

<span class="mw-page-title-main">Circle</span> Simple curve of Euclidean geometry

A circle is a shape consisting of all points in a plane that are at a given distance from a given point, the centre. The distance between any point of the circle and the centre is called the radius.

<span class="mw-page-title-main">Ellipse</span> Plane curve: conic section

In mathematics, an ellipse is a plane curve surrounding two focal points, such that for all points on the curve, the sum of the two distances to the focal points is a constant. It generalizes a circle, which is the special type of ellipse in which the two focal points are the same. The elongation of an ellipse is measured by its eccentricity , a number ranging from to .

<span class="mw-page-title-main">Elementary algebra</span> Basic concepts of algebra

Elementary algebra, also known as college algebra, encompasses the basic concepts of algebra. It is often contrasted with arithmetic: arithmetic deals with specified numbers, whilst algebra introduces variables.

<span class="mw-page-title-main">Natural logarithm</span> Logarithm to the base of the mathematical constant e

The natural logarithm of a number is its logarithm to the base of the mathematical constant e, which is an irrational and transcendental number approximately equal to 2.718281828459. The natural logarithm of x is generally written as ln x, logex, or sometimes, if the base e is implicit, simply log x. Parentheses are sometimes added for clarity, giving ln(x), loge(x), or log(x). This is done particularly when the argument to the logarithm is not a single symbol, so as to prevent ambiguity.

<i>n</i>-sphere Generalized sphere of dimension n (mathematics)

In mathematics, an n-sphere or hypersphere is an n-dimensional generalization of the 1-dimensional circle and 2-dimensional sphere to any non-negative integer n. The n-sphere is the setting for n-dimensional spherical geometry.

In mathematics, a partial derivative of a function of several variables is its derivative with respect to one of those variables, with the others held constant. Partial derivatives are used in vector calculus and differential geometry.

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, 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.

<span class="mw-page-title-main">System of linear equations</span> Several equations of degree 1 to be solved simultaneously

In mathematics, a system of linear equations is a collection of one or more linear equations involving the same variables. For example,

<span class="mw-page-title-main">Cube root</span> Number whose cube is a given number

In mathematics, a cube root of a number x is a number y such that y3 = x. All nonzero real numbers have exactly one real cube root and a pair of complex conjugate cube roots, and all nonzero complex numbers have three distinct complex cube roots. For example, the real cube root of 8, denoted , is 2, because 23 = 8, while the other cube roots of 8 are and . The three cube roots of −27i are:

<span class="mw-page-title-main">Locus (mathematics)</span> Set of points that satisfy some specified conditions

In geometry, a locus is a set of all points, whose location satisfies or is determined by one or more specified conditions.

<span class="mw-page-title-main">Cardioid</span> Type of plane curve

In geometry, a cardioid is a plane curve traced by a point on the perimeter of a circle that is rolling around a fixed circle of the same radius. It can also be defined as an epicycloid having a single cusp. It is also a type of sinusoidal spiral, and an inverse curve of the parabola with the focus as the center of inversion. A cardioid can also be defined as the set of points of reflections of a fixed point on a circle through all tangents to the circle.

In the mathematical field of complex analysis, contour integration is a method of evaluating certain integrals along paths in the complex plane.

The second moment of area, or second area moment, or quadratic moment of area and also known as the area moment of inertia, is a geometrical property of an area which reflects how its points are distributed with regard to an arbitrary axis. The second moment of area is typically denoted with either an or with a . In both cases, it is calculated with a multiple integral over the object in question. Its dimension is L (length) to the fourth power. Its unit of dimension, when working with the International System of Units, is meters to the fourth power, m4, or inches to the fourth power, in4, when working in the Imperial System of Units or the US customary system.

<span class="mw-page-title-main">Polarization identity</span> Formula relating the norm and the inner product in a inner product space

In linear algebra, a branch of mathematics, the polarization identity is any one of a family of formulas that express the inner product of two vectors in terms of the norm of a normed vector space. If a norm arises from an inner product then the polarization identity can be used to express this inner product entirely in terms of the norm. The polarization identity shows that a norm can arise from at most one inner product; however, there exist norms that do not arise from any inner product.

In linear algebra, an augmented matrix is a matrix obtained by appending a -dimensional row vector , on the right, as a further column to a -dimensional matrix . This is usually done for the purpose of performing the same elementary row operations on the augmented matrix as is done on the original one when solving a system of linear equations by Gaussian elimination.

<span class="mw-page-title-main">Sine and cosine</span> Fundamental trigonometric functions

In mathematics, sine and cosine are trigonometric functions of an angle. The sine and cosine of an acute angle are defined in the context of a right triangle: for the specified angle, its sine is the ratio of the length of the side that is opposite that angle to the length of the longest side of the triangle, and the cosine is the ratio of the length of the adjacent leg to that of the hypotenuse. For an angle , the sine and cosine functions are denoted as and .

In mathematics, a system of equations is considered overdetermined if there are more equations than unknowns. An overdetermined system is almost always inconsistent when constructed with random coefficients. However, an overdetermined system will have solutions in some cases, for example if some equation occurs several times in the system, or if some equations are linear combinations of the others.

<span class="mw-page-title-main">Poincaré disk model</span> Model of hyperbolic geometry

In geometry, the Poincaré disk model, also called the conformal disk model, is a model of 2-dimensional hyperbolic geometry in which all points are inside the unit disk, and straight lines are either circular arcs contained within the disk that are orthogonal to the unit circle or diameters of the unit circle.

In the geometry of numbers, Schinzel's theorem is the following statement:

<span class="mw-page-title-main">Chambolle-Pock algorithm</span> Primal-Dual algorithm optimization for convex problems

In mathematics, the Chambolle-Pock algorithm is an algorithm used to solve convex optimization problems. It was introduced by Antonin Chambolle and Thomas Pock in 2011 and has since become a widely used method in various fields, including image processing, computer vision, and signal processing.

References

  1. Donald Hearn; M. Pauline Baker (1994). Computer graphics . Prentice-Hall. ISBN   978-0-13-161530-4.
  2. Pitteway, M.L.V., "Algorithm for Drawing Ellipses or Hyperbolae with a Digital Plotter", Computer J., 10(3) November 1967, pp 282–289
  3. Van Aken, J.R., "An Efficient Ellipse Drawing Algorithm", CG&A, 4(9), September 1984, pp 24–35
  4. For the history of the publication of this algorithm see https://schwarzers.com/algorithms
  5. Zingl, Alois (December 2014). "The Beauty of Bresenham's Algorithm: A simple implementation to plot lines, circles, ellipses and Bézier curves". easy.Filter. Alois Zingl. Retrieved 16 February 2017.