DirectDraw - Rasterisation and 2D Transformations

This article outlines the topics of rasterisation and 2D transformations:

  • Drawing and clipping lines
  • Drawing wireframe polygons
  • 2D transformations
    • Translations
    • Rotations
    • Scaling
  • Transformations with matrices
    • Translations
    • Scaling
    • Rotations
  • Solid filled polygons
  • Triangulating quadrilaterals
  • Polygon collision detection
  • Timing and synchronisation
  • Scrolling and panning

Drawing lines with Bresenham’s Algorithm

Rasterisation in this context is the process of taking a vector based description of a geometric entity and filling (plotting) pixels from one point to another that most closely fit to the real line. This definition is also extended to other primitives, including triangles (or polygons in general).

Drawing lines on a grid will almost always involve approximations. A line will almost certainly not cross pixels exactly, it may cross two or more, and then comes the questions how or which pixels should be part of the rasterised line.

Taking the equation to a straight line \(y = mx + c\) (where x and y are integers), one can draw a line by

  1. determining the gradient \(m = \frac{y_{f} - y_{0}}{x_{f} - x_{0}}\)
  2. plot the initial point at \((x_{0}, y_{0})\)
  3. determine the next value of (x, y) from the gradient \(m = \frac{y - y_{0}}{x - x_{0}}\)
  4. repeat until all values of (x, y) until done at \((x_{f}, y_{f})\)

The problem with this approach is that the rasterised line will likely contain gaps, particularly if the line is steep. To get around this, one could simply calculate values of y for smaller changes to x. This however still won’t work for very steep gradients.

The gradient of the line will ultimately determine the approach taken. If the gradient is greater than one then evidently all rows (y) must have one pixel drawn; similarly, if the gradient is less than one then all columns (x) must be assigned a pixel.

The process of pixel selection can be handled by Bresenham’s algorithm. This attempts to select a point (on the rasterised line) that lies closest to the true line. All rasterised points discussed here will be integer based.

A decision term decision is applied and constantly updated based on the previously plotted point.

/*
*Draws a line between two endpoints at (x0, y0) and (x1, y1), 8-bit mode only
*/
int drawLine8bit(int x0, int y0, int x1, int y1, 
				 UCHAR colour, UCHAR *videoBuffer, int lpitch){

	int dx,   // difference in x's
		dy,   // difference in y's
		dx2,  // equals (dx*2), used to calc. error
		dy2,  // equals (dy*2), used to calc. error
		xInc, // no. of pixels to move along x-axis
	    yInc, // no. of pixels to move along y-axis
		decision, // decision variable
		index; // used for looping

	// pre-compute first pixel address in video buffer
	videoBuffer = videoBuffer + x0 + y0*lpitch;

	// compute horizontal and vertical deltas
	dx = x1 - x0;
	dy = y1 - y0;

	// test which direction the line is going in 
	// and then expect x to change by one unit
	if (dx >= 0){
		xInc = 1;
	} else if (dx < 0) {
		xInc = -1;
		dx = -dx; // need absolute value
	} else {
		dx = 0;
	}

	// test which direction the line is going in 
	// and then expect y to change by one scan line (pitch)
	if (dy >= 0){
		yInc = lpitch;
	} else if (dy < 0) {
		yInc = -lpitch;
		dy = -dy;  // need absolute value
	} else {
		dy = 0;
	}

	// prep
	dx2 = dx << 1;
	dy2 = dy << 1;


	if (dx > dy){
		// |m| < 1, eventually we will 
		// move one unit along the x-axis;
		// ignore the else block, this will never run
		// in this case

		// initialise, then update decision in y
		decision = dy2 - dx;
		
		// draw the line
		for (index = 0; index <= dx; index++){
			// plot pixel
			*videoBuffer = colour;
			
			if (decision >= 0){
				// ready to move pointer to next row (y);
				// bring back decision and test again later
				decision -= dx2;
				videoBuffer += yInc;
			}
			
			decision += dy2;
			
			// move to the next column (x)
			videoBuffer += xInc;
		}
	} else {
		// |m| >= 1, eventually we will 
		// move one unit along the y-axis;
		// ignore the if block, that will never run
		// in this case
		decision = dx2 - dy;
		
		// draw the line
		for (index = 0; index <= dy; index++){
			// set the pixel
			*videoBuffer = colour;
			
			// test if error overflowed
			if (decision >= 0){
				// ready to move pointer to next column (x);
				// bring back decision and test again later
				decision -= dy2;
				videoBuffer += xInc;
			}
			
			decision += dx2;
			
			// move to the next row (y)
			videoBuffer += yInc;
		}
	}

	// return success
	return(1);
}

It’s possible to optimise the above algorithm in a number of ways:

  • ignore functions of lines e.g. y = x, y = constant or x = constant, these do not require Bresenham’s algorithm
  • for straight line functions, rasterise up to the midpoint and then copy the line after the midpoint
  • if possible, identify a set of points (parts of the rasterised line) that resemble a constant function (as a run) that could be handled without Bresenham’s algorithm (this optimisation yields the Run-Slicing algorithm)
  • consider applying the Symmetric Double-Step algorithm: this recognises that for every two points, a line segment can only be composed of one of four 3x3 patterns (below), or a 90 degree rotated version of the pattern. The algorithm looks at the decision (or error) term to decide which pattern to render before continuing along the line and is generally much quicker than Bresenham’s algorithm.

Clipping in 2D

Clipping bitmaps is achieved by overlapping the bitmap’s bounding rectangle with the viewport’s rectangle. The intersection of both rectangles would be the area to blit.

Clipping lines is (computationally) relatively more difficult to do. Given a clipping rectangle and a line, one will need a clipping filter to identify where the line(s) intersect with the clipping rectangle boundaries.

Overall, the clipping process checks:

a. if a line segment (i.e. both endpoints) lies completely within the clipping rectangle b. if a line segment lies completely outside the clipping rectangle c. otherwise perform intersection calculations with one or more clipping boundaries

Before outlining line clipping, we review a few basic mathematical prerequisites.

Finding the intersection of two lines using point-slope form

Using the point-slope form of the equation to a line:

\[y - y_{0} = m(x - x_{0})\]

We have the point of intersection (x, y) for lines that have segments p0 and p1 with gradients m0 and mq respectively:

\[y_{1} - y_{0} = m0(x_{1} - x_{0}) \\ y_{3} - y_{2} = m1(x_{3} - x_{2})\]

Or for any point along each line with, for example:

\[y - y_{0} = m_{0}(x - x_{0}) \\ y - y_{2} = m_{1}(x - x_{2})\]

Solving for a point of intesection at (x, y):

