Trying to run our C++ tutorial on a new Visual Studio version and getting a MSVCR100D.dll missing error

14. May 2014

 

I’ve had a few users run into this error when trying to run the GameFromScratch C++ Game Dev tutorial:

 

image

 

The program can’t start because MSVCR100D.dll is missing from your computer.  Try reinstalling the program to fix this problem.

 

Fortunately this can be pretty easily fixed, simply download and install the Visual Studio 2010 runtime redistributable.  You can download it here.

 

However…

 

The binaries I include with the SFML tutorial of SFML 1.6 are compiled for Visual Studio 2010 and aren’t compatible with Visual Studio 2012/2013.  Normally this is just a matter of recompiling SFML 1.6 in the newest version of Visual Studio, then linking against those Lib/DLL files.  However this process certainly isn't straight forward as the SFML 1.6 code base was actually targeting for Visual Studio 2008 and amazingly enough, depending on some external libraries compiled for Visual C++ 2005!

 

To be honest, if you are running through this tutorial series, by far the easiest solution is to install Visual C++ 2010 Express.  It can be installed side by side with newer versions.

 

If there is enough demand, I can try to make 2013 compatible binaries that you can include with your project.

Programming ,




An “Unreal” week for game developers

10. May 2014

 

First off, sorry for the horrible pun… I wont do it again… at least not today.

 

That said, Unreal may have just flipped the industry on it’s head… or may have just dropped a cleaver marketing gimmick.  By now you have probably heard that Unreal Tournament development will be done in the open.  At least for Unreal Engine subscribers it will be.  Basically if you subscribe to Unreal Engine for 19$ a month, you get Unreal Tournament for free.  The biggest part of the announcement is you get access to a Github repository, so you can watch the game develop, or perhaps even get involved!

 

In Unreal’s own words:

 

HERE’S THE PLAN:
  • We’ve created a small team of UT veterans that are beginning work on the project starting today.
  • From the very first line of code, the very first art created and design decision made, development will happen in the open, as a collaboration between Epic, UT fans and UE4 developers. We’ll be using forums for discussion, and Twitch streams for regular updates.
  • If you are a fan and you want to participate, create a free account and join the forum discussion.
  • All code and content will be available live to UE4 developers on GitHub.
  • The game will be true to its roots as a competitive FPS.
  • Development will be focused on Windows, Mac and Linux.

 

SO WHAT’S THE CATCH?
  • It will take many months until the game is playable by gamers. This is real development from scratch.
  • When the game is playable, it will be free. Not free to play, just free.
  • We’ll eventually create a marketplace where developers, modders, artists and gamers can give away, buy and sell mods and content. Earnings from the marketplace will be split between the mod/content developer, and Epic.  That’s how we plan to pay for the game.

 

So why do I find this move so impressive?  There are a couple reasons…

 

First I was wondering if I would maintain my subscription.  If I am not actively developing in Unreal Engine, was there any point in paying 19$ a month?  I, and many others, wondered if Unreal would keep a stream of content coming that would keep developers paying.  To actively open up a potentially AAA game’s development process is certainly a good hook to keep me watching.  ( Plus, they’ve done a pretty good job keeping the content coming… more on that in a second ).

 

Second, quasi-open sourcing a game could be a brilliant strategy.  Indie developers get to contribute to a large project, probably beyond the scope of what they would otherwise be able to participate in.  Unreal of course gets a ton of free development effort, but retains dictatorial control that large scope games need.  Of course they will have to be selective about what they commit to their main trunk and may bruise some egos, so this could be a bit of a balancing act and will require additional resources on their end, but the trade-offs are probably worth it.  I would generally think this would be mostly a read only process, basically just Unreal developing a game and the community watching.  However they have recently accepted a number of community fixes into the Unreal engine base, so I don’t think this is just marketing.  If nothing else, many indie game developers get the opportunity to eavesdrop on a AAA game’s development, including developer discussions and twitch streams, for a price tag of 19$ a month.

 

The Unreal Tournament github repository is now online:

image

Of course, this is a from scratch project, so have very little expectations for now!

 

 

Finally and perhaps most disruptively “create a marketplace where developers, modders, artists and gamers can give away, buy and sell mods and content. Earnings from the marketplace will be split between the mod/content developer, and Epic”.  This point is MASSIVE.  Basically Unreal are releasing a F2P title where the microtransactions come from the community.  This is a powerful concept, enabling artists and coders to actually get paid for their work, using the exact same tools and process as the parent.  Just as artists and programmers can make a living providing assets to the Unity store, in the future, they will potentially make a living contributing to a game.  A game they potentially helped create.

 

 

Oh, remember earlier where I said Unreal would have to keep a pretty steady stream of updates to keep people subscribed?  Well, impressively enough, they have been.  Since the 1.1 patch ( adding XBox One and PS4 support ) there have been a half dozen new tutorials added, covering topics such as Localization, skeletal meshes and Blueprint complexity management.  Additionally they added a SciFi hallways level:

SciFi Screenshot 1

 

The marketplace is quickly being populated with professional quality examples to work from.  You can read more about the design process here.

 

