# Let's Build a 3D Graphics Engine: Rasterizing Line Segments and Circles Hello, this is the fourth part of our series on 3D graphics engines. This time, we will be covering rasterization: the process of taking a shape described by mathematical formulas and converting it to an image on your screen.

Tip: All of the concepts in this article are built off of classes that we've established in the first three posts, so be sure to check them out first.

## Recap

Here's a review of the classes that we've made so far:

 1 Point Class  2 {  3  Variables:  4  num tuple; //(x,y,z)  5  Operators:  6  Point AddVectorToPoint(Vector);  7  Point SubtractVectorFromPoint(Vector);  8  Vector SubtractPointFromPoint(Point);  9  Null SetPointToPoint(Point);  10  Functions:  11  drawPoint; //draw a point at its position tuple  12 }  13 14 Vector Class  15 {  16  Variables:  17  num tuple; //(x,y,z)  18  Operators:  19  Vector AddVectorToVector(Vector);  20  Vector SubtractVectorFromVector(Vector);  21  Vector RotateXY(degrees);  22  Vector RotateYZ(degrees);  23  Vector RotateXZ(degrees);  24  Vector Scale(s0,s1,s2); //receives a scaling 3-tuple, returns the scaled vector  25 }  26 27 Camera Class  28 {  29  Vars:  30  int minX, maxX;  31  int minY, maxY;  32  int minZ, maxZ;  33  array objectsInWorld; //an array of all existent objects  34  Functions:  35  null drawScene(); //draws all needed objects to the screen  36 } 

You can check out the sample program from the third part of the series to see how they work together.

Now, let's take a look at some new stuff!

## Rasterization

Rasterization (or rasterisation, if you like) is the process of taking a shape described in a vector graphics format (or in our case, mathematically) and converting it into a raster image (where the shape is fit onto a pixel structure).

Because math isn't always as precise as we need it to be for computer graphics, we must use algorithms to fit the shapes it describes onto our integer-based screen. For example, a point can fall onto the co-ordinate $$(3.2, 4.6)$$ in mathematics, but when we render it, we must nudge it to $$(3, 5)$$ so it can fit into the pixel structure of our screen.

Each type of shape that we rasterize will have its own algorithm for doing so. Let's start with one of the more simple shapes to rasterize: the line segment.

## Line Segments

Line segments are one of the simplest shapes that can be drawn, and so are often one of the first things covered in any geometry class. They are represented by two distinct points (one beginning point and one ending point), and the line that connects the two. The most commonly used algorithm in rasterizing a line segment is called Bresenham's Algorithm.

Step by step, Bresenham's Algorithm works like this:

1. Receive a line segment's beginning and ending points as input.
2. Identify a line segment's direction by determining its $$dx$$ and $$dy$$ properties ($$dx = x_{1} - x_{0}$$, $$dy = y_{1} - y_{0}$$).
3. Determine sx, sy, and error catching properties (I'll show the mathematical definition for these below).
4. Round each point in the line segment to either the pixel above or below.

Before we implement Bresenham's Algorithm, lets put together a basic line segment class to be used in our engine:

 1 LineSegment Class  2 {  3  Variables:  4  int startX, startY; //the starting point of our line segment  5  int endX, endY; //the ending point of our line segment  6  Function:  7  array returnPointsInSegment; //all points lying on this line segment  8 } 

If you want to perform a transformation on our new LineSegment class, all you have to do is apply your chosen transformation to the beginning and ending points of the LineSegment and then place them back into the class.  All of the points that fall between will be processed when the LineSegment itself is drawn, as Bresenham's Algorithm only requires the beginning and ending points to find each subsequent point.

In order for the LineSegment class to fit with our current engine, we can't actually have a draw() function built into the class, which is why I've opted for using a returnPointsInSegment function instead. This function will return an array of every point that exists within the line segment, allowing us to easily draw and cull the line segment as appropriate.

Our function returnPointsInSegment() looks a bit like this (in JavaScript):

 1 function returnPointsInSegment()  2 {  3  //create a list to store all of the line segment's points in  4  var pointArray = new Array();  5  //set this function's variables based on the class's starting and ending points  6  var x0 = this.startX;  7  var y0 = this.startY;  8  var x1 = this.endX;  9  var y1 = this.endY;  10  //define vector differences and other variables required for Bresenham's Algorithm  11  var dx = Math.abs(x1-x0);  12  var dy = Math.abs(y1-y0);  13  var sx = (x0 & x1) ? 1 : -1; //step x  14  var sy = (y0 & y1) ? 1 : -1; //step y  15  var err = dx-dy; //get the initial error value  16  //set the first point in the array  17  pointArray.push(new Point(x0,y0));  18 19  //Main processing loop  20  while(!((x0 == x1) && (y0 == y1)))  21  {  22  var e2 = err * 2; //hold the error value  23  //use the error value to determine if the point should be rounded up or down  24  if(e2 => -dy)  25  {  26  err -= dy;  27  x0 += sx;  28  }  29  if(e2 < dx)  30  {  31  err += dx;  32  y0 += sy;  33  }  34  //add the new point to the array  35  pointArray.push(new Point(x0, y0));  36  }  37  return pointArray;  38 } 

The easiest way to add the rendering of our line segments into our camera class is to add in a simple if structure, similar to the following:

 1  //loop through array of objects  2  if (class type == Point)  3  {  4  //do our current rendering code  5  }  6  else if (class type == LineSegment)  7  {  8  var segmentArray = LineSegment.returnPointsInSegment();  9  //loop through points in the array, drawing and culling them as we have previously  10  } 

That's all you need to get your first shape class up and running!  If you want to learn more about the more technical aspects of Bresenham's Algorithm (particularly the error sections), you can check out the Wikipedia article on it.

## Circles

Rasterizing a circle is a bit more difficult than rasterizing a line segment, but not much. We will be using the midpoint circle algorithm to do all of our heavy lifting, which is an extension of the previously mentioned Bresenham's Algorithm.  As such, it follows similar steps to those that were listed above, with some minor differences.

Our new algorithm works like this:

2. Forcibly set the points in each cardinal direction
3. Cycle through each of our quadrants, drawing their arcs

Our circle class will be very similar to our line segment class, looking something like this:

 1 Circle Class  2 {  3  Variables:  4  int centerX, centerY; //the center point of our circle  5  int radius; //the radius of our circle  6  Function:  7  array returnPointsInCircle; //all points within this Circle  8 } 

Our returnPointsInCircle() function is going to behave in the same way that our LineSegment class's function does, returning an array of points so that our camera can render and cull them as needed. This lets our engine handle a variety of shapes, with only minor changes needed for each.

Here is what our returnPointsInCircle() function is going to look like (in JavaScript):

 1 function returnPointsInCircle()  2 {  3  //store all of the circle's points in an array  4  var pointArray = new Array();  5  //set up the values needed for the algorithm  6  var f = 1 - radius; //used to track the progress of the drawn circle (since its semi-recursive)  7  var ddFx = 1; //step x  8  var ddFy = -2 * this.radius; //step y  9  var x = 0;  10  var y = this.radius;  11 12  //this algorithm doesn't account for the farthest points,  13  //so we have to set them manually  14  pointArray.push(new Point(this.centerX, this.centerY + this.radius));  15  pointArray.push(new Point(this.centerX, this.centerY - this.radius));  16  pointArray.push(new Point(this.centerX + this.radius, this.centerY));  17  pointArray.push(new Point(this.centerX - this.radius, this.centerY));  18 19  while(x < y) {  20  if(f >= 0) {  21  y--;  22  ddFy += 2;  23  f += ddFy;  24  }  25  x++;  26  ddFx += 2;  27  f += ddFx;  28 29  //build our current arc  30  pointArray.push(new Point(x0 + x, y0 + y));  31  pointArray.push(new Point(x0 - x, y0 + y));  32  pointArray.push(new Point(x0 + x, y0 - y));  33  pointArray.push(new Point(x0 - x, y0 - y));  34  pointArray.push(new Point(x0 + y, y0 + x));  35  pointArray.push(new Point(x0 - y, y0 + x));  36  pointArray.push(new Point(x0 + y, y0 - x));  37  pointArray.push(new Point(x0 - y, y0 - x));  38  }  39 40  return pointArray;  41 } 

Now, we just add in another if statement to our main drawing loop, and these circles are fully integrated!

Here is how the updated drawing loop may look:

 1  //loop through array of objects  2  if(class type == point)  3  {  4  //do our current rendering code  5  }  6  else if(class type == LineSegment)  7  {  8  var segmentArray = LineSegment.returnPointsInSegment();  9  //loop through points in the array, drawing and culling them as we have previously  10  }  11  else if(class type == Circle)  12  {  13  var circleArray = Circle.returnPointsInCircle();  14  //loop through points in the array, drawing and culling them as we have previously  15  } 

Now that we've got our new classes out of the way, let's make something!

## Raster Master

Our program is going to be simple this time. When the user clicks on the screen, we are going to draw a circle whose center point is the point that was clicked, and whose radius is a random number.

Let's take a look at the code:

 1 main{  2  //setup for your favorite Graphics API here  3  //setup for keyboard input (may not be required) here  4 5  var camera = new Camera(); //create an instance of the camera class  6  camera.objectsInWorld[]; //create 100 object spaces within the camera's array  7 8  //set the camera's view space  9  camera.minX = 0;  10  camera.maxX = screenWidth;  11  camera.minY = 0;  12  camera.maxY = screenHeight;  13  camera.minZ = 0;  14  camera.maxZ = 100;  15 16  while(key != esc) {  17  if(mouseClick) {  18  //create a new circle  19  camera.objectsInWorld.push(new Circle(mouse.x,mouse.y,random(3,10));  20  //render everything in the scene  21  camera.drawScene();  22  }  23  }  24 } 

With any luck, you should now be able to use your updated engine to draw some awesome circles.

## Conclusion

Now that we have some basic rasterization features in our engine, we can finally start drawing some useful things to our screen! Nothing too complicated just yet, but if you wanted to, you could piecing together some stick figures, or something of the kind.

In the next post, we're going to be taking another look at rasterization. - only this time, we're going to be setting up two more classes to be used within our engine: triangles and quadrilaterals. Stay tuned!