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 ,




Sony open source game tool creation kit ATF The Authoring Tools Framework

11. March 2014

 

From this post on reddit I have learned of the open sourcing of Sony’s game tool creation kit Authoring Tools Framework (ATF).  The ATF is a comprehensive .NET/C# based framework for creating game tools.  It has been used to create all kinds of tools for several shipped games including the level editor for Naughty Dog’s epic Last of Us.

 

In Sony’s own words:

Authoring Tools Framework (ATF) is a set of C#/.NET components for making tools on Windows. ATF has been used by most Sony first party game studios to make many custom tools such as Naughty Dog’s level editor and shader editor for The Last of Us, Guerrilla Games’ sequence editor for Killzone games (including theKillzone: Shadow Fall PS4 launch title), an animation blending tool at Santa Monica Studios, a level editor at Bend Studio, a visual state machine editor for Quantic Dream, sound editing tools, and many others. ATF has been in continuous development in Sony's Worldwide Studios central tools group since early 2006.

 

The license is Apache Version 2, which is a very liberal license with no GNU style conditions.

 

Sample Level Editor created using ATF

 

When I said comprehensive earlier, I meant it.  This is an incredibly well documented project.  There is a 75 page PDF DOM programming guide, a 30 page Getting Started PDF as well as a comprehensive online Wiki, including the ATF Programmer’s Guide.

 

The framework itself contains a number of classes.  It is provided as a Visual Studio 2010 project.  As you can see, ATF provides GUI components, Collada and Perforce support and more.  The core however is um… in Atf.Core, which provides the backbone of the framework itself.

 

image

 

From my quick scan, ATF appears to provide a game orriented MFC style document model.  It’s complex, it will take some time digging before I can fully appreciate what this framework provides.  However, to assist in that, there are a number of included samples:

image

 

Unfortunately, a few of them are missing, including probably the one you would be most interested in, LevelEditor.  Hopefully these get released in short order.

 

It is getting increasingly common to create games using C# and this toolkit should make the job a heck of a lot easier!  Very cool release Sony!

News , ,




OpenTK 1.1 released

17. February 2014

 

OpenTK, a low level C# binding for the OpenGL, OpenAL and OpenCL has just hit a milestone 1.1 release.  It’s a project used behind the scenes by a number ofimage projects such as MonoGame.  Funny enough, they keep a low enough profile everyone always thinks they are dead!  Fortunately for .NET loving OpenGL fans, they are not.

 

 

This release brings a number of new goodies, including:

1. support for OpenGL 4.4 and OpenGL ES 3.0
2. strongly-typed enums for OpenGL ES 2.0 and 3.0
3. new, faster OpenGL bindings based on hand-optimized IL
4. a new SDL2 backend for improved platform compatibility
5. new Joystick and GamePad APIs under OpenTK.Input
6. improved startup time and reduced memory consumption
7. inline documentation for all OpenGL and OpenGL ES core functions
8. a greatly expanded math library
9. numerous bugfixes for Mac OS X, Windows 8 and Linux
10. ANGLE support for Windows systems without OpenGL drivers
11. support for Retina / high-DPI monitors
12. monolinker can now be used to reduce the size of OpenTK.dll
13. precompiled binaries for optional dependencies (OpenAL, SDL2, monolinker)

 

You can read the full release notes here and download the full package here.  OpenTK is an open source project hosted on Github here.

News ,




Duality C# based game engine with Visual editor

14. January 2014

I love seeing new game engines pop up, and this one just arrived on reddit.  It’s called Duality and it sounds kinda cool.

 

In the authors own words ( pretty much verbatim from reddit ):

 

What is Duality?

  • It's a 2D game engine that comes with a visual editor.
  • Both engine and editor are Open Source (MIT license).
  • It's all based on C# and OpenTK.
  • The frameworks architecture is built around a plugin system with hotswap support.
  • It is highly extensible, even without touching the original source code.
  • Work on this project began somewhere around November 2011. It's still in active development.

