Serebyte


Home | Tutorials | Portfolio

Win32 Software Renderer in C: Part 3 - Resizing Our Window


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


In the previous tutorial, we looked at creating a render buffer. In his tutorial, we will look at resizing our window and scaling up our buffer.




The Theory:

When we resize our window, including when we make it fullscreen, we want to resize our buffer so that it is scaled up to fill as much of the window as possible. Remeber that we are software-rendering here. Therefore, our rendering process is significantly slower than it would be if we were using a hardware accelerated API like OpenGL or DirectX (although, then we wouldn't necessarily learn as much). This means that we want to render as few pixels to the buffer as possible, as rendering to the buffer can take a long time. The most efficient thing to do here, is to render to a fixed-sized buffer, and to then have the StretchDIBits function scale up our buffer as much as possible.




How the Buffer Resizing Will Work

We can have the StretchDIBits function scale up our buffer, simply by changing the on-screen width and height (the fourth and fifth parameters). The rest is handled automatically, and is a lot faster than manually allocating more memory for our larger buffer and rendering to it. We should only ever multiply our buffer by an integer scale, as, while it is possible to scale the buffer by a fractional amount, it will create an annoying flickering effect, which we would like to avoid. The disadvantage of using integer scales only is that we are left with a grey border around our buffer, but I feel this is better than having flickering on-screen.


We can handle our window resizing by handling the WM_SIZE message in our window procedure. Note that the WM_SIZE message is also called when the window is created. We want to first get the new size of the window's client area. Then, we want to calculate the largest possible integer our renderBuffer can be scaled by, for which it still fits inside said client area. When we draw the StretchDIBits function, we want to centre our buffer in the client area, and then increase its width and height by our maximum scale.




Additions to our RenderBuffer Structure

To make our changes, we need to add three new properties to our structure. All three are integers. The first is the scale by which to multiply the width and height of our buffer. We will call this "scale". The second is the window client area width, which we will call "windowClientWidth". The last is the window client area height, which we will call "windowClientHeight".




Resizing the Window

We can handle window resizing with a WM_SIZE message. Inside our window procedure, inside the "switch(messageID){..." statement, we will want to add a case for the WM_SIZE event. I will add this below the WM_DESTROY event case, but you could order them either way around. We could add this case with the line "case WM_SZE:{".


We now need to get the window client area size. We can create a RECT (rectangle) structure to store the client area. I will call this structure "windowClientRect". We can then get the size of the client rect with the function GetClientRect. GetClientRect takes two arguments. The first is the window handle. We can substitute in the window handle we passed into our window procedure (which we called "windowHandle") here. The second is the pointer to the RECT structure.


Now we want to set the renderBuffer properties. We can set "renderBuffer.windowClientWidth" to "windowClientRect.right - windowClientRect.left". We can set "renderBuffer.windowClientHeight" to "windowClientRect.bottom - windowClientRect.top".


Next, we need to calculate the maximum scale we can multiply our renderBuffer by, for which it will still fit within the window's client area. We can use a while loop for this. First, declare an integer, i, and set it to 1 (we do not want our scale to be less than 1). We want our loop to increment i so long as our buffer width multiplied by i is smaller than the client area width, and our buffer height multiplied by i is smaller than the client area height. We can accomplish this with the condition "while(BUFFER_WIDTH * i <= renderBuffer.windowClientWidth && BUFFER_HEIGHT * i <= renderBuffer.windowClientHeight){". Inside our loop, we want to increas i by 1, using the line "i += 1;". Since i is now the smallest integer scale for which our scaled buffer is too large to fit within the window client area, we want to subtract 1 from i, so that it becomes the largest integer value for which the scaled buffer can fit within the client area.


Once we have the maximum scale, i, we want to set our renderBuffer.scale property to it. We can do this with the line "renderBuffer.scale = i;". Now we can finish this WM_SIZE case, so be sure to add the "break;" line at the end of the case block.




Drawing Our Scaled Buffer

We can now edit our StretchDIBits function. The second argument of StretchDIBits is the starting x coordinate on the client area. This is currently set to 0, indicating the leftmost side of the screen. We want our buffer to be in the centre of the screen. Therefore, we want to pass in the value "renderBuffer.windowClientWidth / 2 - (BUFFER_WIDTH * renderBuffer.scale) / 2". This is because "renderBuffer.windowClientWidth / 2" is the x coordinate of the centre of the window client area. We then want to move our buffer leftwards by half of its width to position it exactly in the centre, hence why "(BUFFER_WIDTH * renderBuffer.scale) / 2" is subtracted. For similar reasons, we will set the third parameter to "renderBuffer.windowClientHeight / 2 - (renderBuffer.scale * BUFFER_HEIGHT) / 2". The fourth and fifth arguments are the width and height of the buffer on screen. We can set these to "BUFFER_WIDTH * renderBuffer.scale" and "BUFFER_HEIGHT * renderBuffer.scale" respectively.


This finishes our theory for this section. As with the previous tutorials, the code for this section is shown below.




The code:

Here is the code required to scale and centre a render buffer on screen. You could add the previously mentioned changes to your code from the previous tutorial, but, if you have the time, I would recommend writing the program out from scratch as it may help you understand and memorise the code for this process. Writing it out again may also help you avoid bugs where you may have forgotten to change a section of code.


If you are using MinGW, you can compile this code with "gcc main.c -lgdi32 -o app". If you are using Visual Studio, be sure to link the gdi32 library or else this code will not work! (I believe you can do this using: #pragma comment(lib, "gdi32"))


main.c

//Software Renderer in C Part 3 - Resizing the Window

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

//render function
void render();

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

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

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

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

/*
 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 the Program:

Running the code should first produce a black screen. This is our render buffer. We should be able to resize this window and have our buffer always be visisble in the centre. If we make our window large enough to contain a buffer twice as big, we should see our buffer scale.

Here is the initial output:


Here is the buffer when made fullscreen:


That's all for this tutorial. In the next tutorial, we will look at drawing rectangles on our buffer.