Tag Archives: free pascal


Short description

Alexland is a 2d shooter in a classical style.

Showcase and Basic Data

Developer granted permission to use these screenshots.

  • Project name: Alexland
  • Author: suve & ZbiXs
  • Latest version: 1.3
  • First release date: 2010-01-31
  • Compiler: Free Pascal 2.4.0 (for the 1.3 release)
  • SDL Version: 1.2
  • Further libraries: BASS for audio handling, SDL_image, SDL_ttf, SDL_net
  • License: Back then we didn’t really think about licensing, and seeing how the game contains assets ripped from plenty of places without even keeping track of source… I say it’d be hard for us to claim copyright to anything apart from code and some original graphics (+edits) we created.
  • Open source: Nope. Maybe if there’s a remake one day.
  • Official website: http://svgames.pl

Interview with suve

Could you please give a short description of Alexland for those who have never heard of it?

suve: Born of RPG Maker nostalgia and the hatred for its default graphics set, Alexland is a 2D shooter where the player controls a lone hero in a fight against never-ending hordes of monsters. Featuring 12 weapons to kick ass with, 11 bonuses to enhance the gameplay, 10 monster types to kill, and 60 achievements to unlock, Alexland can provide long hours of mindless, merciless fun. Available in English, Polish, French, German and Russian.

Why did you decide to choose Pascal as a programming language and SDL/SDL2 as a library for your projects?

suve: I chose Pascal mostly as it’s the language I’m most proficient and comfortable with. As for SDL, after working with a few different libraries in the past, I’ve found SDL easy to use, but nonetheless really versatile and fitting my needs. The library itself doesn’t really enforce anything on you, so you don’t have to change your habits (much), and the seemingly simplistic API is greatly extended by the supplementary SDL_XYZ libraries.

What do you think is the most interesting Pascal/SDL/SDL2 project out there (besides of your own, of course :-D)?

suve: Supraleiter seems the most awesome of them all, I think. Shame that quite probably I won’t be able to play sit, seeing as I only have an integrated GPU.

Are there any further steps for your projects or any new projects planned? What will they be?

suve: I have two projects underway right now, but one is too early in development and I don’t want to disclose it for fear of not delivering… and the other, for a change, is written in C instead of Pascal. 🙂





Pascal SDL Projects?

A new page has been set up which gives an overview of projects done in SDL with Pascal (any dialect). The projects may be games, interpreters, libraries, anything. Of course SDL should play a key role and shouldn’t be just used to set up an OpenGL window (or similar). If possible I try to have an interview with the creator of the project.

The first project listed is the famous EGSL project and its successor Pulsar2D. Both have been created by Cybermonkey who kindly gave an interview and provided a lot of screenshots to me.

Feel free to contact me to let me know about other Pascal SDL projects.

Edit: As of 09/02/2016 I added suve’s Alexland and Colorful to the project page. Thanks for the interview and the screenshots.

EGSL and Pulsar2D

Short description

EGSL and Pulsar2D are LUA script interpreters to develop games in an easy, quick and convenient way.

EGSL: Showcase and Basic Data

Developer granted permission to use these screenshots.

  • Project name: Easy Game Scripting with LUA
  • Author: Cybermonkey
  • Latest version: 1.6.0
  • Release date: 30/12/2012
  • Compiler: >= FPC 2.6.0
  • SDL Version: SDL 1.2
  • Further libraries: Vampyre Imaging Library / Lua 5.1 / Lua 5.2
  • License: zlib
  • Open source: yes
  • Official website: http://www.egsl.retrogamecoding.org

Pulsar2D: Showcase and Basic Data

Developer granted permission to use these screenshots.

  • Project name: Pulsar2d
  • Author: Cybermonkey
  • Latest version: 0.6.2
  • Release date: 31/12/2015
  • Compiler: FPC 3.0.0
  • SDL Version: SDL2
  • Further libraries: Lua 5.2
  • License: zlib
  • Open source: yes
  • Official website: http://pulsar2d.org

Interview with Cybermonkey

Could you please give a short description of EGSL and Pulsard2D for those who have never heard of it?

Cybermonkey: EGSL (Easy Game Scripting with Lua) is a Lua interpreter which allows one to code 2D games in a simple way. I could say in a “classical way” because EGSL is inspired by old BASIC dialects. The main difference between EGSL and Pulsar2D is that Pulsar2D uses now the newer SDL2 libraries (which gives us the possibility to use multiple windows). It’s as easy as that: write 10 lines of Lua code and start the script and you’ll have already a small sprite moving example. Of course it is possible to use the framework with FreePascal. Apart from that I recently ported the Pulsar2D framework to FreeBASIC. So one can code Pulsar2D games/demos whatsoever in Lua, FreePascal or FreeBASIC.

Why did you decide to choose Pascal as a programming language and SDL/SDL2 as a library for these projects?

Cybermonkey: I started programming back in the 1980s with the Commodore 64 and BASIC. I learned Turbo Pascal in school and started programming with FreePascal a few years ago. It’s the language I have the most experience with. Not to mention that the FreePascal compiler is well maintained. I chose SDL/SDL2 because of its cross platform capabilities.

What do you think is the most interesting Pascal/SDL/SDL2 project out there (besides of your own, of course :-D)?

Cybermonkey: Actually I don’t know of any other … But of course the most impressive Pascal project is Lazarus for me.

Are there any further steps for EGSL and/or Pulsar2D or any new projects planned? What will they be?

Cybermonkey: EGSL will not be developed any further. Pulsar2D wil be improved from time to time. My plans are to implement Box2D physics and easy handling of tiled based maps made with the Tiled editor. But this has no priority so it can take a long time…

At the moment I am developing a little BASIC interpreter called “AllegroBASIC”. It’s a C project, though. (The editor, however, is made with Lazarus…) Since I am using Allegro4 libs which are obsolete now, I am porting at the same time the project to SDL2 which will be named “RETROBASIC”. If there are people interested in AllegroBASIC, have a look at allegrobasic.pulsar2d.org.


Chapter 9 application preview

New Chapter 9 about Music and Sound

The new Chapter 9: Music and Sound has been released. It demonstrates how to use the SDL_mixer 2.0 to load music and sound files to use them in your applications.

I was surprised to find that there have been made many important updates to Tim Blume’s SDL 2.0 units since the latest release (version 1.72). This means for everybody who relies on these units, update to the latest master branch release (later than version 1.72)!

Download ZIP button
IMPORTANT: Get the latest master branch release! Download Link

Otherwise you will struggle to get some important sdl features. E.g. key code constants and the code of the new Chapter 9 won’t work. I adapted Chapter 8 about event handling.

An interesting new header translation project was mentioned to me which allows for dynamic loading of SDL 2.0. Check out Chapter 1 to read more about this project by Imants Gulis.

Many smaller updates have been performed, too. Also the color scheme has been updated since it was stated that the contrast of the former color scheme has been too weak. You may also have noticed the amazing new fractal title background image :-)!

Important hint: The Free Pascal compiler got a new stable release on 25th November of 2015, version 3.0.0. Don’t forget to update your favourite compiler :-)!

Chapter 1 – Introduction

The introduction is short.

What is SDL or rather SDL2?

SDL abbreviates Simple Direct Media Layer. In August 2013 the official successor of original SDL (SDL 1.2) has been released, simply called SDL 2.0 (or SDL2). It is a library to develop powerful applications for many different operating systems (platforms) by learning only one set of commands. This is called cross-platform development. The following platforms are officially supported by SDL2:

  • Windows
  • Mac OS X
  • Linux
  • iOS
  • Android.

Internally the SDL library layer translates your commands to the platform specific commands, which is reflected by the followig diagram.

SDL2 Layers Diagram
Image by Adriatikus at English Wikipedia [Public domain], Wikimedia
SDL2 Layer Diagram
It’s especially meaningful to use the SDL library if you plan to develop games or need fast paced rendering. Jump and run-, Role-playing-, Real time/turn based strategy-, side-scrolling-, arcade-, board-, card-, simulation-, multi-user dungeon-, puzzle-, shooter-, network games and so on are possible, and any combination of these ;-).


The SDL 2.0 library, as well as the units for translation, are licensed under the zlib license. This license grants a high degree of freedom. So even closed-source, commercial applications and games are possible with SDL 2.0 and Free Pascal. As a sidenote, you are free to choose the MPL license for the units, if you like.

