Thursday, 3 April 2014

Fearless Fantasy is coming to Steam!

In my last post, more than a year ago, I wrote this:
It is a very ambitious project, that has left little time to do anything else. Hopefully we are ready to announce it officially "very soon from now"
No kidding. It has been a bumpy ride, but finally I can announce that Fearless Fantasy is very soon going to be released on Steam, thanks to publisher Tiny Build Games. We are currently working on the final bits of polish and waiting for an official release date. You can check out the trailer below:


It has been a crazy ride, but for now there is "no time to explain". Following the Steam release we are planning to immediately work on a port to a different rendering engine to bring the game to mobile devices as soon as possible.

We've put everything we got into this game, and for me at least it's by far the biggest project I've ever seen through from start to finish. It's incredible to finally see it all come together.

Saturday, 17 November 2012

Catching Up and CCGs

I promised to update this blog frequently, but nothing of the sort has happened... So what have I been up to?

The reason why I've been busy is that I got the chance to work with the incredibly talented Spike Vallentine on a yet un-announced RPG, and of course I jumped on that chance! It is a very ambitious project, that has left little time to do anything else. Hopefully we are ready to announce it officially "very soon from now", I think you will like it!

Because of this, two other projects have been held on the back burner. One is a small game that was intended as a quick two-weeks experiment, with possible mobile appeal. The web version is almost ready, but the main reason I have not finished it yet is that it uses Stage3D, and I don't know if the web is quite ready for that yet. If you have successfully published a Stage3D game for web sponsoring, I'd love to hear about it!

The other project is an ambitious multiplayer TCG / turn-based-strategy hybrid, which has undergone a few re-designs by now. Since we started on that project, many social games have appeared on gaming portals claiming to be CCGs. CCG once was a synonym for TCG, and a core element of any TCG is the aspect of trading cards. Not just do these so-called-CCG social games completely do away with that important aspect of CCGs (no doubt in order to be able to spam the player with infinite rewards without running into multi-account abuse issues), but also increasingly these games remove the strategic aspect of it, culminating into recent games which completely do away with any interactivity during a card battle.

I really hope that this development will not cause lasting damage to the image of online CCGs, because I strongly believe that the genre still has a lot to offer that is absolutely not represented by these social games. There is something sleazy about this type of game which makes me all the more eager to continue work on our project and provide a counter-weight.

Sunday, 15 July 2012

A New Life

From now on, this blog can be reached from http://www.danielmenezes.net and I am determined to update it frequently.

This marks the beginning of my life as a full-time independent game developer. Exciting times ahead!


Thursday, 23 September 2010

Fixed Timestep With Interpolation (Part 2)

This is a continuation of Fixed Timestep With Interpolation (Part 1). Please refer to that article for a general explanation of the concept and why it is useful.

In this second part I will describe the actual implementation I used for FlashPunk.

The Render Function

First I updated the render() function to take an optional tickAlpha parameter (I named it like that to avoid confusion with colour alpha values). In net.flashpunk.Engine.as:

/**
 * Renders the game, rendering the World and Entities.
 */
public function render(tickAlpha:Number):void
{
  // timing stuff
  var t:Number = getTimer();
  if (!_frameLast) _frameLast = t;

  // render loop
  FP.screen.swap();
  Draw.resetTarget();
  FP.screen.refresh();
  if (FP._world.visible) FP._world.render(tickAlpha);
  FP.screen.redraw();

  // more timing stuff
  t = getTimer();
  _frameListSum += (_frameList[_frameList.length] = t - _frameLast);
  if (_frameList.length > 10) _frameListSum -= _frameList.shift();
  FP.frameRate = 1000 / (_frameListSum / _frameList.length);
  _frameLast = t;
}

Now you have to make sure that this value is propagated down to your entities and graphics. The call stack goes like: <engine.render()><world.render()><entity.render()><graphic.render()>, so make sure to add and pass the parameter in all those render functions, then continue with the subclasses of Graphic (in net.flashpunk.graphics).

We Need a Tick Rate

