Serebyte


Home | Tutorials | Portfolio

Win32 Software Renderer in C: Part 8 - Loading and Drawing a Bitmap


Note: this tutorial series requires significant knowledge of the C programming language


In this tutorial we will look at loading a bitmap from a .bmp file and drawing it to the screen.




The Theory:

Before we can draw a bitmap, we first need to load a bitmap. The bitmap file must be a 24-bit colour depth .bmp file, or else the code and techniques discussed in this tutorial will not work. The one I will be using is the 64x64 px astronaut sprite, called "test.bmp", shown below:



The .bmp File Structure

Before we can hope to load a .bmp from a file, we must first understand the .bmp file structure. Bitmap files are made up of four key parts: the file header, the info header, the colour table and the bitmap data.


The file header of a .bmp file includes file metadata, and is a BITMAPFILEHEADER structure. It is a fixed size, which we can get using "sizeof(BITMAPFILEHEADER)". It contains data such as the size of the file and the file type (although this latter property is always set to an ID indicating that it is a bitmap file).


The info header contains metadata related to the image itself, for example the width and height of the image in pixels. This is a BITMAPINFOHEADER structure, which is the same type of structure as renderBuffer.infoHeader.bmiHeader from earlier on in the series, when we were first setting up our render buffer.


The colour table is not important for us, as we are working with 24-bit bitmaps. 24-bit bitmaps do not have a colour table, as they can have three bytes to use for RGB values. Colour tables are mostly used for 8-bit and 16-bit images. Since there will not be one in our file, we do not have to worry about it (unless you intend to support different types of bitmaps).


The pixel data is stored as an array of pixels. Each pixel is stored as a blue byte, followed by a green byte and then a red byte. Since we have set our buffer up to store data in this format, we use the pixel array data as is, with little modification when drawing our bitmap.




Creating a Bitmap Structure

Before we can load a bitmap, we will need to create our own bitmap structure to store our bitmap data in. It will be made of three properties. The first is a BITMAPFILEHEADER structure called "bitmapFileHeader". The second is a BITMAPINFOHEADER called "bitmapInfoHeader". The third is a pixel pointer called "pixels". This will be used to store our actual pixel array.


We should create our bitmap structure in the main.h file, with the rest of our structures. I will define it as its own type called "Bitmap".




Loading a Bitmap Structure From a .bmp File

We can now create a loadBMPFile function. It should take two arguments, the path file as a string and a pointer to the bitmap structure to fill in. We can do this with the line "int loadBMPFile(char filePath[], Bitmap * bitmap){".


The first thing to do inside our function is to attempt to open the file. We should open the file in read binary mode. I will call the returned file pointer "file". We can do this with the line 'FILE * file = fopen(filePath, "rb");'.


After this, we want to check if the file failed to open. We can check this with the if statement "if(!file){". Inside the if statement, we want to retrn 0.


If our file did open successfully, we want to retrieve the file size. To do this, we should first set the file position indicator to the end of the file using the line "fseek(file, 0, SEEK_END);". We can then retrieve the position of the file position indicator and store it to a variable called "fileSize", using the line "int fileSize = ftell(file);". Then we want to rewind our file position indicator back to the start of the file so we can read the actual data. This can be done with the line "rewind(file);".


Next, we need to check if the file size is too small to be reasonable. We know that the file is at least the size of a BITMAPFILEHEADER and a BITMAPINFOHEADER added together, so we should check if the file size is smaller than sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER). We can do this with the line: "if(fileSize < sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER)){". Inside this if statement, we should close the file (with "fclose(file);") and return 0.


Now we have checked for errors, we can read the file header into our bitmap's fileHeader structure. We can do this using an fread call, like so: "fread(&(bitmap->fileHeader), sizeof(BITMAPFILEHEADER), 1, file);". Here, we are reading 1 structure of sizeof(BITMAPFILEHEADER) bytes from our file, and transferring it into the bitmap's fileHeader structure (by using a pointer to its address).


Next, we need to do the same for the bitmap's info header. We can do this with the line: "fread(&(bitmap->infoHeader), sizeof(BITMAPINFOHEADER), 1, file);".


Now we have read bitmap info header, we can read the width and height of the bitmap from it. We can use this to allocate enough memory for the pixel data. The amount of memory to allocate is equal to the size of a pixel structure * the width of the bitmap * the height of the bitmap. We should allocate this memory and set the "bitmap->pixels" pointer to point to it. This can be done with the line: "bitmap->pixels = (Pixel *) malloc(bitmap->infoHeader.biWidth * bitmap->infoHeader.biHeight * sizeof(Pixel));".