How to get SDL2 for Free Pascal or Object Pascal?

There are several SDL 2.0 units out there (see comparison and discussion here) which translate SDL 2.0 to Pascal, since originally it has been written in C. Over time it turned out that Tim Blume’s SDL 2.0 units are the best choice to use if you like to get into SDL 2.0 development in Free Pascal or Object Pascal.

A detailed installation instruction to set your system up for SDL 2.0 development under Pascal is found in Chapter 2 for Windows or Linux. If you did install SDL 2.0 for Free Pascal or Object Pascal already, proceed to Chapter 3.

Chapter 2 (Windows) → | Chapter 2 (Linux) → | Chapter 3 →

Chapter 2 – Installation and Configuration

What is covered, what not?

  • installation guide for SDL 2.0 under Microsoft Windows
  • installation of Free Pascal Compiler (FPC)
  • installation of Free Pascal IDE and Lazarus IDE
  • installation of SDL 2.0
  • configuration of FP IDE and Lazarus IDE to work with SDL 2.0
  • after this you are ready to code awesome SDL 2.0 stuff 🙂

Free Pascal IDE or Lazarus IDE

IDE stands for integrated development environment. Although you could write your programs in a simple text editor, an IDE makes your life much easier. For example, it highlights keywords, makes it easier for you to set up the compiler, and much more. Now let’s have a look at these two IDEs:

You may notice that the native Free Pascal IDE (left) looks old, but it is shipped right along with the Free Pascal Compiler. In contrast to that the Lazarus IDE (right) looks up-to-date, but requires it to be installed additionally. My advise is nonetheless, use the Lazarus IDE.

The Free Pascal Compiler (FPC)

We need three different software packages. First of all we need the stand-alone Free Pascal Compiler or Lazaruse IDE (which already has a copy of the Free Pascal Compiler included). If you are not sure, I recommend to go with the Lazarus IDE package.

SDL Library and SDL 2.0 units

Additionaly we need the original SDL library files (.dll files). And finally we need units that connect our SDL 2.0 code written in Free Pascal to the SDL library files. The latter will be done by Tim Blume’s SDL 2.0 units.

This table provides all information and sources you need with respect to installation steps 1) – 3). Keep in mind, you have to download either the Lazarus IDE or the stand-alone Free Pascal Compiler, not both.

approx. Size [MB]
Source link
Details and remarks
Lazarus IDE (has FPC included)
1.4.4 or later
Linux and Mac OS X versions are here: http://www.lazarus-ide.org (see Downloads).
Free Pascal Compiler (stand-alone)
3.0.0 or later
Windows 32 bit version
Windows 64 bit version (needs 32 bit version)
If you need the Linux, Mac OS X or other versions, check them out here: http://www.FreePascal.org (see Download).
Tim Blume's SDL 2.0 units
1.72* (see remark)
On the right upper side is a button saying Download ZIP. Click on this button for the download of the latest release. *Better go with the latest availabe version (not version 1.72!) since some important bugfixes have been made lately.
SDL 2.0 dynamic link library
SDL 2.0 > Download > Choose the download suitable for your system.

Download Lazarus or the stand-alone Free Pascal Compiler (FPC)

If you have Free Pascal or the Lazarus IDE installed already, you can skip the steps 1a) and 1b).

1a) For Lazarus IDE: Download the latest version of the Lazarus IDE. It has the Free Pascal Compiler accompanied. Remark: As of today (12/02/2016) the bundle doesn’t provide the most recent Free Pascal Compiler (3.0.0) but the version before (2.6.4). The tutorial examples will work with both versions though.

1b) For Free Pascal IDE: 32 bit Windows: Download the latest stable Free Pascal compiler, version 3.0.0 or higher. 64 bit Windows: You have two choices, 1) Simple way: Go with the 32 bit version of Free Pascal. (Recommended), 2) Install the 64 bit version of Free Pascal on top of the 32 bit version of Free Pascal. In this case you need both files. Hence, you need to download both Free Pascal installers shown above.

Download SDL 2.0 and Header translation

2) Download the latest version of Tim Blume’s SDL 2.0 units, better go with the latest branch (master branch), and do not use version 1.72 since it contains some bugs. Click on “Clone or download” and then on “Download ZIP” (see arrows in image below) of the page and make sure that Branch: master (not v1.72!) is chosen at the left side (see arrow in image below). This is important for any operating system: Windows, Linux, Mac OS X.

Download SDL2 units on GitHub
Choose the master branch (1), click on “Clone or download” (2) and click on Download ZIP (3).

3) Download the latest version of SDL 2.0 runtime library, version 2.0.4 or higher.

Install Lazarus or the Free Pascal Compiler

4a) For Lazarus: 32 and 64 bit Windows: Execute lazarus-1.4.4-fpc-2.6.4-win32.exe  to install Lazarus for a 32 bit or 64 bit Windows system and follow the self-installer. Let the self-installer create a shortcut on your desktop.

4b) For Free Pascal IDE: 32 and 64 bit Windows: Execute fpc-2.6.4.i386-win32.exe  to install Free Pascal for a 32 bit or 64 bit Windows system. Let the self-installer create a shortcut on your desktop. Don’t modify any checked options during installation process. The default path is: C:\FPC\[Compiler version]\. [Compiler version] should be 3.0.0 or higher numbers. 64 bit Windows only: After you installed the 32 bit Free Pascal, you may execute fpc-3.0.0.i386-win32.cross.x86_64-win64.exe optionally to add the 64 bit version on top.

Install SDL 2.0 and Header translation

5) Extract SDL2-2.0.4-win32-x86.zip or SDL2-2.0.4-win32-x64.zip to get the SDL runtime library. This leads to two extracted files. There is a text file and the very important SDL2.dll.

6) 32bit Windows: Copy those files (especially the SDL2.dll!) to your system32-folder, C:\WINDOWS\system32\. 64bit Windows:  Copy those 64bit files to your system32-folder (!), C:\WINDOWS\system32\, Windows is expecting you to do this. Do not use the SysWoW64-folder (Hint: 32 bit files on 64 bit Windows go here).

If it is not possible to copy the files into this folder (or you are unsure about its location) alternativly you can copy the SDL2.dll right into the same folder where the SDL 2.0 application (.exe) is located. That is because SDL 2.0 first  looks for the SDL2.dll in the folder from which it is executed and if it isn’t found there, in the corresponding system folder! Anyway, if it isn’t found anywhere, the program will raise an error.

Now you have installed Free Pascal and the SDL runtime library on your system. Finally Tim Blume’s SDL 2.0 units have to be installed.

7a) For Lazarus IDE: Extract the Pascal-SDL-2-Headers-master.zip. The Free Pascal Compiler is located in a subfolder called “fpc”. I suggest to copy all the files to a folder with full path C:\Lazarus\fpc\[Compiler Version]\units\SDL2\. [Compiler version] should be 2.6.4 or higher numbers. Skip step 7b).

7b) For Free Pascal IDE: Extract the Pascal-SDL-2-Headers-master.zip. I suggest to copy all the files to a folder with full path C:\FPC\[Compiler Version]\units\SDL2\. [Compiler version] should be 3.0.0 or higher numbers. All later chapters will assume you installed to this path.

Configuring the Lazarus IDE

Now the compiler has to be told where to find the new units.

8) Open the Free Pascal IDE (for example by clicking the shortcut on desktop).

Lazarus IDE Desktop Icon

9) In Lazarus the path to external units has to be set for each project. Create a project if no project is set up (Project > New Project …). In the menue choose the following item Project > Project Options …. Now a window should pop up.

10) Under “Compiler Options” choose “Paths” (see red mark). Choose the three dots button (see red mark on the right side) for the “Other units files (-Fu)” field (red mark). This makes the “Path Editor” pop up. In the area “Search paths:”, click on the yellow folder symbol in the right bottom corner. Choose the path to your SDL-units (e.g. C:\Lazarus\2.6.4\units\SDL2). Make sure the path leads to the folder, where the sdl2.pas file is located! This file contains all the basic features of SDL 2.0.

Lazarus IDE Include Paths

Confirm by clicking “OK” until all windows are closed. Your Lazarus IDE is now set up for SDL 2.0 application development :-)!