As mentioned in the first part of the article, one advantage of this timestep method is that your update and render loops can run at different rates. Of course this requires a way to actually define this rate. I will use the terminology "tickrate" for the rate at which your update loop runs, and keep "framerate" for the rate at which your render loop runs (ideally). It is up to you whether you define tickrate as a constant or pass it in the Engine's constructor like framerate, but you need it. Personally, I replaced the frameRate parameter of Engine with tickRate, and simply use the SWF assigned FPS to define the framerate.

Then make sure that the Engine's _rate variable is set to this tickrate instead of the framerate by replacing _rate = 1000 / FP.assignedFrameRate; with _rate = 1000 / tickRate; in onStage().

The Game Loop

For this you will either have to adjust onEnterFrame() or onTimer() in net.flashpunk.Engine.as. Even though it may seem more logical to use onTimer() since FlashPunk already uses it for the fixed-rate timestep, I used onEnterFrame() because timers just don't run nearly as smooth for me. It is up to you, but I strongly recommend onEnterFrame().

Under "//update loop", replace the existing code with this:

var repeats:uint = 0;
while (_delta >= _rate && repeats < MAX_FRAMESKIP)
{
  // run a full tick
  if (!paused) update();

  // update input 
  Input.update();

  // update timer
  _time = getTimer();

  _delta -= _rate;
  _delta += _time - _last;
  _last = _time;

  repeats++;
}

This is fairly similar to the existing fixed framerate loop in FlashPunk, the only difference being that we take a tally of the time that has passed after every loop and add it to the delta time. Now under //render loop, replace the render() line with this:

if (!paused) render(FP.clamp(_delta / _rate, 0.0, 1.0));

This will give us the alpha towards the next tick. This is really all there is to it. Almost...

Death Spiral

If you look at the code above, you may notice that something can go wrong: We keep adding to _delta, and we never process more than MAX_FRAMESKIP ticks per frame. But what happens if _delta is larger than this, and keeps growing larger because the render loop takes too long? Basically you will never catch up and the game will essentially slow down permanently.

Frankly, if that happens you have a serious performance issue in your game, and you may have to tweak your tick- and frame-rate settings. Most importantly, you have to ensure that your game's update() call is by average plenty fast enough to be completed at your tick rate. Occasional spikes are not a problem, as the loop will quickly catch up.

Entity Interpolation

What remains to be done is to actually implement the interpolation in your game entities or graphics. For the sake of simplicity I will limit this tutorial to interpolating the position of your entity positions and camera. This will give you smooth movement, which usually is quite sufficient. I make a point of interpolating whatever I can (including size changes, rotations, color changes, and so on), but I have yet to notice any noticeable difference for anything but basic movement. First, add some new private vars to the end of net.flashpunk.Entity:

// Interpolation.
/** @private */ private var _prevX:Number;
/** @private */ private var _prevY:Number;
/** @private */ private var _prevCameraX:Number;
/** @private */ private var _prevCameraY:Number;

These will simply hold the respective values of the previous state. We do this in the Entity's update() function:

override public function update():void 
{
  // Save previous state values for interpolation. All update logic needs to happen after this.
  _prevX = x;
  _prevY = y;
  _prevCameraX = FP.camera.x;
  _prevCameraY = FP.camera.y;
}

This will work just fine, as long as you remember to call super() before making any changes in the update() function of your Entity subclasses. The actual interpolation then happens in the Entity render() function:

public function render(tickAlpha:Number = 1.0):void 
{ 
  if (_graphic && _graphic.visible)
  {
    if (_graphic.relative)
    {
      // Interpolate entity position.
      _point.x = FP.lerp(_prevX, x, tickAlpha);
      _point.y = FP.lerp(_prevY, y, tickAlpha);
    }
    else 
    {
      _point.x = _point.y = 0;
    }

    // Interpolate camera position.
    _camera.x = FP.lerp(_prevCameraX, FP.camera.x, tickAlpha);
    _camera.y = FP.lerp(_prevCameraY, FP.camera.y, tickAlpha);
    _graphic.render(_point, _camera, tickAlpha);
  }
}

This should be pretty clear. Before rendering the graphic, we interpolate the point and camera according to tickAlpha. You may notice a little issue here: If graphic is not set to relative, the point is always set to 0:0, so what if the graphic itself moves? For these and other reasons I am currently moving all my interpolation to the Graphic classes (note that I pass tickAlpha to _graphic.render() as well). This is just a little bit more complex and I leave it up to you to come up with your own implementations. Alternatively you can follow my GitHub branch.

