New Tutorial on getting started with SDL

New Tutorial on getting started with SDL

SDL REctanglesI had this tutorial pencilled in to do and it’s now done. It’s the old SDL rectangles program that was part of the eBook. I’ve modernised it a bit so the same file will now compile under either MSVC on Windows or VS Code/Clang on Linux without changes.

I used the _WIN32 predefined macro so it compiles the call to Windows cod on Windows. Here’s an example:

#ifdef _WIN32
		sprintf_s(buff, sizeof(buff), "%10.6f", getElapsedTime(&s));
#else
		snprintf(buff, sizeof(buff),"%10.6f",diff(&s));
#endif

I do a similar thing with the path to SDL which is “SDL.h” on Windows but “SDL2/SDL.h” on Ubuntu. Writing code this way makes it  lot less of a hassle.

Widening the scope of this website

Widening the scope of this website

Chaso
Image by levelord from Pixabay

When I first started, I wanted this to be for two purposes. Learning C programming and learning games programming. Apart from a few more tutorials that I have to complete, it’s mostly complete as far as C goes.  I still have to finish my 2nd e-book which is now up to chapter seven. I received some advice after my first eBook and so I’ve completely revised the second one to have a lot more explanation.

But after a year of doing mostly C stuff (and a bit of C#), I have found it harder to get things to write about on C.  I’ve been revising what I’m doing in games programming and so am looking about. I do like Blazor but am going to try an alternative approach. If I succeed, you’ll hear a lot more about it.

The picture probably represents the contents of my head!

 

The game of 2048 in C in your browser

The game of 2048 in C in your browser

2048 game playing in a browserBack in 2014, an Italian developer called Gabriele Cirulli devised a puzzle game called 2048. It has been implemented on many platforms (I have it on my iPhone) and here is a link to a C version of it (in 300 lines) by developer Nishchith Shetty that plays it in a browser using WebAssembly.

The idea behind the puzzle is that you combine the numbered pieces by moving pieces intro same numbered pieces. 2 into 3, 4 into 4 and so on.

WebAssembly is the technology that lets you run programs in many languages (including C and C++) in your browser at speeds up to 50% of native code.  It’s also used in Blazor where you can write C# programs that run in the browser.

To convert the C code to WebAssembly, you have to install a transpiler (a program that converts one programming language to another) called Emscripten, then it’s a single command line instruction to build the WebAssembly from the C sources and SDL2. Or you can just play it online here.

I’ve been meaning to do a WebAssembly version of my asteroids game using Emscripten. it’s just been sheer laziness that I haven’t got round to it.

 

In praise of Visual Studio

In praise of Visual Studio

Visual Studio debuggingLooking at some of the posts on the C subreddit about recommendations for a text editor to help learn C, I see many people recommending editors like Sublime Text, Notepad (on Windows).

I started programming in an era when IDEs were few and far between and an IDE is a wonderful time saving device. It is vastly superior to editing in a text editor then launching a compiler either by command or a batch file.

With an IDE you get immediate feedback on where the errors are, sometimes with a mini-map that lets you navigate directly to the error. It’s quicker to refactor code (though that’s a function of an editor) and usually one key press away from running or debugging.

Debugging in particular is very good in Visual Studio on Windows or Visual Studio Code on Windows/Linux/Mac. It’s visual, you can see multiple lines of code, add breakpoints and step through it with one key press.

I find line debuggers like GDB to be very frustrating by comparison.  Mousing over a variable and seeing its value in a debugger is a big time saver. Also seeing the stack calls and being able to jump to calls in the stack is handy.

Now if you are used to Linux, working in a terminal and compiling code through batch files then fine, but I believe its a bit of a hurdle for new programmers. An IDE makes it easy to switch from editing, compiling and debugging without leaving the program. It is all round more productive and easier to get into for a beginner.

So it’s worth at least trying out the free version (Community Edition) of Visual Studio if you are on Windows.  The days when Microsoft hated Linux (They called it a cancer!) are long past.  And no I don’t get paid for advocating Visual Studio; I just like it. Considering that it’s completely free, it’s remarkable value.

Finding popular open source projects with libhunt

Finding popular open source projects with libhunt

Telescope
Image by Lars_Nissen from Pixabay

I’m quite keen on meta-sites. Those are sites that don’t provide information about sites, applications etc. but they provide ways to find it. I suppose another way to describe this would be to say a categorised search engine for open source.

A case in question is libhunt.com. It tracks mentions of open-source projects and software libraries. So for instance you might want to see the most popular C libraries in the last month or even games in C,

Of course you aren’t limited to C or games; there are other open source libraries to look for, or even by the number of GitHub stars.

Libhunt uses the mention of the project on Reddit as it’s source for finding things. So things can change from day to day or week to week.

 

More notes on my Webassembly web development with Blazor

More notes on my Webassembly web development with Blazor

Web networking
Image by Gerd Altmann from Pixabay

This is another post in the Inselkampf series. Having spent much of my career creating “desktop” application, web always feels a bit different. If it’s a website then HTML/CSS/PHP + MySql is a reasonable way of working. But when its a web application like a browser game that uses a SQL database, then there’s a bit of architecting involved.

I’m using Blazor because it lets me write C# that runs in the browser. I’ve never been a JavaScript fan though I realise many people are. I also have to use database. As I’ve said before Blazor gives you two choices- The WebAssembly version that runs completely in the browser and the Server version that talks to a server using a protocol called SignalR.

I’m trying to be clever by using the WebAssembly version but having the C# talk to a restful interface. Restful just means it has a bunch of http calls to do things like update, fetch data, login etc. On the server runs a ASP.NET program implementing this. It’s headless, as in its not outputting any webpages to the browser but just returns data in JSON (or maybe MessagePack).

This avoids having a SignalR connection for every user logged into the site which is one way to bring a server to its knees. When you create a Blazor Server application, it has a few disadvantages. As Microsoft says: when you use Blazor server.

  • Higher latency usually exists. Every user interaction involves a network hop.
  • There’s no offline support. If the client connection fails, the app stops working.
  • Scalability is challenging for apps with many users. The server must manage multiple client connections and handle client state.
  • An ASP.NET Core server is required to serve the app. Serverless deployment scenarios aren’t possible, such as serving the app from a Content Delivery Network (CDN).

I’m also not using the Microsoft authentication but rolling my own. Yes it’s possibly not perfect but I’ve done it before. This way I get to generate recovery numbers. (Both GitHub and Gmail offer these). A bunch of one off codes that are used to authenticate you, if you’ve lost your password or messed up your email then you login with your account number and an authentication code. This is the only way you get to change email and/or password. You just have to keep the codes safe.

Rolling my own Interface

So things like logging in, getting current status, updating game play are all done by making a call to an HTTPS routine. This is all behind the scenes so players see nothing. Values are sent as POST parameters and also include a nonce. This word (that unfortunately means sex offender in UK English!) , refers to a special code that has to be supplied with each call to the server to authenticate it. Successful logging in returns a nonce that has to be added as a parameter with every call to the server.

The program on the server that serves the restful calls is a simple ASP.NET Razor pages application (Well maybe Razor, I’m not sure if I need them). Behind the scenes I’m using MySQL which was installed as part of VirtualMin (the excellent software I use to setup the VPS).

Simple but effective optimisation in C

Simple but effective optimisation in C

StopwatchHere’s a short program. It repeats a loop twice, indexing through a text string a million times adding up the value. Instead of starting the total at 0, I set it to the outer loop index, to try and reduce the scope for immediate optimisation.

#include<stdio.h>
#include <string.h>
#include "hr_time.h"

stopWatch s;

char* testString = "This is a rather long string just to prove a point";
int main()
{
    int total = 0;
    startTimer(&s);
    for (int i = 0; i < 1000000; i++) {
        total = i;
        for (int index = 0; index < (int)strlen(testString); index++) {
            total += testString[index];
        }
    }
    stopTimer(&s);
    printf("Total =%d Took %8.5f\n", total, getElapsedTime(&s));

    startTimer(&s);
    int len = (int)strlen(testString);
    for (int i = 0; i < 1000000; i++) {
        total = i;
        for (int index = 0; index < len; index++) {
            total += testString[index];
        }
    }
    stopTimer(&s);
    printf("Total =%d Took %8.5f\n",total, getElapsedTime(&s));
    return 0;
}

I compiled and ran it twice, once in Debug and once in Release mode on Windows using MSVC.

Debug:

Total =1004673 Took 0.55710
Total =1004673 Took 0.11465

Release

Total =1004673 Took  0.00762
Total =1004673 Took  0.00765

Clearly in Release compilation, the compiler is smart enough to realise that it can optimise strlen(testString) away so there’s no difference between the two times. But in debug it’s clear that calling strlen() inside a for loop is relatively slow.

I compiled it and ran it with clang on Ubuntu 20.04 in the Hyper-V VM. The times with default optimization were

0.18370 
0.10644

and with “-O3” added to the compile line for maximum optimisation,. this changed to

0.0762
0.0745

which is almost identical to the Windows release compile times.

Portable Life in C

Portable Life in C

apelifeI’ve mentioned Life before, this is the cellular automata as discovered by John Horton Conway. It’s perhaps less of a game and more of a recreation for anyone fascinated by programming. It’s hard to add up how many man-hours have been spent on it.

Developer Justine Tunney (aka Jart on Github) has developed a portable Life called Apelife. Portable as in it can run on Windows (graphically) and Linux (Text User Interface). The application is a modest 112 KB in size and is one of the fastest I’ve seen. When you have a large area and gliders whizz across it, you know its fast.

She is also the author of Cosmopolitan C which Apelife uses.  It lets gcc outputs portable binaries that will run on every Linux distro in addition to Mac OS X, Windows NT, FreeBSD, OpenBSD, and NetBSD. It’s rather ingenious.

 

 

Added a tutorial on memory use in C

Added a tutorial on memory use in C

RAM BoardYou can read the tutorial here. It looks at the different ways memory is used in a C program. Do you know for instance what BSS is and when it is used compared to Data or where variables in a function declared static are held in memory?

I also tried overwriting a text literal out of curiosity to see what happens. Here’s the source:

#include<stdio.h>
#include <string.h>

char* name="My name is David";
int main()
{    
    strcpy_s(name,10, "New name");
    printf("Name = %s\n", name);
    return 0;
}

 
As you’d expect it blew up”

Work in Progress – Web game

Work in Progress – Web game

Blazor AppI did some investigative work on this at the weekend, This is my Inselkampf type web game. Although I know C#, I’m fairly new to ASP.NET and Blazor. Now the first thing you’ll notice about most Blazor examples on the web is that many look like the screenshot. In particular, the purple gradient down the left hand side.

So my first job was find out where that’s defined and try changing it. In the project which is Blazor WebAssembly, there’s a shared folder and it contains two .css files. MainLayout.razor.css and NavMenu.razor.css. These are the files you need to alter.

Now its probably seven or eight years since I last touched CSS and it has come on quite a bit since then. I discovered css-grid which simplifies things enormously.  If you want to find out more about CSS, take a look on FreeCodeCamp.org. This site has lots of example layouts using CSS-Grid and I went for Redefining Grid Areas with Media Queries. 

This lets you specify a width so you can have a responsive website which adapts to mobile phones as well as desktop. I merged the css and HTML from the example into the project and although its an early stage, I’m quite pleased with it.

Game framework This is very early. The font, colours etc will all change but this has given me a web template with round corners, header, footer and two sidebars.

If I shrink the width of the browser the two sidebars move to positions above and below the main content like this below. It would have taken a lot more effort before css-grid to do this.

Narrow game framework