Showing posts with label Programming. Show all posts
Showing posts with label Programming. Show all posts

Tuesday, March 19, 2019

Getting started with SDL2

The Simple Directmedia Layer (SDL) is a mature framework that has been around for quite some time. Though mainly targeted at writing games it is good for any program that requires the creation of arbitrary graphics screens, like for example retro computer emulators. One of the more interesting aspects of SDL is that it is cross-platform. It runs fine on your PC, Mac or Linux computer. And this includes the ever so popular Raspberry Pi.
There are many excellent guides for setting up SDL on every platform.
TwinkleBearDev SDL2 Tutorials
Parallel Realities Game Tutorials
Lazy Foo Productions 

Visual Studio

There is a good step-by step guide on WikiHow to configure Visual Studio. It however is already outdated since the easiest way to set it up today is by using the Nuget package manager. One of the major benefits of going this way is that you can now simply switch between 32 and 64 bit builds by just selecting the target platform in the VS project type dropdown. So : Lets Get Started !

First use 'File->New->Project' to create a 'Visual C++' -> 'Empty Project'.

Right click the 'Project' and select 'Manage NuGet packages'. In the NuGet Package manager go to the 'Browse' tab, and search for SDL2. Select the latest SDL2 package and click install. 
Then scroll down an also install the 'SDL2_image', 'SDL2_ttf' and 'SDL2_mixer' packages for image handling, font management and sound. This basically configures your project completely for use with the SDL2 framework. 
The only thing you have to do manually is selecting the SubSystem target. To do this open up the System page and choose either Console or Windows from the drop down. If you choose Windows you won’t get a console window that opens up with stdout, if you choose Console you will. My advice is to choose Console, as the console window is really handy as a debugging tool.
Note that when you switch your target from 32 to 64 bit or vice-versa you will again have to choose the SubSystem target or your build will fail because it 'Cannot find an entry point for main()'



You are now ready to start your first SDL project. 
Right click the 'Source Files' folder and select 'Add ->; New Item...'. Select a 'C++ File', give it meaningful name if you want, and click OK. Open the empty C++ file, and copy the following:
#include "sdl.h"
#include "sdl_image.h"
#include <iostream>
#include <stdio>


const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;

int main(int argc, char* args[]) {
    SDL_Window* window = NULL;
    SDL_Surface* screenSurface = NULL;
    SDL_Renderer *renderer=NULL;
    SDL_Texture *texture=NULL;
    SDL_Event event;
    SDL_Rect r;

    if (SDL_Init(SDL_INIT_VIDEO) < 0) {
        printf("Could not initialize SDL. SDL_Error: %s\n", SDL_GetError());
    }
    else {
        window = SDL_CreateWindow("SDL Test", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN);
        if (window == NULL) {
            printf("Cannot create window. SDL_Error: %s\n", SDL_GetError());
        }
        else {
            SDL_Rect arect;
            screenSurface = SDL_GetWindowSurface(window);
            SDL_FillRect(screenSurface, NULL, SDL_MapRGB(screenSurface->format, 0x00, 0x00, 0x44));
            arect.x = 64; arect.y = 64; arect.w = SCREEN_WIDTH - 128; arect.h = SCREEN_HEIGHT - 128;
            SDL_FillRect(screenSurface, &arect, SDL_MapRGB(screenSurface->format, 0x00, 0x77, 0x77));
            SDL_UpdateWindowSurface(window);
            SDL_Delay(500);
        }
    }

}


Run the program, and if all is well it will show a window with a blue border and green centre.


Sunday, January 15, 2012

Back to The Valley. (in 8-bit country)

August 3, 1977 was the public introduction of the TRS-80 home computer. Which is as I write this is more than 35 years ago. The most recent episode of this developers life ('Dinosaurs') brought back memories to this first real computer I could get my hands on. The setup as shown here is exactly what my father bought about thirty years ago. A black and white 12" monitor (16 lines of 64 characters), a 1.77 MHz processor and 16KB of RAM. Program storage on a cassette tape recorder which meant loading a decent game would often take 10 minutes or more. And to me it was magic. From the very first time I switched it on and saw the READY> prompt I was hooked. To programming. I remember it started with the sample from the owners manual. No, not the obligatory 'hello world' but a Celsius to Fahrenheit conversion program. And after completing all samples I did a very simple Space Shooter. Written all in Level 1 basic, using all ASCII characters, so you can probably imagine it did not exactly look like "Skyrim' or 'Modern Warfare'...
Then one day I bought the latest edition of 'computing today', mainly because of the cover. Today games actually look like that, but back then those images could only exist in your imagination.
 And programming a real adventure game, with "goblins', 'wizards' and ''barbarians' sounded like an extraordinary challenge.