\[x = \frac{-m_{0}x_{2}}{m_{1} - m_{0}} + m_{0}(y_{2} - y_{0}) + x_{0}\] \[y = \frac{m_{0}y_{0} - m_{1}y_{2} + x_{2} - x_{0}}{m_{0} - m_{1}}\]

Note from above that if both lines are parallel, then |m1| = |m0| and they cannot intersect. The above equations would yield zero as denominators.

Finding the intercept of a line using the general form

Using the general form of the equation to a line:

\[ax + by = c\]

Or for some other value of c as:

\[ax + by + c = 0\]

Taking the above point-slope form and equating coefficients a, b and c in terms of the gradients m, and an intercept at x = 0, we have:

\[y - y_{0} = m(x - x_{0}) \\ y - y_{0} = mx - mx_{0}\]

Then we have the general form for the line:

\[-mx + y = y_{0} - mx_{0} \\\]

Then as:

\[mx - y = mx_{0} - y_{0}\]

The intercept is $mx_{0} - y_{0}$.

Finding the intersection of two lines in Matrix form

Two lines in general form can be expressed as a matrix.

\[a_{1}x + b_{1}y = c_{1} \\ a_{2}x + b_{2}y = c_{2}\]

The matrix is given by: Ax = Y, with A:

A = \(\begin{bmatrix} a1 & b1 \\ a2 & b2 \end{bmatrix}\)

and x =

\[\begin{bmatrix} x \\ y \end{bmatrix}\]

and finally Y =

\[\begin{bmatrix} c1 \\ c2 \end{bmatrix}\]

To solve for the intersection at (x, y) one can use determinants:

\[x = \frac{det(A1)}{det(A)}\] \[y = \frac{det(A2)}{det(A)}\]

The matrices A1 (in y) and A2 (in x) are defined here as:

A1 = \(\begin{vmatrix} c1 & b1 \\ c2 & b2 \end{vmatrix}\)

A2 = \(\begin{vmatrix} a1 & c1 \\ a2 & c2 \end{vmatrix}\)

The determinant (a scalar) for a 2x2 matrix for e.g. A1 and A2 are

\[det(A1) = c_{1}b_{2} - b_{1}c_{2} \\ det(A2) = a_{1}c_{2} - c_{1}a_{2}\]

Then knowing

\[det(A) = a_{1}b_{2} - b_{1}a_{2}\]

Then the solutions are

\[x = \frac{c_{1}b_{2} - b_{1}c_{2}}{a_{1}b_{2} - b_{1}a_{2}}\] \[y = \frac{a_{1}c_{2} - c_{1}c_{2}}{a_{1}b_{2} - b_{1}a_{2}}\]

Clipping lines with the Cohen-Sutherland Algorithm

To reiterate, an clipping algorithm needs to determine:

a. if a line segment (i.e. both endpoints) lies completely within the clipping rectangle b. if a line segment lies completely outside the clipping rectangle c. otherwise perform intersection calculations with one or more clipping boundaries

To reduce unnecessary calculations, the Cohen-Sutherland Algorithm breaks up the task by defining sectors external to the clipping region. Any line segments or parts of line segments located in these sectors are omitted from the viewport.

Each distinct sector is typically given a clip code so as to determine quickly what clipping is required.

The complete function clipLine() is given below. Taking a couple of examples, for the endpoint (x1, y1) found to reside in Clip code NORTH and SOUTH:

case CLIP_CODE_N:
  {
    // deduced: y1 > maxClipY

    // make sure y1 does not exceed upper limit
    y1Clipped = maxClipY;

    // offset x accordingly
    x1Clipped = x1 + 0.5 + (maxClipY-y1)*(x2-x1)/(y2-y1);
  } break;

In all examples shown in this section, the addition of 0.5 to the clipped coordinates is an additional term that is meant to address truncation at the endpoints. During float to int conversions, coordinates will in many cases be truncated (values greater than e.g. 4.5 are rounded to 4 on conversion). Without it, some polygons may appear slightly smaller or not fully characterised, so adding 0.5 is meant to be a compromise.

The complete function:

/*
* Clips a line by updating the endpoints (x1, y1) and (x2, y2)
*/
int clipLine(int &x1, int &y1, int &x2, int &y2){

	// internal clipping codes
	#define CLIP_CODE_C  0x0000 // completely in clipping region
	#define CLIP_CODE_N  0x0008 // crosses top edge (bits 1000)
	#define CLIP_CODE_S  0x0004 // crosses bottom edge (bits 0100)
	#define CLIP_CODE_E  0x0002 // crosses right edge (bits 0010)
	#define CLIP_CODE_W  0x0001 // crosses left edge (bits 0001)

	#define CLIP_CODE_NE 0x000a // bits 1010
	#define CLIP_CODE_SE 0x0006 // bits 0110
	#define CLIP_CODE_NW 0x0009 // bits 1001
	#define CLIP_CODE_SW 0x0005 // bits 0101

	// this function updates the passed coords;
	// store them here temporarily and update
	// at the end if all OK
	int x1Clipped = x1, 
		y1Clipped = y1, 
		x2Clipped = x2, 
		y2Clipped = y2;

	// points 1 and 2 clip codes
	int p1_code = 0, 
		p2_code = 0;

	// determine codes for p1 and p2
	if (y1 < minClipY)
		p1_code |= CLIP_CODE_S;
	else
	if (y1 > maxClipY)
		p1_code |= CLIP_CODE_N;

	if (x1 < minClipX)
		p1_code |= CLIP_CODE_W;
	else
	if (x1 > maxClipX)
		p1_code |= CLIP_CODE_E;

	if (y2 < minClipY)
		p2_code |= CLIP_CODE_S;
	else
	if (y2 > maxClipY)
		p2_code |= CLIP_CODE_N;

	if (x2 < minClipX)
		p2_code |= CLIP_CODE_W;
	else
	if (x2 > maxClipX)
		p2_code |= CLIP_CODE_E;

	// try and trivially reject
	if ((p1_code & p2_code)) 
		return(0);

	// test for totally visible, if so leave points untouched
	if (p1_code == 0 && p2_code == 0)
		return(1);

	// determine end clip point for p1
	switch(p1_code){
		case CLIP_CODE_C: 
			break;

		case CLIP_CODE_N:
			{
				y1Clipped = maxClipY;
				x1Clipped = x1 + 0.5 + 
				  (maxClipY-y1)*(x2-x1)/(y2-y1);
			} break;

		case CLIP_CODE_S:
			{
				y1Clipped = minClipY;
				x1Clipped = x1 + 0.5 + 
				  (minClipY-y1)*(x2-x1)/(y2-y1);
			} break;

		case CLIP_CODE_W:
			{
				x1Clipped = minClipX;
				y1Clipped = y1 + 0.5 + 
				  (minClipX-x1)*(y2-y1)/(x2-x1);
			} break;

		case CLIP_CODE_E:
			{
				x1Clipped = maxClipX;
				y1Clipped = y1 + 0.5 + 
				  (maxClipX-x1)*(y2-y1)/(x2-x1);
			} break;

		// these cases are more complex, must compute 2 intersections
		case CLIP_CODE_NE:
			{
				// north hline intersection
				y1Clipped = maxClipY;
				x1Clipped = x1 + 0.5 + 
				  (maxClipY-y1)*(x2-x1)/(y2-y1);

				// test if intersection is valid
				if (x1Clipped < minClipX || x1Clipped > maxClipX){
					// east vline intersection
					x1Clipped = maxClipX;
					y1Clipped = y1 + 0.5 + 
					  (maxClipX-x1)*(y2-y1)/(x2-x1);
				}
			} break;

		case CLIP_CODE_SE:
			{
				// south hline intersection
				y1Clipped = minClipY;
				x1Clipped = x1 + 0.5 + 
				  (minClipY-y1)*(x2-x1)/(y2-y1);
				
				// test if intersection is valid
				if (x1Clipped < minClipX || x1Clipped > maxClipX){
					// east vline intersection
					x1Clipped = maxClipX;
					y1Clipped = y1 + 0.5 + 
					  (maxClipX-x1)*(y2-y1)/(x2-x1);
				}
			} break;
		 
		case CLIP_CODE_NW:
			{
				// north hline intersection
				y1Clipped = maxClipY;
				x1Clipped = x1 + 0.5 + 
				  (maxClipY-y1)*(x2-x1)/(y2-y1);
				
				// test if intersection is valid
				if (x1Clipped < minClipX || x1Clipped > maxClipX){
					x1Clipped = minClipX;
					y1Clipped = y1 + 0.5 + 
					  (minClipX-x1)*(y2-y1)/(x2-x1);	
				}
			} break;
		
		case CLIP_CODE_SW:
			{
				// south hline intersection
				y1Clipped = minClipY;
				x1Clipped = x1 + 0.5 + 
				  (minClipY-y1)*(x2-x1)/(y2-y1);
				
				// test if intersection is valid
				if (x1Clipped < minClipX || x1Clipped > maxClipX){
					x1Clipped = minClipX;
					y1Clipped = y1 + 0.5 + 
					  (minClipX-x1)*(y2-y1)/(x2-x1);
				}
			} break;
		
		default:break;
	}

	// determine clip point for p2
	switch(p2_code){
		case CLIP_CODE_C: break;

		case CLIP_CODE_N:
			{
				y2Clipped = maxClipY;
				x2Clipped = x2 + (maxClipY-y2)*(x1-x2)/(y1-y2);
			} break;
		
		case CLIP_CODE_S:
			{
				y2Clipped = minClipY;
				x2Clipped = x2 + (minClipY-y2)*(x1-x2)/(y1-y2);
			} break;
		
		case CLIP_CODE_W:
			{
				x2Clipped = minClipX;
				y2Clipped = y2 + (minClipX-x2)*(y1-y2)/(x1-x2);
			} break;
		
		case CLIP_CODE_E:
			{
				x2Clipped = maxClipX;
				y2Clipped = y2 + (maxClipX-x2)*(y1-y2)/(x1-x2);
			} break;
			
		// these cases are more complex, must compute 2 intersections
		case CLIP_CODE_NE:
			{
				// north hline intersection
				y2Clipped = maxClipY;
				x2Clipped = x2 + 0.5 + 
				  (maxClipY-y2)*(x1-x2)/(y1-y2);
				
				// test if intersection is valid
				if (x2Clipped < minClipX || x2Clipped > maxClipX){
					// east vline intersection
					x2Clipped = maxClipX;
					y2Clipped = y2 + 0.5 + 
					  (maxClipX-x2)*(y1-y2)/(x1-x2);
				}
			} break;
		
		case CLIP_CODE_SE:
			{
				// south hline intersection
				y2Clipped = minClipY;
				x2Clipped = x2 + 0.5 + 
				  (minClipY-y2)*(x1-x2)/(y1-y2);
				
				// test if intersection is valid
				if (x2Clipped < minClipX || x2Clipped > maxClipX){
					// east vline intersection
					x2Clipped = maxClipX;
					y2Clipped = y2 + 0.5 + 
					  (maxClipX-x2)*(y1-y2)/(x1-x2);
				}
			} break;
		
		case CLIP_CODE_NW:
			{
				// north hline intersection
				y2Clipped = maxClipY;
				x2Clipped = x2 + 0.5 + 
				  (maxClipY-y2)*(x1-x2)/(y1-y2);
				
				// test if intersection is valid
				if (x2Clipped < minClipX || x2Clipped > maxClipX){
					x2Clipped = minClipX;
					y2Clipped = y2 + 0.5 + 
					  (minClipX-x2)*(y1-y2)/(x1-x2);
				}
			} break;
		
		case CLIP_CODE_SW:
			{
				// south hline intersection
				y2Clipped = minClipY;
				x2Clipped = x2 + 0.5 + 
				  (minClipY-y2)*(x1-x2)/(y1-y2);
				
				// test if intersection is valid
				if (x2Clipped < minClipX || x2Clipped > maxClipX)
				{
					x2Clipped = minClipX;
					y2Clipped = y2 + 0.5 + 
					  (minClipX-x2)*(y1-y2)/(x1-x2);
				}
			} break;
		
		default:break;
	}

	// do bounds check
	if ((x1Clipped < minClipX) || (x1Clipped > maxClipX) ||
		(y1Clipped < minClipY) || (y1Clipped > maxClipY) ||
		(x2Clipped < minClipX) || (x2Clipped > maxClipX) ||
		(y2Clipped < minClipY) || (y2Clipped > maxClipY) ){
			return(0);
	} 

	// update coords
	x1 = x1Clipped;
	y1 = y1Clipped;
	x2 = x2Clipped;
	y2 = y2Clipped;

	return(1);
}

Wireframe polygons

Wireframe polygons are polygons that are not filled, or are hollowed. Polygons consist of three or more points (vertices) each joined by an edge, and are always closed. Polygons can be concave (there exists a connecting line between two edges where the line falls outside the polygon) and convex (in short, are not concave).

Polygons will not always have a fixed point count, so the data structure that stores polygons will utilise the heap to a degree. Each vertex can be represented by a structure:

typedef struct VERTEX2DI_TYP {
	int x, y;
} VERTEX2DI, *VERTEX2DI_PTR;

