Rediscovering Sensible World of Soccer

Back in the days when I actually had time to play computer games, I was a fan of three main genres: RPG, strategy, and FPS. The sports genre never really captured my interest, with maybe a couple of notable exceptions. One of these was Sensible World of Soccer.

swos-goal

This week I treated myself to playing Sensible World of Soccer ’96/97, which I had bought off GOG.com. Although this is not the classic I grew up playing (which was Sensible World of Soccer ’95/’96 European Championship Edition), it’s practically identical to it: the only noticeable difference is that some players have moved between teams.

Sensible World of Soccer (SWOS) is a game where you can both manage a football team and play football. It offers a great deal of flexibility. If you just want to play football, you can choose all sorts of friendly matches or tournaments to play. On the other hand, if you just want to manage your team, you can do that, and see only the game results. You can both manage the team and control it while playing football games. And you can even do neither: watch a game played by computer-controlled teams.

 

swos-menu

The management aspect is menu-driven. When you start a career (which lasts a maximum of four seasons), you are given control of every aspect of your team, including organising and training your team, buying and selling players, keeping track of the match schedule, watching the club’s profit/loss, goal statistics, and even watching the progress of various tournaments in the world.

swos-team

Managing your team alone is complex enough to give the game a great deal of replayability. Each player has a position in which he’s comfortable (e.g. defence, attack, etc). Each player also has a financial value and a set of top skills (e.g. speed, shot power, ball control, etc) denoted by the yellow letters in the screenshot above. It’s not all as easy as it looks, however. A player may thrive or stagnate depending on his position, and his value may change accordingly. Financial value also does not always accurately reflect a player’s skill. So trying out different players in different position is key to forming a functional team.

swos-strategy

Other than that, before and during each match, you can refine your team’s formation, allowing you to try different strategies to adapt to demanding situations.

swos-goal3

The gameplay itself is incredible fun. You control one player at a time while all the rest move automatically. This is where the player skills pose a challenge: depending on whether your player is good at speed, ball control, passing, or whatever, you may opt to pass the ball, dribble past your opponents, or shoot the ball into the goal. Controlling the ball when shooting is a skill in itself; you usually use the arrows to indicate a direction (e.g. top-right), but you can actually use different key combinations after shooting to give the ball a curved effect or elevation, allowing you to score some pretty spectacular goals.

swos-goal2

Once you go beyond the basic skills, you can get creative and have loads of fun, scoring in incredible ways and posing different challenges. For example, instead of just shooting into the goal, you can cross to another player and score with a tackle or header. You can score from a distance, or pass your way around the goalkeeper, and just run in with the ball. Or my personal favourite: get the goalkeeper and defenders to follow you, run the train around for a bit, and then just deposit the ball at the back of the net.

swos-beating

You might want to start with a pretty good team, such as Manchester United or Bayern Munich. But as you get more familiar with the game, it’s a fun challenge to start with a crappy team and buy better players. That allows you to pretty much dominate a league, and give your opponents a beating. For example, the above 12-0 in a typical 3-minute (real time) career game is a pretty nice feat, and a challenge to achieve.

SWOS is a simple game but gives you a world of opportunities to try out. Career games last 3 minutes of real time, but friendlies may be 3, 5, 7 or 10 minutes (you choose the setting). This means you can play the game for just a few minutes, or spend several hours at a time.

If you’re not put off by the dated graphics, and love some genuinely fantastic gameplay, give this game a go.

ASP .NET Web API Dependency Injection with Ninject

In this article, we’re going to set up dependency injection in a new ASP .NET Web API project, using Ninject as our IoC container.

For starters, do the following:

  1. Create a new Web API project.
  2. Install the Ninject.Web.WebApi NuGet package.
  3. Install the Ninject.Web.WebApi.WebHost NuGet package.

Since I need an injectable service to demonstrate this with, I’m also going to install my very own .NET Settings Framework via the Dandago.Settings NuGet package.

When you installed Ninject.Web.WebApi.WebHost, it added a NinjectWebCommon.cs class under the App_Start folder:

ninjectwebapi-ninjectwebcommon

Ignore the boilerplate crap and look for the RegisterServices() method. There, you can set up your dependencies. In my case, it looks like this (needs namespace Dandago.Settings):

        /// <summary>
        /// Load your modules or register your services here!
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        private static void RegisterServices(IKernel kernel)
        {
            kernel.Bind<IConfigKeyReader>().To<AppSettingReader>();
            kernel.Bind<IConfigKeyProvider>().To<ConfigKeyProvider>();
        }     

Great! Now, let’s test it. Find ValuesController and at the following code at the beginning:

        private int x;

        public ValuesController(IConfigKeyProvider configKeyProvider)
        {
            this.x = configKeyProvider.Get<int>("x", 5);
        }

Run it, and we should hit the breakpoint when going to /api/values:

ninjectwebapi-breakpointhit