Configuring the Free Pascal IDE (skip if you use Lazarus)

Now the compiler has to be told where to find the new units.

8) Open the Free Pascal IDE (for example by clicking the shortcut on desktop).

Free Pascal IDE Desktop Icon

9) In the menue choose the following item Options > Directories…. Now a window should pop up.

10) The first tab whitin this new window is called “Units”. Here you add the full path to your SDL-units (e.g. C:\FPC\3.0.0\units\SDL2) right below the other paths. Leave the last backslash out. Make sure the path leads to the folder, where the sdl2.pas file is located! This file contains all the basic features of SDL 2.0.

SDL2 directories
Since the screenshot is old, the compiler version has been 2.6.2, which is reflected in the shown pathes. It should be 3.0.0 or higher numbers for you.

Confirm by clicking “OK”.


Congratulations! You have configured your system for developing SDL 2.0 applications with the Lazarus IDE or the Free Pascal IDE! Simple, isn’t it? 🙂

For those of you who try running a program and get an abortion together
with a messege saying “exitcode = 309”: You skipped step 6! Did you copy
the SDL2.dll to your system32- or system-folder respectively? If so and the
error still occurs you should copy the SDL2.dll into the folder
where the programs are placed. Now it should work.

← Chapter 1 | Chapter 3 →

Chapter 3 – First Steps

Last updated on November 10th, 2018

For this tutorial it is presumed, that you are familiar with procedures, functions, loops, pointers and usual commands of Free Pascal or its dialects. If this is not the case you may face problems because this tutorial deals with the features and usage of the SDL 2.0 library and will not explain basic concepts of Pascal programming. For a quick refresh on some Pascal basics, have a look into this (good) article Modern Object Pascal Introduction For Programmers by Michalis Kamburelis.

How to get the source code of examples?

You can easily copy the example source code directly from the source code box for each chapter.

Diagram how to get source code
Creative Commons License This image by https://www.freepascal-meets-sdl.net is licensed under a Creative Commons Attribution 4.0 International License.
  1. Hover into the source code box with your mouse cursor, a grey mini menu will show up at the top.
  2. Click on the button “Toggle Plain Code” (or just double click into the source code box anywhere). The source code box turns black and white.
  3. Copy the full source code (or parts of it) into your compiler’s IDE or a simple text file.

To reverse the effect, just again hover into the box and click “Toggle Plain Code” again. The source code is displayed as originally. Feel free to try it out further below, there is a source code box :-).

The SDL2 unit and the first application

Let’s start now. The most important rule to get ready for SDL 2.0 in your Pascal programs is:

Always include the SDL2 unit in the uses clause.

The SDL2 unit is the heart of every SDL 2.0 application! If you do so, you are perfectly prepared to start coding.

The different features of SDL 2.0 (screen/video handling, audio handling, keyboard handling, and so on) have to be initilized individually using this function.

It will return 0 on success and a negative error code on failure. You may wonder about the variable types SInt32 and UInt32 in the SDL_Init function declaration. Such integer types (which we will see in other chapters again) originate from the original C-language SDL 2.0 code. For an easier translation to Free Pascal they were kept. The S and U mean “signed” (negative values possible) and “unsigned” (values greater or equal zero only), the Int stands for “integer” and the number stands for the bit value. So UInt32 is an 32 bit unsigned integer (which corresponds to Free Pascal’s longword).

In the first example we want to initialize the SDL 2.0 video subsystem for screen handling. The following code example shows the frame of a typical SDL 2.0 application.

Instead of SDL_INIT_VIDEO you could initilize the respective subsystem by using SDL_INIT_AUDIO for audio subsystem, SDL_EVENTS for event subsystem, and so on. The table shows an overview of all the possible flags and their meaning:

SDL_INIT_TIMERInitilizes timer subsystem for handling of time related events.
SDL_INIT_AUDIOInitilizes audio subsystem for playing music or sound effects.
SDL_INIT_VIDEOInitilizes video subsystem for drawing/showing/manipulating of graphics, textures and screen, usually the most important subsystem.
SDL_INIT_JOYSTICKInitilizes joystick subsystem for handling of joysticks.
SDL_INIT_HAPTICInitilizes haptic (force feedback) subsystem.
SDL_INIT_GAMECONTROLLERInitilizes game controller subsystem.
SDL_INIT_EVENTSInitilizes events subsystem for handling of mouse or keyboard input.
SDL_INIT_EVERYTHINGInitilizes all the subsystems above.
SDL_INIT_NOPARACHUTEIgnores fatal signals. In SDL2 this is set by default and it isn’t possible to change this state. The explanation is given in the official migration guide I will cite here:There’s no SDL parachute anymore. What 1.2 called SDL_INIT_NOPARACHUTE is a default and only state now. This would cause problems if something other than the main thread crashed, and it would interfere with apps setting up their own signal/exception handlers. On the downside, some platforms don’t clean up fullscreen video well when crashing. You should install your own crash handler, or call SDL_Quit() in an atexit() function or whatnot if this is a concern. Note that on Unix platforms, SDL still catches SIGINT and maps it to an SDL_QUIT event.

Of course you are allowed to combine several components by OR, e.g. “SDL_Init(SDL_INIT_VIDEO OR SDL_INIT_AUDIO)” to initilize video and audio support. If you are running some subsystems already but need to load further ones you would use


respectivly. Again 0 ist returned on success and the negativ error code in case of failure.

Quitting your programs

Every SDL program has to be closed by

It cleans up your system. Never forget it! This procedure ensures that all subsystems initilized get unloaded. There is a corresponding procedure to unload specific subsystems defined as

You are allowed to quit two or more subsystems by this function by using OR operator. It is advised to always quit SDL 2.0 applications by SDL_Quit even if you quit all of them individually by SDL_QuitSubSystem before.

Now you can try the example program. You will not see much but if you didn’t get an error message you was successful. Before proceeding, let’s have a quick look into error handling.

SDL 2.0 functions and errors

Every SDL 2.0 function returns an error value for you to check if the function runs properly at runtime. The values returned are of integer or pointer type. There is no general rule what values correspond to which status. In SDL 2.0 usually an integer value of 0 means “function runs/ran succesfully”, values lower than 0 correspond to a status “function couldn’t be run, something is wrong”. For pointers nil means error and any non-nil pointer means success. However, in most cases I won’t do error checking to keep code examples short. I will mention the error values to be expected though.

You should know that there is a function called

which translates the last error received into a message (of type PAnsiChar) that can be read out and printed to the screen by any function that can handle strings as well (e.g. the Pascal’s common write() function). Since SDL 2.0 is written in C originally, the PAnsiChar type is used in contrast to the String type (which is more common among Pascal programmers for message storage and handling).

A quick way to return the error message is to use the SDL2 message box feature:

The flags for the message box could be:


While the flags indicate the reason for the message box, the title and the message argument are used to set a box title and a message. The window argument can be set to the nil pointer.

The following short code snippet demonstrates a convenient way of using the box for showing error messages in the case of SDL2 initialization as done above.

Well, we have initilized the video subsystem and released it afterwards, and we learned about showing error messages in a simple message box. Simple Directmedia Layer deserves its name, isn’t it?

Only if you agree, you may proceed the next chapter ;-)!

← Chapter 2 (Windows) | ← Chapter 2 (Linux) | next Chapter →

Drawing Primitives

Last updated on August 10th, 2018

Displaying of images/sprites/textures as discussed in previous chapters are sometimes accompanied by drawing operations. For some applications and games drawing operations are even essential, e.g. you need to draw buttons of dynamic dimension in your application. Discussion of a more detailed case is found right after the code example.

Supported Primitives: Points, Lines, Rectangles

SDL2 supports natively the drawing of

  • Points
  • Lines
  • Rectangles (outline only)
  • Filled Rectangles.

Drawing in SDL 2.0

Now lets jump right into the code:

Wow, that looks like a big load of new functions, but I promise, drawing in SDL 2.0 is very simple. What the executed program will look like is shown in the following screenshot.

Result screenshot for chapter 5

Now, let’s have a closer look to the first lines of code.

The program is called “Chapter5_SDL2”. We will need a counter variable “i” of native Pascal type integer later. We need a window and a renderer and call them “sdlWindow1” and “sdlRenderer” as known from the previous chapters. Next we declare a variable “sdlRect1” which is of type PSDL_Rect (not TSDL_Rect this time). The same is true for “sdlPoints1” which is an array of 500 elements of type PSDL_Point.