Another Problem

There is only one remaining issue. What if you want to make an entity jump to a new location, without actually moving it? With interpolation, you would get some flickering while the entity is rendered in-between its old and new position. There is more than one solution to this problem, e.g. not to interpolate if the old and new position differ more than a certain threshold, or to add a skipInterpolation var, which will bypass interpolation for the next frame. I am sure you will find something that works best for you.

Conclusion

So now you can tell why I stated that this requires a little more thought than the existing timesteps, but I feel that this is a small price to pay for a timestep that performs well and has none of the disadvantages of the existing ones.

If you don't want to implement your own timestep, you can use my branch at GitHub branch. Beware though, that this is very much a work in progress and will likely contain many other changes too.

Fixed Timestep With Interpolation (Part 1)

I recently started work on our second Flash game and decided to use the FlashPunk engine for this. FlashPunk supports two styles of time steps, variable time steps and fixed time steps. Unfortunately both have issues, which made me look into the subject and look for established best practice. An interesting alternative is a fixed time step with interpolation, which has none of the downsides but requires a little bit more thought. If this sounds good to you, read on!

First, let's look at the limitations of the available time steps:

Variable Time Steps

Variable time steps are the most straight forward and simply run the update and render loops as quickly as possible, trying to keep up with the desired framerate. Because frames can take longer or shorter times to render, movement has to take elapsed time into account. This leads to smooth movement and animations, but it has some significant downsides:

  • As the time between frames is inconsistent, so can be the results of physics simulations. When your game code relies on physics being pixel perfectly accurate, this can be a significant problem. A very common issue is game objects "jumping" over obstacles, because the delay between frames was so large that the object never actually collided with the obstacle but was moved right over it. There are methods to deal with such issues, but the bottom line is that issues can crop up that are hard to debug because they are entirely framerate dependent.
  • Physics and rendering run on the same schedule, effectively reducing maximum possible framerates. You may want to run your game at 60 FPS for smooth animations, but there is no reason that your game update loop (e.g. physics and collisions) has to run at the same rate.
  • For consistent gameplay, basically every value change has to be multiplied by the elapsed time (FP.elapsed in FlashPunk), which is a bother and can easily be overlooked in specific cases.

Fixed Time Steps

To alleviate most of these issues, FlashPunk also offers a fixed rate timestep. This will run the update loop at a specific interval, that is independent of the framerate. If frames are rendered too fast, updates are skipped. If updates lag behind because rendering took too long, update is called multiple times to catch up.

Unfortunately this does not lead to smooth movement, because the number of updates run each frame can differ frequently. While the difference between one or two update loops on each frame may not seem like much, it leads to very visible stuttering, that is unacceptable for most kind of games. Another issue is that there is no point in running the update loop at a slower rate, when nothing changes between multiple render updates. What is the point of 60 FPS, when it just draws the exact same gamestate twice?

Interpolation

The obvious solution to these problems with fixed time steps is interpolation. The basic concept is as follows:

Render loops are called in-between updates, so every time render() is called, a certain fraction of time has passed towards the next update (this is true, even if updates and renders run at the same rate).  This fraction can be thought of as the alpha value between the current and the next update (I call it frameAlpha in my code to avoid confusion). Ideally we would now like to interpolate between the current and the next update, but obviously that is not possible because the next game state is not known yet. What we can do however, is to interpolate between the previous and the current update.

Fortunately, this is just as good. The only downside is a marginal delay from user input to rendering of up to one update tick. In practice, you are not going to notice this.

So our strategy is: Calculate and pass on the alpha value before calling render(). During rendering, interpolate between the previous and current state based on alpha. What is "previous state" can differ from entity to entity (or graphic), depending on your needs. Interpolating entity position is probably the most important, to create smooth movement. To do this, we simply store the current state in the objects update() function before running any update logic. During rendering, a simple linear interpolation will suffice, for which FlashPunk even provides handy shortcuts in form of FP.lerp() and FP.colorLerp().

As this is getting rather long, I will describe the actual implementation in the next post:

Fixed Timestep With Interpolation (Part 2)