Showing posts with label deserialization. Show all posts
Showing posts with label deserialization. Show all posts

June 3, 2014

Power of JSON in Game Development - Items

Hey there, it's been a while since I last time wrote anything here, so... It's time to fix that!

This time, I'm going to tell you about JSON and how it's one of the greatest things ever. Lately, I've been fiddling around with a game that relies heavily on persistent data - I need to store high scores, whether or not the player has seen a certain tutorial tip, what kind of items there are available and so on. All this could be achieved via simple binary files and code to represent everything, but this would soon become rather cumbersome to deal with.

Let's think of an item system in a generic RPG game. You have your swords, bows, daggers and wands, as well as helmets, chest armors, gloves and boots. All of them share similarities: each of them has a unique name, they only fit certain slots, and they provide certain bonuses. Now, often times you would rush into coding and do something like this:


public class Item {

    String name;
    Slot slot;
    Sprite sprite;
    public Item(String name) {
        this.name = name;
    }

}

public class Sword extends Item {
  
    public Sword(String name) {
        super(name);
    }
}

public class SwordOfDoom extends Sword {

    public SwordOfDoom() {
        super("Sword of Doom");
        slot = Slot.MainHand;
    }

}

Now, this seems viable at first, but what if there's tons of items in your game? I'm sure you don't want to go creating as many classes as there are items! To make this so much more easier, let's use JSON!

What's JSON?

As you may already know, JSON is a simple way of storing data in text form. It's really lightweight and allows for easy transfer and storage of data. What you may not know is that you can store Java objects in JSON too. Whaaat?

Yeah, it's true. In libgdx, there's really good JSON classes that do this for you. You can create all your items in JSON and the game will create the actual objects automatically. Talk about awesome, eh?

How?

If you use libgdx, it's rather simple. Let's take item system as an example and write some nifty JSON:

{
    items: [
        SwordOfDoom: {
            class: com.manabreak.awesomerpg.Sword,
            name: "Sword of Doom",
            texture: "swordofdoom",
            damageMin: 7,
            damageMax: 9
        },
        DaggerOfKnowledge: {
            class: com.manabreak.awesomerpg.Dagger,
            name: "Dagger of Knowledge",
            texture: "dagger_green",
            damageMin: 5,
            damageMax: 15
        }
    ]
}

I think it's already pretty clear what's going on in here. We have an array of JSON objects called 'items'. Each item has a name (SwordOfDoom and DaggerOfKnowledge in this case), and each of these items has a set of properties, such as which class to instantiate, which name it should use in-game and so on. As you can also see here, you can mention the name of the texture you want to use and any other properties such as damage output.

Now, to load these items in the game, we'll have to create the classes first:


public class Item {

    // Name of the item
    private String name;

    // Texture to use for the item
    private String texture;

    // We need an empty constructor for (de)serialization
    public Item() {}

}

public class Weapon extends Item {
    
    // Minimum damage
    int damageMin = 0;

    // Maximum damage
    int damageMax = 0;

    // Again, empty constructor
    public Weapon() {}
}

public class Sword extends Weapon {

    public Sword() {}

}

public class Dagger extends Weapon {

    public Dagger() {}

}


Now we have our classes. Notice how the names of the fields are exactly the same as in the JSON. This is important for the reflection and (de)serialization. Now, all we need to do is write a controller that will load the JSON for us:

public class ItemController {

    // Hashmap where we store our items as "item name"-"item" pairs
    private HashMap<String, Item> items = new HashMap<String, Item>();

    public ItemController() {
        loadItemsFromJSON();
    }

    private void loadItemsFromJSON() {
        Json json = new Json();
        items = json.fromJson(HashMap.class, Gdx.files.internal("items.json"));
    }
}


If everything went OK, you should now have both of your weapons in the hash map!

Why separate classes for Sword and Dagger? Why not just Weapon?

This is to provide different functionality to different items. If both swords and daggers behave similarly, then it's OK to use a single class for both of them. However, if you have different functionality for them, you'll need to write the code for both of them. While you still need to write code for each different item type, you still end up writing a lot less code as you don't have to write separate classes for each individual item. You can write hundreds of different swords in the JSON file, and if they all behave the same, you'll only need the one Sword class! Hooray!

Hope you find this post useful. It's written in Java and uses libgdx as an example, but similar reflection systems can be used in other languages and with other tools as well. Cheers!




December 21, 2013

Howto: Use Unity3D as a level editor for your own game

I ran into a small problem while I was writing my own hobby game. I needed a level editor, and I wrote one. The real problem was, though, that the editor wasn't very quick to use, and it lacked a lot of optimization code. Instead of further developing this small editor, I came up with a thought: What if I used Unity3D as an editor?

... Challenge accepted!


