• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
  • entries
  • comments
  • views

FlatBuffers in .NET

Sign in to follow this  
Followers 0


I've been tinkering with Google's new FlatBuffers protocol and have an experimental port of it running in .NET (C#).

FlatBuffers is interesting and there's a couple of other alternatives in the form of ProtoBuf, Cap'n Proto, Simple Binary Encoding (SBE) and, to a lesser extent, JSON, XML and YAML. These protocols all share the same thing in common, to serialize your data into a format that's portable between applications - be it as an on disk format (save game, level, etc) or as a wire object for communicating with network services.

JSON is really the go-to choice now for people who use web services a lot and works well as a configuration file format too. However I've recently been noticing a trend towards binary encoded data, especially in the arena of game (client/server, especially); the reasoning behind this is often due to performance of both encode/decode and that the text-based formats take up more network bandwidth.

One issue with binary protocols has always been that it can be extremely easy to change the schema and render the existing data invalid.

Take the simple object:class Vector3{public: float X; float Y; float Z;}class Monster{public: int Health; Vector3 Position;}
We would probably serialize out with something like this:void SerializeMonster(std::ostream &stream, const Monster &monster){ stream << monster.Health; SerializeVector3(stream, monster.Position);}void SerializeVector3(std::ostream &stream, const Vector3 &vector){ stream << vector.X << vector.Y << vector.Z; // Quantized floats omitted for simplicity}
And deserialization would be something like this:Monster* DeserializeMonster(std::istream &stream){ auto monster = new Monster(); stream >> monster.Health; monster.Position = DeserializeVector3(stream); return monster;}Vector3* DeserializeVector3(std::istream &stream){ auto vector = new Vector3(); stream >> vector.X; stream >> vector.Y; stream >> vector.Z; return vector;}
If I wanted to add additional fields to the Monster class (Mana, Color, Weapons carried, etc), I would have to be very careful to keep my functions in sync, and moreover if I change the serialization order of anything all my stored data is useless.

This problem gets even bigger if you start talking outside of a single application, such as sending data from your client to a network server that might have been written in .NET, Java or any other language.

A few years ago Google released V2 of their Protobuf format which aims to bring a bit of sanity to this problem. They defined their serialization objects in a simple IDL (interface definition language). The IDL used by Protobuf has a formal native type format and then your data is defined as "messages". Protobuf has a "compiler" which then generates your C++ (and other languages) serialization code from the IDL.message Vector3 { required float x = 1; required float y = 2; required float x = 3;}message Monster { required int32 health = 1; required Vector3 position = 2;}
A key thing to note here is the numbering used; this defines the serialization order of the field. Protobuf mandates that if you want to maintain backwards compatibility, you must not change the ordering of existing items, new items are appended with a higher sequence and they are added as "optional" or with a default value. Anyone interested should look here for more details on this.

Protobuf does some clever encoding of the data to minimize the size; things such as packing numeric types and omitting null values.

Projects like FlatBuffers (and the others mentioned above) cite that the encoding/decoding step of Protobuf is expensive - both in terms of processing power and memory allocation. This can be especially true if done frequently - such as if your network server is communicating in protobuf format. In some of the online services I've worked on, serialization to/from the wire format to an internal format has been an area to focus optimization on.

FlatBuffers, Cap'n proto and SBE take the stance that the data belonging to the object is laid out the same in memory as it is on disk/during transport, thus bypassing the encoding and object allocation steps entirely. This strategy becomes an enabler of allowing simple mmap() use or streaming of this data, at the expense of the data size. I'm not going to go in the pro/cons here, as the Cap'n Proto FAQ does a better job. However, all of these in-memory binary data formats all acknowledge that having a "schema" which can be modified and retain backwards compatibility is a good thing. Basically, they want the benefits of Protobuf, with less overhead.

So back to the topic of this post; how does .NET fit into this? Given that engines such as Unity provide C# support and XNA / MonoGame / FNA are all managed frameworks capable of targeting multiple platforms, FlatBuffers in .NET has a couple of obvious use cases:

  • Data exchange between native code and C# editors/tools
  • Game data files with a smaller footprint than JSON/XML/YAML
  • Wire data exchange between Flatbuffer enabled client/servers (to a lesser extent, due to bandwidth concerns, but viable in the same datacentre)
  • Interprocess communication between .NET and native services (same box scenarios)

    I started porting the Flatbuffers protocol to .NET and hit a slight dilemma; should we treat Flatbuffers as a serialization format, or should it also be the "memory" format too?

    In Marc Gravell's Protobuf-net project he explicitly took the stance that "r[color=rgb(0,0,0)][font=arial]

    ather than being "a protocol buffers implementation that happens to be on .NET", it is a ".NET serializer that happens to use protocol buffers" - the emphasis is on being familiar to .NET users (for example, working on mutable, code-first classes if you want)."



    Right now, I'm facing a similar question. What is more important for .NET users? Is it the ability to code first and serialize, or to be able to access Flatbuffer data without serializing?



    Here's an example of the code-first approach:

    [/font][/color][FlatBuffersContract(ObjectType.Struct)]public class Vector3{ public float X { get; set; } public float Y { get; set; } public float Z { get; set; }}[FlatBuffersContract(ObjectType.Object)]public class Monster{ public int Health { get; set; } public Vector3 Position { get; set; }}var someBufferStream = ...;var monster = FlatBuffers.Serializer.Deserialize(someBufferStream);
    We declared our various classes and used an attribute to annotate them. Then we explicitly take data from the stream to create a new Monster (and Vector3) object. From here, we can discard the buffer as we have our .NET objects to work with.

    Serialization would be the opposite: create your objects in .NET and call a Serialize() method to fill a Flatbuffer.

    The benefits of this are that is it is very .NET centric; we are used to code-first approaches and serializing to/from our entity classes. Conversely, we now have to either manually synch our IDL files, or write a tool to generate them. We also begin allocating many objects - especially if the buffer is large and has a lot of depth.

    An alternative approach is the accessor pattern which the FlatBuffers Java port takes. Here, we effectively pass a reference to the data in Flatbuffer format and use a accessor methods to read what we need. The accessor classes would be generated by the IDL parser tool.public class MonsterAccessor{ public MonsterAccessor(FlatBufferStream flatBuffer, int objectOffset) { .. } public int Health { get { flatBuffer.ReadInt(... objectOffset + offset of health ...); } } public Vector3Accessor Position { get { return new Vector3Accessor(flatBuffer, flatBuffer.ReadOffset(... objectOffset + offset of position ...)); } }}public class Vector3Accessor{ public Vector3Accessor(FlatBufferStream flatBuffer, int objectOffset) { .. } public float X { get { flatBuffer.ReadInt(... objectOffset + offset of x ...); } } public float Y { get { flatBuffer.ReadOffset(... objectOffset + offset of y ...); } } // etc }var someBufferStream = ...;var offset = ...;var monsterAccessor = new MonsterAccessor(someBufferStream, offset);var monsterHealth = monsterAccessor.Health;var vector3Accessor = monsterAccessor.Position;// etc
    In addition to the Reads, we would also supply "Write" methods to populate the buffer structures.

    The benefit of this approach is that the buffer access becomes lightweight; we are no longer deserializing whole objects if we don't need to - we're not allocating memory (except for things like strings). We also get direct sync with the IDL version.
    The downside of this is that working like this feels quite alien in the .NET world; the code to handle buffer access is very manual and in the case of the position access, very clunky. It's likely that we will end up creating lots of accessors - unless we rely on everything being static. Which also becomes pretty... nasty.

    This latter approach is more akin to a "port" of Flatbuffers, rather than treating it like a serialization type.

    So - with these approaches in mind; what would YOUR favoured access method for FlatBuffers be in .NET? Would you focus primarily on FlatBuffers as a serialization format, much like Marc Gravell did with protobuf-net? Or would you look at a true port? Or maybe there's some hybrid approach?

    What would your use cases be?

Sign in to follow this  
Followers 0

1 Comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now