After this, we can read the bitmap pixel data straight into our bitmap->pixels array with another fread call (remember that there is no colour table in the bitmap we are using, so we can move straight onto reading pixel data). This can be done with the line "fread(bitmap->pixels, sizeof(Pixel), bitmap->infoHeader.biWidth * bitmap->infoHeader.biHeight, file);". To finish of our function, we should close our file (using "fclose(file);") and return 1 to indicate success.


That finishes our loadBMPFile function.




Storing Bitmaps

We will store our bitmaps as global variables to make them easy to use (you could use another way if you would rather). I will declare a test bitmap in the main.h file using "Bitmap bmp_test;".


We need to load our bitmaps before we can draw them, so we should create a function to load all our bitmap variables and run it inside the WinMain function, just before we start the main loop. I will name this function loadAllBitmaps. It will be a void function and have no parameters.


I will declare the loadAllBitmaps function in the main.h file, and I will define it just after our loadBMPFile function call in the render.c file. Inside the function, we will load our bitmap file (test.bmp) into our bitmap structure bmp_test. This can be done with the line 'loadBMPFile("test.bmp", &bmp_test);'. This completes our loadBitmaps function for now (we may wish to add other bitmaps later).


Now we need to call our loadAllBitmaps function just before our first mainLoop call.




Drawing Bitmaps

Now we've loaded a bitmap, we need to look at drawing it. We will create a drawBitmap function to do this. It will be avoid function and will have three parameters. The first two should be integers and should be the x and y coordinates of the bottom left corner of the bitmap on the render buffer (I will call these "x" and "y"). The last should be a pointer to our bitmap structure (which I will call "bitmap"). This function will be written in render.c and should be declared in main.h.


Inside our drawBitmap function, we should first create a pixel pointer. This will always point to the pixel we want to render to. We will create our pixel pointer with the line "Pixel * pixel;". We then need to create two loop counters, i and j, which we can create with the following lines: "int i = 0;" and "int j = 0;".


After setting up our variables, we want to loop through each row of our bitmap. We can use the bitmap->infoHeader.biHeight property to get the height of our bitmap. We can loop through all the rows of our bitmap with the following line: "for(i = 0; i < bitmap->infoHeader.biHeight; i++){". At the top of this loop, we want to set the pixel pointer to the start of the row. This can be found by taking the renderBuffer.pixels array and adding ((y + i) * BUFFER_WIDTH + x) to it. (y + i) * BUFFER_WIDTH will take the pointer to the correct y-coordinate, and the "+ x" part moves it along to the correct x coordinate. We can write this in code with the following line: "pixel = renderBuffer.pixels + (y + i) * BUFFER_WIDTH + x;".


Now that our pixel pointer has been set to the correct row, we want to iterate through each pixel on said row. We can do this with the line: "for(j = 0; j < bitmap->infoHeader.biWidth; j++){". Within this loop, we need to check that the pixel we are trying to render is actually on screen, which can be done with the line "if(j >= 0 && j < BUFFER_WIDTH && y + i >= 0 && y + i < BUFFER_HEIGHT){".


If the current pixel is on screen, we want to retrieve the correct pixel from the source bitmap and draw it. We can retrieve the correct pixel by finding the pixel at bitmap->pixels + i * bitmap->infoHeader.biWidth + j. We can store this to a pixel pointer, which I will call srcPixel, with the line: "Pixel * srcPixel = bitmap->pixels + i * bitmap->infoHeader.biWidth + j;".


The next step is optional, but is something I find helpful. You may wish to set one specific colour to be a transparent colour. This means that when we come across a pixel of said colour in our bitmap image, we do not draw it, and any colours of said pixel are simply ignored. I will implement this, and will use a vibrant pink colour (that I am not using in my bitmap image) as the transparent colour.


Before drawing the pixel, we need to check that the srcPixel is not the transparent colour. How you check this depends on what you want your transparent colour to be, but I am checking for mine with the line: "if(!(srcPixel->red == 163 && srcPixel->green == 73 && srcPixel->blue == 164)){".


If our colour is not transparent, we should draw it to the screen. This can be done by setting the pixel value at our pixel pointer to the srcPixel's set of RGB values. We can do this with the lines "pixel->red = srcPixel->red;", "pixel->green = srcPixel->green;" and "pixel->blue = srcPixel->blue;".


Before we close off our horizontal loop (our j loop), we want to increment our pixel pointer to the next one along using the line "pixel++;".


This completes our drawBitmap function. Now we just have to call it in our render function. I will call it using the following line: "drawBitmap(100, 100, &bmp_test);", but you can, of course, change the arguments inputted.