If you have a large amount of points or rectangles, it is usually better to use the pointer types because they will be stored in the heap.

Nothing new here, we initilize SDL 2.0, create a window with 500 pixels width and 500 pixels height and associate the renderer with this window.

Colours, alpha value and RGB(A) notation in SDL 2.0

Now we have something new here, SDL_SetRenderDrawColor() sets a colour for drawing operations, just as if you choose for a pencil colour to draw something. This function doesn’t draw anything though. It returns 0 on success and the negative error code on failure.

SDL_SetRenderDrawColor(renderer: PSDL_Renderer; r: UInt8; g: UInt8; b: UInt8; a: UInt8): SInt32

First you need to set the renderer for which this drawing colour is meant. After that you have to set the colours red, green, blue and the alpha value. They can range from 0 to 255 (integer values only). Think in terms of 255 being 100% and 0 being 0% of that colour or the alpha value. As a start let’s neglect the alpha value.

If you like to have a red colour, you need to set the value for the red colour high, e.g. 100%, the maximum value is 255, and since you don’t want to mix in green and blue, they get the minimum value of 0 (hence 0%). Setting up red therefore corresponds to 255/0/0 in terms of r/g/b. For comparision, 0/255/0 will lead to green, 255/255/255 is white and 0/0/0 is black, and so on. In the example code we used 0/255/255 which leads to cyan (mixing up green and blue additively). With these three values you can generate every colour possible.

So what is the meaning of the alpha value then? Well, it determines the transparency. 255 means fully opaque and 0 means full transparency. This is very important for blend effects in computer graphics and will be demonstrated later on in the code. By the way, instead of 255 you could use SDL_ALPHA_OPAQUE. If you count the alpha value also as colour variation you have 4.29 billion different possibilities.

Setting up a background in SDL 2.0

The function SDL_RenderClear() is for clearing the screen with the drawing colour. As argument you just need to tell the renderer. It is simple as that :-). Since we set the drawing colour to cyan before, the screen will be cleared with a cyan colour.

SDL_RenderClear(renderer: PSDL_Renderer): SInt32

This function will return 0 on success and a negative error code on failure. The cleared screen will be shown for one second by SDL_RenderPresent() and SDL_Delay(). These two procedures are known from the previous chapter.

Drawing Lines and Points in SDL 2.0

Now we change the drawing colour by SDL_SetRenderDrawColor() to red and use SDL_RenderDrawLine() to draw a simple line.

SDL_RenderDrawLine(renderer: PSDL_Renderer; x1: SInt32; y1: SInt32; x2: SInt32; y2: SInt32): SInt32

Again you need the renderer, which is “sdlRenderer” in our case. After that you specify the x/y coordinates where the line should begin and then the x/y coordinates where the line should end. Remember that the origin 0/0 is at the top left corner of the window. The coordinates 10/10 mean to start at the point ten pixels to the right and ten pixel to the bottom relative to the origin. Thus, the coordinates 490/490 for the second point will lead to a diagonal line across the window. This function returns 0 on success and a negative error code on failure.

After that again we ask to render this line to the screen by SDL_RenderPresent() and wait one second by SDL_Delay().

Now we change the colour to black and draw some points by the function SDL_RenderDrawPoint(). It is nearly identical to SDL_RenderDrawLine() but instead of four coordinates you need just two coordinates where the point should be drawn.

SDL_RenderDrawPoint(renderer: PSDL_Renderer; x: SInt32; y: SInt32): SInt32

This function returns 0 on success and the negative error code on failure.

I thought it would be nice to have more than just one point to be drawn, so the function is used in a for-loop to draw altogether 48 points. Here we need the counter variable “i”. Maybe you can guess from the code where the points are and how they are arranged, if not, just run the code ;-). Finally the result is rendered to the screen by SDL_RenderPresent() and the program waits one second by SDL_Delay().

Let’s proceed to the next chunk of code now.

The drawing colour is set to green by SDL_SetRenderDrawColor() and the rectangle is drawn by SDL_RenderDrawRect().

SDL_RenderDrawRect(renderer: PSDL_Renderer; rect: PSDL_Rect): SInt32

It requires the renderer, which is “sdlRenderer” for us and a PSDL_Rect we just defined: “sdlRect1”. This function returns 0 on success and the negative error code on failure. Notice, we neither render the result to the screen now nor do we delay here. Anyway, we want a second rectangle! 🙂

We change the rectangles x/y coordinates for the second rectangle but keep its width and height. What we are looking for is a filled rectangle that has some transparency. Until now we always used 255 (opaque) as alpha value. We set the colour to draw the second rectangle to blue by SDL_SetRenderDrawColor(). Notice that the fourth value is 128 (half-transparent) instead of 255 (opaque). So everything behind the blue rectangle, e.g. the cyan background, should therefore shine through. To generate a filled rectangle SDL_RenderFillRect() is used:

SDL_RenderFillRect(renderer: PSDL_Renderer; rect: PSDL_Rect): SInt32

The renderer and the rectangle of type PSDL_Rect are the parameters of this function. So we use “sdlRenderer” and “sdlRect1” again to draw the rectangle. This function returns 0 on success and the negative error code on failure.

The Blend Mode in SDL 2.0

But to be honest, even if you change the alpha value it will be opaque. This is because the blend mode is set to SDL_BLENDMODE_NONE by default. We need to change this to be able to use the alpha value as desired. SDL_SetRenderDrawBlendMode() is what we are looking for:

SDL_SetRenderDrawBlendMode(renderer: PSDL_Renderer; blendMode: TSDL_BlendMode): SInt32

First the renderer for which the blend mode has to be set is chosen. In our case it is “sdlRenderer” again. Then there are four blend modes available. Their description is taken from the official SDL 2.0 Wiki.

    • no blending
    • dstRGBA = srcRGBA
    • alpha blending
    • dstRGB = (srcRGB * srcA) + (dstRGB * (1-srcA))
    • dstA = srcA + (dstA * (1-srcA))
    • additive blending
    • dstRGB = (srcRGB * srcA) + dstRGB
    • dstA = dstA
    • color modulate
    • dstRGB = srcRGB * dstRGB
    • dstA = dstA

We are looking for alpha blending, so we use SDL_BLENDMODE_BLEND as argument for the blend mode. This function returns 0 on success and the negative error code on failure.

After doing so the result is rendered to the screen by SDL_RenderPresent() and shown for one second by SDL_Delay(). Both rectangles, the green one and the half-transparent blue one appear at the same time.

Spread Points Randomly using PSDL_Point

randomize is a Free Pascal procedure to initilize the random number generator. Imagine this as shaking the dice.

Again we use the “i” counter variable for a for-loop. The loop allocates memory for the 500 points of type PSDL_Point in the “sdlPoints1” array by new. PSDL_Point is a record which is shown here:

As expected, the PSDL_Point record has two values, the x/y coordinates of the point. Free Pascal’s random() function generates random numbers between 0 and the number which is used as argument substracted by one. So we generate 500 times a random x and y value between 0 and 499 and save them into the 500 SDL_Point records.

A grey colour is set by SDL_SetRenderDrawColor() for the points. To draw the points in the array “sdlPoints1” we use SDL_RenderDrawPoints().

SDL_RenderDrawPoints(renderer: PSDL_Renderer; points: PSDL_Point; count: SInt32): SInt32

This function returns 0 on success and the negative error code on failure. First you need to set the renderer, then just the first element of an array of PSDL_Point type and finally the number of points. Notice how we are not using a loop here to draw all 500 points by calling a certain function 500 times. Instead we just use an array of points and its first element. This way we save a lot of time at runtime, especially if you think of a real application where even more points have to be drawn. There are similar functions for lines, rectangles and filled rectangles. They are not used in the example but it may be interesting to know, so here they are:

SDL_RenderDrawLines(renderer: PSDL_Renderer; points: PSDL_Point; count: SInt32): SInt32

SDL_RenderDrawRects(renderer: PSDL_Renderer; rects: PSDL_Rect; count: SInt32): SInt32

SDL_RenderFillRects(renderer: PSDL_Renderer; rects: PSDL_Rect; count: SInt32): SInt32