Each vertex is stored in a array of type VERTEX2DI_TYP, in another structure:

typedef struct POLYGON2DI_TYP {
	int state;
	int numVerts;
	int x0, y0;
	int xv, yv;
	DWORD colour;
	VERTEX2DI *vList;
} POLYGON2DI, *POLYGON2DI_PTR;

The naming convention 2DI emphasises int (x, y). This is fine for now but will be updated to support float (x, y) as 2DF, to maintain some level of accuracy during transformations (demonstrated later).

The order in which each vertex is initialised clearly matters, since the action to draw a polygon will follow the sequence in the array and define the shape. In this article, it can be seen that vertices are listed in a clockwise manner.

To initialise e.g. a triangle:

POLYGON2DI triangle;

triangle.state = 1; // e.g. enabled/viewable
triangle.numVerts = 3;
triangle.x0 = 100;
triangle.y0 = 100;
triangle.xv = 0; // initial velocity
triangle.yv = 0;
triangle.colour = 50; // assuming 8-bit, colour index 50
triangle.vList = new VERTEX2DI[triangle.numVerts];

The central point (x0, y0) tends to be used to translate the polygon en masse, preserving the relative position of the vertices. The local coordinates are coordinates relative to the central point and each vertex is normally described as local coordinates. A polygon is transformed via global coordinates (discussed later).

Drawing a polygon is an extension of drawing lines and is given below:

int draw2DIPolygon8Bit(POLYGON2DI_PTR polygon, UCHAR *videoBuffer, int lPitch){
	if (polygon->state){
		int index;
		for (index = 0; index < polygon->numVerts - 1; index++){
			drawClipLine8bit(
				// first endpoint
				polygon->vList[index].x + polygon->x0,
				polygon->vList[index].y + polygon->y0,
				// next endpoint
				polygon->vList[index + 1].x + polygon->x0,
				polygon->vList[index + 1].y + polygon->y0,
				polygon->colour,
				videoBuffer,
				lPitch);
		}

		// close the polygon
		drawClipLine8bit(
				// first endpoint
				polygon->vList[0].x + polygon->x0,
				polygon->vList[0].y + polygon->y0,
				// next endpoint
				polygon->vList[index].x + polygon->x0,
				polygon->vList[index].y + polygon->y0,
				polygon->colour,
				videoBuffer,
				lPitch);

		return(1);
	}

	return(0);
}

Transformations

Translation

A translation is about moving an object from one point to another. The global coordinates assume the origin is at the top-left corner of the viewport. It then follows that the translation by (dx, dy) to give the new global coordinates (xt, yt) is:

\[xt = x + dx; \\ yt = y + dy;\]

A translation to a position to the lower-right would require dx > 0 and dy > 0. Similarly, a translation to the lower-left position would require dx < 0 and dy > 0.

int translatePolygon2D(POLYGON2D_PTR polygon, int dx, int dy){
	if (!polygon){
		return (0);
	}

	polygon->x0 += dx;
	polygon->y0 += dy;

	return(1);
}

Rotation

Rotation is a more involved operation. Taking a standard cartesian coordinate system:

  • Quadrant I - sine(x), cosine(x) and tangent(x) are all positive
  • Quadrant II - sine(x) > 0
  • Quadrant I - tangent(x) > 0
  • Quadrant I - cosine(x) > 0

Some conventions in 2D:

  • rotation occurs about an axis perpendicular to the 2D plane in a anticlockwise motion
  • C and C++ sine and cosine functions work with radians only

Later, we will outline how to map (transform) the standard viewport (with the origin at the top-left) with the four quadrants shown above.

It is also worth noting the following trigonometric identities with C and C++:

  • csc(theta) = 1/sin(theta)
  • sec(theta) = 1/cos(theta)
  • cot(theta) = 1/tan(theta)

Other useful identities include:

\[sin^{2}{\theta} + cos^{2}{\theta} = 1\]

For conversion:

\[sin{\theta} = cos{(\theta - \frac{\pi}{2})}\]

For reflection:

\[sin{\theta} = -sin{\theta}\] \[cos{(-\theta)} = cos{\theta}\]

For addition:

\[sin{(\theta_{1} + \theta_{2})} = sin{\theta_{1}}cos{\theta_{2}} + cos{\theta_{1}}sin{\theta_{2}}\] \[cos{(\theta_{1} + \theta_{2})} = cos{\theta_{1}}cos{\theta_{2}} - sin{\theta_{1}}sin{\theta_{2}}\] \[sin{(\theta_{1} - \theta_{2})} = sin{\theta_{1}}cos{\theta_{2}} - cos{\theta_{1}}sin{\theta_{2}}\] \[cos{(\theta_{1} - \theta_{2})} = cos{\theta_{1}}cos{\theta_{2}} + sin{\theta_{1}}sin{\theta_{2}}\]

Referring to quadrant 1 for the moment, for a circle of radius r, one can characterise the polar coordinates of a point (or vertex) as:

\[x = r cos{\theta} \\ y = r sin{\theta}\]

Pictorially:

If one were to rotate an additional \(\alpha\) radians, then the resultant polar coordinates on the same axes would be:

\[x_{rot} = r cos{(\theta + \alpha)} \\ y_{rot} = r sin{(\theta + \alpha)}\]

It would be reasonable to see that on rotating anticlockwise, one can state \(x_{rot} < x\) and \(y_{rot} > y\). Taking the addition identity, rotating (x, y) by some angle \(\alpha\), then along the abscissa:

\[x_{rot} = r cos{(\theta + \alpha)} \\ x_{rot} = r (cos{\theta}cos{\alpha} - sin{\theta}sin{\alpha}) \\ x_{rot} = xcos{\alpha} - ysin{\alpha}\]

Along the ordinate:

\[y_{rot} = r sin{(\theta + \alpha)} \\ y_{rot} = r (sin{\theta}cos{\alpha} + cos{\theta}sin{\alpha}) \\ y_{rot} = ycos{\alpha} + xsin{\alpha}\]

To conclude:

\[x_{rot} = xcos{\alpha} - ysin{\alpha} \\ y_{rot} = xsin{\alpha} + ycos{\alpha}\]

To reduce demand on the application, one can build a lookup table to convert between degrees and radians during initialisation:

const double PI = 3.1415926535;

float cosLookup[360];
float sinLookup[360];

for (int ang = 0; ang < 360; ang++){
    // convert ang to radians
    float thetaRad = (float)ang*PI/(float)180;

    // insert next entry into table
    cosLookup[ang] = cos(thetaRad);
    sinLookup[ang] = sin(thetaRad);
}

Thus, looking up e.g. cosLookup[5] is equivalent to finding the \(cos{(5)}\), for some angle 5 degrees.