The Code:

Below is the code for all three of our files. I am using the MinGW compiler and will compile it with the command "gcc main.c -lgdi32 -o app", but you can use another compiler, so long as you are able to link the gdi32 library.


main.h

/*
 Software Renderer in C - Part 8

 main.h

 This header file groups all our headers, structure declaration, global variables and function declarations into one file.
*/


//include headers
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <math.h>

//define window size constants
#define BUFFER_WIDTH 640
#define BUFFER_HEIGHT 480

//create pixel structure
//this is a 24-bit structure that stores a red, green and blue byte
typedef struct Pixel {
 uint8_t blue;
 uint8_t green;
 uint8_t red;
} Pixel;

//define render buffer structure
typedef struct RenderBuffer {
 HWND windowHandle; //handle to the window that the buffer belongs to
 HDC deviceContextHandle; //handle to device context (a device context is an area of memory stored by the OS that will be rendered directly to the window client area)
 Pixel * pixels; //pixel buffer to render to the screen
 BITMAPINFO bitmapInfo; //a bitmap info structure that stores necessary metadata for our renderBuffer (required to draw our data to the screen)
 int scale;
 int windowClientWidth;
 int windowClientHeight;
} RenderBuffer;

//bitmap structure
typedef struct Bitmap {
 BITMAPFILEHEADER fileHeader;
 BITMAPINFOHEADER infoHeader;
 Pixel * pixels;
} Bitmap;

//create global variables
int running = 1; //1 when program is running, 0 when program is closed
RenderBuffer renderBuffer; //our global render buffer

//create bitmaps
Bitmap bmp_test;

//main loop function
void mainLoop();

//handle events function
void handleEvents();

//declare render functions
void drawRectangle(int startX, int startY, int endX, int endY, uint8_t red, uint8_t green, uint8_t blue);
void drawLine(int startX, int startY, int endX, int endY, uint8_t red, uint8_t green, uint8_t blue);
void drawRow(int x1, int x2, int y, uint8_t red, uint8_t green, uint8_t blue);
void drawTriangle(int x1, int y1, int x2, int y2, int x3, int y3, uint8_t red, uint8_t green, uint8_t blue);
void drawCircle(int centreX, int centreY, int radius, uint8_t red, uint8_t green, uint8_t blue);
int loadBMPFile(char filePath[], Bitmap * bitmap);
void loadAllBitmaps();
void drawBitmap(int x, int y, Bitmap * bitmap);
void render();

//declare window procedure (event handler) function
LRESULT CALLBACK windowProcedure(HWND windowHandle, UINT messageID, WPARAM wParam, LPARAM lParam);

render.c

/*
 render.c

 This file contains all of the code used for rendering shapes, sprites, etc.

 This file is included into main.c directly, so we can still use global variables.
*/


//draw rectangle
void drawRectangle(int startX, int startY, int endX, int endY, uint8_t red, uint8_t green, uint8_t blue){
/*
  drawRectangle
  
  This function draws a rectangle to the render buffer.
  It takes seven parameters:
   -The x coordinate of the bottom left corner
   -The y coordinate of the bottom left corner
   -The x coordinate of the top right corner
   -The y coordinate of the top right corner
   -The red value of the pixel
   -The green value of the pixel
   -The blue value of the pixel
 */


//create pixel pointer
 Pixel * pixel;

//iterate from startY to endY (iterate through each row)
 int i = 0;
 int j = 0;

 for(i = startY; i <= endY; i++){
  /*
   The bottom left corner of the render buffer is (0,0).
   We need to set the pixel pointer to left side of rectangle on row i so that we
   can begin rendering the new row.
   Therefore, we want set the pixel pointer to renderBuffer.pixels + i * BUFFER_WIDTH + startX.
   renderBuffer.pixels marks the start of the buffer. We want to add a row (of width BUFFER_WIDTH) to our
   pixel pointer until we get to the row we want to draw on. Therefore, we want to move i rows
   up. We then add startX to move the pixel pointer to the left side of the rectangle on that row.
  */


  //set pixel pointer to left side of rectangle on current row
  pixel = renderBuffer.pixels + i * BUFFER_WIDTH + startX;
  
  //iterate from startX to endX and draw pixels on row
  for(j = startX; j <= endX; j++){
   //check if pixel is on screen 
   if(i >= 0 && i < BUFFER_HEIGHT && j >= 0 && j < BUFFER_WIDTH){
    //render pixel by setting red, green and blue values
    pixel->red = red;
    pixel->blue = blue;
    pixel->green = green;
   };
   
   //increment pixel
   pixel++;
  };
 };
};

