Thursday, 12 September 2013

Database - radiation hazard

Now that I've shat on mutability in prior posts, let's talk about how it pervades my game code.

I'm a fan of the component model for game-objects. Basically, an object is a unique ID, and there is a database of properties associated to IDs. This isn't a disk-based database. Rather, it's an in-memory key-value store, often implemented by hashtable (though anything fitting the STORE signature can be provided).

This database is where most mutation is, hence the title of this post. So far this has been a nice fusion — functional code for the most part, with game-state held in a database. Updating/setting values in the database is typically done by high-level code, based on calculations performed by all the workhorse functions.

Components (a.k.a. properties)

Here's a character (pruned for brevity):

  let make_severin () =
    Db.get_id_by_name "Severin"
    |> Characteristics.s {int=3;per=0;str=0;sta=1;pre=0;com=0;dex=0;qik=0}
    |> Size.s 0
    |> Age.s (62,35)
    |> Confidence.s (2,5)
    |> Nature.(s human)
    |> Fatigue.Levels.(s standard)
    |> Virtue.(s [
        PlaguedBySupernaturalEntity( Db.get_id_by_name "Peripeteia" );
    |> Ability.(s [
        of_score ArtesLiberales 1 "geometry";
        of_score Chirurgy 2 "self";
        of_score (AreaLore("Fallen Covenant")) 3 "defences";
        of_score MagicTheory 5 "shapeshifting";
        of_score (Language(French)) 5 "grogs";
        of_score ParmaMagica 5 "Terram";
        of_score SingleWeapon 3 "Staff";
        of_score Survival 3 "desert";
    |> Hermetic.House.(s Tytalus)
    |> Hermetic.Arts.(s (of_score { cr=8; it=0; mu=6; pe=6; re=20
                                  ; an=0; aq=0; au=0; co=6; he=15
                                  ; ig=0; im=0; me=0; te=8; vi=0 }))
    |> Hermetic.KnownSpells.s [
        Spell.mastery 4 "Acorns for Amusement"
          Hermetic.([FastCasting;MultipleCasting;QuietCasting;StillCasting]); "Carved Assassin"; "Wall of Thorns"; "Circular Ward Against Demons";
    |> equip_and_inv ["Wizardly Robes";"Staff"] ["Small Pouch"]

Each of the modules here represents a component which objects may have. So Severin's Age is (62,35) — that is actual age and apparent age (Wizards age slowly).

The function make_severin will return an ID. The first line Db.get_id_by_name "Severin" looks up an ID for that name, or generates a new ID if none exists. Each component module has a function "s", which is the same as "set" except it returns the given ID. It's a convenience function for setting multiple component values at once for the same ID — which is exactly what's happening here, with Severin's ID being threaded through all of these property-setting calls.

This is the signature common to all components:

  module type Sig = sig
    type t
    val get : key -> t             (* get, obeying table's inheritance setting *)
    val get_personal : key -> t    (* ignore inheritance *)
    val get_inheritable : key -> t (* permit inheritance (overriding default) *)
    val get_all : key -> t list    (* for a stacked component *)
    val set : key -> t -> unit     (* set value on key; stacking is possible *)
    val s : t -> key -> key        (* set, but an alternate calling signature *)
    val del : key -> unit          (* delete this component from key *)
    val iter : (key -> t -> unit) -> unit
    val fold : (key -> t -> 'a -> 'a) -> 'a -> 'a

I've used first-class modules so I can unpack a table implementation inside a module, making it a "component". For example, in the file I have this:

  module House = struct
    type s = Bjornaer | Bonisagus | Criamon  | ExMiscellanea
           | Flambeau | Guernicus | Jerbiton | Mercere
           | Merinita | Tremere   | Tytalus  | Verditius
    include (val (Db.Hashtbl.create ()): Db.Sig with type t = s)

Now the Hermetic.House module has functions to set/get it's values by ID. In the definition of the character, earlier, you can see Hermetic.House.(s Tytalus).

This manner of database, organized by modules, has been very pleasant to use. It's easy to create a new component-module, adding it's own types and extra functions. It doesn't need to be centrally defined unless other modules are genuinely dependent on it. In practice, I define these components where they make sense. There's no need to "open" modules, thanks to the relatively recent local-open syntax of: Module.(in_module_scope). Variants and record-fields are neatly accessed while keeping them in their appropriate module.

One of the rationales behind a component-model like this is that you can process or collect things by property. This is where the iter and fold are useful. It's easy to grab all entity IDs which have a Wound component (and is therefore able to be injured), for example.


The database, conceptually, is the collection of components. In practice though, I want the components to be non-centrally declared otherwise all datatypes would be centralized as well — so instead, the database is ID management and table-instantiation functors.

First, you create a database of a particular key type...

(* Gamewide 'Db' is based on IDs of type 'int' *)
module Db = Database.Make (Database.IntKey)

The resulting signature has functions related to IDs, and table-instantiation, something like this (I've removed the generic table interfaces, for brevity):

  module Db : sig
    type key = Database.IntKey.t

    val persistent_id : unit -> key
    val transient_id : unit -> key
    val find_id_by_name : 'a -> key
    val get_id_by_name : string -> key
    val get_name : key -> string
    val string_of_id : key -> string
    val delete : key -> unit
    (* <snip> module type Sig *)

    module Hashtbl : sig
      val create : ?size:int -> ?default:'a -> ?nhrt:bool -> unit ->
        (module Sig with type t = 'a)
    module SingleInherit : sig
      val get_parent : key -> key
      val set_parent : key -> key -> unit
      val del_parent : key -> unit
      (* <snip> Hashtbl.create... *)
    module MultiInherit : sig
      val get_parents : key -> key list
      val set_parents : key -> key list -> unit
      val add_parents : key -> key list -> unit
      val del_parent : key -> key -> unit
      (* <snip> Hashtbl.create... *)

Creating a component (aka table, or property) can be as simple as:

(* A basic property is just a table with an already-known type *)
module Size = (val (Db.Hashtbl.create ~default:0 ()): Db.Sig with type t = int)

A common alternative is shown in the House example earlier, where the first-class module is unpacked and included within an existing module.


There are three kinds of tables which can be instantiated: no inheritance, single inheritance, and multiple inheritance. Oh, did that last one make your hair stand on end? Haha. Well, multiple inheritance of data or properties can be a lot more sensible than the OO notion of it.

The way inheritance works is that an ID may have a parent ID (or a list of IDs for multiple). If a component is not found on ID, it's parent is checked. So if I: Size.get target, then target might inherit from a basic_human which has the size (among other "basic human" traits).

Multiple inheritance allows for the use of property collections. You might see the value of this when considering the basic_human example... say you wanted to also declare foot_soldier properties which imparted some equipment, skills, and credentials. To make a basic_human foot_soldier with multiple inheritance, they're both parents (list-order gives a natural priority).

On the other hand, if only humans could reasonably be foot_soldiers, then you might be okay with single inheritance for this case — setting basic_human as the parent of foot_soldier.

Currently I'm not using inheritance for the bulk of the game, but the GUI (work in progress) is based on components and uses multiple-inheritance. This is a fragment of the GUI code, so Prop becomes the module used for instantiating components, and it also has the parent-related functions. I've included a few of the components too:

(* GUI uses multiple-inheritance (of data), so style and properties may be
 * mixed from multiple parents, with parents functioning as property-sets. *)
module Prop = Db.MultiInherit

let new_child_of parents =
  let id = new_id () in
  Prop.set_parents id parents;

module Font = (val (Prop.Hashtbl.create ()): Db.Sig with type t = Fnt2.t)
module Pos = (val (Prop.Hashtbl.create ()): Db.Sig with type t = Vec2.t)
module Color = (val (Prop.Hashtbl.create ~default:(1.,0.,1.) ()):
               Db.Sig with type t = float*float*float)


It's not all roses. One big pain-in-the-tuchus is deleting an ID. This means removing every entry it has in any of these tables. To do this, when a table is instantiated, it's also registered with the database. The delete operation for any table only needs to know ID, the signature being key -> unit. The real ugly part is what this means at runtime: doing a find-and-remove on every table - every time an entity is deleted. Various optimizations are possible, but for now I'm keeping it brute force.

The Source

If you want to see the source, or to *gasp* use it, here is a gist of / mli. It's very unpolished, needing fleshing-out and useful documentation. I intend to release it at some future point, along with some other code. But if you have tips or suggestions, please share them! I've been going solo with OCaml and suspect that's limiting me — I could be doing crazy or nonsensical things. Well, I'm sure I am in a few places... maybe right here with this code!

Wednesday, 11 September 2013

Programming a Game in OCaml

Herein I'll provide an introductory taste of what it's been like making a game in OCaml.

I've been developing a "Tactical RPG" game, which is based on the Ars Magica roleplaying setting and rules. Developement name is "Ars Tactica". (I haven't sought out Atlas Games about legal ramifications, deals, or licensing — not until I have something worthwhile to share!)

There isn't much to show off now, but here's a screenshot:

The figures are placeholders. They're from photos of painted miniatures, found online. At this point I'm using other people's images, fonts, and game system — so what am I doing?

I'm writing code, in a language which should be better known: OCaml.

OCaml is an unusual choice for games. Almost all games are written in C++; before that it was C, and before that ASM. Now we have games being made in C#, Java, Python, and more... and these are imperative languages. OCaml is an unusual choice because, at heart, it's functional.

Rising awareness

In the past couple of years I've watched the growing interest in functional programming with some elation. Game developers have been making forays into it for a bit longer. Chris Hecker tried OCaml way back around 2005. Tim Sweeney did a presentation: The Next Mainstream Programming Language (link is to a PDF of the slides). Carmack has addressed the value of functional techniques applied toward games numerous times: Functional Programming in C++ (blog post), Portion of 2013 keynote (youtube). Of course, there's also Naughty Dog with their scripting language being Scheme-like... since Crash Bandicoot?

How do you make a game in a functional language?

When I was first looking into OCaml (2005), it was beyond my comprehension how a (non-trivial) game could be made. What does functional game code look like!?

Functional code favors return-values, rather than changing a variable in-place. However, typical game code looks like a whole bunch of loops, controlled by counters or other changing variables, with the loop bodies mutating data in-place, step by step. Probably easy to imagine if you think of a loop over "all active game pieces", calling some update function on each — which might loop over sub-components, updating those in turn.

So how do you even do a loop in functional code without some kind of mutable counter? (Well, a practical language like OCaml does support imperative loops... but I rarely use them.) Recursion works...

  let rec loop count =
    Printf.printf "Countdown: %d\n%!" count;
    if count > 0 then loop (count-1)
    else ();;

  loop 10

This will loop with a count-down, feeding back the new count each time. If you think this is pretty terrible, I'll agree — a while or for-loop would be more straight-forward in this trivial example.

Here's a bit of my current main-loop, showing its overall form:

  let rec mainloop ~stage ~actors ~controls ~lasttime =
    let t = time () in
    let dt = min (t -. lasttime) dt_max in
    (* ... *)
    let controls' = controls surface dt in
    (* ... *)
    if run_state = StateQuit then ()
    else mainloop ~stage ~actors ~controls:controls' ~lasttime:t

    ~actors: ordered
    ~controls: (Control.init [ exit_control; time_control; game_control cam_id ])
    ~lasttime: 0.

It follows the same structure as the simple recursive countdown: initial value(s), a terminal condition, and feeding-back the changing state.

I used labeled parameters here (eg ~controls) to help make it clear what can change from frame-to-frame. Since almost everything can change in a game, the data hiding under stage (for example) might be quite extensive.

Now it might be apparent how functional code looks: rather than updating things in-place, you create new values, (old values are discarded if unused, via garbage-collection). This might seem atrocious from a game-programming perspective: you've already allocated space — re-use it!

Honestly, it took me a while to be able to put aside that concern and just accept the garbage collector. But over time, the continual feedback was a combination of: fewer bugs, more pleasant code with less worry, and the garbage-collector was quiet enough that I rarely notice it. Much like acquiring a taste for a suspicious food, I was hooked once the suspicion was put to rest and the taste turned out to be good.

Note that a sufficiently smart compiler could re-use allocations, effectively generating the same code as in-place mutation — and only in cases where it has deemed this to be safe! I don't know if OCaml does this in any cases, but its garbage collector has been handling my massive per-frame allocations surprisingly well.

Returning to looping, most loops aren't explicit like my mainloop. Instead they are abstracted as a fold, map, or iter. These abstractions are enough to cover most use-cases, but you don't see them in imperative languages because they rely on higher-order functions.

OCaml has imperative features. You can modify values in-place, and I'll sometimes use global references for changable state until I figure out a better fit:

  let g_screenwid = ref 0
  g_screenwid := 800;

Arrays are mutable by default, and I use these for image and vertex data. Most of my game logic and data-structures are immutable lists, trees, zips, or queues.

I've made another post with some of my take on: What is bad about mutable state?

With most of the code striving for immutability, I get to enjoy easier composition of functions. Some of the most elegant code (I think) ends up piping data. An example from the game is part of the "casting score" calculation:

    (value,botch) |> fast_cast fastcasting
                  |> raw_vis pawns
                  |> Realm.(apply_aura aura Magic)
                  |> Modifier.apply magus score'k
                  |> apply_mastery mastery

Here, the computed (value,botch) pair is further modified by circumstances, passed through other systems, finally returning the result of apply_mastery mastery. This is a simple case of such piping, in that the type of input and output is the same at each stage (an integer pair). Often there will be a transformative aspect, which works as long as an output type is matched to the input type in each stage.

This post may be a bit haphazard and rambling, as I'm not clear who my audience might be... game-developers looking into functional programming, or OCaml programmers looking to make a game? I think I tried to cut a middle-ground. I expect future posts will be much more focused.

Tuesday, 10 September 2013

What is bad about mutable state?

Sometimes mutable state is good, or at least practical. For large or complex projects (more than a school assignment), it's not a good default. Mutability introduces a brittleness which amplifies as code scales-up.

What's so fragile about mutable state? You can reference a value before it's changed or after -- one of these cases is almost certainly wrong in a given situation. Not only is this easy to get wrong (writing), but it's easy to misinterpret (reading), and changes to code might fall afoul of this explicit (yet subtle) sequencing.

Someone gave me an example of how it's more intuitive to code like this:

    balance = balance + deposit
    // or
    balance = balance - withdrawal

And cited that "the real world is mutable, so it's natural to represent things this way."

"The real world is mutable" -- is it really? One could just as well consider the world-state as new variables with time-subscripts. This would convey the variance through time, yet also formalize the apparent lack of classic time-travel. "What's past is past." (And: immutable)

    let newbalance = oldbalance + deposit

Now you can refer to both, and if you move some statement using newbalance before this one, you get an error. With just balance, you could move something intending to operate on the updated balance to happen before the update -- changing results.

It's a simple thing, and here it might seem more verbose, but as you build code into compositional expressions, you can connect parts together without so many explicit, intermediate "state containers" -- instead you're handing-off results to the next step: dataflow.

Objects, as they are commonly used, are morsels of mutability wrapped in a package which makes them seem safe. Object-oriented programming had grand promises of modularity and safety, which I think have been hindered by mutability being the default.

The big problem with global variables was (and is) mutability -- not their scope. A global constant isn't a worry, is it? With objects, it's like we stash "global variables" into a more restricted scope, but the mutability is still a problem. We'll hide things behind abstractions so we aren't updating a variable directly using language primitives (eg +=), and we'll try to limit the scope of code which can touch certain objects... but in practice we encounter the same race-conditions and multiple arms of code stomping on data that global variables suffer -- the problem is only somewhat contained.

To re-iterate: the black-boxing lends a sense of safety to stashing mutable state everywhere with complex interfaces as gatekeeper. So we practice this -- stashing little state enums, counters, flags... all these mutable bits in objects that we twiddle from code everywhere (but using the objects' nice functions to do it). How far did we really get from those global variables? It's the same style of code, just organized a bit better (hopefully). Sometimes mutable state is good, but a variable should have a good reason to be mutable, rather than this being the default.