Thursday, August 9, 2012

Writing a HTML5 Game Engine - UI Layout

Prologue

I will be starting a series of blog posts that will document my experience in creating a HTML5 game engine. First of all, what is the purpose of creating this game engine, aren't there already tons of game engines out there? Yes, surely there are already some great engines out there but I treat this more as an attempt to have a hands-on experience and experiment the inner workings of designing a game engine. This is both challenging and interesting to me so I hope to share my findings along the way that might help others as well.

The target platform for now is mainly desktop browsers. However, as HTML5 becomes more mature, there will be more and more hardware acceleration supported on mobile platforms as well (Testing HTML5 on different platform by Scirra). Typically people would talk about power consumption but I would argue that caching, bandwidth, latency are more of concern. But most of the time the display is what takes up the most energy anyways.

NOTE: None of the contents posted are conclusive so please judge based on your own needs  :)

1) UI Layout 

The first thing to consider is how we should define layout of game entities. Looking at other frameworks, this can either by through markup languages e.g. HTML, Microsoft's XAML, Adobe's MXML or just through code directly e.g. Cocos2D, C/C++. The choice in deciding on the architecture will be very tied into event handling and also rendering algorithm used. Markup languages allow programmers to quickly identify UI elements through scanning tree hierarchy.

<Div> Layout

In HTML5, we can obviously use DOM <div>'s to define our layout. There are several ways of doing this, one way is to do this using jQuery is $(document.body).append("<div class='new'/>");[2]. The issue with this is every time we would need to find the DOM and modify and re-render the HTML generated for it to work. The same applies to using CSS with selector strings. This isn't an efficient process as it requires to parse through the DOM element tree. This process can be slightly sped up with generating id's for each DOM to explicitly find the precise element. 

How about caching selectors? In the context of games, this will require a lot of dynamically DOM elements being injected and removed. For example, if a lot of elements are frequently being added/removed when monsters are being killed. Using the DOM would be slow regardless of caching selectors. 

MainGameContainer









<div id="mainPanel"> MainGameContainer
<div id="childPanel1">Left Panel</div>
<div id="childPanel2">Right Panel</div>
</div>

Left Panel
Right Panel

<style type="text/css">
#mainPanel {
background-color: White;
color: Black;
position:relative;
height:150px;
}
#childPanel1 {
background-color: Blue;
color: White;
position: absolute;
top: 20px;
left: 10px;
width: 30%;
height: 40px;
}
#childPanel2 {
background-color: Red;
color: White;
position: absolute;
top: 40px;
left: 20px;
width: 30%;
height: 60px;
}
</style>

Custom Node Tree

The alternative solution is to have our own custom node tree. Everything will be encapsulated in a object in javascript (equivalent of div) and we can make manipulations on it. It will have children just like DOM divs do. We will have to parse our own node tree to decide which children should appear on top of the other. Obviously this choice comes with great implementation cost but it will allow us to not touch the DOM at all. On the HTML side, it will just look like an embedded Flash application. It is arguable whether this tree traversal is faster than the browser traversing its DOM tree. However, this seems more of an implementation-specific issue for the browser and how you code the tree traversal in javascript.


This seems a lot of work but in later sections it may prove useful for controlling events and rendering. Another factor to consider is related to implementing a rendering engine for this. For the DOM model, we will have to rely on what the CSS styles support and positioning of elements which is sometimes hard to figure out or varies across different browsers. E.g. images may appear blurry on some browsers when u scale it using CSS but not if you specify the image width/height using canvas.context.drawImage [3]. Using your own custom tree will give you the full control in that aspect. You can use a single canvas to draw the entire game space for example.

Compared to the DOM model, the custom nodes we define in javascript will only contain the essentials of what's needed for us to render objects (a DOM object is much heavier [4]) in a game. So I decided to create this custom node tree first. Later I will discuss how this correlates to the rendering engine and UI event handling.

Thursday, February 2, 2012

The Power of Abstraction

This is an old video about evolution of design of programming languages for abstraction by Barbara J. Liskov from MIT, one of the earliest researchers on software abstraction. Most of the fundamental concepts are still used or still can be applied today. 

It provides good insights to those who have difficulty understanding the prime goal and reasoning behind abstraction. It also talks a bit about some future research, things for us to ponder about :-)


Sunday, January 29, 2012

北菇蒸雞 - Steamed Chicken with Shiitake Mushroom

A good Chinese "北菇蒸雞 - Steamed Chicken with Shiitake Mushroom" is defined by the juicy and smooth texture of the chicken along with the vibrant taste of Dried Shiitake Mushroom. This is one of my favourite home-cooked dish as I find a lot of the ones cooked outside are unnecessarily oily.

Please read HowTo: Prepare 冬菇 - Chinese Dried Shiitake Mushroom before starting this.

Key: The key to this dish is not to let it overcook. The timing for steaming must be just right. For wings I found it just right around 12-15 mins depending on whether you can lay it out equally. It is also important to make sure your steamer is already steaming! (Unless your using electric ones)

Ingredients:
(Enough for 2-3 servings)
~500g of Chicken (Either Wings, Thighs, or Chicken pieces, preferably not breast - hard to make it smooth)
6-8 Dried Shiitake Mushrooms (冬菇 Must use dried ones, buy from Chinese groceries)
Light Soy Sauce (生抽)
Sesame Oil
Sugar
Salt
1 tsp Potato Starch
Chinese cooking wine




















Preparation:

  1. First complete  HowTo: Prepare 冬菇 - Chinese Dried Shiitake Mushroom 
  2. Wash, clean, dry chicken meat
  3. Marinate chicken using Chinese cooking wine (~2 tbsp) for around 10 minutes
  4. Add in 1 tsp sugar, 1/2 salt, and ~2-3 tbsp of  Light Soy Sauce (生抽)
  5. Add in 1 tsp of potato starch