//draw line
void drawLine(int startX, int startY, int endX, int endY, uint8_t red, uint8_t green, uint8_t blue){
//calculate changes in x and y
 int dx = endX - startX;
 int dy = endY - startY;

//individual steps for x and y
 float xStep;
 float yStep;
 int totalSteps = 0;

//check if dy > dx
 if(abs(dy) > abs(dx)){
  /*
  The total number of steps is equal to the total increase in y, as we are increasing y by 1 (or -1 if dy < 0) each time.
  We are increasing y by 1 (or -1 if dy < 0) because it dy is larger than dx in terms of magnitude, so we must choose to increment y
  to avoid skipping pixels. If we were to increase x by 1, we would get increases of y larger than 1 as dy/dx > 1. This would cause
  some pixels to be left out of our line.
  */

  totalSteps = abs(dy);
 } else {
  /*
  The total number of steps is equal to the total increase in x, as we are increasing x by 1 (or -1 if dx < 0) each time.
  We are increasing x by 1 (or -1 if dx < 0) because it dx is larger than dy in terms of magnitude, so we must choose to increment x
  to avoid skipping pixels. If we were to increase y by 1, we would get increases of x larger than 1 as dx/dy > 1. This would cause
  some pixels to be left out of our line.
  */

  totalSteps = abs(dx);
 };

//absolute value of gradient is steeper than 1, so increase by 1 along the y-axis each step
 yStep = (float) dy / totalSteps; //calculate the change in y per step
 xStep = (float) dx / totalSteps; //the increase in x per unit y (i.e. the amount to increase x by each step)

//create loop counter and set to 0
 int i = 0;

//create x and y values
 float x = startX;
 float y = startY;

//create pixel pointer - this will always point to the pixel to set
 Pixel * pixel;

//iterate for all steps
 for(int i = 0; i <= totalSteps; i++){
  //check that x and y are within bounds
  if(x >= 0 && x < BUFFER_WIDTH && y >= 0 && y < BUFFER_HEIGHT){
   //plot (x,y)
   //first, set pixel pointer to current pixel (equal to renderBuffer.pixels + y * BUFFER_WIDTH + x)
   //Note that we add y * BUFFER_WIDTH, as we are adding y rows of size BUFFER_WIDTH to the start of our pixel pointer to move it to the correct y-value
   pixel = renderBuffer.pixels + ((int) y) * BUFFER_WIDTH + (int) x;
   
   //set pixel colours
   pixel->red = red;
   pixel->green = green;
   pixel->blue = blue;
  };
  
  //increase x and y
  x += xStep;
  y += yStep;
 };
};

//draw row
void drawRow(int x1, int x2, int y, uint8_t red, uint8_t green, uint8_t blue){
//create pixel pointer
 Pixel * pixel;

//create min and max x coordinates
 int minX;
 int maxX;

//check x coordinates
 if(x1 < x2){
  minX = x1;
  maxX = x2;
 } else {
  minX = x2;
  maxX = x1;
 };

//set pixel to start of row
 pixel = renderBuffer.pixels + (BUFFER_WIDTH * y) + minX;

//iterate through all pixels in the row
 int i;
 for(i = minX; i <= maxX; i++){
  //check if on screen
  if(i >= 0 && i < BUFFER_WIDTH && y >= 0 && y < BUFFER_HEIGHT){
   pixel->red = red;
   pixel->green = green;
   pixel->blue = blue;
  };
  
  //increment pixel
  pixel ++;
 };
};

//render triangle
void drawTriangle(int x1, int y1, int x2, int y2, int x3, int y3, uint8_t red, uint8_t green, uint8_t blue){
//create lists of points
 int pointsX[3];
 int pointsY[3];

 pointsX[0] = x1;
 pointsX[1] = x2;
 pointsX[2] = x3;

 pointsY[0] = y1;
 pointsY[1] = y2;
 pointsY[2] = y3;

 int i = 0;

 for(i = 1; i < 3; i++){
  int j = i;
  
  while(j > 0 && pointsY[j - 1] > pointsY[j]){
   //swap
   int temp = pointsY[j];
   pointsY[j] = pointsY[j - 1];
   pointsY[j - 1] = temp;
   
   temp = pointsX[j];
   pointsX[j] = pointsX[j - 1];
   pointsX[j - 1] = temp;
   
   //decrement j
   j -= 1;
  };
 };

//draw first half of triangle
//create x coordinates for lines of triangles
 float lineX1 = pointsX[0];
 float lineX2 = pointsX[0];

//calculate the change in x per unit change in y for the lines 0->1 and 0->2
 float xStep1 = (float) (pointsX[1] - pointsX[0]) / (pointsY[1] - pointsY[0]);
 float xStep2 = (float) (pointsX[2] - pointsX[0]) / (pointsY[2] - pointsY[0]);

//iterate through all rows
 for(i = pointsY[0]; i < pointsY[1]; i++){
  //draw row between x1 and y1
  drawRow((int) lineX1, (int) lineX2, i, red, green, blue);
  
  //increase line x coordinates
  lineX1 += xStep1;
  lineX2 += xStep2;
 };

//draw second half of triangle
//recalculate xStep1, so that it is now the change in x per unit y
 xStep1 = (float) (pointsX[2] - pointsX[1]) / (pointsY[2] - pointsY[1]);

//iterate through all rows
 for(i = pointsY[1]; i < pointsY[2]; i++){
  //draw row between x1 and y1
  drawRow((int) lineX1, (int) lineX2, i, red, green, blue);
  
  //increase line x coordinates
  lineX1 += xStep1;
  lineX2 += xStep2;
 };
};