I have to say Unreal are impressing the hell out of me.  They are taking bold risks and truly are throwing their resources at this, it’s not some half assed indie release like CryEngine or prior UDK releases… this is a slick well supported product and most importantly a thriving community.  Unreal are willing to try some very disruptive strategies and we should applaud them for it.

 

I for one will be keeping my 19$ a month subscription going.

 

Oh yeah, and on that topic, they’ve also laid out a blueprint ( ugh, bad accidental pun! ) for future Unreal development.  You can check it out here on Trello.  This transparency is certainly a good thing.  You can also vote and comment on features that are most important to you, a nice feedback loop with subscribers.

News, Programming ,




LibGDX Tutorial 11: Tiled Maps Part 2: Adding a sprite and dealing with layers

1. May 2014

 

In the prior tutorial we got a simple top down tile map working.  Now we want to add some character to it, literally.  Depending on your needs this can be laughably simple or somewhat complex.  Let’s take a look at a basic example.  This is building on our previous code example and if you’ve worked through the prior tutorials in this series, there is nothing new here yet.

 

package com.gamefromscratch;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapRenderer;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;

public class TiledTest extends ApplicationAdapter implements InputProcessor {
    Texture img;
    TiledMap tiledMap;
    OrthographicCamera camera;
    TiledMapRenderer tiledMapRenderer;
    SpriteBatch sb;
    Texture texture;
    Sprite sprite;
    
    @Override public void create () {
        float w = Gdx.graphics.getWidth();
        float h = Gdx.graphics.getHeight();

        camera = new OrthographicCamera();
        camera.setToOrtho(false,w,h);
        camera.update();
        tiledMap = new TmxMapLoader().load("MyCrappyMap.tmx");
        tiledMapRenderer = new OrthogonalTiledMapRenderer(tiledMap);
        Gdx.input.setInputProcessor(this);

        sb = new SpriteBatch();
        texture = new Texture(Gdx.files.internal("pik.png"));
        sprite = new Sprite(texture);
    }

    @Override public void render () {
        Gdx.gl.glClearColor(1, 0, 0, 1);
        Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        camera.update();
        tiledMapRenderer.setView(camera);
        tiledMapRenderer.render();
        sb.begin();
        sprite.draw(sb);
        sb.end();
    }

    @Override public boolean keyDown(int keycode) {
        return false;
    }

    @Override public boolean keyUp(int keycode) {
        if(keycode == Input.Keys.LEFT)
            camera.translate(-32,0);
        if(keycode == Input.Keys.RIGHT)
            camera.translate(32,0);
        if(keycode == Input.Keys.UP)
            camera.translate(0,-32);
        if(keycode == Input.Keys.DOWN)
            camera.translate(0,32);
        if(keycode == Input.Keys.NUM_1)
            tiledMap.getLayers().get(0).setVisible(!tiledMap.getLayers().get(0).isVisible());
        if(keycode == Input.Keys.NUM_2)
            tiledMap.getLayers().get(1).setVisible(!tiledMap.getLayers().get(1).isVisible());
        return false;
    }

    @Override public boolean keyTyped(char character) {

        return false;
    }

    @Override public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        return false;
    }

    @Override public boolean touchUp(int screenX, int screenY, int pointer, int button) {
        return false;
    }

    @Override public boolean touchDragged(int screenX, int screenY, int pointer) {
        return false;
    }

    @Override public boolean mouseMoved(int screenX, int screenY) {
        return false;
    }

    @Override public boolean scrolled(int amount) {
        return false;
    }
}

 

 

So what exactly did we do?  Well first off, we added this sprite to the project in the android/asset folder.

pik

It might look somewhat familiar… 

In create() we allocate a sprite batch, load our texture and create a sprite with it.  Finally in render() after the map is drawn, we simply draw our sprite to the batch.  Order is of critical importance.  One other thing I should probably point out… I don’t dispose() of anything, so this code leaks like mad…  Now if you run the code you see:

image

 

So far so good! 

 

First problem we’ve got here is, how do we position our sprite within the world?  In this case I am simply drawing at the origin, but how would we go about positioning the sprite in the tile a user clicks?  Let’s go ahead and see!

 

Add the following to the touchDown handler:

public boolean touchDown(int screenX, int screenY, int pointer, int button) {
    Vector3 clickCoordinates = new Vector3(screenX,screenY,0);
    Vector3 position = camera.unproject(clickCoordinates);
    sprite.setPosition(position.x, position.y);
    return true;
}

 

Now we need to make a small change to our sprite batch.  We need to apply our camera transformations to it, so when we scroll the screen around using the arrow keys, our sprite stays put.  This is easily accomplished in render():

public void render () {
    Gdx.gl.glClearColor(1, 0, 0, 1);
    Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    camera.update();
    tiledMapRenderer.setView(camera);
    tiledMapRenderer.render();
    sb.setProjectionMatrix(camera.combined);
    sb.begin();
    sprite.draw(sb);
    sb.end();
}

 

Now when you run it, the sprite will draw where you click in the world:

image

 

There’s a small possible problem here… what if you wanted your sprite to be BEHIND those rocks, or items in the higher level layers? 

 