As a hint, I had troubles using SDL_RenderDrawLines, I expected them to connect one point by another with lines to get kind of a polygon structure but instead the points just draw vertical lines to the bottom. Seems to me like a bug.

Finally all the memory reserved for points, the rectangle, the renderer and the window is free’d and SDL 2.0 shut down by SDL_Quit.

Congratulations, you just finished this chapter :-).

You may read

  • Case: Drawing for Dynamic Colouring
  • Understanding Colours in Computer Graphics

below, or you may directly skip to the next chapter .

← previous Chapter | next Chapter →

Case: Drawing for Dynamic Colouring

SDL2 drawing and images diagram

As an example when drawing can be very helpful, think of the following situation. You create a game, let’s say a racing game. There are different players. Of course, each player’s car has to have a different colour. There are generally two ways to achieve this:

1) You create several images with differently coloured cars and store them on your harddrive.

This is perfectly okay if you have a small number of cars (and colours) to be chosen. But what if you want the player to choose from a large variety of colours, 100 colours or more, or what if you want to let the player to choose the colour of his car by himself? Notice, in case of 16 bit colouring that means 65536 possibilities after all! Would you want to create that many images? In case of 32 bit colouring you have fantastic 4.29 billion colours!! Amazing, but you will never be able to create so many images in just one human being’s life. Furthermore, this would take up a lot of hard drive memory (4.29 billion times the file size of the car image) for just a simple car racing game. Look at the following image. It contains the discussed method from left to the middle. On the right to the middle is the solution :-).

Instead of having each car coloured as an image file, why not using just one image file of a car without colouring? It is kind of a template. Now you can easily ask the player what colour he prefers (and he may pick from 4.29 billion colours if necessary), and then you simply colour the car on the fly. This is the second way:

2) You create one template image on your harddrive and colour it during runtime of the program.

This is just one example where drawing is very helpful.

Understanding Colours in Computer Graphics

The colour is composed of four components, RGBA, that is red, green, blue and the alpha value. The physical screen consists of many small units. Every unit itself consists of three different coloured lights. These colours are red, green and blue. If you mix them up, you can get every other colour. These colours are mixed up additively. For example if you mix red and green you get yellow. For three colours that can be mixed with each other, there are eight combinations possible which lead to different colours (RGB, RG, RB, R, GB, G, B, all lights off). If you mix red, green and blue (all lights on, RGB), you get white, and if all lights are off, you get black. Some may say, white and black are no colours at all. Well, that is right but doesn’t matter here and to keep simpliness I will talk of colours even if I talk of black and white.

Your screen definitvly has more than eight colours, doesn’t it? The reason is, your screen isn’t just able to switch lights on or off. Besides it is able to differ the intensities of the lights. The more intensity levels you have the more colours you can display. The case that you have eight colours as discussed before means that you just have one intensity level, on or off. If your screen is in 8 bit mode every pixel on the screen has the possibility to display 2 power 8 colours. That are 256 different colours. Every of the three lights has therefore a certain amount of different light intensity levels. If you have 16 bit mode you have 2 power 16 and that are 65536 colours. Each light therefore has the appropriate amount of intensity levels. Since we prefer 32 bit mode, we have 4.29 billion different colours!

Chapter 8 Pt. 2 – Mouse handling

This is part 2 of the chapter about event handling. Mouse and window handling is treated here.

Let’s start with the full example code:

Mouse handling in SDL 2.0

If you got the basic concept of event handling, you will find that mouse handling and keyboard handling have a lot in common.

For mouse motions, mouse buttons and the mouse wheel there are three different mouse event structures: SDL_MouseMotionEvent, SDL_MouseButtonEvent and SDL_MouseWheelEvent.

Mouse motion handling in SDL 2.0

If you are moving the mouse, the SDL_MOUSEMOTION event is triggered. The record structure of the SDL_MouseMotionEvent is shown below:

Again there are the type_, the timestamp and the windowID fields. Nothing new here. The field which contains the mouse id. This is important if you have more than one mouse device attached to your computer. Think for example of a laptop with a touchpad area to move the mouse cursor and at the same time there is an usb mouse attached to the laptop. To distinguish between the two, you may retrieve their id’s.

The state field is known from the SDL_KeyBoardEvent structure. It may be a difference if you have a mouse button pressed and move the mouse or if you don’t have a button pressed. The most famous example is if you want to select a bunch of files on your desktop or in a folder. By the way, the state field encodes a number which is different depending on which buttons you pressed actually. This works similar to the key modifiers, if you keep two mousebuttons pressed while moving, the state is the sum of each individual mouse button state value. As an example for my mouse: No mouse button 0, left mouse button 1, right mouse button 4, middle mouse button 2, thumb button 8. If I keep pressed left and right mouse button 5 (sum 1 + 4).

The x and y fields contain the coordinate of the mouse cursor in pixels. These coordinates are relative to the window of the SDL 2.0 application. Keep in mind, the coordinates (0/0) correspond to the left upper corner. Positive x values are counted from left to right and positive y values are counted from top to bottom.

The fields xrel and yrel are used to determine how fast the mouse has been moved from one point to another. Let’s assume you move the mouse surcor from left to right in your application’s window. The first time you do it slowly, xrel might be 1, means, you just moved pixel from left to right between two mouse motion events. If you move fast, xrel might be 50, meaning that this time you moved by 50 pixels between two mouse motion events. Especially for game programming this can be a extremely important information. E.g., think of first person shooter, if the movement speed of the first person view would be independent of the actual movement of the mouse, this game wouldn’t make much sense.

To access these fields the event’s motion field has to be read out. In the example code the (x/y) coordinates and the relative positions xrel and yrel are read out by





and simply printed out to the screen. Let’s go for the next chunk of code.

Pressing a mouse button in SDL 2.0

As for the SDL_KeyBoardEvent, you would want to know if a mouse button and which one is pressed or released. If a mouse button is pressed, a SDL_MOUSEBUTTONDOWN event is triggered. On releasing a mouse button a SDL_MOUSEBUTTONUP event is triggered. It has SDL_MouseButtonEvent structure. Let’s have a look into the structure:

If you compare this structure to the structure of the SDL_MouseMotionEvent, you will find, only the two field xrel and yrel are gone and a new field, a crucial one to be clear, is new, which is button of 8 bit unsigned integer type.

I won’t discuss all the fields again we discussed for the SDL_MouseMotionEvent structure. Attention, if you compare the state field of the SDL_MouseButtonEvent, it works another way. It allows just for two values, SDL_PRESSED or SDL_RELEASED, as known from SDL_KeyBoardEvent. As a reminder: For the SDL_MouseMotionEvent, it represented that full state of all the buttons being pressed while mouse motion.

The button field allows to recognize which button has triggered the SDL_MouseButtonEvent. Each button of the mouse has its own index. As an example for my mouse they are as follows: Left mouse button 1, right mouse button 3, middle mouse button 2, thumb mouse button 4. Do not confuse these index numbers with the mouse button state values of the SDL_MouseMotionEvent structure. There can only be one button which triggered this event! Combinations as for the motion event are not possible. In the example code this value is just printed to the screen using


You see, to access the fields of this record you need to address the event’s button field. This mustn’t be confused with SDL_MouseButtonEvent’s button field discussed above.

The x and y fields contain the (x/y) coordinates when the mouse button (whose index is stored in field button) has been pressed (or released). This is crucial to know. What would an application be worth if you could recognized that a certain button has been pressed but you don’t know where exactly? Not shown in the code but you could access these fields by



The mouse wheel in SDL 2.0

If the mouse wheel is used a SDL_MOUSEWHEEL event is triggered. Let’s look into the corresponding SDL_MouseWheelEvent structure.

New fields here are the x and y field which do not correspond to the mouse cursor position this time. Instead of that they refer to the direction of the mouse wheel being scrolled. If you scroll the mouse wheel upwards or forward it will return 1, and if you scroll it backwards it will return -1. If you have a mouse wheel which can be scrolled horizontally, it will be similar. By the way scrolling a mouse wheel can be considered as pressing a button very quickly for that direction.

