Hey! I'm David Amador,
and I'm a programmer. I do mostly game development. Oh I have a twitter

My latest Game

This is the latest game I developed. Buy it if you want to support me and my work. More info

Latest tweets

    Even tough it’s not mandatory to support all screen orientations it’s always nice to support at least 2 of them.

    Let’s imagine your game is landscaped, by some reason the user may want to use either with the home button on the left or on the right. Most games support this, if you flip the device, the game will too.

    I’ve been using OpenGL to support the device orientation, most people on forums want an automatic solution, but belive me, it’s best that you have control on this.

    So for Landscape with Home button on the right

    It’s something like:

     glPushMatrix();   // Push a matrix to the stack
     glRotatef(90.0f, 0.0f, 0.0f, 1.0f); // Rotate 90 degrees
     glTranslatef(0.0f, -320, 0.0f);  // Move vertically the screen Width
     
     /// Draw Stuff
     
     glPopMatrix();

    So basically we are drawing all in a regular direction but rotating everything 90 degrees and translating to fit the screen properly.

    For the home button on the left

    glPushMatrix();
    glRotatef(-90.0f, 0.0f, 0.0f, 1.0f);
    glTranslatef(-480, 0.0f, 0.0f); // Move horizontally the screen Height
     
    // Draw Stuff
     
    glPopMatrix();

    These are the tricky ones, you can figure out the Portrait Upside down =)
    Oh, I’ve hard-coded the values (480 and 320) but you should make this a variable to support higher resolutions, IPhone 4 and IPad for instance.

    Although you could use iOS api to auto rotate this automatically I’ve read on numerous places that it’s slows down everything a bit and doing this on OpenGL is pretty quick and clean and if you ever port your game to another device (Android, etc) you don’t have to care about this again.

    So now for the tricky part, to detect the device current orientation, the accelerometer can help out pretty good. We can check for the current angle to calculate where the device is pointing.

    - (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration
     {
    	// Get the current device angle
    	float x = [acceleration x];
    	float y = [acceleration y];
    	float angle = atan2(y, x); 
     
            if(angle >= -2.25 && angle <= -0.25)
    	{
    	/// Orientation is regular Portrait
    	}
    	else if(angle >= -1.75 && angle <= 0.75)
    	{
    	/// Orientation is Landscape with Home Button on the Left 
    	}
    	else if(angle >= 0.75 && angle <= 2.25)
    	{
    	/// Orientation is Portrait flipped upside down
    	}
    	else if(angle <= -2.25 || angle >= 2.25)
    	{
    	/// Orientation is Landscape with Home Button on the Right
    	}
    }

    So what you should do is keep a variable that stores the current Orientation so when you draw you know exactly what rotation to apply to the matrix.

    I’ve tested this code on a real device with pretty good results. Also it won’t slow down everything and if you think it does just check screen orientation at greater intervals.

    Some cool things you can do it when switching to iterate the rotation angle, that way you can simulate the screen rotation same way iOS does. Also you may want to put some sort of delay when switching.

    Here’s the result

    It’s been awhile since I last updated this, I’ve have my hands full with Vizati IPhone.

    Ever since I got an IPod Touch 2G it was easier for Rita to get a sense of the screen size (although we knew to be 320×480) it’s different when you are testing on the real thing, text looks smaller, other stuff looks way too big.

    Here’s a picture she took after a few adjustments.

    Vizati IPhone

    Initial testing

    First thing I notice when testing on the device were slowdowns when the cube is fading, it had a lot of particles filling the screen and the framerate dropped down, although this only happens when each level loads and doesn’t interfere with gameplay itself I got a little frustrated.
    On the simulator It slowed down a little but only on Debug and even more OpenGL on the emulator is by software.
    Another issue was the sound, I’m using OpenAL + a custom OGG parser, and sound was also slow, with hiccups.

    Sound
    For the sound it turned out a little easier than I expected, there as nothing wrong with the parser, what would happen is that if the CPU would sometimes take longer than expected on someplace and the player would run out of data making those hiccups, since it was constantly running out of data and getting more.
    I increased the buffers size and numbers, so now I have 5 buffers with 65536 bytes each. Every time a buffer is parsed I read another one and queue it.
    Solved the problem immediately. Yesterday while playing the game (after 10-20m) the sound started having hiccups again, although the game was fine, so I may still have some flaw in there, must research it more.

    Here’s a video where of me playing with some particles:

    Primitives
    I can get much more particles on screen now because my first attempt to draw primitives in OpenGLES was drawing Quads with an mapped texture. When I got that working I would just send vertex points and texture coordinates and iterate all objects I wanted to draw.
    WROONGGGGGGG…..
    Although this works you should always batch as much geometry (within limits of course) as you can to make it on as fewer draw calls as you can. On both OpenGL and DirectX draw calls are the slowest part.
    It’s faster to draw 1000 triangles in one call than on 1 triangle per call. You get the point.
    So I started by making a PrimitiveBatch, sort of what XNA has, I just pass along vertex points, texture coordinates, color refs etc.
    Since it’s 2D I try to group by texture and by Z. All primitives with same texture on the same Z position can be drawn at once. You can’t draw all with same texture regardless of the Z some elements may be occluded when it was not intended, basically because it will keep drawing on top of what you have, at least for the current Buffer.

    After this I got enough drawing boost to have the same amount of particles that the PC version, which is cool.

    Some tips
    Although I’m still kind of new at this all IPhone things I can give you a few tips, they work for everything but are particular handy on devices with lower CPU power.

    • Avoid using std::list:end(), on big lists it carries an extra burden.

    If you don’t intend to add/remove anything from the list during the cycle just save that at first

       std::list::iterator b = _mylist.begin();
       std::list::iterator e = _mylist.end();
       while(b!=e)
        {
           /// Do stuff
          ++b;
        }
    • Avoid deleting stuff on loops. One example, I have a list where I stack stuff to be drawn on my PrimitiveBatch, typically when you start drawing you add everything, the lists keeps growing, you draw and then delete, and you go back to “start drawing” again. You can optimize this by never deleting and only creating on a need basis. Belize me it makes huge difference, and besides you will need to create that again so might as well not delete it and when starting over just update values. Small things like this may not be an issue on PC but on small devices every cycle counts.

    Most of this stuff you may already know but there are many who don’t. I’ll try to update this more often.

    So now I’ll get back to my testing to see if we get to testing and later to the app store asap =)

    PS: I need IPhone/IPod Touch testers, drop me an email with your UDID if you are interested…

    Just a quick post.
    GamersGate is having a Summer Special and Vizati is with a 50% discount, costing $4.47 / €3.72 during this week only

    Buy your copy here and check out other awesome promotions here

    This deal end up this August 15th

    I think the first game I ever played was Tetris on a 286 if my memory isn’t failing me.


    My father worked at restaurant nearby a small apartment rental office, one of the dudes that worked there occasionally would let me play. I remember one day he had this new game, Prince of Persia, my chin just fell, awesome,

    I thought games couldn’t get any better. I remember always asking him to “type the code to play” as I called it, since it was DOS based. Probably something like “cd /games/prince~” =P
    I spent hours playing that game, I do know I never managed to see the end thought.

    Next in line were Super Mario Bros. games. Some neighbors had a NES

    and when my parents were there that was to entertain the visitors kids, I didn’t even know there were any home consoles before seeing a NES before, I later discovered the Spectrum which was older but my first contact with a home console was with the NES and it’s gigantic cartridges.

    I never got at PC or console until I turn 12 I think, when my mother brought back from one of her trips a what she called “expensive toy on promotion” which was basically a Super Nintendo Street Fighter 2 Turbo Edition, a Super Scope and another game Battletoads in BattleManiacs

    This is a picture of the box, containing the Super Nintendo and Street Fighter 2 Turbo


    Sure was a sweet game, probably one of the best fight games I ever played. Since most of my friends at the time didn’t had this game I had quite the advantage when borrowing games.

    Battletoads in Battlemaniacs was a Beat ‘em up game much like Street of Rage on the Mega Drive ( Genesis in US). This game had one of the hardest levels I ever played on a game, the “brain track race thingy”

    If people are complaining about Limbos deaths I imagine with this game. It took me ages to beat that level.

    The Super Scope was this huge bazooka, had 6 games in it but they all sucked. I don’t think Nintendo released much more games for this.

    Since most of my friends had the SNES + Super Mario World bundle I pretty much always had a copy at home. It is one of my favorite games ever. Even my sister loved to play it. Along side Battletoads this was another game that made me had rage attacks one a particular level, Tubular, it’s considered the hardest levels in the game because of the lack of ground to stand on and the large amount of enemies.

    Another one of my favorite SNES games is The Legend of Zelda A Link to the Past, for me it’s the best Zelda game. Sure Zelda Ocarina of Time was awesome but it didn’t brought anything new to the series, even more the removed what made Link to the Past so great, the Light and the Dark world. After exploring the all Light World and defeating Ganondorf you are transported to the Dark World

    Wait wait… but you could also go back in forward from one world to another, most of the castle and secrets implied that you had to activate or move something in a world to affect the other one. How cool is that?

    I don’t remember all the other games that I’ve played on the SNES but here are some box arts from some I do remember:

    Damn this post is getting way big, I think I’m going to split this into several parts, I’ll cover Mega Drive on the next run. What about you, what are your favorite SNES games?

    I decided to run a little poll to track what platforms do you target as a game developer. I think this should be interesting. Please share this post link or the direct link to the poll (http://twtpoll.com/dar51l) so that we can have more accurate results.

    The poll closes in about 6 days and you can select various options of course.

    I ran into this issue a couple hours ago working on the IPhone sdk:

    See the darker borders around the image?

    It’s a png image and that’s was supposed to be a gradient of alpha. So why am I getting this strange stuff around it?
    Well that’s because that alpha isn’t 0 or 1 or 0 or 255.

    The first thing I found out is that XCode grabs the png images and multiplies the RGB component with the alpha. So you can understand now why only 0 or 1 works right? Everything in between get’s changed. This is why Apple recommends using PNG over JPGS, although they consume more space they are altered for speed.

    This is refereed as using images with pre-multiplied alpha.

    If you don’t care about this and just want to use regular alpha blend one quick fix up for this is on each image load to reset the correct RGB values and maintain the A component

     int pixelcount = width*height;
     // Image data is a pointer for your image data
      int count = width*height;
      unsigned char* off = (unsigned char*)imageData;
     
      for( int i=0; i < count; ++i )
      {
    	unsigned char alpha = off[3];
    	if( alpha!=255 || alpha!=0 )
    	{
    		off[0] = ((int)off[0])*255/alpha;
    		off[1] = ((int)off[1])*255/alpha;
    		off[2] = ((int)off[2])*255/alpha;
    	}
    	off += 4;
    }

    There may be other solutions but this won’t have any impact on the game, just when loading images. Let me know if you find any other solution.

    EDIT: Quick note here: this is not the correct way to deal with pre-multiplied alpha but a patching. XNA recently embraced pre multiplied alpha to avoid this issues. More here (Thanks Elisée Maurer)

    One of the things that was probably forgotten but the dudes who made C++ standard were callbacks, there’s no out of the box solution for Instance based Callbacks, just for functions.
    When I moved to C# I was really happy with the way delegates work, it’s simple, easy and most of all, it works.

    On game development one of the things callbacks are usually used is for Buttons, you have a menu and want to attribute a function to each button. Sure you can point it to the same one and make a bunch of if’s and then point to a Global var which does the correct action, but this is not elegant and sure as hell not easy to add/modify stuff.

    I came across a couple of solutions for having an instance based callback:
    1- Do your own – I’ve made one that worked but couldn’t get around to add parameters. I think we might skip this one since you are probably looking for a quick solution.
    2 – Use boost – If you don’t know this have a look, even for other stuff, Boost has tons of awesome apis for helping C++ development. Including smart pointers that basically delete themselves automatically.
    3 – Use PlusCallback – I decided to use this one.

    And it’s simple to use

    // Callback without parameters
     
    // My example class
    Sprite* sprite = new Sprite();
     
    cb::Callback0<void> call1;
    // Bind callback
    call1.Reset(sprite, &Sprite::SomeFunction);
     
    // Call callback
    call1();.
     
    // Example with parameter
    cb::Callback1<void, Sprite*> call2; 
    // Bind callback
    call2.Reset(sprite, &Sprite::SomeFunctionWithParameterSprite);
     
    // Your function should be something like 
    // Sprite::SomeFunctionWithParameterSprite(Sprite* sprite);
    call2(sprite);

    Easy right? It even work with return, just switch that void to something else. Let me know if you find a better solution. For now I’m sticking with this one.

    It’s been around two weeks since my last post. Basically because I’ve been busy porting my engine Basalt to IPhone/IPad.
    If you follow me on twitter you might have known this already since I ranted pretty much at start, moving platform and language is always painful if you are used to other conventions/shortcuts etc.

    So it all started with my wish to port Vizati to the IPhone, since the game is already running on PC, Xbox360 and Windows Phone 7 one can only wish for an easy and quick port since pretty much all base code is done.

    As you know for developing on the IPhone you require an actual Mac, I know there’s virtualization but my 5 year old PC can’t take it, believe me I tried. So I bought myself a mini mac which are much cheaper that IMac and macbooks, around $499 or so, and another extra $30 for a mini-Dvi to VGA adapter for my 1080p Samsung.

    Let me tell you, that bastard is silent, I mean I can’t listen to anything, powering off my desktop PC and I have this relaxing environment to work in, it’s great for coding during the night when everyone is asleep. I can only hear my keyboard strokes and my cat snoring.
    Here’s a picture of it near the keyboard, it’s really small.

    Now, moving on to the development part, on MacOS your IDE is XCode.

    It’s no Visual Studio but it gets the job done. Has some strange shortcuts but I’ve found a neat shortcut pdf.

    Next was my struggle for testing available engines and frameworks and learning how much of Objective-C do you have to know and can I run C++ on it?

    I tested some engines:
    Cocos2D – 2D engine, Purely Objective-C, very consistent API, it’s was very close to my way of making things on Basalt actually, with scenes and layers.
    SIO2 – Mainly 3D stuff, might be a good starting point, it’s mainly coded in C++, has built in physics, Lua, lightning and shadow
    OolongEngine – 3D engine, imports .3dsmax and .blend, bullet physics
    Bork3D – C++ engine based on Rude Engine. Seems good but I could only find one game made with it from the author itself, lacks documentation but at least it works. Had major performance issues on the IPad sample that comes with the SDK.

    I research a little on those well know tools such as Unity3D, ITorque, etc but those kind of editor aren’t really my thing.

    At one point I convinced myself that the way to go would be learning Objective-C since most tutorials for IPhone are written using it, it’s Iphone OS native language and everyone recommends learning it, but after a few hours watching the amount of square brackets that things has on it I decided another way.

    I ported my C# engine Basalt to C++, literally making .h and .cpp files. I hooked up my main animation and draw pump to some Objective-C classes (don’t forget to use .mm if you are mixing Objective-C with C++) and everything started working.

    The next bit was implementing the SpriteBatch class and make it draw in OpenGL, took me around two days to have the Matrices working, correct texture mapping to quads, Alpha Blend and Additive. The idea is that by the time I port an XNA game to C++ I can still use SpriteBatches, Texture2D etc.

    After these two weeks of development here’s what’s working:

    • Draw Sprites – SpriteBatch is working, texture regions, SpriteBlendModes, Matrices etc
    • Sprite Animations
    • Particle System 2D – Although not a priority it allowed me to test Additive
    • Independent Resolution Rendering – Wasn’t much of deal actually, it’s basically a matrix
    • JPG/PNG load – I made this in Objective-C, 20 lines of code or so

    Here’s a video showing what I have so far:

    Next in my list is Input, Script, music and then porting the whole game to C++, which I think will work nicely once the whole engine base is done.
    Oh, and probably try to get a real device for proper testing.

    PS: Monkey Island 2 Special Edition is awesome….

    See the little black country on the map? It’s Portugal. The green zone are countries around Portugal that have XBOX Live Indie Games. We are surrounded by countries that can place their games on Creator’s Club but we were left behind. I won’t say there aren’t many others but they can speak for themselves.

    I’m tired of watching developers from other countries being able to place their games there and we have to sit and watch.

    Yeah I know there’s money involved and it’s not easy to add a country just because. Even more Portugal doesn’t have a great reputation on gaming and some even think we don’t have anything worth it (Microsoft XNA Pizza Night proved that wrong) but we have a cool xna community that’s fading away and moving to other platforms because it’s not only about making games but also getting money from that.
    If they can’t find it on Xbox they move to others, IPhone, PC etc.

    I have Vizati ready for Playtesting and I’m waiting that someday we get XBLIG here. I hope that with the release of Windows Phone 7, which will be available here that some other doors might also open.

    I am going to start with a little rant about Visual Studio default Installer, you know, the one you can make for yout XNA games inside VS. Ugly and not very handy, sure it installs every dependency but doesn’t leave many options like….hum…I don’t know choosing the location where you want to install?

    Moving along…I discovered this little cool installer called InnoSetup, and best of all it’s free.

    InnoSetup has different ways of you building a proper installer but I am going to cover the script way, much more control.

    I found a little startup script from Caliban Darlock for XNA 2 I think and I modified it for XNA 3.1

    Start by downloading vcredist_x86.exe, DotNetFX35Setup.exe and xnafx31_redist.msi and place them in a folder, I placed mine on D:\Game Development Tools\

    Then onto the script

    ; Script generated by the Inno Setup Script Wizard.
    ; (Then extensively modified by Caliban Darklock.)
    ; (And yet again modified by David Amador) Should work property with XNA 3.1
    ; SEE THE DOCUMENTATION FOR DETAILS ON CREATING INNO SETUP SCRIPT FILES!
     
    ; Enter the name of your game here
    #define MyAppName "Vizati"
     
    ; Enter the name of your game and a version number here
    #define MyAppVerName "Vizati"
     
    ; Enter the name of your company, or just your name
    #define MyCompany "Different Pixel"
     
    ; Enter the URL of your website
    #define MyAppURL "http://vizati.differentpixel.com/"
     
    ; Enter the path to your game project - check Visual Studio properties for the path
    #define MyAppLocation "D:\Projects\Vizati\Vizati"
     
    ; Enter the name of your game executable
    #define MyAppExeName "Vizati.exe"
     
    ; Enter the location where XNA Game Studio is installed
    #define MyGameStudioLocation "C:\Program Files (x86)\Microsoft XNA\XNA Game Studio\v3.1"
     
    ; Enter the name for the correct version of the XNA Framework MSI
    #define XNARedist "xnafx31_redist.msi"
     
    ; Enter the location where you have placed the VC and .NET redistributables
    #define MyRedistLocation "D:\Game Development Tools"
     
    ; search microsoft.com for "visual c++ sp1 redistributable" to get the VC redist
    ; enter the name of the executable file here
    #define VCRedist "vcredist_x86.exe"
     
    ; Download latest .NET from http://www.microsoft.com/net/ (download button on menu)
    ; enter the name of the executable file here
    #define DotNetSetup "DotNetFX35Setup.exe"
     
    ; Once you've filled in all the variables above and downloaded your redist packages,
    ; everything under this point should JUST WORK for most XNA projects.
     
    [Setup]
    AppName={#MyAppName}
    AppVerName={#MyAppVerName}
    AppPublisher={#MyCompany}
    AppPublisherURL={#MyAppURL}
    AppSupportURL={#MyAppURL}
    AppUpdatesURL={#MyAppURL}
    DefaultDirName={pf}\{#MyAppName}
    DefaultGroupName={#MyAppName}
    OutputBaseFilename={#MyAppName}Setup
    Compression=lzma
    SolidCompression=yes
    SetupIconFile = "D:\Projects\Vizati\Vizati\vizati.ico"
    UninstallIconFile = "D:\Projects\Vizati\Vizati\vizati.ico"
     
    [Languages]
    Name: english; MessagesFile: compiler:Default.isl
     
    [Tasks]
    Name: desktopicon; Description: {cm:CreateDesktopIcon}; GroupDescription: {cm:AdditionalIcons}; Flags: unchecked
     
    [Files]
    ; DirectX and XNA Framework redistributables
    Source: {#MyGameStudioLocation}\Redist\DX Redist\*; DestDir: {tmp}
    Source: {#MyGameStudioLocation}\Redist\XNA FX Redist\{#XNARedist}; DestDir: {tmp}
     
    ; .NET and VC redistributables - VerifyDotNet35 MUST run BEFORE VerifyDotNet35sp1!
    Source: {#MyRedistLocation}\{#DotNetSetup}; DestDir: {tmp}; AfterInstall: VerifyDotNet35
    Source: {#MyRedistLocation}\{#VCRedist}; DestDir: {tmp}; AfterInstall: VerifyDotNet35sp1
     
    ; The game itself
    Source: {#MyAppLocation}\bin\x86\Release\{#MyAppExeName}; DestDir: {app}; Flags: ignoreversion
    Source: {#MyAppLocation}\bin\x86\Release\*; DestDir: {app}; Flags: ignoreversion recursesubdirs createallsubdirs
     
    [Icons]
    Name: {group}\{#MyAppName}; Filename: {app}\{#MyAppExeName}
    Name: {group}\{cm:UninstallProgram,{#MyAppName}}; Filename: {uninstallexe}
    Name: {commondesktop}\{#MyAppName}; Filename: {app}\{#MyAppExeName}; Tasks: desktopicon
     
    [Run]
    Filename: {tmp}\{#DotNetSetup}; Flags: skipifdoesntexist; Parameters: "/q /noreboot"
    Filename: {tmp}\{#VCRedist}; Flags: skipifdoesntexist; Parameters: "/q"
    Filename: {tmp}\dxsetup.exe; Parameters: /silent
    Filename: msiexec.exe; Parameters: "/quiet /i ""{tmp}\{#XNARedist}"""
    Filename: {app}\{#MyAppExeName}; Description: {cm:LaunchProgram,{#MyAppName}}; Flags: nowait postinstall skipifsilent
     
    ; The code section doesn't like comments for some reason.
    ; VerifyDotNet35 removes the .NET setup if you already have .NET 3.5 installed.
    ; VerifyDotNet35sp1 removes the VC redist if you already have .NET 3.5 SP1, -or-
    ; if you don't have .NET 3.0 at all (it will be installed along with .NET 3.5).
    ; Using the skipifdoesntexist flag allows the setup to ignore the missing files.
    [Code]
    var
      hasDotNet3 :Boolean;
      hasDotNet3sp :Boolean;
      whichDotNet3sp :Cardinal;
     
    procedure VerifyDotNet35();
    begin
      hasDotNet3 := RegKeyExists(HKEY_LOCAL_MACHINE, 'SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5');
    	if hasDotNet3 then
          DeleteFile(ExpandConstant('{tmp}\{#DotNetSetup}'));
    end;
     
    procedure VerifyDotNet35sp1();
    begin
      hasDotNet3sp := RegQueryDWordValue(HKEY_LOCAL_MACHINE, 'SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5', 'SP', whichDotNet3sp);
      if (hasDotNet3sp and (whichDotNet3sp > 0)) or not hasDotNet3 then
          DeleteFile(ExpandConstant('{tmp}\{#VCRedist}'));
    end;

    So you can basically copy paste this and save it as a .iss file. Should open on double click with Inno Setup Compiler once you install it.

    It’s pretty straight forward and you can modify it with your paths and specific need.

    Things to care about:
    #define MyAppLocation – This is where your Game Project is, typically one folder below the solution
    #define MyGameStudioLocation Folder to XNA Game Studio 3.1 Installation
    #define MyRedistLocation Folder where vcredist_x86.exe and xnafx31_redist.msi and DotNetFX35Setup.exe should be

    The installer will also fetch every file inside you Release Folder. So you might wanna delete those .pdb files before doing it.

    Hit Compile and there you go.

    If everything goes alright the installer should test the registry for XNA and .NET 3.5 and install it if needed. I used Virtual PC with a clean Windows XP installation to test it and it worked. XNA got installed =)

    top

    Bad Behavior has blocked 45 access attempts in the last 7 days.