Given that there would be a loss of accuracy when determining new coordinates (x, y) for small rotations, the above vertex list should be defined as a float (x, y) version, as:

typedef struct VERTEX2DF_TYP {
	int x, y;
} VERTEX2DF, *VERTEX2DF_PTR;

Each vertex is stored in a array of type VERTEX2DF_TYP (F for float), in another structure:

typedef struct POLYGON2DF_TYP {
	int state;
	int numVerts;
	int x0, y0;
	int xv, yv;
	DWORD colour;
	VERTEX2DF *vList;
} POLYGON2DF, *POLYGON2DF_PTR;

The draw and rotation functions would take the form:

int draw2DFPolygon8Bit(POLYGON2DF_PTR polygon, UCHAR *videoBuffer, int lPitch){
	if (polygon->state){
		int index;
		for (index = 0; index < polygon->numVerts - 1; index++){
			drawClipLine8bit(
				// first endpoint
				polygon->vList[index].x + polygon->x0,
				polygon->vList[index].y + polygon->y0,
				// next endpoint
				polygon->vList[index + 1].x + polygon->x0,
				polygon->vList[index + 1].y + polygon->y0,
				polygon->colour,
				videoBuffer,
				lPitch);
		}

		// close the polygon
		drawClipLine8bit(
				// first endpoint
				polygon->vList[0].x + polygon->x0,
				polygon->vList[0].y + polygon->y0,
				// next endpoint
				polygon->vList[index].x + polygon->x0,
				polygon->vList[index].y + polygon->y0,
				polygon->colour,
				videoBuffer,
				lPitch);

		return(1);
	}

	return(0);
}

int rotatePolygon2D(POLYGON2DF_PTR poly, int thetaDeg){
	if (!poly)
		return(0);

	for (int currVert = 0; currVert < poly->numVerts; currVert++){
		
		float xr = 
			(float) poly->vList[currVert].x * cosLookup[thetaDeg] - 
				(float) poly->vList[currVert].y * sinLookup[thetaDeg];

		float yr = 
			(float)poly->vList[currVert].x * sinLookup[thetaDeg] + 
				(float)poly->vList[currVert].y * cosLookup[thetaDeg];

		poly->vList[currVert].x = xr;
		poly->vList[currVert].y = yr;
	}

	// return success
	return(1);
}

Generally, one should rotate the central point (about an axis) of a polygon and then refer to the local coordinates when rendering the new position of the polygon. Otherwise, with multiple rotations and loss of accuracy, it’s possible to distort the original shape of the polygon.

Scaling

Scaling involves recalculating the local coordinates according to some scaling factor, without changing the central coordinate.

The following scales polygons with float coordinates:

int scalePolygon2DF(POLYGON2DF_PTR polygon, float sx, float sy){
	// validate
	if (!polygon || sx <= 0 || sy <= 0)
	   return(0);

	// loop and scale each point
	for (int curr_vert = 0; curr_vert < polygon->numVerts; curr_vert++){
		// scale and store result back
		polygon->vList[curr_vert].x *= sx;
		polygon->vList[curr_vert].y *= sy;
	}

	// return success
	return(1);
}

The following scales polygons with int coordinates:

int scalePolygon2DI(POLYGON2DI_PTR polygon, float sx, float sy){
	// validate
	if (!polygon || sx <= 0 || sy <= 0)
	   return(0);

	// loop and scale each point
	for (int curr_vert = 0; curr_vert < polygon->numVerts; curr_vert++){
		// scale and store result back
		polygon->vList[curr_vert].x *= sx;
		polygon->vList[curr_vert].y *= sy;
	}

	// return success
	return(1);
}

Review of matrices

In practice, transformations are carried out with matrices. Before proceeding, we review matrix properties and operations.

Properties

Matrices have dimensions mxn, where m is the number of rows and n is the number of columns. They express multiple linear equations.

An identity matrix I is a square matrix in which all elements along the diagonal have the value 1. A zero matrix 0 is a square matrix where all elements have the value zero.

Operations

The addition of matrices (or rather the sum of an element from one matrix and the corresponding element in another matrix) can only be performed between matrices of the same dimension.

Multiplication of a scalar quantity with a matrix involves all elements, for example:

3 A = \(3\begin{bmatrix} a1 & b1 \\ a2 & b2 \end{bmatrix} = \begin{bmatrix} 3a1 & 3b1 \\ 3a2 & 3b2 \end{bmatrix}\)

Multiplication between two matrices was demonstrated previously. The operation is non-commutative (with exception to identity matrices, zero matrices or two identical matrices) and always yields another matrix. It involves multiplying the elements of a row from the first matrix with the elements of a column from the second matrix.

This also means that multiplication between matrices A and B if both matrices have the same inner dimensions: A has dimensions pxn and B has dimensions nxq, where p, n and q are integers. It is not necessary for p to equal p or for either matrix to be square.

Continuing, matrix multiplication involves calculating the sum of the products of each required element (i.e. the dot product), to eventually yield a matrix of dot products (scalars).

Ax = \(\begin{bmatrix} a & b \\ c & d \end{bmatrix} \begin{bmatrix} x \\ y \end{bmatrix} = \begin{bmatrix} ax + by \\ cx + dy \end{bmatrix}\)

The above product has the dimensions 2x1, or following the above example, more generally: pxq.

Implementing matrix multiplication

To multiply two matrices, we can first define a structure for a 3x3 matrix (quite common to express three unknowns in 3D):

typedef struct MATRIX3X3_TYP{
	float M[3][3];
} MATRIX3X3, *MATRIX3X3_PTR;

A 3x3 matrix can be initialised with:

int matrixInit3X3(MATRIX3X3_PTR ma,
				  float m00, float m01, float m02,
				  float m10, float m11, float m12,
				  float m20, float m21, float m22){

	ma->M[0][0] = m00; ma->M[0][1] = m01; ma->M[0][2] = m02; 
	ma->M[1][0] = m10; ma->M[1][1] = m11; ma->M[1][2] = m12; 
	ma->M[2][0] = m20; ma->M[2][1] = m21; ma->M[2][2] = m22; 

	// return success
	return(1);
}

One can then define a function for the multiplication of two 3x3 matrices as:

int multiplyMatrix(MATRIX3X3_PTR matrixA, MATRIX3X3_PTR matrixB, MATRIX3X3_PTR matrixProduct){
  for (int row = 0; row < 3; row++){
    for (int col = 0; col < 3; col++){
      // compute the dot product
	  float sum = 0;

	  for (int index = 0; index < 3; index++){
		if (matrixA->M[row][index] != 0 || matrixB->M[index][col] != 0){
		  sum += matrixA->M[row][index] * matrixB->M[index][col];
		}
	  }

	  matrixProduct->M[row][col] = sum;
    }
  }

  return(1);
}