Duality1

 

Why does it exist?

  • My initial goal was to stop writing a new engine for every game I made, and instead create one framework that can serve as a basis for all of my future projects, regardless of genre or gameplay elements. This would allow me to spend less time on engine coding and more time on making games. Ironically, where I ended up is doing even more engine coding for quite a while - but by now, Duality has grown to be pretty usable, and I've developed a lot of projects just using it.
  • Duality exists, because I've always wanted a C# framework like this, but there was none that "had it all": Focused on 2D games, fast iteration times and visual editing, but at the same time free, Open Source and designed to be vastly extensible. While there are a lot of products on the engine market that do a really great job, most of them are still closed systems: Something that you might buy in a shop and use regularly, but wouldn't bother modifying, because it is generally a bad idea or downright impossible. On the other hand, Duality is kind of a construction kit.
  • Also, I have always been a fan of modding, i.e. being able to take an existing game as a player, and add my own stuff. One of the core ideas behind Duality is, that you, the developer, will use it to build your game and extend it wherever necessary. It's visual editor can serve as level editor, content database, sandbox and testing environment. When releasing your game - just leave the editor in there. It doesn't cost you anything, but your players get to use the same editing system you had: Duality, tailored exactly to fit your game.

 

Duality2

What can it do?

  • Content and Resource Management: Serialization, Importing and Updating Content, Custom Resource format using Binary or XML data, Friendly to Version Control systems, Robust in case of errors and old data
  • Scene Graph and Object Management: Component based GameObjects, Parent-child relations and transformation, Shared extensible Component interfaces, Scene queries
  • Audio: Playing and configuring sound effects and music, Streaming, Randomized sounds, 3D audio
  • Rendering: Camera based, Multiple Renderpasses, Postprocessing, Automated Batching and Z Sorting, Fake perspective using parallax scaling and scrolling
  • Physics: Based on a custom OpenTK version of Farseer Physics, Collision Detection, Rigidbody Physics, Visual Shape Editing
  • User Input: Keyboard, Mouse, Joysticks, Gamepads, Open to Custom Input methods
  • Visual Editor: What-You-See-Is-What-You-Get, Resource Hotswap, Plugin Hotswap, User Advice based on XML code comments, Extensive Dragdrop support, Multiple Views, Docking based on WeifenLuo library
  • A lot of other fancy stuff: Profiling, Logging, Text Formatting, Animation, Prefabs, Cloning, etc.

 

 

Where can I find more information?

 

What I don’t currently know is what platforms it runs on!  I am personally a fan of C#, so it’s always nice to see more options out there.

 

EDIT: According to the author, Duality is currently Windows only.  Being written in C# and on top of the OpenTK ( OpenGL for .NET ) libraries should make it fairly portable.

News, Programming ,




Zynga release PlayScript, a C# 5/ActionScript hybrid that targets the mono runtime

5. April 2013

The project is currently up on Github.

PlayscriptLogo

 

 

 

 

 

 

I will let them describe it in their own words:

PlayScript is an open source Adobe ActionScript compatible compiler and Flash compatible runtime that runs in the Mono .NET environment, targeting mobile devices through the Xamarin Studio MonoTouch and Mono for Android platforms. With a combination of Adobe FlashBuilder for Web and Xamarin Studio for mobile complex large scale cross-mobile-web projects can be developed with full IDE, source debugging and intellisense support on all platforms, with access to the full native mobile API's on the mobile platform.

The PlayScript compiler also targets both C++ and JavaScript (similar to the Haxe compiler) allowing ActionScript code to be run via JavaScript on the Web, or natively on PC and mobile (with some limitations). (NOTE: Presently the JS and C++ targets are at an experimental stage)