It’s working, and that’s all you need.

In case it wasn’t that smooth, however, here are a couple of things that might have gone wrong.

ninjectwebapi-parameterless-constructor

If you’re getting the above error complaining about not having a parameterless public constructor, then you probably forgot to install the Ninject.Web.WebApi.WebHost package.

ninjectwebapi-activationexception

If on the other hand you went ahead and installed Ninject.Web.WebApi.WebHost first, that brings in an older version of the Ninject.Web.WebApi package, causing the above ActivationException. The solution is to upgrade Ninject.Web.WebApi.

Lessons Learned from the Patreon Security Breach

Patreon is a popular crowdfunding platform, providing “recurring funding for artists and creators”. I was considering using it myself. I’m glad I didn’t.

Almost two months ago, Patreon suffered a security breach, and several gigabytes of data including a copy of their production database and their source code were leaked on the internet. An article at Ars Technica covers some of the details of the breach.

As I read the press release from Patreon about this incident, my feeling was of utter disbelief, particularly when reading these two points (emphasis mine):

  • “The unauthorized access was confirmed to have taken place on September 28th via a debug version of our website that was visible to the public. Once we identified this, we shut down the server and moved all of our non-production servers behind our firewall.
  • “There was no unauthorized access of our production servers. The development server included a snapshot of our production database, which included encrypted data.”

I’m not sure whether I need to explain why having your development environment publicly accessible, and why using production data in your development environment, are both very stupid things to do. Either way, now I don’t need to explain that. What happened to Patreon shows exactly why no one in his right state of mind would do this.

Further down, Jack Conte, CEO/Co-founder of Patreon, writes:

“I take our creators’ and patrons’ privacy very seriously.”

Sorry, but given what happened here, I find that very hard to believe. It doesn’t matter what steps are being taken to increase security. It’s already too late. People’s private data are now on the internet, and there’s no going back.

So if you want to spare your company a lot of embarrassment, here’s what you need to take away from this incident:

  • Keep your development environment isolated from your production environment.
  • Use dummy data, not production data, in your development environment.

Unity3D: Moving an Object with Keyboard Input

This is an updated version of the article originally posted on 24th May 2013 at Programmer’s Ranch. The original article used Unity 4.1.3f3, MonoDevelop, and 3D settings (2D in Unity didn’t exist back then), on Windows XP. This updated article uses Unity 5.2.2f1, Visual Studio 2015, and 2D settings, on Windows 10. Parts of the article have been rewritten, and syntax highlighting has been added.

The Unity3D game development engine has gained a lot of popularity in recent years. It supports various target operating systems, can be scripted in various languages, has a large community, and is always evolving. In this article, we’ll see how we can set up a simple project and have the player move an object by pressing the arrow keys on the keyboard.

The first thing you will need to do is to download and install Unity from their website. Once you’ve installed it and gone through the initial registration screens, you can opt to create a new project:

unity3d-input-startup

Click on the “New” button (shown in the image above). Here, you can choose the name and location of your new project, as well as whether to use 3D or 2D settings. For this particular article it doesn’t matter; the original article used 3D settings, while for this updated version I’ve done everything using 2D settings.

unity3d-input-newproject

Once you click “Create project“, your project will open in the Unity IDE.

From the GameObject menu, select 3D Object -> Cube to place a cube into the game world:

unity3d-input-create-cube

The cube will now be listed in the Hierarchy section – this section shows you a list of objects in your game world. You can also see the objects in the game world itself, in the left portion of the screen. If you click on the cube, you can see and manipulate its properties (e.g. position in the game world) in the Inspector:

unity3d-input-cube-properties

Right click on the Assets panel inside the Project section, and create a new C# script:

unity3d-input-create-cs-script

The script appears under Assets. Call the script “Movement“. Then, double-click the script to edit it. This will launch an external editor, probably MonoDevelop or Visual Studio:

unity3d-input-visual-studio

In the Update() method, add the following code:

if (Input.GetKeyDown(KeyCode.LeftArrow))
{
    Vector3 position = this.transform.position;
    position.x--;
    this.transform.position = position;
}

What are we doing here? In Unity, you can attach scripts to objects in order to make them do stuff. In our case, we will attach this script to the cube to be able to move it with the arrow keys.

The “this” in a Unity script refers to the object that the script is attached to (e.g. the cube). Each object has a transform property, which contains stuff like its position in the world. The position consists of a Vector3 which contains the x-, y- and z-coordinates of the object in the world.

The code above simply makes the object move left when the left arrow key is pressed, by varying the x-coordinate of the object’s position. While it would normally make sense to modify x directly, you can’t do that in Unity.

In the external editor, build the project to make sure it compiles (F8 in MonoDevelop, or Ctrl+Shift+B in Visual Studio). Then, switch back to Unity. Drag the Movement script onto the Cube object in the Hierarchy section. Once you click on the Cube in the Hierarchy section, you should see the Movement script in the Inspector:

unity3d-input-attached-script

Now, Press the Play button at the top of the Unity interface to start playing. The world view changes into an interactive rendering of the game:

unity3d-input-run-start

Test the game by pressing the Left Arrow key. Doing this should move the cube to the left:

unity3d-input-run-moved

Press the Play button again to stop the game. In the external editor, update the code to handle movement in all four directions:

if (Input.GetKeyDown(KeyCode.LeftArrow))
{
    Vector3 position = this.transform.position;
    position.x--;
    this.transform.position = position;
}
if (Input.GetKeyDown(KeyCode.RightArrow))
{
    Vector3 position = this.transform.position;
    position.x++;
    this.transform.position = position;
}
if (Input.GetKeyDown(KeyCode.UpArrow))
{
    Vector3 position = this.transform.position;
    position.y++;
    this.transform.position = position;
}
if (Input.GetKeyDown(KeyCode.DownArrow))
{
    Vector3 position = this.transform.position;
    position.y--;
    this.transform.position = position;
}

Press Play again in Unity to test it. Note that the cube returned to its original position. That is because each time you press Play, a new session is started with all objects having their default values.

So in this article, we have learned a few things about the Unity IDE, and we wrote a small script to move a cube in the game world. The intention was to get something working as quickly as possible, giving the reader a feel of working with Unity3D, while leaving details for other articles.

Pasting JSON/XML as Classes in Visual Studio

Note: This feature is available as from Visual Studio 2015.

REST and JSON together have revolutionised the way we expose and consume data in recent years. For this reason it has become increasingly common to need to integrate with REST services, and data itself is provided in either XML or JSON format. This typically involves creating a set of classes that match the data provided by the service, so that the application may take care of serialisation and deserialisation, and work with structured data.

Although you can create these data classes manually, Visual Studio provides a shortcut to generate classes from XML or JSON data. For instance, let’s say that we want to work with the data from the GitHub API:

github-api

We can easily generate a class for this by copying that data, and in Visual Studio going into Edit -> Paste Special -> Parse JSON As Classes:

paste-json-as-classes

And as if by magic, the following class gets generated:

        public class Rootobject
        {
            public string current_user_url { get; set; }
            public string current_user_authorizations_html_url { get; set; }
            public string authorizations_url { get; set; }
            public string code_search_url { get; set; }
            public string emails_url { get; set; }
            public string emojis_url { get; set; }
            public string events_url { get; set; }
            public string feeds_url { get; set; }
            public string followers_url { get; set; }
            public string following_url { get; set; }
            public string gists_url { get; set; }
            public string hub_url { get; set; }
            public string issue_search_url { get; set; }
            public string issues_url { get; set; }
            public string keys_url { get; set; }
            public string notifications_url { get; set; }
            public string organization_repositories_url { get; set; }
            public string organization_url { get; set; }
            public string public_gists_url { get; set; }
            public string rate_limit_url { get; set; }
            public string repository_url { get; set; }
            public string repository_search_url { get; set; }
            public string current_user_repositories_url { get; set; }
            public string starred_url { get; set; }
            public string starred_gists_url { get; set; }
            public string team_url { get; set; }
            public string user_url { get; set; }
            public string user_organizations_url { get; set; }
            public string user_repositories_url { get; set; }
            public string user_search_url { get; set; }
        }

Now, the class and property names might not be exactly the way you want them, and you might need to change some things, but this will still save you a lot of typing.

If you’re still not convinced, try it with a more complex example that involves nested data structures. For instance, let’s say we have this JSON data:

{
	"name" : "John Smith",
	"summary" : "Wannabe Superhero",
	"workexperience" : [{
			"title" : "Insurance Guy",
			"company" : "ABC Ltd.",
			"start" : "Feb 2015",
			"description" : "Current job, very bad"
		}, {
			"title" : "Cleaning Guy",
			"company" : "Super Clean Ltd.",
			"start" : "Jan 2013",
			"end" : "Jan 2015",
			"description" : "Dirty work",
			"recommendations" : [{
					"name" : "Boss guy",
					"position" : "Boss"
				}, {
					"name" : "Colleague girl",
					"position" : "Cleaning Girl"
				}
			]
		}
	]
}

With no effort whatsoever, you can get these classes generated for you:

        public class Rootobject
        {
            public string name { get; set; }
            public string summary { get; set; }
            public Workexperience[] workexperience { get; set; }
        }

        public class Workexperience
        {
            public string title { get; set; }
            public string company { get; set; }
            public string start { get; set; }
            public string description { get; set; }
            public string end { get; set; }
            public Recommendation[] recommendations { get; set; }
        }

        public class Recommendation
        {
            public string name { get; set; }
            public string position { get; set; }
        }

And there’s a similar function for XML.

You’re welcome.

