Monday, February 22, 2016

C# Reflection - It's What Allows The Entity Component System Pattern At Runtime.

Here is the C# Language Specification 5.0.

From the introduction:

C# is an object-oriented language, but C# further includes support for component-oriented programming. Contemporary software design increasingly relies on software components in the form of self-contained and self-describing packages of functionality. Key to such components is that they present a programming model with properties, methods, and events; they have attributes that provide declarative information about the component; and they incorporate their own documentation. C# provides language constructs to directly support these concepts, making C# a very natural language in which to create and use software components.

If you had never used components, you might walk away from this paragraph scratching your head "well what is component-oriented programming?"

Sadly, this is all the specification spells out specifically about component-oriented programming.

-------------------------------------------------------------------------------

Enter the Entity Component System design pattern.  Apparently there are multiple flavors, and many discussions and purists concerned with how to implement the ECS pattern, and one of those flavors is implemented in Unity, which allows components to be added to game objects in the editor, and at runtime:


// add a script foo to the gameObject
gameObject.AddComponent ("foo");


// add a collider to gameObject
gameObject.AddComponent("SphereCollider");



Unity must be taking advantage of C#'s Reflection feature to find out which components have been added to a gameObject.  I believe Reflection opened the world of component-oriented programming in C#, which is quite wonderful!  Yet searching the C# Language Specification for "reflection" only lightly discusses the reflection feature, and you might not grasp the significance by reading.

Where is the ECS pattern used?  So far I'm only aware of games.  I'm guessing Galactic Civilizations (ship editor), Fate, Reassembly, probably Skyrim, probably Trackmania, Robocraft, and WazHack among many others.

I say "probably Skyrim" and "probably Trackmania", because some features might still be implemented without ECS, but it's cleaner to add components rather than trying to anticipate every possible feature that may ever need to be added to an object.  Thus a modding feature might be best implemented with ECS, but there are other ways to allow a game to be moddable - they just won't be as future-proof.

For example, if you wanted a collapsible wall which responded to impacts, it could be coded without ECS, but it would be a nightmare.  With ECS, a collapsible wall is trivial to implement, as each section of the wall can independently respond to impacts and distribute damage to adjoining sections.

There is also some discussion that Unity "breaks" the ECS pattern by allowing code to reside in components.  Some people want the components to be data only with no methods.  My impression is they have overlooked other messaging features and Unity does it fine; it's a rabbit hole I'm not interested in digging into right now.  The way Unity implements ECS is to divide concerns into individual components.

The ECS pattern in Unity organizes the software in such a way that components can be attached to initial objects without much emphasis on inheritance.  I've written applications without ever deriving from anything other than monobehavior.

Also, if you want to understand Reflection by itself, watch C# Reflection to the Max, and thanks Jamie King for helping me grasp the concept!

Tuesday, February 9, 2016

Using C# Expression Trees for Compiling Run-time Code

This is a follow up on the Genetic Algorithms Used to Search Solution Space post several years ago.

I just became aware of C# Expression trees.  The common application is for SQL database queries.

More exciting: Expression trees can also be used to compile arbitrary code, the first step in implementing the genetic algorithms as described in the post above.

For excellent tutorials on expression trees, see Jamie King's C# Expression Trees youtube video playlist.  If you like his videos, consider supporting him in some way.


Consider the following code for Unity:

using UnityEngine;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq.Expressions;
using System.Reflection.Emit;

public class Test : MonoBehaviour {

// Use this for initialization
void Start () {
int myC =

UnityEngine.Random.Range(0,30);


int myTI =

UnityEngine.Random.Range(-5,50);


ConstantExpression cE =

Expression.Constant( myC, typeof(int) );


ParameterExpression iP =

Expression.Parameter( typeof(int), "i" );


List<BinaryExpression> exps =

new List<BinaryExpression>(3) 
Expression.GreaterThan( iP, cE ), 
Expression.LessThan( iP, cE ), 
Expression.Equal( iP, cE ) 
};


int indexExp =

UnityEngine.Random.Range(0, exps.Count );


BinaryExpression myExp =

exps[indexExp];


Expression<Func<int, bool>> testRand =

Expression.Lambda<Func<int, bool>>( myExp, iP );


Func<int, bool> dele =

testRand.Compile();


Debug.Log ( "myC="+myC);
Debug.Log ( "myTI="+myTI);
Debug.Log ( "myTI " + myExp.NodeType + " myC = " + dele(myTI) );


}

}



Attach this script to an object in Unity (I used the main camera) and run, and you should get output something like this over several runs:

myC=17
myTI=-4
myTI LessThan myC = True

myC=20
myTI=9
myTI GreaterThan myC = False

So what is this code doing?  It's generating a random BinaryExpression at runtime, then compiling and running the expression at runtime.

When I found this I was overjoyed!  This is a relatively straightforward way to compile algorithms at runtime to search any random algorithm space.