It turned out to be quite a simple task, in the end. I wrote the export code as an editor extension, which would save the scene in my own binary format. This way, I can design a level just like I would when developing a "full" Unity3D game.

So, let's begin! First, create a new Unity3D project:


After you've created the project, create a new C# script. I called it "ExportScript.cs":


Now, the actual script! In its basic form, the export script is like this:


using UnityEditor;
using UnityEngine;
using System.Collections;
using System.IO;

// This class is responsible for exporting the scene to our own file format
public class ExportScript : EditorWindow
{
    [MenuItem("File/Export")]
    public static void ShowWindow()
    {
        EditorWindow.GetWindow(typeof(ExportScript));
    }
 
    void OnGUI()
    {
        // Create a button that will start the export function
        GUILayout.Label("Export Level", EditorStyles.boldLabel);
        if(GUI.Button(new Rect(10, 50, 100, 32), "Export"))
        {
            // Start the export
            Export();
        }
    }

    // Our output writer
 BinaryWriter writer;
 
 // The export function
 void Export()
 {
  // Create a new output file stream
  writer = new BinaryWriter(new FileStream("out.lvl", FileMode.Create));
  
  // TODO: Write all the data we need (gameobjects, lights, components etc.)
  
  // All done, close the writer
  writer.Close();
 }
}

And that's it! Now, what do we actually want to write to the file? It depends. In my own game project, I wanted to get textures, meshes, game objects, lights, colliders, joints, sounds, background music... Just about everything contained in the scenes. I will not show all the code for this as it would be too much, but the basic concept goes like this: First, write the basic information about the game objects, like name, location, orientation, and scale. Then, for each component you require, check if the game object has that component (say, a mesh filter), and if it does, write all the information available for that component.

It's really simple to do, although it takes some time to write all the component stuff down. When doing this, Unity3D's script reference helps a lot, and you can always check the inspector view to see if you've missed something. :)

Anyhoo, let's take a look at the final example. In this example, the script goes through all the game objects in the scene and saves their names and transforms, as well as checks for the mesh filter components.


    void Export()
 {
  // Create a new output file stream
  writer = new BinaryWriter(new FileStream("out.lvl", FileMode.Create));
  
  // Loop through the transforms in the scene, exporting only what's necessary
  foreach(Transform t in Object.FindObjectsOfType(typeof(Transform)))
  {
   Debug.Log("Exporting " + t.gameObject.name);
   WriteTransform(t);
  }
  
  // All done, close the writer
  writer.Close();
 }

    // Writes the transform object
 void WriteTransform(Transform t)
 {
  // Write the basic transform components (location, orientation, scale)
  writer.Write(t.position.x);
  writer.Write(t.position.y);
  writer.Write(t.position.z);
  writer.Write(t.rotation.x);
  writer.Write(t.rotation.y);
  writer.Write(t.rotation.z);
  writer.Write(t.rotation.w);
  writer.Write(t.localScale.x);
  writer.Write(t.localScale.y);
  writer.Write(t.localScale.z);
  
  // Write the mesh renderer (cast / receive shadows, materials)
  WriteMeshRenderer(t.GetComponent<meshrenderer>());
  
  // Write the actual mesh
  WriteMesh(t.GetComponent<meshfilter>());
 }
 
 void WriteMeshRenderer(MeshRenderer mr)
 {
  if(mr != null)
  {
   // Mesh renderer found, write '1'
   writer.Write(1);
   
   // Write the mesh renderer properties
   writer.Write(mr.castShadows);
   writer.Write(mr.receiveShadows);
   
   // TODO: Write the materials
   
  }
  else
  { 
   // No mesh renderer found, write '0'
   writer.Write(0);
  }
 }
 
 void writeMesh(MeshFilter mf)
 {
  if(mf != null)
  {
   writer.Write(1);
   Mesh mesh = mf.mesh;
            // TODO: Write the mesh data (vertices, indices, UVs etc.)
  }
  else
  {
   writer.Write(0);
  }
 }

There! When you want to run the script, go to the menu "File > Export". The level will be saved to a file called "out.lvl" in the Unity3D project root.

Now, things to consider: You should keep track of all the assets you've written (meshes, materials, textures, sounds etc.), and only write them once. You can also create multiple files, for example save materials to one file, meshes to one and so on. A more sophisticated approach is to create atlas files where you have every asset you need neatly packed. You can also create texture atlases on-the-fly, create dummy scripts in Unity3D to have references about doors between scenes, set dummy objects for player spawns, and just about whatever you need! Remember, you can take full advantage of the tags, layers and such Unity3D has to offer. You can also write the output in JSON, do conversions between classes with reflection, you name it!

I hope you found this small tutorial useful, and as always, feel free to comment and ask questions. You can also make requests about future blog posts and tutorials. :)