In the code, if a SDL_MOUSEWHEEL event is triggered, the y value is checked to be positive or negative. This decides if an upward or downward scrolling has happened and the corresponding value (1 or -1) will be returned and printed out. Anyway, could you guess what happens if anyone would use a mouse wheel that is scrolling horizontally? – The same block will be executed since a SDL_MOUSEWHEEL event is triggered. Instead of y being 1 or -1, it will be 0 but the x value will be 1 or -1. Nevertheless, the else-block will be executed since y is not greater than 0. So for the example program it will print out wrongly that an backward scroll has happened. Anyway, you get the idea.

Window handling in SDL 2.0

Modern applications are always run in windows. The famous operation system “Windows” by Microsoft even derived it’s name from this. The first task for most of SDL 2.0 applications is the creation of a window. The example code creates a window of width 500 pixels and height 500 pixels. It may be important to know if the user interacts with the application window. Whenever this happens a SDL_WINDOWEVENT is triggered.

If the an event of type SDL_WINDOWEVENT is triggered, the text message “Window event: ” is printed out.

To access the window event fields, you need to access the event’s window field. The field event contains the window event’s type information, hence what window event has been triggered.


In contrast to the keyboard and the mouse event we discussed before, the different event types are not distinguished by the type_ field but by an additional field event.

In the example code six different window event types are checked: SDL_WINDOWEVENT_SHOWN, SDL_WINDOWEVENT_MOVED, SDL_WINDOWEVENT_MINIMIZED, SDL_WINDOWEVENT_MAXIMIZED, SDL_WINDOWEVENT_ENTER and SDL_WINDOWEVENT_LEAVE. From the texts printed out you can guess when they get triggered. I think no further explanation is needed here.

By the way, there are more window event types which are shown a little bit later. Sometimes if one of these is triggered, only the text that a window event has been triggered is shown but without any further details since the example code doesn’t covers further treatment. Feel free to extent the code yourself.

Let’s have a look at the event structure of SDL_WindowEvent.

The fields type_, timestamp and windowID are known and have the same meaning as discussed before.

The field event stores an identifier (SDL_WindowEventID) to distinguish between different window events. Here they are listed and in brackets you find the window related action which has triggered them:

  1. SDL_WINDOWEVENT_SHOWN (window has been shown)
  2. SDL_WINDOWEVENT_HIDDEN (window has been hidden)
  3. SDL_WINDOWEVENT_EXPOSED (window has been exposed and should be redrawn)
  4. SDL_WINDOWEVENT_MOVED (window has been moved to data1, data2)
  5. SDL_WINDOWEVENT_RESIZED (window has been resized to data1xdata2; this is event is always preceded by SDL_WINDOWEVENT_SIZE_CHANGED)
  6. SDL_WINDOWEVENT_SIZE_CHANGED (window size has changed, either as a result of an API call or through the system or user changing the window size; this event is followed by SDL_WINDOWEVENT_RESIZED if the size was changed by an external event, i.e. the user or the window manager)
  7. SDL_WINDOWEVENT_MINIMIZED (window has been minimized)
  8. SDL_WINDOWEVENT_MAXIMIZED (window has been maximized)
  9. SDL_WINDOWEVENT_RESTORED (window has been restored to normal size and position)
  10. SDL_WINDOWEVENT_ENTER (window has gained mouse focus)
  11. SDL_WINDOWEVENT_LEAVE (window has lost mouse focus)
  12. SDL_WINDOWEVENT_FOCUS_GAINED (window has gained keyboard focus)
  13. SDL_WINDOWEVENT_FOCUS_LOST (window has lost keyboard focus)
  14. SDL_WINDOWEVENT_CLOSE (the window manager requests that the window be closed)

This list is based upon information found at the SDL 2.0 wiki.

If you read through the list carefully you will notice the mention of data1 and data2 which rather explains their occurance in the event structure :-)! They need to be read out for SDL_WINDOWEVENT_MOVED and SDL_WINDOWEVENT_RESIZED to get the new window position or dimensions.

At the moment I’m not sure why for window events the distinction between the individual window events (e.g. SDL_WINDOWEVENT_MOVED, SDL_WINDOWEVENT_RESIZED, and so on) is not done by the type_ field as for keyboard, mouse and other events, but rather by the additional event field.

Not much to learn in the final part. The loop is delayed by 20 milliseconds for better recognizability of the text output.

If the loop is left, the event pointer gets free’d, the SDL 2.0 window gets destroyed and SDL 2.0 quit. That’s it :-)!

Touchscreen events, Joystick events and many more!

This chapter covered keyboard, mouse and window events in some detail. Keep in mind, SDL 2.0 has much more to show! – There are many more events you can use for application development. They basically cover any modern type of interaction you could wish for. This includes touchscreen events (important for smartphone development), joystick events (game console development), and even a dropfile event (drag and drop files) and more.

← Chapter 8, Part 1 | next Chapter →

Chapter 8 Pt. 1 – Event handling, Keyboard handling

Last updated on February 9th, 2019

What’s an event and event handling in programming?

Event handling is a major concept in game and application programming. It allows for the user to interact with your program. Whenever you move your mouse cursor, press or release a key on the keyboard or use a touch screen, all these interactions are recognized as so-called events.

Events in SDL 2.0, SDL_Event

In SDL 2.0 whenever an event occurs, for instance a key gets pressed on the keyboard, all the information related to that specific event is stored in a SDL_Event record. Depending on the event type (e.g. mouse motion, key pressed on a keyboard, maximizing the application window) there are very different fields which can be accessed. For a mouse motion you can read out the x and y position of the cursor whereas there is no sense in having x and y values for a pressed key on the keyboard, but to know which specific key has been pressed on the keyboard.

Event types available in SDL 2.0

There are many more types of events than a mouse motion and a key being pressed on a keyboard. Think of using a joystick, using a touchscreen, minimizing/maximizing the application window, and so forth. There are plenty of different events that could occur.

All these event types have certain names, e.g. the event type which indicates a mouse motion is called SDL_MOUSEMOTION. The full list according to the official SDL 2.0 documentation is:

Event types, Event structure and SDL_Event field
Event type Event structure SDL_Event field
SDL_AudioDeviceEvent adevice
SDL_ControllerButtonEvent cbutton
SDL_ControllerDeviceEvent cdevice
SDL_DollarGestureEvent dgesture
SDL_TouchFingerEvent tfinger
SDL_KeyboardEvent key
SDL_JoyButtonEvent jbutton
SDL_JoyDeviceEvent jdevice
SDL_MOUSEMOTION SDL_MouseMotionEvent motion
SDL_MouseButtonEvent button
SDL_MOUSEWHEEL SDL_MouseWheelEvent wheel
SDL_MULTIGESTURE SDL_MultiGestureEvent mgesture
SDL_QUIT SDL_QuitEvent quit
SDL_TEXTEDITING SDL_TextEditingEvent edit
SDL_TEXTINPUT SDL_TextInputEvent text
SDL_WINDOWEVENT SDL_WindowEvent window
Other events SDL_CommonEvent none use .type
Source: SDL 2.0 Documentation: SDL_Event

This list is overwhelmingly long but don’t worry, as soon as you get the concept behind events you will easily understand which of these event types will play a role for the applications you like to develop. The most important events are covered by this tutorial in detail anyway. You will be able to work with the remaining events once you got the concept.

In contrast to SDL 1.2 there are some event types gone and many new types available in SDL 2.0 which are useful to use new forms of interaction between the user and the application (e.g. touch screen technology).

What is the difference between event type, event structure and the event field?

In the table above you’ll notice the first column covers the event type. It determines which type of event occured, e.g. a key is pressed down on the keyboard (SDL_KEYDOWN).

The event structure in the second column is the record structure which is dependend upon the event type. As discussed before, a pressed key will need a record structure which stores the key identifier rather than x,y-coordinated (which would in turn be necessary for a mouse motion). Each event type has a certain apropriate (event) record structure to hold the event information.

Many event types can share the same event structure. The event types SDL_KEYDOWN and SDL_KEYUP which are generated by pressing or releasing a key share the same event structure SDL_KeyboardEvent since the information are the same, e.g. the key identifier.

The third column shows the SDL_Event field name to access the event specific fields. In case of an event type SDL_KEYDOWN the event structure is SDL_KeyboardEvent. The specific information, e.g. the key identifier, is accessible via the field key in the SDL_Event record.

This may sound confusing. Later on the relation is discussed in more detail. Let’s right proceed into the code.