//draw circle
void drawCircle(int centreX, int centreY, int radius, uint8_t red, uint8_t green, uint8_t blue){
/*
  The circle is made up of 2 * radius rows of pixels.
  We want to iterate from the bottom-most row (centreY - radius) to
  the top-most row (centreY + radius).
 */

 int i = 0;

 for(i = centreY - radius; i <= centreY + radius; i++){
  /*
   The equation of a circle is given by the formula (x - a)^2 + (y - b)^2 = r^2,
   where (a,b) is the centre of the circle and r is the radius.
   We know that y = i, a = centreX, b = centreY and r = radius.
   This gives the equation: (x - a)^2 = k, where k is a constant
   equal to r^2 - (y - b)^2
   Therefore, x - a = + or - sqrt(k).
   Therefore the two values of x to draw a row between are:
   a + sqrt(k)
   a - sqrt(k)
  */

  
  //set k value
  double k = radius * radius - (i - centreY) * (i - centreY);
  
  //draw row from centreX - sqrt(k) to centreX + sqrt(k)
  drawRow((int) centreX - sqrt(k), (int) centreX + sqrt(k), i, red, green, blue);
 }; 
};

//load BMP file
int loadBMPFile(char filePath[], Bitmap * bitmap){
//attempt to open file
 FILE * file = fopen(filePath, "rb");

//check if file opened correctly
 if(!file){
  //return unsuccessful
  return 0;
 };

//get file size
 fseek(file, 0, SEEK_END);
 int fileSize = ftell(file);
 rewind(file);

//check if file is too small to be a bitmap file
 if(fileSize < sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER)){
  fclose(file);
  
  //return unsuccessful
  return 0;
 };

//read bitmap file header
 fread(&(bitmap->fileHeader), sizeof(BITMAPFILEHEADER), 1, file);

//read bitmap info header
 fread(&(bitmap->infoHeader), sizeof(BITMAPINFOHEADER), 1, file);

//allocate memory for pixels
//the size of the bitmap can be found using bitmap->infoHeader.biWidth * bitmap->infoHeader.biHeight * sizeof(Pixel)
 bitmap->pixels = (Pixel *) malloc(bitmap->infoHeader.biWidth * bitmap->infoHeader.biHeight * sizeof(Pixel));

//copy bitmap data into pixel buffer
 fread(bitmap->pixels, sizeof(Pixel), bitmap->infoHeader.biWidth * bitmap->infoHeader.biHeight, file);

//close file
 fclose(file);

//return successful
 return 1;
};

//load all bitmaps
void loadAllBitmaps(){
//load test bitmap
 loadBMPFile("test.bmp", &bmp_test);
};

//draw BMP file
void drawBitmap(int x, int y, Bitmap * bitmap){
//create pixel pointer
 Pixel * pixel;

//create loop counters
 int i = 0;
 int j = 0;

//iterate through all rows of bitmap
 for(i = 0; i < bitmap->infoHeader.biHeight; i++){
  //set pixel pointer to start of row y + i
  pixel = renderBuffer.pixels + (y + i) * BUFFER_WIDTH + x;
  
  //iterate through x coordinates
  for(j = 0; j < bitmap->infoHeader.biWidth; j++){
   //check that pixel is on screen
   if(j >= 0 && j < BUFFER_WIDTH && y + i >= 0 && y + i < BUFFER_HEIGHT){
    //get pointer to source pixel
    Pixel * srcPixel = bitmap->pixels + i * bitmap->infoHeader.biWidth + j;
   
    //check that pixel is not the colour we will be using as transparent
    if(!(srcPixel->red == 163 && srcPixel->green == 73 && srcPixel->blue == 164)){
     //pixel is not colour used to indicate transparency
     
     //set colour of pixel on renderBuffer pointed to by pixel pointer
     pixel->red = srcPixel->red;
     pixel->green = srcPixel->green;
     pixel->blue = srcPixel->blue;
    };
    
    //increment pixel pointer
    pixel++;
   };
  };
 };
};

