Serebyte


Home | Tutorials | Portfolio

Win32 Software Renderer in C: Part 4 - Drawing a Rectangle


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


In this tutorial we will look at drawing a rectangle to our render buffer.




The Theory:

Before we get into the theory of drawing a rectangle to the screen. We will first separate our code into three files: main.h, render.c and main.c.


main.h will contain our file includes, our structure definitions, our global variable declarations and our function declarations. We will include main.h at the top of our main.c file.


render.c will contain our render() function as well as all of the code used to draw shapes and sprites now and later on. We will include render.c directly into main.c after we include main.h,so that we can use our global variables in render.c.


main.c will continue to contain all of our code for creating our window and render buffer and for handling events.




Our drawRectangle Function

Before we can draw anything, note that the bottom left corner of the render buffer is the point (0,0). This is unlike the window itself, where the top left is (0,0). Therefore, when drawing shapes to the screen, we should treat the bottom left as (0, 0). Rightwards is the positive x-direction, upwards is the positive y-direction.


Now we need to create a drawRectangle function. This should not return a value (i.e. be a void function). It should take seven parameters. The first two should be the x and then y coordinates of the bottom left corner. The third and fourth to should be the x and then y coordinates of the top right corner. The fifth, sixth and seventh are the red, green and blue values of the colour of the rectangle (which should be unsigned 8-bit integer).


We need to declare our drawRectangle function. This should be done in the main.h file, with the other function declarations. We can do this with the line: "void drawRectangle(int startX, int startY, int endX, int endY, uint8_t red, uint8_t green, uint8_t blue);".


Now we need to define our drawRectangle function. We should do this in the render.c file. The first thing to do inside of our drawRectangle function is to create a pixel pointer with the line "Pixel * pixel;". This pointer will always point to the pixel we are going to modify. Next we will create two loop counters, i and j. When drawing our rectangle, we want to iterate through each row, and then iterate through all of the pixels in each row and draw them.


Next, we want to start a loop for each for of the rectangle. We can do this with the line: "for(i = startY; i < endY; i++){". The first line in this loop should set our pixel pointer to the start of the row. We want to render to row i of the render buffer. We can start at renderBuffer.pixels (the start of the buffer), and add on i * BUFFER_WIDTH to get to the start of row. After this, we should add on startX, so that our pixel pointer points to the leftmost side of the rectangle on this row. We can do this with the line: "pixel = renderBuffer.pixels + i * BUFFER_WIDTH + startX;".


After setting our pixel pointer, we want to loop through the width of the rectangle and draw to it. We should first start a loop, using the line "for(j = startX; j <= endX; j++){". Inside this loop, we want to check if the pixel at coordinates (j, i) is actually within the bounds of the buffer, as attempting to draw to a pixel outside of the buffer will usually cause a crash. We can check that our pixel is on screen using the line "if(i >= 0 && i < BUFFER_HEIGHT && j >= 0 && j < BUFFER_WIDTH){".


If our pixel is on screen, we want to draw it. We can do this by setting the colours of the pixel that our pixel pointer is currently pointing to. We should set them to the red, green and blue values we passed in as parameters. We can do this with the lines: "pixel->red = red;", "pixel->blue = blue;" and "pixel->green = green;". Outside of the if-statement that checks if our pixel is on screen, we want to increment our pixel pointer to the next pixel with the line "Pixel++".


Now our drawRectangle function is complete. We should run this function inside our render function, and draw a rectangle. I will do this with the line: "drawRectangle(100, 50, 400, 250, 255, 0, 0);", but you can pass in whatever arguments you would like. Note that this line must be inserted after our screen-clearing memset call, and before our StretchDIBits call.


That's it for the theory of this tutorial. As usual, the code for each of our files is shown below.




The Code:

Here is the code needed to draw a rectangle. If you are using MinGW, you can compile it with the command "gcc main.c -lgdi32 -o app". You should be able to use any Windows compiler - just be sure to link the gdi32 library.



main.h

/*
 Software Renderer in C - Part 4

 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>

//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;

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

//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 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++;
  };
 };
};

//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 test rectangle
 drawRectangle(100, 50, 400, 250, 255, 0, 0);

/*
  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 4 - Draw a Rectangle

//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);

//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 we run our program, we should see a rectangle appear in the colour we chose and the coordinates we plotted, similar to the image below:


That's all for this tutorial. In the next tutorial, we will look at drawing lines to the screen.