The result will not be seen in the actually SDL 2.0 window but in the command line window (which usually is showing up along with the SDL 2.0 window on Windows environments).

Chapter 8 - result

The initial lines of code are:

The program is called “Chapter8_SDL2”. Since event handling is a basic feature of SDL 2.0, no further units except for SDL2 itself necessary.

We need three variables. “sdlWindow1” is necessary to create a window as known from previous chapters. This time we won’t draw anything to it but use it to recognize events (e.g. mouse clicks into the window).

The SDL_Event variable “sdlEvent” stores the events generated by the user of the application. It is of pointer type PSDL_Event. Then there is a simple Pascal boolean variable “exitloop” which is set to false since we don’t want to leave the program loop initially. Also we have a “text1” string variable we will need to demonstrate text input later.

Nothing new for the following lines, SDL 2.0 is initilised and the SDL 2.0 window is created.

Since “sdlEvent” is a pointer type variable we need to allocate some memory. This is done by the new command, as known.

First a while-do loop is started which will run as long as the variable “exitloop” is false. If it is changed to true the loop will be exited. (This is triggered by pressing ESC, later this is discussed in detail.)

Within the outer loop the first thing is to poll for an event, which is done by function SDL_PollEvent.

This function returns integer value 1 if one or more events are in the queue. The event data is allocated to the SDL_Event variable and deleted from the queue. If there are no events waiting, it returns 0 and the event variable is filled with nil instead of specific event data.

If there is an event waiting, its information are fed to “sdlEvent” and 1 is returned. The inner while loop is running until all events in the queue are treated. This will print out a text saying “Event detected” and, more important, check for the event type!

Don’t use an if-clause (instead of the inner while loop) to check for the events because that means we only check once a event each every cycle of the outer loop. By combining two while loops and check for all the events in the inner loop we can treat every event occured for this program loop cycle.

The type_ field

The event type can be read out from the field type_, hence we check for the type in sdlEvent^.type_ by a case-statement.

If _type is a SDL_KEYDOWN event a begin-end block is entered. There are several writeln output lines. Let’s discuss them one after another.

In the first line the SDL (virtual) key code is returned, which is represented by an integer value. For special keys (e.g. F-keys, Insert, …) these values often range beyond the scope of SmallInt (-32768 to 32767) or Word (0 to 65535) variables, which you should keep in mind if you intend to return these values to variables. The SDL virtual key code can be accessed by


Let’s try to break this down a little bit. The event is stored in sdlEvent which is of pointer type so to access the content we need sdlEvent^. In the keyboard event there is a field keysym which itself is a record. The SDL virtual key code is stored in the field sym of the keysym record. Don’t worry if this sounds kind of confusing, in the next part we treat these two records (SDL_KeyboardEvent record and keysym record) in detail.

Most of the key codes have a name, e.g. “Escape” for the escape key. In the next line of the code, the function SDL_GetKeyName is used to get the name of the key whose key code we found:

function SDL_GetKeyName(key: TSDL_ScanCode): PAnsiChar

The other way round it is also possible by this function:

function SDL_GetKeyFromName(const name: PAnsiChar): TSDL_KeyCode

This is not shown in the code though.

The scancode of a key is another representation. The details about the difference between key codes and scancodes are discussed a little bit later. Anyway, the scancode is stored in the scancode field of the keysym record. So it can be accessed by:


and its name can be read out by

function SDL_GetScancodeName(scancode: TSDL_ScanCode): PAnsiChar.

Also here you can do it the other way round by

function SDL_GetScancodeFromName(const name: PAnsiChar): TSDL_ScanCode.

For completion and your information, it is possible to get the key code from the scancode and vice versa. The functions to use are:

function SDL_GetKeyFromScancode(scancode: TSDL_ScanCode): TSDL_KeyCode


function SDL_GetScancodeFromKey(key: TSDL_KeyCode): TSDL_ScanCode.

You see, there is a strong relation between the two but they are not the same. Lets have a short example of what happens if you press a key:

Keycodes and Scancodes
Keycodes and Scancodes

The tutorial code returns these key- and scancodes for the “Q”-key, the escape key and the return key. As you can see the codes do not only differ between different keys but also for the same key, e.g. the key code for the escape key is 27 but the scanscode is 41. Anyway, the key names seems to be consistent. Later we will see an example where even the names differ.

The last line returns the code value of key modifiers. Key modifiers are keys which literally modify them. E.g., if you press a letter key while holding the shift key, usually you modify the letter to be the capital letter. Typical key modifiers are shift, ctrl and alt. The field which stores the key modifier value is called _mod. Later we will discuss this field more in detail.

We check for the value of the key code by a case-statement with sdlEvent^.key.keysym.sym. If we know the key code of a certain key, we may check for this key and react accordingly. First, we check if the event’s key code is SDLK_ESCAPE since this is the key code of the escape key (ESC). If so, the variable exitloop is set to true to stop the outer while loop and exiting the program.

Every key code is represented by the key code constant (e.g. SDLK_ESCAPE), a decimal value (27 here) and a hexadecimal value ($001B here).  You may check the key codes in the following (official) SDL 2.0 key code lookup table:

https://wiki.libsdl.org/SDLKeycodeLookup or SDL 2.0 Key code lookup table (Backup hosted here)

In the fifth row the escape key key code is found.

In this table you find additionally to the decimal value, the hexadecimal value. You may try to use $001B instead of 27. This will do the trick either :-)! Also there is a character representation shown if possible.

If the the F1-key is pressed we would like to turn on or off the text input mode. This time we do not use a decimal key code to recognize the key but rather a constant representation (SDLK_F1). You could guess you have the choice and could use either the decimal value, the constant representation (what about SDLK_ESCAPE in the case before?) or the hexadecimal representation. – SDLK_ESCAPE even exists(!) but guess what, that doesn’t work. For some special keys this works like shown for the F1-key, for most of the other keys it doesn’t work (you will find that most keys are stored as string constants so the compiler will complain that they are of wrong type). So for most keys you have to look up the decimal representation and do as shown.

In the same way we check if the F1 key got pressed by checking for SDLK_F1. If F1 got pressed it is checked if the so called Text input mode is active by

function SDL_IsTextInputActive: TSDL_Bool.

If it is active, it gets deactivated by

procedure SDL_StopTextInput

and if it is not active, it gets activated by

procedure SDL_StartTextInput.

Finally a short text is returned which states that the Text input mode has been changed. More about the input mode later.

Last but not least, if _type is a SDL_KEYUP event, we know a key has been released, hence it physically moves up on the keyboard. We just print out “Key released”, we don’t care what exactly key is released here.

The keyboard events SDL_KEYDOWN and SDL_KEYUP

Let’s have a look at the structure of the keyboard event record and discuss the fields from top to bottom:

type_ is an unsigned 32 bit integer (hence UInt32) value which determines what exact type of event you have. As usual the integer values are represented by constants, here SDL_KEYDOWN (if pressed down) and SDL_KEYUP (if key has been released). They share the same overall event record structure (SDL_KeyboardEvent). As a sidenote, all the SDL 2.0 events have a type_ field for obvious reason.

The next field timestamp obviously contains a timestamp of integer type which is used internally by SDL 2.0 to resolute the sequence in which all the events were triggered. All SDL 2.0 events have the timestamp field.

The windowID field is necessary to distinguish between events raised from different SDL 2.0 windows if there is more than one. Let’s assume your program has two SDL 2.0 windows, window1 and window2. These two windows have certain constant id’s allocated by SDL 2.0. Now, if you have the focus on window1 (meaning the active window is window1) and press a key, the event’s windowID contains the specific id for window1. If the active SDL 2.0 window is window2 and you press a key, the specific id of window2 will be present in windowID. This way you can easily distinguish for which window the program should react to the keyboard event, e.g. a pressed key. Anyway, the capability to handle more than one window has been introduced by SDL 2.0, so you can imagine that for many programs and if you do not have more than one window in your program, you may ignore this field. The windowID field isn’t present (and necessary) for all the events SDL 2.0 provides.