Animations with Sprite Sheets in SDL2

This is an updated version of “SDL2: Animations with Sprite Sheets“, originally posted on 30th March 2014 at Programmer’s Ranch. The source code is available at the Gigi Labs BitBucket repository.

Many of the previous SDL2 tutorials have involved working with images. In this article, we’re going to take this to the next level, using a very simple technique to animate our images and make them feel more alive.

Our project setup for this article is just the same as in “Loading Images in SDL2 with SDL_image“, and in fact our starting code is adapted from that article:

#include <SDL.h>
#include <SDL_image.h>

int main(int argc, char ** argv)
{
    bool quit = false;
    SDL_Event event;

    SDL_Init(SDL_INIT_VIDEO);
    IMG_Init(IMG_INIT_PNG);

    SDL_Window * window = SDL_CreateWindow("SDL2 Sprite Sheets",
        SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, 0);
    SDL_Renderer * renderer = SDL_CreateRenderer(window, -1, 0);
    SDL_Surface * image = IMG_Load("spritesheet.png");
    SDL_Texture * texture = SDL_CreateTextureFromSurface(renderer, image);

    while (!quit)
    {
        SDL_WaitEvent(&event);

        switch (event.type)
        {
            case SDL_QUIT:
                quit = true;
                break;
        }

        SDL_RenderCopy(renderer, texture, NULL, NULL);
        SDL_RenderPresent(renderer);
    }

    SDL_DestroyTexture(texture);
    SDL_FreeSurface(image);
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    IMG_Quit();
    SDL_Quit();

    return 0;
}

sdl2-spritesheet-borders

This image is 128 pixels wide and 64 pixels high. It consists of 4 sub-images (called sprites or frames), each 32 pixels wide. If we can rapidly render each image in quick succession, just like a cartoon, then we have an animation! 😀
Now, those ugly borders in the image above are just for demonstration purposes. Here’s the same image, without borders and with transparency:

sdl2-spritesheet-actual

If we now try to draw the above on the default black background, we’re not going to see anything, are we? Fortunately, it’s easy to change the background colour, and we’ve done it before in “Handling Keyboard and Mouse Events in SDL2“. Just add the following two lines before the while loop:

    SDL_SetRenderDrawColor(renderer, 168, 230, 255, 255);
    SDL_RenderClear(renderer);

Now we get an early peek at what the output is going to look like. Press Ctrl+Shift+B to build the project, and then copy SDL2.dll, all the SDL_image DLLs, and the spritesheet into the Debug folder where the executable is generated.

Once that is done, hit F5:

sdl2-spritesheet-early

So at this point, there are two issues we want to address. First, we don’t want our image to take up the whole window, as it’s doing above. Secondly, we only want to draw one sprite at a time. Both of these are pretty easy to solve if you remember SDL_RenderCopy()‘s last two parameters: a source rectangle (to draw only a portion of the image) and a destination rectangle (to draw the image only to a portion of the screen).

So let’s add the following at the beginning of the while loop:

        SDL_Rect srcrect = { 0, 0, 32, 64 };
        SDL_Rect dstrect = { 10, 10, 32, 64 };

…and then update our SDL_RenderCopy() call as follows:

        SDL_RenderCopy(renderer, texture, &srcrect, &dstrect);

Note that the syntax we’re using to initialise our SDL_Rects is just shorthand to set all of the x, y, w (width) and h (height) members all at once.

Let’s run the program again and see what it looks like:

sdl2-spritesheet-clipped

Okay, so like this we are just rendering the first sprite to a part of the window. Now, let’s work on actually animating this. At the beginning of the while loop, add the following:

        Uint32 ticks = SDL_GetTicks();

SDL_GetTicks() gives us the number of milliseconds that passed since the program started. Thanks to this, we can use the current time when calculating which sprite to use. We can then simply divide by 1000 to convert milliseconds to seconds:

        Uint32 seconds = ticks / 1000;

We then divide the seconds by the number of sprites in our spritesheet, in this case 4. Using the modulus operator ensures that the sprite number wraps around, so it is never greater than 3 (remember that counting is always zero-based, so our sprites are numbered 0 to 3).

        Uint32 sprite = seconds % 4;

Finally, we replace our srcrect declaration by the following:

        SDL_Rect srcrect = { sprite * 32, 0, 32, 64 };

Instead of using an x value of zero, as we did before, we’re passing in the sprite value (between 0 and 3, based on the current time) multiplied by 32 (the width of a single sprite). So with each second that passes, the sprite will be extracted from the image at x=0, then x=32, then x=64, then x=96, back to x=0, and so on.

Let’s run this again:

sdl2-spritesheet-irregular

You’ll notice two problems at this stage. First, the animation is very irregular, in fact it doesn’t animate at all unless you move the mouse or something. Second, the sprites seem to be dumped onto one another, as shown by the messy image above.