//render function
void render(){
//set all pixels to 0 red, 0 blue, 0 green
 memset(renderBuffer.pixels, 0, BUFFER_WIDTH * BUFFER_HEIGHT * sizeof(Pixel));

//render bitmap
 drawBitmap(100, 100, &bmp_test);

/*
  Send renderbuffer data to client area of window.
  We can do this with the StretchDIBits function.
  This takes many parameters, which are detailed below:
 */

 StretchDIBits(
  renderBuffer.deviceContextHandle, //a handle to the device context we wish to render to
  renderBuffer.windowClientWidth / 2 - (renderBuffer.scale * BUFFER_WIDTH) / 2, //the x coordinate of the top left coordinate of our buffer on the window client area
  renderBuffer.windowClientHeight / 2 - (renderBuffer.scale * BUFFER_HEIGHT) / 2, //the y coordinate of the top left coordinate of our buffer on the window client area
  BUFFER_WIDTH * renderBuffer.scale, //the width of the buffer on the window client area
  BUFFER_HEIGHT * renderBuffer.scale, //the height of the buffer on the window client area
  0, //the starting x coordinate on the source buffer to render from (we want to render all data, so this is 0)
  0, //the starting y coordinate on the source buffer to render from (we want to render all data, so this is 0)
  BUFFER_WIDTH, //the width of the source buffer
  BUFFER_HEIGHT, //the height of the source buffer
  renderBuffer.pixels, //a pointer to the actual data we want to send
  &renderBuffer.bitmapInfo, //a pointer to the bitmap info structure for our renderBuffer
  DIB_RGB_COLORS, //use RGB colours
  SRCCOPY //copy the source into the window's buffer
 );
};

main.c

//Software Renderer in C Part 8 - Loading and Drawing a Bitmap

//include main header
#include "main.h"

//include render file
#include "render.c"