The 8 bit integer state field may be read out to get the state of the key (pressed or release) which are encoded by SDL_PRESSED and SDL_RELEASED. You may be a little bit confused what the difference between the pair SDL_PRESSED and SDL_RELEASED and the pair SDL_KEYDOWN and SDL_KEYUP is. Essentially they have the same meaning for a key of a keyboard. Formally, the difference is that SDL_KEYDOWN and SDL_KEYUP are two different event types whereas SDL_PRESSED and SDL_RELEASED are two different key states. In the case of a pressed key on a keyboard the state is kind of redundant because if you get a SDL_KEYDOWN event you already know that a key was pressed and to read out the state (which will be SDL_PRESSED) is unnecessary. Anyway, the state field seems to be introduced for completeness, since for other event types (e.g. mouse events) there is a huge difference if you move the mouse and have mouse buttons pressed or released.

_repeat let’s you know if the corresponding key is in repeat mode. For most operation systems the repeat mode kicks in after a short delay when you keep a key pressed. You may try out to open up a simple text editor. If you press any key that has a letter (e.g. “a”-key), in the text editor you will see an “a”. If you keep the key pressed after a short delay the repeat mode kicks in and rapidly several further a’s are coming up. If you are in repeat mode for a certain key, repeat_ has a value different from 0 (most likely 1) and otherwise it will be 0. Especially for games, you may want to turn off the initial delay if you keep a key pressed and let the constant repeat mode kick in without delay. In SDL 1.2 I described here how to do it simply by using function called SDL_EnableKeyRepeat, this function is obsolete and does not exist in SDL 2.0 anymore!

A simple solution to the “repeat-delay”-problem: Instead of looking for the actual event being repeatedly triggered by an key event, use a switch which gets turned on if the key down event is occuring and which is turned off if the key up event is occuring. Example: Let’s assume you have a spaceship which should move left on pressing the “a”-key. Instead of changing it’s coordinates only once when the key down event is triggered, you start a switch (e.g. MoveSpaceshipLeft := true). The trigger is treated independently of the events treatment somewhere in the main game loop. As soon as the key up event is triggered for the “a”-key, the switch is turned off (e.g. MoveSpaceshipLeft := false).

I don’t know about meaning of the fields padding2 and padding3. Maybe they are kind of place holders for future developments or used internally.

Last but not least a very important field. The field keysym of SDL_KeySym type contains several information about the identity of the pressed key. In most cases we need to know which exact key has been pressed. Let’s have look into the SDL_KeySym record:

As you can see the first two fields contain keycode representations for identitifcation of the key pressed or released. Even though both fields seem to have again special records, namely SDL_ScanCode and SDL_KeyCode, they actually consist of only one field each, DWord (integer type) for SDL_ScanCode and SInt32 (integer type) for SDL_KeyCode.

You may have a look into the SDL 2.0 scancode lookup table: https://wiki.libsdl.org/SDLScancodeLookup or SDL 2.0 Scancode lookup table (Backup)

The difference between scancode and key code

The difference is that the scancode refers to a specific physical location of a key on the keyboard. The scancode is referenced to the typical US keyboard layout (QWERTY layout). The term “QWERTY” just refers to the the first six letters from left to right in the first row with letters on a typical US keyboard. For example: The German keyboard layout (QWERTZ layout) is similar to the US one (for most of the letter keys), though the “Y”-key and the “Z”-key have exactly opposite positions (hence QWERTZ for the German layout in contrast to QWERTY for the US layout). If I press the “Z” key on the German keyboard, the returned scancode will represent the “Y” key since the position of the key (independent of the layout) is equal to the position of the “Y” key on an US keyboard. Scancodes are layout-independent.

The key code refers to the virtual representation of the key according to the keyboard layout. Here you consider the layout, hence key codes are layout-dependent. As discussed before the scancode for the “Z”-key on a German keyboard will return that the “Y”-key has been pressed since the key has the location of the “Y”-key of an US keyboard. But the key code will not return it is the “Y”-key but it will correctly return that the “Z”-key has been pressed. The red marked output in the following image illustrates the result if the”Z” key is pressed on a German keyboard.

Difference Key code and Scancode

You may say, then I should always use keycodes to read out text input, right? – Wrong :-). In fact since SDL 2.0 it depends strongly on what you actually want to do. If you want to get a text or a single character from the user, you should neither use scancodes nor use key codes (anymore). (In former SDL 1.2 key codes or the unicode representation were indeed the preferable choice.) Treatment of real text input is not done this way anymore. We will discuss this case later. Anyway, this quote from the SDL 1.2 to SDL 2.0 migration guide sums it up excellently:

Use SDL_KEYDOWN to treat the keyboard like a 101-button joystick now. Text input comes from somewhere else.

Think of the famous T-shaped WASD key arrangement (arrangement of the four keys “W”, “A”, “S” and “D”) in the US layout, even if you keyboard without any latin letters, you may want to use these four keys to move a game character forward (“W”), left (“A”), backward (“S”) or right (“D”). The labeling of the keys doesn’t matter in that case and the keys are not used to input some text.

Again, keep in mind:

Never use key codes or scancodes to read out text input in SDL 2.0 (anymore)

The remaining _mod field is a 16 bit unsigned integer (corresponds to Pascal’s Word) and represents key modifiers (ctrl, alt, shift, num lock, caps lock, …). If one or more key modifiers are pressed the _mod value has a unique number for each key or the key combination. For example, the left shift key has the decimal value 1, the right shift key has the value 2, the left control (ctrl) key has the value 64, the right ctrl key has the value 128. If the left shift and ctrl key are pressed at the same time the _mod vlue will be 65 (1 + 64). Let’s assume you want to have your application to be quit by the user pressing the ctrl key and “Q”. So you read out the key code for “Q” and check if _mod is 64 or 128. Since there doesn’t seem to exist a table for key modifiers, here the most important ones:

Modifier key decimal values
Modifier key UInt16 value
Left shift 1
Right shift 2
Left ctrl 64
Right ctrl 128
Left alt 256
Right alt 576 (64 + 512?)
Caps lock 8192
Num lock 4096

The unicode field is deprecated and will not be discussed here. By the way, also procedure SDL_EnableUnicode is gone, which turned on the unicode mode.

Text input in SDL 2.0

Let’s have a look in the next part of the code and learn about the correct text input in SDL 2.0.

With SDL 2.0 there is a new event type named SDL_TEXTINPUT. This one has been explicitly introduce to SDL 2.0 to make text input more flexible and easy.

Let’s have a look into the record structure of SDL_TextInputEvent.

In contrast to the event structure SDL_KeyBoardEvent where two event types (SDL_KEYDOWN and KEYUP) were available, at the moment for the event structure SDL_TextInputEvent only one event type, SDL_TEXTINPUT, is possible.

The timestamp and windowID field have been discussed earlier in great detail. They contain some general information about when this event was triggered and which application window had the focus when the event was triggered. You may scroll up to get more information about this.

Unique about this event structure is the field text which is an array of char elements. This array contains from 0 to SDL_TEXTINPUTEVENT_TEXT_SIZE char elements. SDL_TEXTINPUTEVENT_TEXT_SIZE has a size of 32 by default. Attention here, this doesn’t mean you can only have 32 characters in texts or something like this! It means that in the moment this event is triggered not more than 32 characters are submittable to the event. Keep in mind though, if you use a Western language with Latin characters you always only submit one chracter at a time by each key stroke.

So why there are 32 possible characters anyway then? – To understand this, it would be necessary to go deeper into the construction of non-Western languages and how words and sentences are constructed. The massive amount and complexity of the way words and sentences are constructed makes it so that these are constructed beforehand before they are submitted to the text field of SDL_TextInputEvent. These constructs are not simply created by just a single key stroke which could be read out. For these constructs there are 32 chars reserved. (I would be glad to give a more detailed explanation here, please feel free to contact me to improve this paragraph.)

Let’s go back to the code. If a SDL_TEXTINPUT event has been found, its record (SDL_TextInputEvent) can be accessed by text. Its text input information is stored in the text field which we have seen recently. That is why we can use


to access the text input information. In the first line of the code we simply print out the content of the text field. The string variable “text1” is used to store the found character and add to the characters which have been found before. This string is also printed out.

Note how special characters (e.g. currency symbols, French accent symbols, the German “ß” symbol, …) and capital letters are recognized correctly. Try this with key codes or scancodes (it is a pain).

Note also that function keys ( F1, Backspace, …) are not recognized as characters. It is your responsibility for them to work the desired way :-).

← previous Chapter | next Chapter →