Transformations with matrices

In short, the coordinates are expressed as a matrix and then transformed by multiplying the matrix with another. Each operation (rotation, scaling and translation) are characterised by a specific transformation matrix.

In 2D, a point is expressed as a row matrix (or row vector) as [x, y, 1], where the value 1 is used as a scaling factor. The scaling factor also renders the matrix with homogeneous coordinates, allowing the row matrix to be transformed by other 3xm transformation matrices, and will be important when expressing 3D constructs (later).

One can slightly modify the aforementioned structure and multiplication function for a 1x3 matrix to handle transformations with matrices:

typedef struct MATRIX1X3_TYP{
	float M[3];
} MATRIX1X3, *MATRIX1X3_PTR;

The multiplication of the 1x3 coordinate matrix with a 3x3 transformation matrix (again, note the order matters) would yield a product matrix with dimensions 1x3 with:

int matrixMultiply1X3_3X3(MATRIX1X3_PTR ma, MATRIX3X3_PTR mb, MATRIX1X3_PTR mprod){
    for (int col = 0; col < 3; col++){
        // compute dot product from row of ma 
        // and column of mb

        float sum = 0;

        for (int row = 0; row < 3; row++){
			// add in next product pair
			sum += (ma->M[row] * mb->M[row][col]);
		}

        mprod->M[col] = sum;
	}
	
	return(1);
}

Translation

To translate a polygon, we need to adjust the central coordinates by some delta:

\[xt = x + dx \\ yt = y + dy\]

With the central coordinates c expressed as a row matrix:

\[\mathbf{c} = \begin{bmatrix} x & y & 1 \end{bmatrix}\]

then the transformation matrix M required would be:

\[\mathbf{M} = \begin{bmatrix} 1 & 0 & 0 \\ 0 & 1 & 0 \\ dx & dy & 1 \end{bmatrix}\]

Then the product (the transformation) would be:

\[\begin{align*} \mathbf{c'} &= \mathbf{cM} \\ &= \begin{bmatrix} x & y & 1 \end{bmatrix} \begin{bmatrix} 1 & 0 & 0 \\ 0 & 1 & 0 \\ dx & dy & 1 \end{bmatrix} \\ &= \begin{bmatrix} x + dx & y + dy & 1 \end{bmatrix} \end{align*}\]

The C++ function to translate a polygon (assumed float based) with matrices could be handled by:

int translatePolygon2DFM(POLYGON2DF_PTR polygon, int dx, int dy){
	if (!polygon)
	   return(0);

	MATRIX3X3 mt; // used to hold translation transform matrix

	// initialize the translation matrix
	matrixInit3X3(&mt,1,0,0, 0,1,0, dx,dy,1); 

	// create a 1x3 matrix to do the transform
	MATRIX1X3 p0 = {polygon->x0, polygon->y0, 0};
	MATRIX1X3 pTemp = {0,0,0};

	// now translate via a matrix multiply
	matrixMultiply1X3_3X3(&p0, &mt, &pTemp);

	// now copy the result back into polygon
	polygon->x0 = pTemp.M[0];
	polygon->y0 = pTemp.M[1];

	// return success
	return(1);
}

The integer based polygon would essentially be the same.

Scaling

We scale each local coorindate so that we get:

\[x_{s} = x(sx) \\ y_{s} = y(sy)\]

The transformation matrix M required would be:

\[\mathbf{M} = \begin{bmatrix} sx & 0 & 0 \\ 0 & sy & 0 \\ 0 & 0 & 1 \end{bmatrix}\]

Then the product (the transformation) would be:

\[\begin{align*} \mathbf{p'} &= \mathbf{pM} \\ &= \begin{bmatrix} x & y & 1 \end{bmatrix} \begin{bmatrix} sx & 0 & 0 \\ 0 & sy & 0 \\ 0 & 0 & 1 \end{bmatrix} \\ &= \begin{bmatrix} x(sx) & y(sy) & 1 \end{bmatrix} \end{align*}\]

The C++ function to scale a polygon (assumed float based) with matrices could be handled by:

int scalePolygon2DFM(POLYGON2DF_PTR polygon, float sx, float sy){
	if (!polygon || sx <=0 || sy <= 0)
	   return(0);

	MATRIX3X3 ms; // used to hold scaling transform matrix

	matrixInit3X3(&ms,sx,0,0, 
					  0,sy,0, 
					  0,0,1); 

	for (int curr_vert = 0; curr_vert < polygon->numVerts; curr_vert++){
		MATRIX1X3 p0 = {polygon->vList[curr_vert].x, polygon->vList[curr_vert].y, 0};
		MATRIX1X3 pTemp = {0,0,0};

		// now scale via a matrix multiply
		matrixMultiply1X3_3X3(&p0, &ms, &pTemp);

		// now copy the result back into vertex
		polygon->vList[curr_vert].x = pTemp.M[0];
		polygon->vList[curr_vert].y = pTemp.M[1];
	}

	// return success
	return(1);
}

Rotation

In this case, we need to adjust each local coordinate about a fixed central coordinate (no translation) as:

\[x_{rot} = xcos{\alpha} - ysin{\alpha} \\ y_{rot} = xsin{\alpha} + ycos{\alpha}\]

With the same local coordinate p, the transformation matrix M required would, when multiplied, yield the required result:

\[\begin{align*} \mathbf{p'} &= \mathbf{pM} \\ &= \begin{bmatrix} x & y & 1 \end{bmatrix} \begin{bmatrix} cos{\alpha} & sin{\alpha} & 0\\ -sin{\alpha} & cos{\alpha} & 0 \\ 0 & 0 & 1 \end{bmatrix} \\ &= \begin{bmatrix} xcos{\alpha} - ysin{\alpha} & xsin{\alpha} + ycos{\alpha} & 1 \end{bmatrix} \end{align*}\]

The C++ function to rotate a polygon (assumed float based) about the centre coordinate with matrices could be handled by:

int rotatePolygon2DFM(POLYGON2DF_PTR polygon, int thetaDeg){
	if (!polygon)
	   return(0);

	// test for negative rotation angle
	if (thetaDeg < 0)
	   thetaDeg += 360;

	MATRIX3X3 mr; // used to hold rotation transform matrix

	matrixInit3X3(&mr, cosLookup[thetaDeg],sinLookup[thetaDeg],0,
					 -sinLookup[thetaDeg],cosLookup[thetaDeg],0, 
					  0,0,1); 

	for (int curr_vert = 0; curr_vert < polygon->numVerts; curr_vert++){
		MATRIX1X3 p0 = {polygon->vList[curr_vert].x, polygon->vList[curr_vert].y, 0};
		MATRIX1X3 pTemp;

		// now rotate via the rotation matrix mr
		matrixMultiply1X3_3X3(&p0, &mr, &pTemp);

		// now copy the result back into vertex
		polygon->vList[curr_vert].x = pTemp.M[0];
		polygon->vList[curr_vert].y = pTemp.M[1];
	}

	// return success
	return(1);
}

Solid filled polygons

To render filled polygons, one must draw each edge and then raster (or scan) each row within the polygon, filling in the area.

This discussion will be limited to:

  • polygons (any number of sides) that are convex, i.e. no line segment exists in space that joins two points within the polygon that also crosses an area outside the polygon
  • polygons that do not have any edges that cross other edges (is a simple polygon)

Triangles

There are four types of triangles to cover:

  • flat top: where the top two vertices have the same y-coordinate
  • flat bottom: where the bottom two vertices have the same y-coordinate
  • right side major: where all vertices have different y-coordinates, with the longest edge on the right-hand side
  • left side major: where all vertices have different y-coordinates, with the longest edge on the left-hand side

As will be outlined shortly, quadrilaterals and other polygons with at least four sides can be broken down into triangles (a process referred to as triangular deconstruction).

In general, a simple way to drawing triangles is to break down triangles and all other polygons into flat top or flat bottom triangles. This is because filling in flat top or flat bottom triangles is simpler, and only involves drawing lines within the triangle from the top or bottom, without being concerned about slopes:

  1. Compute the inverse of the gradient for each side of the flat top or flat bottom triangle, as dx/dy. The change in x for each y allows one to determine the width of the scanline.
  2. Start at the vertex with its own y-coordinate (i.e. opposite flat top or flat bottom edge) and set some initial conditions xleft, xright and y.
  3. Add the inverted gradient dx/dy of each side to xleft and xright accordingly. This will set a trace between each edge.
  4. Draw the line.
  5. Repeat steps 3 and 4 until the full height of the triangle has been rasterised.

The mathematical derivation is based on Cartesin coordinate systems. Going further, a gradient can be used to determine the new value of x for a change to one pixel in y.

\[\begin{align*} m &= \frac{y_{k} - y_{k-1}}{x_{k} - x_{k-1}} \end{align*}\]

The coordinates \((x_{k}, y_{k})\) are on a scan line above \((x_{k-1}, y_{k-1})\).

If we apply an iterative loop and scan downwards, we have:

\[y_{k-1} - y_{k} = 1\]

Then solving for the value of \(x_{k}\) at a lower scan line:

\[\begin{align*} \frac{1}{m} &= x_{k-1} - x_{k} \\ x_{k-1} &= x_{k} + \frac{1}{m} \end{align*}\]

Computing the inverse of the gradient for both left and right-hand edges yields the scan line coordinates.

As an aside, for a flat top triangle for which scan lines go upwards, then

\[\begin{align*} m &= \frac{y_{k+1} - y_{k}}{x_{k+1} - x_{k}} \end{align*}\]

With a change of scan line as:

\[y_{k+1} - y_{k} = 1\]

Then finally:

\[\begin{align*} \frac{1}{m} &= x_{k+1} - x_{k} \\ x_{k+1} &= x_{k} + \frac{1}{m} \end{align*}\]

Assuming we are working with flat bottom triangles for now (i.e. triangular deconstruction is not required), then a suitable method would be:

// inverted gradient for the left side
float dxy_left = (x2 - x0)/(y2 - y0);

// inverted gradient for the right side
float dxy_right = (x2 - x1)/(y2 - y1);

float x_left = x0;
float x_right = x1;

// note the upper vertex and lower edge are not drawn
for (int y = y0; y <= y2; y++){
  // assume colour is initialised/known
  drawLine((int) (x_left + 0.5), (int) (x_right + 0.5), y, colour);

  x_left += dxy_left;
  x_right += dxy_right;
}

Triangular deconstruction

Breaking down a triangle into independent flat top or flat bottom triangles requires some thought. Overall, the approach is to determine the height of the short side of the triangle, and then trace a horizontal line across to the long edge. The triangle above would represent the flat bottom triangle and the triangle below would represent the flat top triangle.

Some points to consider re. the algorithm:

  • Avoid overdrawing the edges where both triangles intersect
  • Clip the image (that is the image space) during triangle deconstruction
  • Avoid drawing single points (lone upper or lower vertices, and all horizontal straight edges)
  • Set up an ordering (convention) of the deconstructed triangles so that one can select/identify each (resultant) triangle from a list of triangles. We will follow the convention top to bottom, left to right.

The triangle deconstruction function is supported by flat top triangle and flat bottom triangle drawing functions. The polygon coordinates are provided in an anticlockwise manner.

To draw a flat top triangle (with vertex (xb, yb) opposite the flat top):

void drawFlatTopTriangle(
	int xleft, int yleft, int xright, int yright, int xb, int yb,
	int colour, UCHAR *dest_buffer, int mempitch){

	float dx_right,    // the dx/dy ratio of the right edge of line
		  dx_left,     // the dx/dy ratio of the left edge of line
		  xStart, xEnd,    
		  height;

	int temp_x,        // used during sorting as temps
		temp_y,
		right,         // used by clipping
		left;

	// destination address of next scanline
	UCHAR *dest_addr = NULL;

	// test order of xleft and xright
	if (xright < xleft){
		temp_x = xright;
		xright = xleft;
		xleft = temp_x;
	}

	// compute delta's
	height = yb - yleft;

	dx_left  = (xb - xleft) / height;
	dx_right = (xb - xright) / height;

	// set starting points
	xStart = (float) xleft;
	xEnd = (float) xright + (float) 0.5;

	// perform y clipping
	if (yleft < minClipY){
	   xStart += dx_left*(float)(-yleft + minClipY);
	   xEnd += dx_right*(float)(-yleft + minClipY);

	   // reset yleft
	   yleft = minClipY;
	}

	if (yb > maxClipY)
	   yb = maxClipY;

	// compute starting address in video memory
	dest_addr = dest_buffer + yleft*mempitch;

	// test if x clipping is needed
	if (xleft >= minClipX && xleft <= maxClipX &&
		xright >= minClipX && xright <= maxClipX &&
		xb >= minClipX && xb <= maxClipX){
			
			for (temp_y = yleft; temp_y <= yb; temp_y++, dest_addr += mempitch){
				memset((UCHAR *)dest_addr + (unsigned int)xStart,
					colour, (unsigned int)(xEnd - xStart + 1));

				// adjust starting point and ending point
				xStart += dx_left;
				xEnd += dx_right;
			}

		} else {
			// clip x axis with slower version
			
			for (temp_y = yleft; temp_y <= yb; temp_y++, dest_addr += mempitch){
				// do x clip
				left  = (int)xStart;
				right = (int)xEnd;
				
				// adjust starting point and ending point
				xStart += dx_left;
				xEnd += dx_right;
				
				// clip line
				if (left < minClipX){
					left = minClipX;

					if (right < minClipX)
						continue;
				}

				if (right > maxClipX){
					right = maxClipX;
					
					if (left > maxClipX)
						continue;
				}
				
				memset((UCHAR *) dest_addr + (unsigned int)left,
					colour, (unsigned int)(right - left + 1));
			}
	}
}

To draw a flat bottom triangle (with vertex (xt, yt) opposite the flat bottom):

void drawFlatBottomTriangle(
	int xt, int yt, int xleft, int yleft, int xright, int yright, 
	int colour, UCHAR *dest_buffer, int mempitch){

	float dx_right,    // the dx/dy ratio of the right edge of line
		dx_left,     // the dx/dy ratio of the left edge of line
		xStart, xEnd,
		height;

	int temp_x,        // used during sorting as temps
		temp_y,
		right,         // used by clipping
		left;

	// destination address of next scanline
	UCHAR *dest_addr;

	// test order of xleft and xright
	if (xright < xleft){
		temp_x = xleft;
		xleft     = xright;
		xright     = temp_x;
	}

	// compute delta's
	height = yright - yt;

	dx_left  = (xleft - xt) / height;
	dx_right = (xright - xt) / height;

	// set starting points
	xStart = (float) xt;
	xEnd = (float) xt; // +(float)0.5;

	// perform y clipping
	if (yt < minClipY){
		xStart += dx_left * (float)(-yt + minClipY);
		xEnd += dx_right * (float)(-yt + minClipY);

		// reset yt
		yt = minClipY;
	}

	if (yright > maxClipY)
		yright = maxClipY;

	// compute starting address in video memory
	dest_addr = dest_buffer + yt*mempitch;

	// test if x clipping is needed
	if (xt >= minClipX && xt <= maxClipX &&
		xleft >= minClipX && xleft <= maxClipX &&
		xright >= minClipX && xright <= maxClipX){
			
			for (temp_y = yt; temp_y <= yright; temp_y++, dest_addr += mempitch){
				memset((UCHAR  *)dest_addr + (unsigned int)xStart,
					colour,(unsigned int)(xEnd - xStart + 1));

				// adjust starting point and ending point
				xStart += dx_left;
				xEnd += dx_right;
			}

	} else {
		// clip x axis with slower version

		for (temp_y = yt; temp_y <= yright; temp_y++, dest_addr += mempitch){
			// do x clip
			left  = (int)xStart;
			right = (int)xEnd;

			// adjust starting point and ending point
			xStart += dx_left;
			xEnd += dx_right;

			// clip line
			if (left < minClipX){
				left = minClipX;

				if (right < minClipX)
					continue;
			}

			if (right > maxClipX){
				right = maxClipX;

				if (left > maxClipX)
					continue;
			}
			
			memset((UCHAR *)dest_addr + (unsigned int)left,
				colour,(unsigned int)(right - left + 1));
		}
	}
}

Finally, to draw a triangle, with potential to deconstruct and build triangles with above helper methods:

void drawTriangle2DI(
	int x1, int y1, int x2, int y2, int x3, int y3,
	int colour, UCHAR *dest_buffer, int mempitch){

	int temp_x, // used for sorting
		temp_y,
		new_x;

	// test for h lines and v lines
	if ((x1 == x2 && x2 == x3)  ||  (y1 == y2 && y2 == y3))
		return;

	// sort p1, p2, p3 in ascending y order
	if (y2 < y1){
		temp_x = x2;
		temp_y = y2;
		x2     = x1;
		y2     = y1;
		x1     = temp_x;
		y1     = temp_y;
	}

	// now we know that p1 and p2 are in order
	if (y3 < y1){
		temp_x = x3;
		temp_y = y3;
		x3     = x1;
		y3     = y1;
		x1     = temp_x;
		y1     = temp_y;
	}

	// finally test y3 against y2
	if (y3 < y2){
		temp_x = x3;
		temp_y = y3;
		x3     = x2;
		y3     = y2;
		x2     = temp_x;
		y2     = temp_y;

	}

	// do trivial rejection tests for clipping
	if ( y3 < minClipY || y1 > maxClipY ||
		(x1 < minClipX && x2 < minClipX && x3 < minClipX) ||
		(x1 > maxClipX && x2 > maxClipX && x3 > maxClipX) )
		return;

	if (y1 == y2){

		// this means (x3, y3) are the lower vertex;
		// coords: (xleft, yleft), (xright, yright), (xb, yb)
		drawFlatTopTriangle(x1, y1, x2, y2, x3, y3, colour, dest_buffer, mempitch);

	} else if (y2 == y3){

		// this means (x1, y1) are the top vertex;
		// coords: (xt, yt), (xleft, yleft), (xright, yright)
		drawFlatBottomTriangle(x1, y1, x2, y2, x3, y3, colour, dest_buffer, mempitch);

	} else {
		// general triangle that's needs to be broken up along long edge
		new_x = x1 + (int)(0.5+(float)(y2 - y1) * (float)(x3 - x1)/(float)(y3 - y1));

		// coords: (xt, yt), (xleft, yleft), (xright, yright)
		drawFlatBottomTriangle(x1, y1, new_x, y2, x2, y2, colour, dest_buffer, mempitch);

		// coords: (xleft, yleft), (xright, yright), (xb, yb)
		drawFlatTopTriangle(x2, y2, new_x, y2, x3, y3, colour, dest_buffer, mempitch);
	}
}

Note, the application of fixed-point arithmetic while more appropriate for much older game engines and CPUs, these days CPUs and GPUs have better support for floating-point arithmetic (as applied above).

Quadrilaterals

Assuming the quadrilateral coordinates are set out in a clockwise manner, one can deconstruct it as two triangles by taking one triangle as vertices 0, 1 and 3, and a second triangle as vertices 1, 2 and 3.

void drawQuad2DI(int x0, int y0, int x1, int y1, int x2, int y2, int x3, int y3, 
				 int colour, UCHAR* destBuffer, int memPitch){

	// this assumes x0 to x3 are given in a clockwise manner
	drawTriangle2DI(x0, y0, x1, y1, x3, y3, colour, destBuffer, memPitch);
	drawTriangle2DI(x1, y1, x2, y2, x3, y3, colour, destBuffer, memPitch);
}