/*
 Entry point
 -In Win32, the entry point is WinMain, not main

 -Like main, WinMain returns an int

 -The calling convention of the function is called WINAPI (you do not need to know what this means as it isn't used elsewhere)

 -The calling convention of a function determines how it stores data on the program's call stack

 -Note that all parameters are passed into the function by the OS

 -On Windows, a handle is a numerical identifier used to identify objects and structures controlled by the OS. Handles pop up quite frequently.

 -A HINSTANCE is a handle to an application instance - the first parameter is the numerical identifier for a specific instance of
 the program, given to it by the OS at runtime

 -The second parameter, hPrevInstace is a feature that is now useless. It served a purpose on 16-bit Windows versions, but now
 must simply be included for compatiblity's sake (each version of Windows mostly aims to be compatible with the previous versions)

 -The third parameter is the command line arguments as a single string. LPSTR stands for long pointer to string, and is simply just
 a redefinition of a char * on modern systems.

 -Note that long pointers are also a redundant feature from 16-bit windows, when pointers could either be 16-bit or 32-bit. Nowadays,
 a long pointer and a pointer are the same on Windows.

 -The fourth parameter is an integer used to specify how the program should be displayed. Again, this is given to us by the OS - we
 do not set this, as we do not set any of the parameters of WinMain.
*/

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstace, LPSTR cmd, int nCmdShow){
//create window class structure and initialise to 0
 WNDCLASSEX windowClass = {0};

//set window class properties
//set size of structure
//cbSize is short for "count bytes size" - it is the size of the structure in bytes
 windowClass.cbSize = sizeof(WNDCLASSEX);

//set class name - this is a string used by the operating system to identify our window class
//lpszClassName is short for "long pointer to string class name"
 windowClass.lpszClassName = "MAIN_WINDOW_CLASS";

//set window style - this is the default behaviour of the windows. We are telling the window to redraw when either horizontally or vertically resized (or both)
 windowClass.style = CS_HREDRAW | CS_VREDRAW;

//set window procedure - this is the event handler function, and is declared at the top of the file
//lpfnWndProc is short for "long pointer to function window procedure", and is used to identify the window procedure (event handler function) for this window class
 windowClass.lpfnWndProc = windowProcedure;
  
/*
 set background colour - we set a handle to a colour we create.
 A brush is just a drawing style stored on the OS. Here, we are
 asking the OS to create a solid colour "brush" and return a
 handle to it so that we can use it.
 */

 windowClass.hbrBackground = (HBRUSH) CreateSolidBrush(RGB(100, 100, 100));

//send window class to operating system to be registered
 RegisterClassEx(&windowClass);

//create window size structure
//note that here, we specify the size of the client area, i.e. the area we can draw to
 RECT windowSize = {0, 0, BUFFER_WIDTH, BUFFER_HEIGHT};

//get window frame size
//AdjustWindowRectEx takes a client area, and adds the size of the window frame to it
 AdjustWindowRectEx(
  &windowSize, //pointer to client area rectangle to be modified
  WS_OVERLAPPEDWINDOW, //window style(behaviour) - WS_OVERLAPPEDWINDOW is the default
  0, //no menu bar (this is a boolean value)
  WS_EX_OVERLAPPEDWINDOW //extended style (behaviour) - WS_EX_OVERLAPPEDWINDOW is the default
 );

//windowSize now contains the size of the window (including the window frame)

//create window from window class
//a HWND is a window handle
 renderBuffer.windowHandle = CreateWindowEx(
  WS_EX_OVERLAPPEDWINDOW, //default extended window style - a basic window that may be overlapped
  windowClass.lpszClassName, //the class name of the window class this window will use
  "My First Window!!!", //the title text of the window
  WS_OVERLAPPEDWINDOW, //default window style - a basic window that may be overlapped
  CW_USEDEFAULT, CW_USEDEFAULT, //the starting x and y coordinates of the window - use default
  windowSize.right - windowSize.left, //width of window frame
  windowSize.bottom - windowSize.top, //height of window frame
  NULL, //no parent window
  NULL, //no menu bar - we will not need one for our window
  hInstance, //application instance that window belongs to
  NULL //no LPARAM (an LPARAM is an additional piece of data in Win32)
 );

//check if window created successfully
 if(!renderBuffer.windowHandle){
  //window failed to create - display an alert
  MessageBox(
   NULL, //no parent window - this should display on its own
   "Error - could not create window", //inner text
   "Window Error", //the title text of the message box
   MB_OK | MB_ICONERROR //flags - message box has an OK button, message box has an error icon
  );
  
  return -1;
 };

//allocate memory for render buffer pixels
 renderBuffer.pixels = (Pixel *) malloc(BUFFER_WIDTH * BUFFER_HEIGHT * sizeof(Pixel));

//check if memory could not be allocated - terminate program if so
 if(!renderBuffer.pixels){
  //failed to allocate memory for render buffer
  MessageBox(
   NULL, //no parent window - this should display on its own
   "Error - could not allocate memory for render buffer", //inner text
   "Render Buffer Error", //the title text of the message box
   MB_OK | MB_ICONERROR //flags - message box has an OK button, message box has an error icon
  );
  
  return -1;
 };

/*
  Get window device context and set renderBuffer context to it.
  The window's device context is the region of memory that is rendered to it.
  This is managed by the OS, so we need to retrieve and handle to it. We do this
  so that we can use the StretchDIBits function to send our buffer data to said region
  of memory, as we cannot simply write to the region ourselves.
 */

 renderBuffer.deviceContextHandle = GetDC(renderBuffer.windowHandle);

//set all bitmap info properties to 0
 memset(&renderBuffer.bitmapInfo.bmiHeader, 0 , sizeof(BITMAPINFOHEADER));

/*
  Fill out bitmapinfo structure for renderBuffer.
  This is necessary so that when we wish to send our data to the window's device context
  the OS knows how to interpret our data.
  
  Remeber that our buffer is really just a large bitmap.
  
  The BITMAPINFO structure is made up of two parts: the bitmap info header and the colour
  table. The bitmap info header contains all of the metadata we must set before we can
  draw our buffer data to the screen. We do not need to worry about the colour table, as
  it is mostly only used for defining colour codes for 16-bit or 8-bit colour palettes.
 */

 renderBuffer.bitmapInfo.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); //the size of the BITMAPINFOHEADER structure in bytes
 renderBuffer.bitmapInfo.bmiHeader.biWidth = BUFFER_WIDTH; //the width of our buffer in pixels
 renderBuffer.bitmapInfo.bmiHeader.biHeight = BUFFER_HEIGHT; //the height of our buffer in pixels
 renderBuffer.bitmapInfo.bmiHeader.biPlanes = 1; //this is the number of planes to render - this has to be set to 1
 renderBuffer.bitmapInfo.bmiHeader.biBitCount = 24; //we are using 24-bit colours
 renderBuffer.bitmapInfo.bmiHeader.biCompression = BI_RGB; //uncompressed - we are simply using 3 bytes for the RGB values of each pixel