There are a couple of ways to do this.  First you could actually create a layer for player sprites.  You could simply create a layer in Tiled that you kept empty and add your sprite into it.  Here instead I am going to do so programmatically.  Let me make something perfectly clear, this is most certainly *NOT* how you would do it, but it does give an interesting bit of insight into how tiles and layers are composed.

public void create () {
    float w = Gdx.graphics.getWidth();
    float h = Gdx.graphics.getHeight();

    camera = new OrthographicCamera();
    camera.setToOrtho(false,w,h);
    camera.update();
    tiledMap = new TmxMapLoader().load("MyCrappyMap.tmx");
    tiledMapRenderer = new OrthogonalTiledMapRenderer(tiledMap);
    Gdx.input.setInputProcessor(this);

    sb = new SpriteBatch();
    texture = new Texture(Gdx.files.internal("pik.png"));
    sprite = new Sprite(texture);

    
    // Get the width and height of our maps
    // Then halve it, as our sprites are 64x64 not 32x32 that our map is made of
    int mapWidth = tiledMap.getProperties().get("width",Integer.class)/2;
    int mapHeight = tiledMap.getProperties().get("height",Integer.class)/2;

    // Create a new map layer
    TiledMapTileLayer tileLayer = new TiledMapTileLayer(mapWidth,mapHeight,64,64);
    
    // Create a cell(tile) to add to the layer
    TiledMapTileLayer.Cell cell = new TiledMapTileLayer.Cell();
    
    // The sprite/tilesheet behind our new layer is a single image (our sprite)
    // Create a TextureRegion that is the entire size of our texture
    TextureRegion textureRegion = new TextureRegion(texture,64,64);
    
    // Now set the graphic for our cell to our newly created region
    cell.setTile(new StaticTiledMapTile(textureRegion));
    
    // Now set the cell at position 4,10 ( 8,20 in map coordinates ).  This is the position of a tree
    // Relative to 0,0 in our map which is the bottom left corner
    tileLayer.setCell(4,10,cell);

    // Ok, I admit, this part is a gross hack. 
    // Get the current top most layer from the map and store it
    MapLayer tempLayer = tiledMap.getLayers().get(tiledMap.getLayers().getCount()-1);
    // Now remove it
    tiledMap.getLayers().remove(tiledMap.getLayers().getCount()-1);
    // Now add our newly created layer
    tiledMap.getLayers().add(tileLayer);
    // Now add it back, now our new layer is not the top most one.
    tiledMap.getLayers().add(tempLayer);
}

 

And look, we are behind a tree!

image

 

 

The comments explain it all really.  We basically are programmatically creating a new Tile Layer within the map and positioning it below the top most layer.  You would never do it this way for a sprite for several reasons.  First you will only be able to move in cell by cell chunks ( aka, 64 pixels at a time ).  In certain maps that makes sense, like old school Ultima 4 type role playing games.  Next, to move you actually will have to remove the tile from it’s current location and add it to the new one.  Finally, it’s probably pretty slow to boot.  However if you want to dynamically populate a layer, say with power ups or things you create programmatically instead of using the level editor, this is how you can do it.

 

What about when dealing with the players sprite and moving it only a few pixels at a time?  Well that’s slightly more complicated.

 

One option you have, especially if you want to use the Sprite class, is to extend the map rendering class, in this case OrthogonalTiledMapRenderer then override the render method and render your sprite(s).  Here is a simple example:

package com.gamefromscratch;

import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.maps.MapLayer;
import com.badlogic.gdx.maps.MapObject;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapTileLayer;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;

import java.util.ArrayList;
import java.util.List;

public class OrthogonalTiledMapRendererWithSprites extends OrthogonalTiledMapRenderer {
    private Sprite sprite;
    private List<Sprite> sprites;
    private int drawSpritesAfterLayer = 1;

    public OrthogonalTiledMapRendererWithSprites(TiledMap map) {
        super(map);
        sprites = new ArrayList<Sprite>();
    }

    public void addSprite(Sprite sprite){
        sprites.add(sprite);
    }

    @Override
    public void render() {
        beginRender();
        int currentLayer = 0;
        for (MapLayer layer : map.getLayers()) {
            if (layer.isVisible()) {
                if (layer instanceof TiledMapTileLayer) {
                    renderTileLayer((TiledMapTileLayer)layer);
                    currentLayer++;
                    if(currentLayer == drawSpritesAfterLayer){
                        for(Sprite sprite : sprites)
                            sprite.draw(this.getSpriteBatch());
                    }
                } else {
                    for (MapObject object : layer.getObjects()) {
                        renderObject(object);
                    }
                }
            }
        }
        endRender();
    }
}

 

Now we simply use it in place of the other TileMapRenderer.  Not now that we no longer need a SpriteBatch, since we are using the map renderer’s.  Here’s the updated code:

package com.gamefromscratch;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;
import com.badlogic.gdx.math.Vector3;

public class TiledTest extends ApplicationAdapter implements InputProcessor {
    Texture img;
    TiledMap tiledMap;
    OrthographicCamera camera;
    OrthogonalTiledMapRendererWithSprites tiledMapRenderer;
    Texture texture;
    Sprite sprite;
    