So I spent weeks typing the the listings and converting the code from the original Commodere PET basic until I had a real working game which eventually I hardly ever played. It showed me that for me the real fun was in the programming itself, which it has been ever since.
The program as I written it has been long lost. It was stored on a cassette which we probably gave away when we sold the TRS-80, and I did not have a printer then to make a hard-copy. But guess what: it's on the internet. It took some searching but finally I found an article by Paul Robson and this one by Tony Smith on reghardware.com .
Both more or less describe the same experience, and on the site of Frank Fraser there is even a full scan of the listings. Looking at the scans I suddenly realized that I probably still had a copy of the magazine somewhere and so I did. The scans shown here all come from my personal copy. Actually I thought my copy would be 'cleaner' than Franks scans. But memory tricked me and the weeks of intensive use also left their marks on the pages, as can be seen in the section where the different graphics are explained.
For a moment I considered trying to rewrite the program using a TRS-80 Emulator. Just to see if I could re-live the excitement of that time. Probably not. And after playing the BBC version (which is included in the zip-file that contains the scans) I found this type of game is still not my favourite.


Lets face it, the most enjoyable part of recovering an old computer magazine are reading the ads. Like this one on the rear. 'Fully expandable to 32K of user RAM' and a 'Full set of upper and lower-case characters'. What else would you ever need ?

Thursday, November 10, 2011

Holy Cow, I Wrote An App !

(Of course the title refers to Raymond Chens post about the only book he ever wrote..)


In 15 lines of code... And it's an unique one. And it does something that is probably useful to (a maximum of) 10 people in the whole world.
Last year I bought an Archos 7HT Android Tablet. It was one of the cheapest tablets then and this means it has limited capabilities. One of the limitations is that it does not have an option to switch to portrait mode. It has no tilt sensor and there is no special button or built-in option for it. So if you display a webpage it is always in landscape mode which is sometimes inconvenient. Like when I want to view the a popular site that shows when and where it will rain in the coming hours. As I live in a small country, it could fit in one screen IF displayed in portrait mode.
So I decided to look into the possibility to force the standard browser to start in portrait mode, which is (as far as I'm aware) not possible. Then I found a reference to the 'WebView' ("A View that displays web pages") component and guessed that this could be a way to solve the problem.  And it is. I just created a standard Android application, followed the instructions on the WebView reference page to place the component on the main page, and forced the view to portrait using the appropriate function (that I found on StackOverflow).. That's all. Here is the code:

package CScope.Buienradar;

import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.webkit.WebView;

public class BuienRadarActivity extends Activity {
    /** Called when the activity is first created. */
     WebView mWebView;
     Button myButton;
     @Override
     public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mWebView = (WebView) findViewById(R.id.webview);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.loadUrl("http://buienradar.mobi");
           setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }
    }

The blue lines are actually the only code written by me, all the rest was generated by the Eclipse 'New Project' wizard. And when you press Run or Build a complete installation package is created in the 'bin' folder of the project that can be copied to the device.  Let's face it, this is almost too simple.... So that even left me time to create a fancy icon.


(And if you by coincidence are one of these 10 people: you can download it it from here: BuienRadar,apk)

Monday, August 17, 2009

Criss Cross Platforming Speedup


I've written a lot so far about my fascination for cross platform development. Unfortunately my time is limited so I do not spend as much time on it as I would like. And every time I find a little time to pick it up I find to my surprise that others are proceeding down the multi platform road at a much larger pace. Like the Mono team, lead by the the brilliant Miguel de Icaza . Check out StackOverflow podcast #61 to find out he's also a amusing speaker (which is a well known rarity among good programmers...)
Here he also announces the introduction of Mono tools for Visual Studio. This will allow simultaneous development on Linux an Windows. And since Mono is also working towards iPhone application development it is getting really interesting. I believe that we are now slowly working towards the real future of software development. It will not be long before it is relatively easy to create applications that run on Windows, Windows Mobile, Mac, Linux and the iPhone. Something I would not have thought possible two years ago.

Wednesday, July 01, 2009

I'm not alone in .NET Cross Platform land