Fortunately, both of these problems can be solved with code we’ve already used in “Handling Keyboard and Mouse Events in SDL2“. The first issue is because we’re using SDL_WaitEvent(), so the program doesn’t do anything unless some event occurs. Thus, we need to replace our call to SDL_WaitEvent() with a call to SDL_PollEvent():

        while (SDL_PollEvent(&event) != NULL)
        {
            switch (event.type)
            {
                case SDL_QUIT:
                    quit = true;
                    break;
            }
        }

The second problem is because we are drawing sprites without clearing the ones we drew before. All we need to do is add a call to SDL_RenderClear() before we call SDL_RenderCopy():

        SDL_RenderClear(renderer);

Great! You can now admire our little character shuffling at one frame per second:

sdl2-spritesheet-goodslow

It’s good, but it’s a bit slow. We can make it faster by replacing the animation code before the srcrect declaration with the following (10 frames per second):

        Uint32 ticks = SDL_GetTicks();
        Uint32 sprite = (ticks / 100) % 4;

Woohoo! 😀 Look at that little guy dance! (The image below is animated, but this seems only to work in Firefox.)

sdl2-spritesheet-animated

So in this article, we learned how to animate simple characters using sprite sheets, which are really just a digital version of a cartoon. We used SDL_RenderCopy()‘s srcrect parameter to draw just a single sprite from the sheet at a time, and selected that sprite using the current time based on SDL_GetTicks().

Displaying Text in SDL2 with SDL_ttf

This is an updated version of the article originally posted on 29th March 2014 at Programmer’s Ranch. The source code for this article is available at the Gigi Labs BitBucket repository.

In this article, we’re going to learn how we can write text in our window. To do this, we’ll use the SDL_ttf library. Setting it up is almost identical to how we set up SDL_image in “Loading Images in SDL2 with SDL_image“. You need to download the Visual C++ development libraries from the SDL_ttf homepage:

sdl2ttf-download

Then, extract the lib and include folders over the ones you have in your sdl2 folder. You should end up with an SDL_ttf.h in your include folder, and you should get SDL2_ttf.lib and a few DLLs including SDL_ttf.dll in your lib\x86 and lib\x64 folders.

In your Linker -> Input, you’ll then need to add SDL2_ttf.lib:

sdl2ttf-linker-input

Good. Now, let’s start with the following code which is a modified version of the code from about halfway through “Displaying an Image in an SDL2 Window“:

#include <SDL.h>

int main(int argc, char ** argv)
{
    bool quit = false;
    SDL_Event event;

    SDL_Init(SDL_INIT_VIDEO);

    SDL_Window * window = SDL_CreateWindow("SDL_ttf in SDL2",
        SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640,
        480, 0);
    SDL_Renderer * renderer = SDL_CreateRenderer(window, -1, 0);

    while (!quit)
    {
        SDL_WaitEvent(&event);

        switch (event.type)
        {
            case SDL_QUIT:
                quit = true;
                break;
        }
    }

    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    SDL_Quit();

    return 0;
}

The first thing we need to do in order to use SDL_ttf is include the relevant header file:

#include <SDL_ttf.h>

Then, we initialise the SDL_ttf library right after we call SDL_Init():

TTF_Init();

…and we clean it up just before we call SDL_Quit():

TTF_Quit();

Right after we initialise our renderer, we can now load a font into memory:

 TTF_Font * font = TTF_OpenFont("arial.ttf", 25);

TTF_OpenFont() takes two parameters. The first is the path to the TrueType Font (TTF) that it needs to load. The second is the font size (in points, not pixels). In this case we’re loading Arial with a size of 25.

A font is a resource like any other, so we need to free the resources it uses near the end:

TTF_CloseFont(font);

We can now render some text to an SDL_Surface using TTF_RenderText_Solid(). which takes the font we just created, a string to render, and an SDL_Color which we are passing in as white in this case:

 SDL_Color color = { 255, 255, 255 };
 SDL_Surface * surface = TTF_RenderText_Solid(font,
  "Welcome to Gigi Labs", color);

We can then create a texture from this surface as we did in “Displaying an Image in an SDL2 Window“:

    SDL_Texture * texture = SDL_CreateTextureFromSurface(renderer, surface);

And yet again, we should not forget to release the resources we just allocated near the end, so let’s do that right away:

 SDL_DestroyTexture(texture);
 SDL_FreeSurface(surface);

Now all we need is to actually render the texture. We’ve done this before; just add the following just before the end of your while loop:

  SDL_RenderCopy(renderer, texture, NULL, NULL);
  SDL_RenderPresent(renderer);

Okay, now before we actually run this program, we need to put our Arial TTF font somewhere where our program can find it. Go to C:\Windows\Fonts, and from there copy the Arial font into the Debug folder where your executable is compiled. This will result in several TTF files, although we’re only going to use arial.ttf. We will also need the usual SDL2.dll, along with the SDL_ttf DLLs (libfreetype-6.dll, zlib1.dll and SDL2_ttf.dll):