    @Override
    public void create () {
        float w = Gdx.graphics.getWidth();
        float h = Gdx.graphics.getHeight();

        camera = new OrthographicCamera();
        camera.setToOrtho(false,w,h);
        camera.update();

        texture = new Texture(Gdx.files.internal("pik.png"));
        sprite = new Sprite(texture);

        tiledMap = new TmxMapLoader().load("MyCrappyMap.tmx");
        tiledMapRenderer = new OrthogonalTiledMapRendererWithSprites(tiledMap);
        tiledMapRenderer.addSprite(sprite);
        Gdx.input.setInputProcessor(this);
    }

    @Override
    public void render () {
        Gdx.gl.glClearColor(1, 0, 0, 1);
        Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        camera.update();
        tiledMapRenderer.setView(camera);
        tiledMapRenderer.render();
    }

    @Override
    public boolean keyDown(int keycode) {
        return false;
    }

    @Override
    public boolean keyUp(int keycode) {
        if(keycode == Input.Keys.LEFT)
            camera.translate(-32,0);
        if(keycode == Input.Keys.RIGHT)
            camera.translate(32,0);
        if(keycode == Input.Keys.UP)
            camera.translate(0,-32);
        if(keycode == Input.Keys.DOWN)
            camera.translate(0,32);
        if(keycode == Input.Keys.NUM_1)
            tiledMap.getLayers().get(0).setVisible(!tiledMap.getLayers().get(0).isVisible());
        if(keycode == Input.Keys.NUM_2)
            tiledMap.getLayers().get(1).setVisible(!tiledMap.getLayers().get(1).isVisible());
        return false;
    }

    @Override
    public boolean keyTyped(char character) {

        return false;
    }

    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        Vector3 clickCoordinates = new Vector3(screenX,screenY,0);
        Vector3 position = camera.unproject(clickCoordinates);
        sprite.setPosition(position.x, position.y);
        return true;
    }

    @Override
    public boolean touchUp(int screenX, int screenY, int pointer, int button) {
        return false;
    }

    @Override
    public boolean touchDragged(int screenX, int screenY, int pointer) {
        return false;
    }

    @Override
    public boolean mouseMoved(int screenX, int screenY) {
        return false;
    }

    @Override
    public boolean scrolled(int amount) {
        return false;
    }
}

 

Now when you run it, where you click the player sprite will be positioned correctly and behind objects:

image

.

Under this system however, you just treat your sprite normally.  Update it’s position and it’s updated in the game world.

 

There is one other possible way to support this functionality, that is a bit of a hybrid of both approaches.  Like the earlier example, we add a new layer in to the map, in this case we are going to do it in Tiled instead of programmatically.

 

In Tiled, create a new object layer and position it like so:

image

 

Now we are going to access it using the MapObject class, specifically the TextureMapObject ( a somewhat confusingly named class… ).  Once again this requires a custom TileRenderer implementation, this time overriding the renderObject class, like so:

package com.gamefromscratch;

import com.badlogic.gdx.maps.MapObject;
import com.badlogic.gdx.maps.objects.TextureMapObject;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.renderers.OrthogonalTiledMapRenderer;

public class OrthogonalTiledMapRendererWithSprites extends OrthogonalTiledMapRenderer {

    public OrthogonalTiledMapRendererWithSprites(TiledMap map) {
        super(map);
    }

    @Override
    public void renderObject(MapObject object) {
        if(object instanceof TextureMapObject) {
            TextureMapObject textureObj = (TextureMapObject) object;
                spriteBatch.draw(textureObj.getTextureRegion(), textureObj.getX(), textureObj.getY());
        }
    }
}

 

renderObject() is called to render the various well… MapObjects in the tilemap.  The default implementation is empty, so we need to provide one.  Here we simply check to see if our object is a TextureMapObject and if it is we draw it using the spriteBatch, much like before.

 

A side effect is we no longer use the Sprite class for positioning.  Instead we create a TextureRegion again and control position via the TextureMapObject setX/setY methods.  Let’s take a look at the result on our main application:

package com.gamefromscratch;

import com.badlogic.gdx.ApplicationAdapter;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input;
import com.badlogic.gdx.InputProcessor;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.Sprite;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.maps.MapLayer;
import com.badlogic.gdx.maps.objects.TextureMapObject;
import com.badlogic.gdx.maps.tiled.TiledMap;
import com.badlogic.gdx.maps.tiled.TiledMapRenderer;
import com.badlogic.gdx.maps.tiled.TmxMapLoader;

import com.badlogic.gdx.math.Vector3;

public class TiledTest extends ApplicationAdapter implements InputProcessor {
    Texture img;
    TiledMap tiledMap;
    OrthographicCamera camera;
    TiledMapRenderer tiledMapRenderer;
    SpriteBatch sb;
    Texture texture;
    Sprite sprite;
    MapLayer objectLayer;

    TextureRegion textureRegion;