So I'm not the only one to work on cross platform .NET applocations (how come I'm not really surprised..?) The Banshee Project is a cross-platform multi media player based on .NET and Mono. Though my only experience with the Banshee player is not positive ( It could not play MP3 without hickups on my EEEPC ) it is a great project to show the power of cross platform development. And I'm sure one of these 95 developeres working on it will eventually solve the EEEPC problem.
Banshee creator Aaron Bockover talks about it in a recent Hanselminutes Podcast. Both the show and the shownotes mention that it will run on Windows, but I actually could not find it on the Banshee homepage. On his Blog he mentions working on it, (despite of his aversion to Windows programming) but the status of it is not really obvious.

Monday, May 11, 2009

User friendly, or friendly users ?


UI development has been a source for discussion. Books have been written, entire blogs are dedicated to it and when you start reading and digging deeper you'll just get to a point where you will become completely stuck. You'll think weeks about every single menu item, background colour gradient angle and button placement.
Yet I've written an application that has a UI that would not even pass the basic test for usability and I never had a single complaint about the interface! The menu structure is not really logical nor standard, dialog boxes for similar functions vary widely in appearance and their buttons are placed almost at random. And when you click 'Help' it just opens a .pdf document that contains only the very basic instructions.
All this happened because it started as an 'internal use only' application and grew by demand through the years. Functionality was added on the fly if someone required it to get a specific job done and often I just 'plugged in' a windows form from a different app just because that already contained most of the functionality of what I needed at that time.
And then suddenly the application was 'promoted' to end user software and supplied with an expensive piece of hardware and used by a slowly expanding group of people around the world. So on regular intervals I get feedback and requests for change but it's always about the functionality. A calculation is found incorrect, export functions should export more values, graphs should show more details and so forth. Never ever did somebody complain about the arcane data editing function, the strange menu structure or the crippled help.
The users are certainly not computer specialists. They are people whose main job is just to do measurements. They just need that software as an additional tool in a similar way they need a four wheel drive, rubber boots and ropes. And it seems they don't really care how it works, as long as it gets the work done.
"So I have to press the left mouse button three times while holding control, shift and F4 to get a printout ? Al right. I'll write it down."
And they will always do it like that. And if they have to instruct their new colleague it will give them a good feeling that they know this awkward combination by heart. My feeling is that they treat it like any other professional tool. You have to learn how to master it and it becomes part of your professional skills. I suppose that is the reason why Linux adepts stay enthusiastic about their operating system, even though they have to get to the command line and type their cryptic commands for anything but the most trivial tasks.
"So you can operate the LHC ? Big deal, I know how to get connected to my bluetooth phone from my Linux powered laptop !"
(Don't mail me about this last remark. I have no idea..;-)

Tuesday, April 21, 2009

Finally: One language, three worlds.

Eureka. At last. With the release of the System.Windows.Forms assembly for Mono a dream comes true. Well, this sounds a little over the top but it felt like that the first time I got my 'SimpleTerm' application running on Ubuntu. SimpleTerm is C# application for serial port (RS232) communication that I originally created for the PocketPC using SharpDevelop. By using only CLR functions that are available in the Compact Framework I could build an application that runs on a PDA and a desktop, unchanged!. So it was exactly the same bytecode on both platforms. Now this does not work on the Mono platform (although there seems to be a way to patch the bytecode itself) but after I imported the project into MonoDevelop and just compiled it, it actually worked ! Which could be considered as a breakthrough merely for the fact that it supports serial communication !. So it's not just a 'Hello World window' with an OK button but its a real application that even supports the most underappreciated form of digital communication. And I say 'underappreciated' because the RS232 specification was established in 1969 and it has been the main form of communication between computers for over 35 years. But it is only since the release of System.IO.Serialport in version 2 of the CLR that serial communication is really supported out of the box in a mainstream development framework. I know this is not an issue for most people, but if you are working with instruments and microcontrollers whose only means of communication is still plain RS232 it is a real revelation.
The image shown here is a combination of three screenshots, one of a PocketPC emulator, one from an Ubuntu system running within a virtual machine and one from a 'standard' Windows XP computer. The text in the main window of the application shows the result of a call to 'Environment.OSVersion' which indeed reports the operating system and version on all three systems.

Saturday, March 14, 2009

Creative AdWords


Usually I feel the 'intelligence' of Google is impressive. Almost every search I do leads me to the right pages within the first two or three results. And the ads shown on the right of the search pages are also often remarkably relevant. That's why the WTF page shown here really surprised me. (Yes, you hae to click on it to see the details). I saved it as a screendump, since it is unlikely that you would get the same results if you visited the original article now.
On the other hand, the WTF site is definitely a site for real nerds, so the first ad ('How To Pick Up Girls ?') might be in the right place after all.
For those of you that do not master the Dutch language: ad 3 and 5 both lead to shops that sell underwear. Clearly AdWords got mislead by the multiple occurrence of the word 'String' in the source code Which is strange if you realise that Google programmers are probably among the 0.001% of people whose first association to this word is 'string of characters'.

Friday, August 22, 2008

Dreaming on: Chandler 1.0 released

You might not have noticed, but on August 8th, 2008 at 1:47 pm, Chandler, the ' "Note-to-Self Organizer", designed for personal and small-group task management and calendaring' finally came to release 1.0 ! Now Chandler is an Open Source project, and 80% of these projects probably never reaches this stage at all, but Chandler is a special case. It is created by the Open Source Application Foundation which was founded and and is sponsored by Mitch Kapor. The Chandler project is a unique example of where a project that has no deadline and an unlimited funding can lead to: unlimited development.
And no matter what finally comes out of it, the first three years of the project already gave us the magnificent novel by Scot Rosenberg : Dreaming in Code. A great book that may well outlive the software itself. It describes the development process from the initial idea upto version 0.7. Three years have passed then and Rosenberg realises he just has to draw the line himself and publish the book before the project is finished. And he was right. The book was written by the end of 2005 and so it has taken roughly two and a half years before they they finally came to version 1.0 . I'm glad he didn't wait for that, since by now I already read the book twice. I really recommend it to any developer, manager or just anybody using software (Yep, that's you by default, or you would not be reading this..).
Apart from it being really fun to read, it's description of ever shifting deadlines, continuously changing specifications and numerous code re-writes is so recognizable to me as a developer. Just check out Joel Spolsky's review to see what I mean.
And what about the software itself ? Well, I haven't tried it yet but the concept is great, though not as revolutionary as it might has seemed in 2002. As already mentioned in the book, 37Signals already provides most of the functionality as a web application. With all the benefits: no server maintenance, available everywhere through every browser and automatic upgrades.
But the Outlook / Exchange combination is still used in many corporate environments. And since Chandler is aimed at replacing that, they might still have a chance.

Monday, May 26, 2008

Too hard, or a challenge ?

Quote:

'it's a fun programming exercise that you're doing because it's just hard enough to be interesting but not so hard that you can't figure it out.'

Never thought of it that way, but this is indeed the kind of project I like to do most. And if most programmers are like me they will always tend to bend a projects towards this edge. If it's too simple we'll add functionality that creates new challenges. And if it seems just to hard we try to figure a way around it (buying a third party library or let someone else do it..) so we can spend more time at the things we like, like the slow fading in and out of our super-fancy splash-screen...

Tuesday, November 20, 2007

The Mysterious Breakpoint

(Or how even Microsoft programmers sometimes forget to clean-up..)

While working on a piece of software that relied on a ActiveX control, I regularly found my debugger stopping at an address somewhere in memory that was not part of the program. First I tried to find out where the bug was, then I found that just continuing the program worked fine, and that there were apparently no side-effects. But it kept stopping there, no matter how much of the debugger features I disabled. So I decided to get into it a bit deeper and found out it always stopped at an address named 'DbgBreakPoint' in module NTDLL.DLL. It looked like it stopped on a breakpoint, but not one that I had set. And the 'Disable all breakpoints' option in the Borland C++ Builder debugger did not make any difference. It really looked like Microsoft forgot to remove a breakpoint from one of the most important DLL's in Windows. A bit of Googling made clear that this was indeed the case, and also that it was not easy to get around it. Patching NTDLL.DLL appears impossible since it is one of the most 'protected' core-pieces of Windows. If you try to modify it, Windows will just 'restore' it on start-up. And if you are clever and modify the backup copy it uses for this restoration, Windows just won't start at all...
So the only way around seems to 'patch' the DLL in memory after it is loaded by your program by overwriting the memory location containing the breakpoint with a 'NOP' instruction. Here is the function to do it:

void PatchINT3()
{
unsigned char NOP=0x90;
void* pNTDLL;
DWORD BytesWritten ;
FARPROC Address;
if (Win32Platform != VER_PLATFORM_WIN32_NT){ return; }
pNTDLL = GetModuleHandle("NTDLL.DLL");
if (pNTDLL == 0) {return;}
Address = GetProcAddress(pNTDLL, (LPCSTR)"DbgBreakPoint");
if (Address == NULL){ return;}
unsigned char Byte= *(char *)Address;
if (Byte != 0xCC) {return;}
try

{
if (WriteProcessMemory(GetCurrentProcess(), Address, &NOP, 1, &BytesWritten))
{
if(BytesWritten == 1)
{
FlushInstructionCache(GetCurrentProcess(), Address, 1);
}
}
}catch(EAccessViolation &E){}
//Do not panic if you see an EAccessViolation here, it is perfectly harmless!

}

I suppose anyone who got to here has enough knowledge of Windows programming to see how it works :-)
And so, by calling PatchINT3() at the start of the program the breakpoint is erased and won't show up again.
(Thanks to Peter Morris at HowToDoThings , who wrote the Delphi version that I translated here)

Wednesday, August 15, 2007

The Big Step: Microsoft Visual Studio

So it finally had to happen. I purchased and started to use Visual Studio 2005. After using Borland C++ Builder for more than 10 years for all my Windows (and even DOS) programming, the Pocket PC platform turned out be the decision maker. From the start the only way to write programs for the Pocket PC platform has been through Microsoft. And they also made it very easy by giving away the free Embedded Visual Basic, followed by Embedded VisualC. But today, now everybody has a Pocket PC, none of these tools is being supported, and they also refuse to work with the new Windows Mobile 5 devices. Now this could be a great starting point for some Microsoft bashing, but actually I read some explanation on a MS-Developer blog that makes sense. Since the embedded versions where completely separate projects within Microsoft, the development and support started to suffer from the fact that the developers also worked on the commercial Visual Studio product. And it's just a fact of life that supporting a commercial product has a higher priority...
But I've written all my software using EVC 3 and 4. And so I struggled some time by using old PocketPC's for debugging, actually waiting for Borland to come up with the 'Delphi for PocketPC'. But I don't think this will happen for a while, and I even wonder if they ever will produce something for the PocketPC platform. So I finally had to get Visual Studio 2005 to continue supporting my embedded Visual C apps. Fortunately I could go for an Visual Studio 2005 Upgrade, because I already owned C++ Builder, making it a bearable € 250,-.
And now I must agree, the Visual Studio environment a a giant leap forward compared to the old EVC programs. The editor is much more up to date, it compiles faster, has a better debugger, and (surprise, surprise) also supports direct emulation on your desktop PC, even when your program uses ActiveX controls or external DLL's !.

Tuesday, May 01, 2007

Creating Q-Web

To visualise data that is related to geographical locations (e.g. the local weather) nothing beats a good map with some clear symbols that reveal data from a database. The following series describes my route towards a database driven ASP.NET application that shows data as collected by the 'Discharge measurement' stations. The company I work for (Qmetrix) supplies these stations to local water management authorities. They measure the flow of water in a river or stream, combine it with the water-level and the local depth-profile and calculate the total cubic meters of water per second that passes by.
First I needed a nice map. I used MapBuilder, the excellent tool to manipulate Google maps. Now what I need for the webpage is a image for the area of interest, for which I know the exact coordinates of the left-top and right-bottom corner. Here is how:
In MapBuilder first click 'New Map' and enter a (short) name and a description. Then return to 'Edit Map'. Disable the 'Automatic Zoom' feature. Make sure the area of interest is completely visible. (Find it quick by just typing the name and country of a city that that in the area in the "Location Search & Quick Navigation" box )
Click in the left top corner, this will show a blinking marker. Select a small marker type, type 'Left Top' in the 'Caption' box and click 'Add'.
Repeat these steps for the 'Right-Bottom' marker. Now click 'Save Center, Zoom, Maptype'. Select 'Map Controls' in the menu, and disable all visible features. Don't forget to click the 'Save' button at the bottom of this screen.
Now choose 'Preview' in the menu. It might be required to shift the map a little to get both markers in the right place.

If required you can go back to the 'Map Controls' screen, and increase the map width and height. Now if you don't want to include the Google and Mapbuilder trademarks you must make sure they fall outside the area as enclosed by the two markers. If the map is right, capture the whole screen, using a screen-capture utility or just [Shift][PrtScreen]. Load the captured image in an image editor, and cut out the exact area Top left to Bottom right. Save this as a new (.jpg or .png) image.
Now go back to MapBuilder, and make a note of the exact coordinates of Top-Left and Right-Bottom. (I usually just click on the markers, and Copy-Paste the 'Latitude' and 'Longitude' fields to a Notepad text file.)
While this text file is open you might also write down the exact sizes (in pixels) of the map image we just created. Usually this can be found using the image editor, but you can also locate the file in Explorer, right click it and select 'Properties'. Hidden under an 'Advanced->' button you find the exact size of the image in pixels.