sdl2ttf-fonts

Great, now let’s admire the fruit of our work:

sdl2ttf-blocky2

Nooooooooooooooo! This isn’t quite what we were expecting, right? This is happening because the texture is being stretched to fill the contents of the window. The solution is to supply the dimensions occupied by the text in the dstrect parameter of SDL_RenderCopy() (as we did in “Displaying an Image in an SDL2 Window“). But how can we know these dimensions?

If you check out Will Usher’s SDL_ttf tutorial, you’ll realise that a function called SDL_QueryTexture() can give you exactly this information (and more). So before our while loop, let’s add the following code:

    int texW = 0;
    int texH = 0;
    SDL_QueryTexture(texture, NULL, NULL, &texW, &texH);
    SDL_Rect dstrect = { 0, 0, texW, texH };

Finally, we can pass dstrect in our call to SDL_RenderCopy():

SDL_RenderCopy(renderer, texture, NULL, &dstrect);

Let’s run the program now:

sdl2ttf-text2

Much better! 🙂

In this article, we learned how to use the SDL_ttf to render text using TTF fonts in SDL2. Using the SDL_ttf library in a project was just the same as with SDL_image. To actually use fonts, we first rendered text to a surface, then passed it to a texture, and finally to the GPU. We used SDL_QueryTexture() to obtain the dimensions of the texture, so that we could render the text in exactly as much space as it needed. We also learned how we can set up our project to use the same path regardless of whether we’re running from Visual Studio or directly from the executable.

Converting an Image to Negative using SDL2

The source code for this article is available at the Gigi Labs BitBucket repository. It’s the same as in the Grayscale article, plus the code for the Negative effect in this article.

In “Converting an Image to Grayscale using SDL2”, we manipulated the pixels of an existing image in order to convert it to grayscale. It is now very easy to add all sorts of effects by changing pixel values in different ways.

Another effect we can apply is the Negative of an image. This means that the dark areas become light, and the light areas become dark. For instance, if we have this image of a Canadian goose:

sdl2-negative-goose-positive

By using any image editor, say Irfanview, we can get the following Negative:

sdl2-negative-goose-negative

This is a very easy effect to apply. Since each of the Red, Green and Blue channels is represented by a byte, its value is in the range between 0 and 255. So we can compute the Negative by subtracting each value from 255. That way a bright value (e.g. 210) will become dark (e.g. 45), and vice versa.

Here’s the code for the Negative image effect:

            case SDLK_n:
                for (int y = 0; y < image->h; y++)
                {
                    for (int x = 0; x < image->w; x++)
                    {
                        Uint32 pixel = pixels[y * image->w + x];

                        Uint8 r = pixel >> 16 & 0xFF;
                        Uint8 g = pixel >> 8 & 0xFF;
                        Uint8 b = pixel & 0xFF;

                        r = 255 - r;
                        g = 255 - g;
                        b = 255 - b;

                        pixel = (0xFF << 24) | (r << 16) | (g << 8) | b;
                        pixels[y * image->w + x] = pixel;
                    }
                }
                break;

The code for Negative is very similar to Grayscale in that we’re looping over each pixel, calculating new values for Red, Green and Blue, and then applying the new value to the pixel.

Let’s try this out with a photo I took of Eldon House in London, Canada last September. Here’s the photo in its normal state:

sdl2-negative-eldon-positive

When I press the N key to apply the Negative effect, here’s the result:

sdl2-negative-eldon-negative

I can also press N again to apply Negative on the Negative, and end up with the original image again:

sdl2-negative-eldon-positive

That’s an important difference between Grayscale and Negative. Grayscale is an operation that loses colour information, and you can’t go back. Negative, on the other hand, is symmetric, and you can go back to the original image simply by applying the same operation again.

Introduction to Indexing and Search