    @Override
    public void create () {
        float w = Gdx.graphics.getWidth();
        float h = Gdx.graphics.getHeight();

        camera = new OrthographicCamera();
        camera.setToOrtho(false,w,h);
        camera.update();
        tiledMap = new TmxMapLoader().load("MyCrappyMap.tmx");
        tiledMapRenderer = new OrthogonalTiledMapRendererWithSprites(tiledMap);
        Gdx.input.setInputProcessor(this);
        texture = new Texture(Gdx.files.internal("pik.png"));

        objectLayer = tiledMap.getLayers().get("objects");
        textureRegion = new TextureRegion(texture,64,64);

        TextureMapObject tmo = new TextureMapObject(textureRegion);
        tmo.setX(0);
        tmo.setY(0);
        objectLayer.getObjects().add(tmo);
    }

    @Override
    public void render () {
        Gdx.gl.glClearColor(1, 0, 0, 1);
        Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA);
        Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
        camera.update();
        tiledMapRenderer.setView(camera);
        tiledMapRenderer.render();
    }

    @Override
    public boolean keyDown(int keycode) {
        return false;
    }

    @Override
    public boolean keyUp(int keycode) {
        if(keycode == Input.Keys.LEFT)
            camera.translate(-32,0);
        if(keycode == Input.Keys.RIGHT)
            camera.translate(32,0);
        if(keycode == Input.Keys.UP)
            camera.translate(0,-32);
        if(keycode == Input.Keys.DOWN)
            camera.translate(0,32);
        if(keycode == Input.Keys.NUM_1)
            tiledMap.getLayers().get(0).setVisible(!tiledMap.getLayers().get(0).isVisible());
        if(keycode == Input.Keys.NUM_2)
            tiledMap.getLayers().get(1).setVisible(!tiledMap.getLayers().get(1).isVisible());
        return false;
    }

    @Override
    public boolean keyTyped(char character) {

        return false;
    }

    @Override
    public boolean touchDown(int screenX, int screenY, int pointer, int button) {
        Vector3 clickCoordinates = new Vector3(screenX,screenY,0);
        Vector3 position = camera.unproject(clickCoordinates);
        TextureMapObject character = (TextureMapObject)tiledMap.getLayers().get("objects").getObjects().get(0);
        character.setX((float)position.x);
        character.setY((float)position.y);
        return true;
    }

    @Override
    public boolean touchUp(int screenX, int screenY, int pointer, int button) {
        return false;
    }

    @Override
    public boolean touchDragged(int screenX, int screenY, int pointer) {
        return false;
    }

    @Override
    public boolean mouseMoved(int screenX, int screenY) {
        return false;
    }

    @Override
    public boolean scrolled(int amount) {
        return false;
    }
}

 

It’s mostly the same, except of course the different renderer, the fact we no longer use a Sprite object and in touchDown() we locate the TextureMapObject in the “objects” layer and update its positions.

 

 

Which method you use is up to you, your personal preference and the requirements of your game.  Myself, I find the second to be probably the most clean.  Of course if your sprite doesn’t need to care about tile depth at all, you can ignore all of this and just use SpriteBatch over top and save yourself many headaches!

Programming , , ,




Using Microsoft’s Azure for your game’s server

24. April 2014

 

This post actually came about by accident.  I’ve been playing around with Telerik’s recently open sourced Kendo UI suite and I found myself needing a web back end.  Of course I could have used my own server, but every time you do something like that you open up another potential security concern.  Ages ago I did an HTML5 tutorial where I used a free version of Heroku Node hosting and a CouchDB back end, but truth is, it was kindof a pain in the ass.  This time I decided to take a look at the state of Azure and see if it was an appropriate option.

 

So what exactly is Azure… well, that’s a confusing thing to answer.  Basically it’s Microsoft’s ____________ as a service offering.  In the ___________ you can insert the words platform, database, cloud, etc.  Basically it’s a number of cloud based offerings, from straight VM based hosting like Amazon’s EC2, to a cloud based SQL server.  What we are most interested here is “Mobile”, which is a scalable back end for mobile software and websites.  This is a way for you to deploy your code to the cloud and let someone else worry about the infrastructure, scaling, backups, etc.  It is most similar to solutions like Heroku and Google App Engine, it straddles the point between running your own servers and using a prebuilt gaming solution.

 

This article looks at Azure for smaller mobile or HTML5 games.  Things like scoreboards, matchmaking, cloud saves, that kind of thing.  If you are looking at creating a server heavy game such as an MMO you need to look elsewhere, like here.

 

So, why Azure Mobile?

  • no server to maintain
  • easy scaling
  • a free tier is available for just getting started
  • it’s pretty cheap ( relative term of course )
  • it’s Microsoft.  They’ve literally spent billions creating Servers. Bandwidth and uptime should never be an issue
  • it’s not Google.  Every time I use a Google technology like App Engine, I want to punch a donkey
  • JavaScript and now, C# backends
  • Visual Studio tooling support
  • Authentication and Notifications built in ( Google, Twitter, MS, Facebook, etc… ).  Normally a huge pain point
  • As hard as it is to believe, they are probably better at security than you

 

Why not?

  • JavaScript/C# only… want Rails for example, Mobile isn’t for you
  • Can be confusing as hell.  Documentation isn’t as good as it should be
  • Visual Studio…  some people hate it.  It’s clearly easiest working in VS, but VS can be a daunting beast
  • It’s Microsoft, for some people this is a huge negative.
  • Less control

 

So… Costs?

 