In addition to accurate ActionScript language support, the PlayScript compiler also supports a new language - PlayScript - which is derived from both C# and ActionScript. This new language supports all of the features of C#, including generics, properties, events, value types, operator overloading, async programming, linq, while at the same time being upwards compatible with ActionScript. The PlayScript language can be used to target both web and mobile (via Xamarin and JavaScript), and existing Flash code can easily be converted to PlayScript code by simply renaming files from .as to .play, and fixing a few issues related to the stricter syntax and semantics of the PlayScript language.

Finally, the PlayScript runtime supports a full Stage3D compatible implementation of the Flash runtime allowing games that are Stage3D compliant to run with very minor modifications on mobile via the Xamarin/Mono runtime. A subset of the "display" library is implemented to support Stage3D libraries such as Starling, Away3D, and Feathers, though there are no plans at the present time implement the full Flash display system.

And:

Features:

Native Performance

  • Using "unsafe" code.
  • Direct interop with native code (Cocos2D-X, other C++ based engines such as Page44, etc).
  • Optimized compiler for JavaScript generation.
  • Optional full C++ target with minimal app size and startup overhead.

Advanced Tools Support

  • Complete tool support including Syntax Highlighting and intellisense in the MonoDevelop IDE.
  • Source Debugging on all platforms (FlashBuilder for Flash).
  • Fast Release mode compiles and rapid iteration.

Full Platform API's

  • Complete iOS platform API via Xamarin MonoTouch and Mono for Android
  • Complete Windows/MacOSX API's.
  • Complete integration with UI builder (iOS), and Android GUI builder via Xamarin Studio.

Differences between PlayScript and ActionScript

  • PlayScript supports most features of C# 5.
  • PlayScript requires semicolons after all statements.
  • PlayScript uses block scoping for variables.
  • PlayScript requires breaks in switch statements.
  • PlayScript supports generics using the .<> syntax introduced in AS3 with the normal C# feature set.
  • PlayScript supports properties using the "property" keyword with syntax similar to C#.
  • PlayScript supports indexers and operator overloads using the "indexer" and "operator" keywords.
  • PlayScript implements AS3 namespaces by converting them to .NET internal.

Differences between PlayScript and CSharp

  • PlayScript requires the use of the "overload" keyword on addtional overload methods (allows more readable JavaScript code by only mangling overload method names).
  • PlayScript does not support using blocks.
  • PlayScript does not support checked, unchecked.
  • PlayScript does not "presently" support unsafe code (though this will be added in the future). Currently unsafe code can be added to mobile projects via C#.
  • In PlayScript you may not directly access the base properties of Object (ToString(), GetType(), GetHashCode()) unless you cast an objet to a System.Object. Doing this however will make your code incompatible with the C++ or JavaScript target backends.

 

The provided the following example code:

// Basic types
var b:byte;
var sb:sbyte;
var s:short;
var us:ushort;
var i:int;
var u:uint;
var l:long;
var ul:ulong;
var f:float;
var d:double;

// Conditional compilation
#if DEBUG
#else
#endif

// Fixed arrays
var a:int[] = new int[100];

// Properties
public property MyProperty:int {
   get { return _myInt; }
   set { _myInt = value; }
}

// Events
public event MyEvent;

// Delegates
public delegate MyDelegate(i:int):void;

// Operators
public static operator - (i:int, j:int):int {
}

// Indexers
public indexer this (index:int) {
   get { return _a[index]; }
   set { _a[index] = value; }
}

// Generics
public class Foo.<T> {
    public var _f:T;

    public function foo<T>(v:T):void {
    }
}

// Async
async function AccessTheWebAsync():Task.<int> 
{ 
    var client:HttpClient= new HttpClient();
    var getStringTask:Task.<String> = client.GetStringAsync("http://msdn.microsoft.com");
    var urlContents:String = await getStringTask;
    return urlContents.Length;
}

Very interesting. So basically they are making a HaXe like cross platform tool based on a hybrid of ActionScript and C#, targeting existing Stage3D libraries.

News, Programming ,