This article was originally posted as “Indexing and Search (C#)” on 15th June 2013 at Programmer’s Ranch. It has been slightly updated here. The source code is available at the Gigi Labs BitBucket repository.

This article is about indexing and search: what is it that allows you to search through thousands of documents in less than a second?

In order to understand how indexing works, we will use an example where we have the following three documents:

doc1.txt contains:
The Three Little Pigs
doc2.txt contains:
The Little Red Riding Hood
doc3.txt contains:
Beauty And The Beast

Now, let’s say you want to find out which of these documents contain a particular word, e.g. “Little”. The easiest way to do this would be to go through each word in each document, one by one, and see if the word “Little” is in that document. Conceptually, we’re talking about this:

indexingsearch-donkeyway

Doing this in C# is very easy:

            string[] documents = { "doc1.txt", "doc2.txt", "doc3.txt" };

            string keyword = Console.ReadLine();

            foreach (string document in documents)
            {
                if (File.ReadAllText(document).Contains(keyword))
                {
                    Console.WriteLine(document);
                }
            }

            Console.ReadKey(true);

Remember to put in a using System.IO; at the top, to be able to use File. If you press F5 and test this program, you’ll see that it works:

indexingsearch-donkeyout

However, this method isn’t good because it will take longer as the documents get larger (more words) and more numerous (more documents).

The proper way to process search requests quickly is to build an index. This would look something like this:

indexingsearch-index

The index stores a list of all words, each with a list of documents that contain it. If you compare it with the first diagram, you’ll notice that we reversed the mapping of words and documents; this is why we call this an inverted index.

We can do this in C# by first building the index (remember to add using System.Collections.Generic; at the top):

            // Build the index

            string[] documents = { "doc1.txt", "doc2.txt", "doc3.txt" };
            Dictionary<string, List<string>> index = new Dictionary<string, List<string>>();

            foreach (string document in documents)
            {
                string documentStr = File.ReadAllText(document);
                string[] words = documentStr.Split();

                foreach (string word in words)
                {
                    if (!index.ContainsKey(word))
                        index[word] = new List<string>();

                    index[word].Add(document);
                }
            }

…and then using the index to search the documents quickly and efficiently:

            // Query the index

            string keyword = Console.ReadLine();

            if (index.ContainsKey(keyword))
            {
                foreach (string document in index[keyword])
                {
                    Console.WriteLine(document);
                }
            }
            else
                Console.WriteLine("Not found!");

            Console.ReadKey(true);

In this way, there is no need to search every document for the keyword each time the user wants to search for a word. The keyword is simply located in the index (if it exists), and a list of documents that contain it is immediately available:

indexingsearch-indexout

This was a simple proof of concept of how indexing and search works, but here are a few additional notes:

  • The index is usually built as documents are added to it, and then stored in one or more files (unlike in this program, where the index is rebuilt every time the program is run – that’s just to make the illustration easier).
  • Words such as “and” and “the” which are very common are called stop words and are normally excluded from the index.
  • It is common practice to make searches case insensitive, e.g. by converting indexed words and query keywords to lowercase.

This article presented the concept of indexing and how it is used to search for a single keyword. Although there are other techniques used in text search, indexing is definitely one of the most important, and has many applications including databases and text retrieval (e.g. search engines). A fundamental concept to remember is that the whole point of indexing is to make search fast!

Converting an Image to Grayscale using SDL2

This article was originally posted on 22nd February 2014 at Programmer’s Ranch. It has been slightly updated here. The source code is available at the Gigi Labs BitBucket repository.

In the previous article, “SDL2 Pixel Drawing“, we saw how to draw pixels onto a blank texture that we created in code. Today, on the other hand, we’ll see how we can manipulate pixels on an existing image, such as a photo we loaded from disk. We’ll also learn how to manipulate individual bits in an integer using what are called bitwise operators, and ultimately we’ll convert an image to grayscale.

The first thing we’re going to do is load an image from disk. Fortunately, we’ve covered that already in “Loading Images in SDL2 with SDL_image“, so refer back to it to set things up. We’ll also start off with the code from the article, which, adapted a little bit, is this:

#include <SDL.h>
#include <SDL_image.h>

int main(int argc, char ** argv)
{
    bool quit = false;
    SDL_Event event;

    SDL_Init(SDL_INIT_VIDEO);
    IMG_Init(IMG_INIT_JPG);

    SDL_Window * window = SDL_CreateWindow("SDL2 Grayscale",
        SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, 640, 480, 0);
    SDL_Renderer * renderer = SDL_CreateRenderer(window, -1, 0);
    SDL_Surface * image = IMG_Load("PICT3159.JPG");
    SDL_Texture * texture = SDL_CreateTextureFromSurface(renderer,
        image);

    while (!quit)
    {
        SDL_WaitEvent(&event);

        switch (event.type)
        {
            case SDL_QUIT:
                quit = true;
                break;
        }

        SDL_RenderCopy(renderer, texture, NULL, NULL);
        SDL_RenderPresent(renderer);
    }

    SDL_DestroyTexture(texture);
    SDL_FreeSurface(image);
    SDL_DestroyRenderer(renderer);
    SDL_DestroyWindow(window);
    IMG_Quit();
    SDL_Quit();

    return 0;
}

You see, the problem here is that we can’t quite touch the texture pixels directly. So instead, we need to work a little bit similarly to “SDL2 Pixel Drawing“: we create our own texture, and then copy the surface pixels over to it. So we throw out the line calling SDL_CreateTextureFromSurface(), and replace it with the following:

    SDL_Texture * texture = SDL_CreateTexture(renderer,
        SDL_PIXELFORMAT_ARGB8888, SDL_TEXTUREACCESS_STATIC,
        image->w, image->h);

Then, at the beginning of the while loop, add this:

        SDL_UpdateTexture(texture, NULL, image->pixels,
            image->w * sizeof(Uint32));

If you try and run program now, it will pretty much explode. That’s because our code is assuming that our image uses 4 bytes per pixel (ARGB – see “SDL2 Pixel Drawing“). That’s something that depends on the image, and this particular JPG image is most likely 3 bytes per pixel. I don’t know much about the JPG format, but I’m certain that it doesn’t support transparency, so the alpha channel is out.

The good news is that it’s possible to convert the surface into one that has a familiar pixel format. To do this, we use SDL_ConvertSurfaceFormat(). Add the following before the while loop:

    SDL_Surface * originalImage = image;
    image = SDL_ConvertSurfaceFormat(image, SDL_PIXELFORMAT_ARGB8888, 0);
    SDL_FreeSurface(originalImage);

What this does is take our surface (in this case the one that image points to) and return an equivalent surface with the pixel format we specify. Now that the new image has the familiar ARGB format, we can easily access and manipulate the pixels. Add the following after the line you just added (before the while loop) to typecast the surface pixels from void * to Uint32 * which we can work with:

    Uint32 * pixels = (Uint32 *)image->pixels;

So far so good:

sdl2-grayscale-display-normal-image

Now, let’s add some code do our grayscale conversion. We’re going to convert the image to grayscale when the user presses the ‘G’ key, so let us first add some code within the switch statement to handle that:

        case SDL_KEYDOWN:
            switch (event.key.keysym.sym)
            {
            case SDLK_g:
                for (int y = 0; y < image->h; y++)
                {
                    for (int x = 0; x < image->w; x++)
                    {
                        Uint32 pixel = pixels[y * image->w + x];
                        // TODO convert pixel to grayscale here
                    }
                }
                break;
            }
            break;

This is where bit manipulation comes in. You see, each pixel is a 32-bit integer which in concept looks something like this (actual values are invented, just for illustration):

Alpha Red Green Blue
11111111 10110101 10101000 01101111

So let’s say we want to extract the Red component. Its value is 10110101 in binary, or 181 in decimal. But since it’s in the third byte from right, its value is much greater than that. So we first shift the bits to the right by 16 spaces to move it to the first byte from right:

Alpha Red
00000000 00000000 11111111 10110101

…but we still can’t interpret the integer as just red, since the alpha value is still there. We want to extract just that last byte. To do that, we perform a bitwise AND operation:

Pixel 11111111 10110101
Mask 00000000 11111111
Pixel AND Mask 00000000 10110101

We do an AND operation between our pixel value and a value where only the last byte worth of bits are set to 1. That allows us to extract our red value.

In code, this is how it works:

                            Uint8 r = pixel >> 16 & 0xFF;
                            Uint8 g = pixel >> 8 & 0xFF;
                            Uint8 b = pixel & 0xFF;

The >> operator shifts bits to the right, and the & is a bitwise AND operator. Each colour byte is shifted to the last byte and then ANDed with the value 0xFF, which is hexadecimal notation for what would be 255 in decimal, or 11111111 in binary. That way, we can extract all three colours individually.

We can finally perform the actual grayscaling operation. A simple way to do this might be to average the three colours and set each component to that average:

                            Uint8 v = (r + g + b) / 3;

Then, we pack the individual colour bytes back into a 32-bit integer. We follow the opposite method that we used to extract them in the first place: they are each already at the last byte, so all we need to do is left-shift them into position. Once that is done, we replace the actual pixel in the surface with the grayscaled one:

                            pixel = (0xFF << 24) | (v << 16) | (v << 8) | v;
                            pixels[y * image->w + x] = pixel;

If we now run the program and press the ‘G’ key, this is what we get:

sdl2-grayscale-average-grayscale

It looks right, doesn’t it? Well, it’s not. There’s an actual formula for calculating the correct grayscale value (v in our code), which according to Real-Time Rendering is:

grayscale-formula

The origin of this formula is beyond the scope of this article, but it’s due to the fact that humans are sensitive to different colours in different ways – in fact there is a particular affinity to green, hence why it is allocated the greatest portion of the pixel colour. So now all we have to do is replace the declaration of v with the following:

                            Uint8 v = 0.212671f * r + 0.715160f * g + 0.072169f * b;

And with this, the image appears somewhat different:

sdl2-grayscale-correct-grayscale

This approach gives us a more even distribution of grey shades – in particular certain areas such as the trees are much lighter and we can make out the details more easily.

That’s all, folks! 🙂 In this article, we learned how to convert an image to grayscale by working on each individual pixel. To do this, we had to resort to converting an image surface to a pixel format we could work with, and then copy the pixels over to a texture for display in the window. To actually perform the grayscale conversion, we learned about bitwise operators which assisted us in dealing with the individual colours. Finally, although averaging the colour channels gives us something in terms of shades of grey, there is a formula that is used for proper grayscale conversion.