First thing you have to head over to http://azure.microsoft.com/ and sign up.  A bit of a warning, you need to sign up and give a valid credit card, but you don’t have to pay anything.  When prompted select a Pay As You Go plan.  Oh yeah, costs, like talk about that for a minute:

 

image

 

Oddly enough, changing the region has no effect on the price.  So basically you can start for free for up to 1/2 million calls per month from 500 devices and a total of 20MB of data.  At the free tier you can have up to 10 different “services”, which considering a service can have tons of API calls, isn’t really a major limit.

When you jump into the “pay” tier, you are looking at 27$ a month per “unit”.  A unit is a theoretical computing unit, for which I couldn’t for the life of me find the definition of ( in Amazon, it is strictly defined as for example 1x 1.7ghz core, 768MB RAM, etc… ) anywhere.  API calls are tripled up to 1.5M per unit.  As you can see, the BASIC tier is the first one that allows you to start scaling up performance as needed.  So if your site is getting slammed, you can crank the processing power up to 6X the base.  Perhaps the most important aspect is there is no longer any device limits… so if you have 10 users or 10 million, same price for you.  Standard basically 10X’s the resources but at about 8X the price.

 

So, what about data costs?  20MB is obviously a pretty small amount, what’s this cost?  This is pretty straight forward as well:

 

image

 

So basically > 20MB and < 100MB is $5.27 a month.  Then another $5.27 to raise that cap to a GB, then basically a lowering amount for each additional GB as you add more, eventually settling at about 1$ a GB a month.  Trying to do direct pricing comparison to Amazon is tricky, as the bill in a completely different manner.  For example, storage for their RDS MySQL hosting is only 12.5 cents a GB however you pay for processing, transactions, etc.  Frankly it was the confusion of Amazon pricing that lead me to choose SoftLayer ages ago.

 

Creating a Mobile Services service

 

Everything is managed from the Azure portal and for the most part it’s pretty straight forward.  Its located at http://manage.windowsazure.com

image

 

All your various Azure services, websites, databases, etc… are available down the right hand side.  For now we just care about Mobile Services.

To get started, Click the Mobile Services tab then the + NEW in the bottom left corner.

image

 

Now simply click Create

image

 

The process is about as easy as it gets.  You need to select a unique ( across Azure, not just your projects ) prefix for the URL.  The key question is what kind of Backend you want, JavaScript or .NET.  I personally like .NET so that is what I am going with.

image

 

Finally you configure your database settings and then you are done:

image

 

Enter Visual Studio

 

Now head back to the Mobile Services tab if it doesn’t take you there automatically.  Now you want to select an App type ( it really doesn’t matter ), then download the project file.

 

image

 

The download file is simply a Visual Studio solution coupled with a NuGet install.  Extract the archive then double click the sln file to open it in Visual Studio.  Don’t worry, this works fully with the free version of Visual Studio if that’s what you’ve got.

It should look something like this:

image

 

Don’t worry, it’s nowhere near as complicated as it looks.  By default the project comes with a working value TodoItem.  You can go ahead and run your Mobile Service, it works 100% locally, which is kinda cool.  Press F5 and you will see:

image

 

Click Try it out and you will see the scaffolding it created for you:

image

Pretty cool.  Keep in mind, HighScore was created by me, so you wont have that. 

 

Mobile Services works just like any typical RESTful service.  You make a request using URLs, for example http://localhost:51289/tables/TodoItem (your port number will vary!) returns:

image

While http://localhost:51289/tables/TodoItem/1 returns the TodoItem with the id 1, like so:

image

Of course a complete description of REST is wayyyyy beyond the scope of this tutorial.  For more details IBM did a pretty good job explaining them, but there are hundreds of similar documents on the web.

 

Finally some freaking coding

 

Now let’s add our own service.  First let’s create a Controller.  A controller is basically what maps a URL to an action.  In your solution, right click the Controllers folder, select Add and Controller, like so

image

 

Select Web API 2 Controller – Empty

image

Then click Add.

 

In the dialog, name it.  This is going to be about the easiest controller you’ve ever seen in your life.  The Hello World of web services.

image

Now let’s look at some code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace arghService.Controllers
{
    public class HelloController : ApiController
    {
        public string Get()
        {
            return "Hello World from GET request";
        }

        public string Post()
        {
            return "Hello world from POST request";
        }
    }
}

 

Now if you request /api/Hello/ either via POST (form) or GET (url), it will return a Hello string.

 

Of course, this example isn’t really all that useful, let’s try and create a more useful service, a simple high score board.  First we need a datatype to store our highscore’s in.  Simply right click the Models folder and select Add->Class…

image

 

Name it HighScore.cs and click Add.  Add the following code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace arghService.Models
{
    public class HighScore
    {
        public int Id { get; set; }
        public int Score { get; set; }
        public string Name { get; set; }
    }
}

 

Now add a new Controller, just like before.  This time call it HighScoreController.cs.  Let’s take a look at some code:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using arghService.Models;
using Microsoft.WindowsAzure.Mobile.Service.Security;

namespace arghService.Controllers
{