//there are other properties of the BITMAPINFOHEADER structure, but we can set these all to 0 as they are not relevant to us


//show window if window created successfully
//this function takes the window handle and an integer indicating how it should be shown
//this integer is the nCmdShow parameter passed by the OS upon starting our program
 ShowWindow(renderBuffer.windowHandle, nCmdShow);

//load all bitmaps
 loadAllBitmaps();

//start program loop
 mainLoop();

 return 0;
};


/*
 mainLoop
 -The job of this function is to iterate until the "running" global variable is set to 0
 -Each iteration, it should handle any events and render the current data to the screen
*/

void mainLoop(){
//iterate while window is running
 while(running){
  //handle events for global render buffer
  handleEvents();

  //render to global render buffer
  render();
 };
};

/*
 handleEvents
 -The job of this function is to handle all events for the window that the global render buffer belongs to
 -All messages on the message queue are processed by using the PeekMessage function in a while loop
*/

void handleEvents(){
//create message structure to store incoming event
//remember "message" is just the Windows name for event
 MSG message;

//start message loop
/*
  The PeekMessage function takes five parameters
  -The first is a pointer to a message structure to fill out
  -The second is the window to get events for. This can be
  set to NULL to detect all events that occur on the system.
  -The third is the minimum message ID to retrieve
  -The fourth is the maximum message ID to retreive
  -Note that by setting both the minimum and maximum
  message IDs to 0, the PeekMessage call will detect all
  messages and thus override the minimum-maximum range
  setting
  -The fifth is for flags. We want to add the PM_REMOVE
  flag, which will remove our message from the system's
  message queue once processed
  
  Note that PeekMessage will not block, so if no messages are
  present on the system's message queue, the loop simply just ends.
 */


//get all messages
 while(PeekMessage(&message, renderBuffer.windowHandle, 0, 0, PM_REMOVE)){
  /*
   Translate the message.
   This involves converting key codes into characters for text-based events
   we shouldn't need it, but it is a good practice to include it anyway,
   as if we decide to use a message requiring translation later and forget
   this line, the resulting errors may be hard to debug
  */

  TranslateMessage(&message);
  
  //dispatch message - send message and its corresponding window to the relevant window procedure
  DispatchMessage(&message);
 };
};

/*
 Window procedure - this is the window procedure, the event handler function.
 It takes four parameters:
 -The handle (numerical ID) to the window calling the function
 -The message ID (indicating what type of event has occurred)
 -wParam, a general purpose parameter used to store event-dependent data
 -lParam, another general purpose parameter

 Note that it is common to see WPARAM and LPARAM pop up in many Win32 functions.
 Remember that these are just general purpose parameters, and typically
 contain integer values or pointers

 Note that an LRESULT is just a "long long int" type.
*/

LRESULT CALLBACK windowProcedure(HWND windowHandle, UINT messageID, WPARAM wParam, LPARAM lParam){
//check event type/ID
 switch(messageID){
  //window is closed (i.e. X button is clicked)
  case WM_CLOSE:{
   //send quit message to close window
   PostQuitMessage(0);
   
   //set running to 0 to close program
   running = 0;
   return 0;
  };
  
  //window is resized
  case WM_SIZE:{
   //get window client area size
   RECT windowClientRect;
   GetClientRect(windowHandle, &windowClientRect);
   
   //set window width and height in renderBuffer structure
   renderBuffer.windowClientWidth = windowClientRect.right - windowClientRect.left;
   renderBuffer.windowClientHeight = windowClientRect.bottom - windowClientRect.top;
   
   //calculate the maximum scale that the renderBuffer can be increased by so that it fits in the window
   int i = 1;
   
   while(BUFFER_WIDTH * i <= renderBuffer.windowClientWidth && BUFFER_HEIGHT * i <= renderBuffer.windowClientHeight){
    //increment i
    i += 1;
   };
   
   //subtract 1 from i, since i is equal to the first integer scale where the buffer extends out of the bounds of the window and we want the largest scale before this
   i -= 1;
   
   //set buffer scale to i
   renderBuffer.scale = i;
   
   break;
  };
 };

/*
  There are thousands of different types of message
  on Windows. We cannot check for them all, so we
  can simply call the default window procedure on all
  our parameters for the vast majority of events
 */


//return default window procedure
 return DefWindowProc(windowHandle, messageID, wParam, lParam);
};



Running Our Program:

If you run your program, you should get an output similar to the image below:

That's all for this tutorial. In the next tutorial, we will be cutting a sprite out of a bitmap image. We will also look at scaling our sprite.