Cooking Instruction:
  1. Place the chicken in a dish/tray that can be used by steamer 
  2. Make sure each piece gets equal surface area, or some parts might not be cooked
  3. Lay the mushrooms on top of the chicken
  4. Steam for 15 mins (Varies depending size of piece and/or bones)
Images:
Enjoy!

HowTo: Prepare 冬菇 - Chinese Dried Shiitake Mushroom

冬菇 - Chinese Dried Shiitake Mushroom, is an essential ingredient in Chinese cuisine. Its use range from common stir-fry noodles to exotic dishes with Abalone 鮑魚. This post will provide instructions in how to prepare it for dishes used in stir-fry or steaming but not really applicable other uses such as boiling (You are always welcome to adventure into the wild...)

Why do the ones in restaurant tastes so much better than mine!?:

  1. You used crappy mushrooms (bad source, can't fix)
  2. You didn't follow this recipe - the mushroom although strongly flavoured, is not enough for it to be "tasty". This recipe is to allow you to make it more "complete"

How to identify good 冬菇?:

  1. The smell - what you smell from it has strong correlation to how it tastes. So just think how it should taste like
  2. The size - not too big (I find large ones less tastey), nor too small (for softer texture). 
  3. The stem - the stems are very tough, so it's not beneficial if it's too large (they charge per pound)
  4. The look - It's natural for it to have cracks and it should be a brownish colour

Ingredients:
6-8 冬菇 Dried Chinese Shiitake Mushrooms  (Must use dried ones, buy from Chinese groceries)
Sugar
Salt
Sesame oil
Potato Starch

Preparation Instructions:
  1. Clean and soak the mushrooms for at least 4 hours
  2. Remove from water and clip the stem of the mushroom away using a pair of kitchen scissors
    • (Its roots are very tough, unless you're using it for some other dish -might make a post for that- just toss it away)
    • The water can also be used in other dishes, e.g. use it for cooking rice
    1. Add around 1/2 tsp of sugar, a pinch of salt to the mushrooms and mix well
    2. Add just less than 1 tsp of sesame oil 
    3. Add around 1 tsp of potato starch (you can play around with this amount)
    4. Mix well
    5. Steam for 20 mins+
    key: The starch will allow the mushroom to be smoother than usual and keeps the flavour held in the mushroom instead of watering it out. You can play around with the amount yourself to figure a good balance. It depends on how wet your mushrooms are.

    Cooking Instructions:
    After the preparation work, the mushrooms are essentially cooked. This means you can store it in the fridge and use it another day. Since the time it takes to soak the mushroom is so time consuming, you should either soak it over night or make enough for several dishes (e.g. some might be for steaming, some for stir fry). If it's stir fry, you can slice it. 

    Enjoy!

    Test your English!

    Test your english with this poem. Hmm I should record myself saying this in Canto accent...+1/Like if you want me to do that!
    http://www.thepoke.co.uk/2011/12/23/english-pronunciation/

    Test Recipe: Turkey Meatballs

    Notes:
    • Play around with the herb amounts as you wish. 
    • Try it with beef/lamb as alternative to turkey for stronger meat flavour. 
    • Add grated cheese if you like
    • This goes well with pasta as one would expect!

    Ingredients: 
    (Enough for two dozen medium-sized meatballs)
    ~500g (Extra Lean) Minced Turkey
    1/4 of Red Onion (Minced/Finely Chopped, depends on preference of texture)
    3 Cloves of Minced/Finely Chopped Garlic (same as above)
    1 Egg
    1/2 tsp Cumin Powder
    Salt & Pepper
    Starch/Flour
    Parsley/Basil (I didn't want to buy a whole bunch so just used the blended version)
    ~1 tsp Oregano
    ~1 tsp
     Rosemary
    ~1 tsp
     Thyme
    Preparation Instructions:
    1. Heat up medium-sized pan with some oil at medium to low heat 
    2. Place the garlic and onion and saute it along with dry herbs (oregano, rosemary, thyme)
    3. Add pinch of salt&pepper and saute until onion softens and turns slightly yellowish brown
    4. Place the sauteed garlic/onion into a mixing bowl, then add the minced turkey meat in
    5. Add the remainder of green herbs and cumin powder along with another pinch of salt& pepper
    6. Mix the contents well, then add an egg
    7. If the mixture is too wet (test whether a ball of the mixture will be able to stand firmly by itself), then add some starch/flour and mix again
    8. Repeat 7. until mixture is right dryness
    9. Use your palm to form balls (around 2-3cm width). You don't want it too big because it will be hard to cook later
    Cooking Instructions:
    After the previous preparation, you can place the meatballs in refrigerator or freezer for future use. I personally cannot finish this all in one meal. They can store it quite a while if you put in freezer.

    There are various ways to cook it. You can pan fry it, oven bake it or...even steam if you really are that type of person...

    For Oven: (Good for large batch)
    1. Pre-heat to 300 F for baking
    2. Place meatball on oven tray/pan which has aluminium foil with a bit of oil brushed over it (so it doesn't stick)
    3. Place in oven and bake for 15-20mins (depends on size of meatball, add 10mins if frozen)
    4. Turn oven into grill mode for 5-10mins for browning effect
    5. Ready to serve! 
    For Pan:  (not recommended for large meatballs)
    1. Heat up medium-sized pan with some oil at medium heat 
    2. Place meatballs and cook for several minutes (don't move it too much but also not let it burn)
    3. Repeat 2. in batched (I find it hard to manage more than 5 meatballs at the same time)
    4. Ready to serve! 
      Images:

      Here's the mixture of meat



      First set of meatballs


      Then some more...

      And some more....
      Ready to eat!