    public class HighScoreController : ApiController
    {
        public static List<HighScore> scores = new List<HighScore> {
            new HighScore {Id=1,Name="Mike",Score=42},
            new HighScore {Id=2,Name="Bob",Score=43}
        };

        protected override void Initialize(System.Web.Http.Controllers.HttpControllerContext controllerContext)
        {
            base.Initialize(controllerContext);
        }

        public IEnumerable<HighScore> GetAllHighScores()
        {
            return scores;
        }


        [HttpGet]
        public IHttpActionResult GetHighScoreByName(string name)
        {
            var score = scores.FirstOrDefault((s) => s.Name == name);
            if (score != null)
                return Ok(score);
            return NotFound();
        }

        public IHttpActionResult PutHighScore(HighScore highScore){
            scores.Add(highScore);
            return Ok();
        }
    }
}

 

Run this code and then in the generated help page you will now see:

image

Click the PUT api/HighScore link and you can test your new service out clicking the Try This Out link.

image

 

Now try out the GET api/HighScore link and you will see your new entry in the results:

image

 

So there you go, an ultra simple REST web service exposing a high score list.  Granted, the code is pretty awful.  It’s not thread safe, it has no persistence when the server ends, no security, etc.  But it illustrates how simple the basics actually are.

 

Going Live

 

Now that you’ve got your service working locally, its time to deploy to Azure.  Fortunately it’s as simple as right clicking your project and selecting Publish:

image

 

To configure your publish profile, you can download this from the Azure Mobile Services portal.  In the Dashboard tab, select Download publish profile.

image

 

And now your Azure service is online, assuming there were no errors.  Mine for example is at http://argh.azure-mobile.net/.  Now here is one of the infuriating parts of dealing with Microsoft…  no matter how far I search, I cant figure out the authentication being requested here if you want to access the generated HTML5 scaffolding.  Fortunately it shouldn’t matter at this point, as you should only be accessing your service from code at this point.

 

 

Let’s look at calling our service in Fiddler.

Here is a request:

image

And here is the response:

image

 

Woot!

 

Other nice things

 

There are a few other perks to using Azure…  first is the out of the box authentication options:

image

 

Writing OAuth code is frankly a bit of a pain in the ass, so its nice to see Microsoft have taken care of it for you.  So if you want your users to authenticate against Twitter, Facebook, Google, etc… it’s incredibly simple.

 

The Database.  We never each touched on the SQL side of Azure and it makes your life pretty easy.  Basically it works just like the Azure project did, you download a local project to work and test with, then deploy it back to Azure:

image

 

You have a standard SQL Connection string you can connect with, so you can treat an Azure database just like any other local or remote DB.

 

Push Notifications.  Just like they have made authenticating to multiple services easy, so have they done with push notifications:

image

Windows, Windows Phone, Apple and Google Notification are all supported.

 

Automatic scaling…

image

While not supported on the free tier, you can easily set up your service to scale up when needed, or perhaps more important, to not scale up.

 

 

All told, Azure is a pretty impressive service but needs better documentation.  You spend a lot of time trying to work out things that should be extremely simple ( not what account to log in with… ), but what is there is pretty intuitive.  The scope of Web API ( the library used for actually writing the code ) is massive and again, could use some better documentation.  Normally MSDN is a bastion of information, but in this case, the pickings are pretty slim.

 

From my experiences, this is vastly more polished than Amazon’s offerings… or at least, easier.  That said, Amazon has an entire ecosystem built over their offerings that provide that polish for you.  Google…  well it’s just crap frankly.  Besides after they pulled this and with their habit of killing of popular products rather suddenly, I wouldn’t dream of using their services personally.

General, Programming ,




The Unreal Engine 4 Rosetta Stone

21. April 2014

 

Comprehending any large code base is never a simple factor.  This is especially true of C++ with hits heavily used (and abused) typedef system.  The Unreal Engine has a very well defined and consistent naming convention but trying to crack it can take a bit of effort, as it’s explained piecemeal throughout the documentation. RosettaStone That is, until I found the Coding Standard document, which frankly is the very first page a C++ programmer working with UE4 should start with.  This document is the titular Rosetta Stone, the method that makes reading UE code possible.

 

Understanding their naming conventions will help you a great deal when trying to work through code samples.  A few of their choices strike me as a bit unusual, especially if you were raised on Hungarian like I was.  Here are the naming convention:

  • The first letter of each word in a name (e.g. type or variable) is capitalized, and there is usually no underscore between words. For example, Health and UPrimitiveComponent, but not lastMouseCoordinates or delta_coordinates.

  • Type names are prefixed with an additional upper-case letter to distinguish them from variable names. For example, FSkin is a type name, and Skin is an instance of a FSkin.

    • Template classes are prefixed by T.

    • Classes that inherit from UObject are prefixed by U.

    • Classes that inherit from AActor are prefixed by A.

    • Classes that inherit from SWidget are prefixed by S.

    • Classes that are abstract interfaces are prefixed by I.

    • Most other classes are prefixed by F, though some subsystems use other letters.

  • Type and variable names are nouns.

  • Method names are verbs that describe the method's effect, or describe the return value of a method that has no effect.

Variable, method, and class names should be clear, unambiguous, and descriptive. The greater the scope of the name, the greater the importance of a good, descriptive name. Avoid over-abbreviation.

All variables should be declared one at time so that a comment on the meaning of the variable can be provided. Also, the JavaDocs style requires it. You can use multi-line or single line comments before a variable, and the blank line is optional for grouping variables.

All functions that return a bool should ask a true/false question, such as "IsVisible()", or "ShouldClearBuffer()". All boolean variables must be prefixed with a "b" character (e.g. "bPendingDestruction", or "bHasFadedIn").

A procedure (a function with no return value) should use a strong verb followed by an object. An exception is if the object of the method is the object it is in; then the object is understood from context. Names to avoid include those beginning with "Handle" and "Process"; the verbs are ambiguous.

Though not required, we encourage you to prefix function parameter names with "Out" if they are passed by reference and the function is expected to write to that value. This makes it obvious that the value passed in this argument will be replaced by the function.

 

This explains all the AClass and UProperty you will encounter through out the code, and explains the far to common FSomethings you see in the code..

 

There are a few things I find unwieldy about these choices.  First, I am so used to instances starting with lower case that this seems like Anathema to me.  Second, if you are going to prefix with all capital letters, why not BBoolValue instead of bBoolValue, this seems inconsitent to me.  Next, why F for types? Finally why SWidget and S instead of Widget and W?  WButton makes a ton more sense than SButton for example.

 

At the end of the day it doesn’t really matter, the most important thing is to be consistent, which they have.  Now with a thorough understanding of their naming convention, groking the code is a heck of a lot easier.

 

Also of great important are the C++ type usage guidelines.  This is both a power and flaw of working with C++, there are more types than grains of sand in the desert, so knowing which to use is critical.

 

Portable Aliases for Basic C++ Types

  • bool for boolean values (NEVER assume the size of bool). BOOL will not compile.

  • TCHAR for a character (NEVER assume the size of TCHAR)

  • uint8 for unsigned bytes (1 byte)

  • int8 for signed bytes (1 byte)

  • uint16 for unsigned "shorts" (2 bytes)

  • int16 for signed "shorts" (2 bytes)

  • uint32 for unsigned ints (4 bytes)

  • int32 for signed ints (4 bytes)

  • uint64 for unsigned "quad words" (8 bytes)

  • int64 for signed "quad words" (8 bytes)

  • float for single precision floating point (4 bytes)

  • double for double precision floating point (8 bytes)

  • PTRINT for an integer that may hold a pointer (NEVER assume the size of PTRINT)

Don't use the C++ int type in portable code, since it's dependent on the compiler how large it is.

 

So if you are just starting out with C++ programming in Unreal, start here, it will make the journey a lot easier.

 

Finally C++ 11 guidelines are also important.  C++11 support across compilers is by no means universal but many of the features of C++11 are pretty damned useful.  Keep in mind, these guidelines are for Unreal staff working on the engine, not the end user working with the engine, so if you are say… only using Visual C++ 13, then feel free to use whatever features you want.  If you want to target as many platforms as possible though, you should be mindful of these instructions:

 

C++ 11 and Modern Language Syntax

Unreal Engine is built to be massively portable to many C++ compilers, so we're careful to use features that are compatible with the compilers we can imagine supporting. Sometimes features are so useful that we'll wrap them up in macros and use them pervasively (such as the 'override' keyword), but usually we'll wait until all of the compilers we could imagine supporting are up to the latest standard.

We are utilizing certain C++ 11 language features that appear to be well-supported across modern compilers, such as the "auto" keyword, range-based-for and lambdas. In some cases we're able to wrap up usage of these features in preprocessor conditionals (such as rvalue references in containers.) However, certain language features we may opt to avoid entirely until we're confident we won't be surprised by a new platform appearing that cannot digest the syntax.

Unless specified below as a modern C++ compiler feature we are supporting, you should refrain from using compiler-specific language features unless they are wrapped in preprocessor macros or conditionals and used sparingly.

The 'auto' Keyword

The 'auto' keyword is supported by all compilers UE4 targets and you are encouraged to use it in your code where it makes sense to do so.

Remember you can and should use const, & or * with auto just like you would with the type name. With auto, this will coerce the inferred type to be what you want.

We encourage use of the auto keyword for iterator loops (eliminates boilerplate), and also when you are initializing a variable to a new instance (eliminates redundant type name.) Some of the other uses are more contentious, but feel free to use it however you want for now and we can learn and improve best practices as we go.

Tip: If you hover over a variable in Visual Studio, it will usually tell you the inferred type.

Range Based For

This is allowed in all engine and editor code and encouraged where it can help to keep the code easier to understand and more maintainable.

Lambdas and Anonymous Functions

Lambdas are now allowed, however we are cautious about use of stateful lambdas that capture stack variables -- we're still learning about where those are appropriate. Also, stateful lambdas cannot be assigned to function pointers which we tend to use a lot. We expect to update this documentation in the future as we establish best practices.

 

So, basically ranged based for loops, stateless lambdas good, stateful lambda bad and auto is a maybe.  For the remaining features that aren’t cross platform like override, they’ve provided preprocessor conditionals to work with them.  I really wish they listed them all here though.

Programming ,