Planning the Spontaneous

It's more than just a blueprint.

Archive for January, 2010

ConfusedEventHandler += (s, e) => ConfusedEventHandler(Me.Extend(s, e));

Posted by Robert Chow on 21/01/2010

So I’ve just been informed that there are a couple more additions to event handling in .NET.

Before notifying an event handler of any new events, you MUST always check to see if it is null.  If it is, then don’t send any events – apparently you get really messed up runtime errors.

Secondly, you can subscribe to an event handler using a lambda method too – it’s quite a pretty neat trick.  As a result, it also allows you to subscribe more than the one method to the event handler.

Here’s the code for the main part of the demo, but rewritten to accomodate the two factors.  I’ve also added in the functionality of one of the subscribers being taken away part way through the program.

public class Program
{
public static event IncreaseNumberEventHandler numberIncreasedEventHandler;

public static IncreaseNumberEventHandler n52Subscribe;

public static void Main(string[] args)
{
public static Number n27 = new Number(27);
public static Number n39 = new Number(39);
public static Number n52 = new Number(52);
numberIncreasedEventHandler += (s, e) => {n27.Increase(s, e); n39.Increase(s, e);};
numberIncreasedEventHandler += (n52Subscribe = (s, e) => n52.Increase(s, e));

Run();
}

public static void Run()
{
for (int i = 0; i < 10; ++i)
{
if (i == 5)
{
numberIncreasedEventHandler -= n52Subscribe;
}
if (numberIncreasedEventHandler != null)
{
numberIncreasedEventHandler(null, new IncreaseNumberEventArgs(i));
}
}
}
}

And the output:

n27: 27 increased by 0 to 27
n39: 39 increased by 0 to 39
n52: 52 increased by 0 to 52
n27: 27 increased by 1 to 28
n39: 39 increased by 1 to 40
n52: 52 increased by 1 to 53
n27: 28 increased by 2 to 30
n39: 40 increased by 2 to 42
n52: 53 increased by 2 to 55
n27: 30 increased by 3 to 33
n39: 42 increased by 3 to 45
n52: 55 increased by 3 to 58
n27: 33 increased by 4 to 37
n39: 45 increased by 4 to 49
n52: 58 increased by 4 to 62
n27: 37 increased by 5 to 42
n39: 49 increased by 5 to 54
n27: 42 increased by 6 to 48
n39: 54 increased by 6 to 60
n27: 48 increased by 7 to 55
n39: 60 increased by 7 to 67
n27: 55 increased by 8 to 63
n39: 67 increased by 8 to 75
n27: 63 increased by 9 to 72
n39: 75 increased by 9 to 84

Advertisements

Posted in Computing, Placement | Tagged: , , , , , , , , , | Leave a Comment »

ConfusedEventHandler += new ConfusedEventHandler(Me.Confused);

Posted by Robert Chow on 20/01/2010

… Or at least that’s how I first felt when I started looking at event handling in .NET.

And I still do slightly – I’ve literally just looked at this 10 minutes ago, and I’m writing this down now while it’s still fresh in my head.

Observer Pattern

The observer pattern uses the notion of an Observer interface.  The state of each object that implements this can be updated through the interface.  The idea of using this interface allows a publisher to update all the objects in one swift movement.  Obviously, only those that are referenced by the publisher can be updated – those that are, are known as subscribers.  This design pattern is also a subset of the publish/subscribe pattern – any object that is subscribed will recieve any notifications sent by the publisher.

Publish/Subscribe.  A publisher sends events to subscribers.  This image has been taken from http://msdn.microsoft.com/en-us/library/ms978603.aspx.

So yesterday, I set about creating my own observable pattern implementation.  Yet today I learnt that there is a .NET implementation using events.

Event Handling

So with a little help from Microsoft and a lot more help from CodeProject, I’m going to try and explain to myself how to use them.

We start of with declaring the publisher.  The publisher contains a list of all the methods that should be invoked when an event is recieved.  This is done using 2 keywords and the name.

event EventHandler eventHandler;

event – declares that this is an event handler.
EventHandler – this is the default delegate type for event handlers.  This 2nd keyword must always be a delegate type it seems.

To add a subscriber, this is relatively simple.

eventHandler += new EventHandler(method);

+= – this symbol implies that we are wanting to subscribe a method to the event handler.  Similarly, to unsubscribe use the -= operator instead.
method – this is the method to be invoked when the publisher recieves an event to be sent on.

So now that we have a publisher and subscribers, lastly is to send an event to the publisher so it can pass it on to the subscribers.

eventHandler(sender, new EventArgs());

sender – the object that sent the event.  This is not compulsory and can be null.
new EventArgs() – event arguments for the event just occurred.  Again, this is not compulsory and can be null.  The methods subscribed to the publisher can always be invoked regardless of event arguments.

It’s actually fairly easy really once you get your head around it – at first I got hurrendously confused because I kept seeing “event” everywhere.

And of course, the sample I’ve just shown is fairly useless – it’s a lot more useful when you use your own delegate type as the event handler in conjunction with your own event arguments – most probably derived from EventArgs.

Increase Number Event

Below is a simple demo I’ve made just to make it a little more understandable, and it was also particularly useful when I was trying to figure it all out.  It uses a publisher, numberIncreasedEventHandler, whereby the Number objects n27, n39, n52 all have their Increase method subscribed.  This is invoked during Run, passing on an IncreaseNumberEventArgs which increases each object by the number contained in the argument.

public delegate void IncreaseNumberEventHandler(object sender, IncreaseNumberEventArgs e);

public class IncreaseNumberEventArgs : EventArgs
{
public int Increase;

public IncreaseNumberEventArgs(int increase)
{
this.Increase = increase;
}
}

public class Program
{
public static event IncreaseNumberEventHandler numberIncreasedEventHandler;

public static void Main(string[] args)
{
Number n27 = new Number(27);
Number n39 = new Number(39);
Number n52 = new Number(52);
numberIncreasedEventHandler += new IncreaseNumberEventHandler(n27.Increase);
numberIncreasedEventHandler += new IncreaseNumberEventHandler(n39.Increase);
numberIncreasedEventHandler += new IncreaseNumberEventHandler(n52.Increase);
Run();
}

public static void Run()
{
for (int i = 0; i < 10; ++i)
{
numberIncreasedEventHandler(null, new IncreaseNumberEventArgs(i));
}
}
}

public class Number
{
int number;
string name;

public Number(int initialNumber)
{
this.number = initialNumber;
this.name = “n” + initialNumber;
}

public void Increase(object o, IncreaseNumberEventArgs e)
{
Console.WriteLine(name + “: “ + number + ” increased by “ + e.Increase + ” to “ + (number += e.Increase));
}
}

And the output:

n27: 27 increased by 0 to 27
n39: 39 increased by 0 to 39
n52: 52 increased by 0 to 52
n27: 27 increased by 1 to 28
n39: 39 increased by 1 to 40
n52: 52 increased by 1 to 53
n27: 28 increased by 2 to 30
n39: 40 increased by 2 to 42
n52: 53 increased by 2 to 55
n27: 30 increased by 3 to 33
n39: 42 increased by 3 to 45
n52: 55 increased by 3 to 58
n27: 33 increased by 4 to 37
n39: 45 increased by 4 to 49
n52: 58 increased by 4 to 62
n27: 37 increased by 5 to 42
n39: 49 increased by 5 to 54
n52: 62 increased by 5 to 67
n27: 42 increased by 6 to 48
n39: 54 increased by 6 to 60
n52: 67 increased by 6 to 73
n27: 48 increased by 7 to 55
n39: 60 increased by 7 to 67
n52: 73 increased by 7 to 80
n27: 55 increased by 8 to 63
n39: 67 increased by 8 to 75
n52: 80 increased by 8 to 88
n27: 63 increased by 9 to 72
n39: 75 increased by 9 to 84
n52: 88 increased by 9 to 97

I think I’m fairly calm and a lot less confused now…

(Before you say anything, yes I am aware that the code’s snazzed up a bit – it wasn’t the most readable at first, especially when there’s a massive chunk of it…)

Posted in Computing, Placement | Tagged: , , , , , , , , , | 1 Comment »

Renderer: Renderables

Posted by Robert Chow on 15/01/2010

So with the majority of the Renderer library nearly finished (with the exception of layers and fonts; well, there are fonts, they’re just not perfect), the process of refactoring has started.  On top of that is also creating a toolkit which will be used as a helper library to make using the Renderer library a bit more user-friendly. Less typing means for more time to do other things.

Renderable Objects

So Renderer is based on the concept of having Renderable objects.  These are exactly what they say on the tin.  They’re are renderable.  To render them, you will need to access their properties.  These properties are fairly straight forward, and are what you would expect a Renderable object to have.  Of course, these have been fine-tuned to the usage of vertex buffer objects, so the properties are:

Vector[] Vertices; // vertices of the shape
Colour[] Colours;  // colours specified at each vertex
Vector[] Normals;  // normals specified at each vertex
Vector[] TexCoords;// 2D texture co-ordinate specified at each vertex, these map to the Renderable texture
uint[] Indices;    // the order of how the vertices are to be drawn 
IMaterial Material;// any material properties this Renderable may hold
ITexture Texture;  // the texture, if, bound to the Renderable
DrawType DrawType; // an enum representing each OpenGL drawtype, specifying how the Renderable is drawn

Without the Vertices, Indices or DrawType, the Renderable is unrenderable, so these are forced in the constructor.  Using the vertices as a core property, this cannot be changed, but all the other properties can be.  That is, due to validity checks.

Duplicate Duplicate

Drawing each Renderable as a vertex buffer object seems rather silly to store the core data multiple times, as it will already be in the GPU, as well as the artificial buffering system in Renderer (used to control and keep a track of what is in the GPU), so it is not necessary to have it in the Renderable object itself.  Instead, I have used the notion of a ‘pointer’ per property.  This is not the conventional pointer traditionally used in computing, as it does not directly correspond to a place in memory.  Instead it points to a place in the artificial buffer where the corresponding data is held.  Using this method means the Renderable object is rather lightweight and is cost effective in memory.

To obtain the ‘pointer’, the client needs to ask the Renderer library.  This is done through the RendererFacade (Facade design pattern), and only takes in the one parameter – the core data.  This core data is sent to the artificial buffer, and the ‘pointer’ is returned.

Where the vertex buffer objects are concerned, this changes the properties in the Renderable object to type ‘pointer’.  Of course this could cause problems, allowing clients to assign Colours ‘pointer’s to TexCoords, Indices ‘pointer’s to Normals and so forth, eventually causing the computer to crash because of a GPU error.  To solve this, each ‘pointer’ is wrapped in a DataPacket interface, and deriving from this are corresponding DataPackets for Vertices, Colours, Normals etc. making sure that the correct ‘pointer’ is matched with the right property.

IVerticesDataPacket Vertices;
IColoursDataPacket Colours;
INormalsDataPacket Normals;
ITexCoordsDataPacket TexCoords;
IIndicesDataPacket Indices;

Using the standard get and set methods that properties have, changing a property is relatively easy (we can also write these manually to do our validity checking).  But it could be better.

Fluent Refactoring

Since we are refactoring, we might as well try to make this as easy to understand and read as possible.  For this, I have touched upon fluent interfaces.

The idea behind this is relatively simple when assigning a property.  It’s a little more difficult when it comes to multiple states.  But more on that later.

For example, we want to assign a ColourDataPacket, a TexCoordsDataPacket and a Texture to a Renderable, it’s as easy as this:

renderable.Colours = colourDataPacket;
renderable.TexCoords = texCoordsDataPacket;
renderable.Texture = texture;

However, to create a fluent interface, I have created extension methods that more or less do exactly the same thing.  The difference is that it reads better, it’s less typing, and it’s also a single statement.

renderable.Assign(colourDataPacket)
.Assign(texCoordsDataPacket)
.Assign(texture);

The extension methods are simple.  Not only do they do pretty much exactly the same as per normal assignment, but they also return the Renderable instead of void, allowing more methods to be called – this is a form of method chaining.  To make it even more simple, I have also used polymorphism to defer from what is assigned to what, allowing me to just use variants of the one method, Assign(), throughout.

Pretty cool, eh?

 

Posted in Computing, Placement | Tagged: , , , , , , , , | 2 Comments »

Snow Go From Here

Posted by Robert Chow on 08/01/2010

If you haven’t heard, Britain’s having one of it’s coldest winters for a long time – cold enough to rival that of 1963 where the snow was at some places 6 metres deep.

I was suppose to go back to Devon to work last Tuesday, and unsurprisingly, due to the weather conditions, this wasn’t the case.

Instead I’ve been stationed here for another week.  Another week spent in Manchester, and some might say lucky you.

I thought so too, but that only lasted so long.  I actually wish I was back in Devon for now.  Ok, it might not be the most exciting of places, but regardless, I do enjoy my time at work.

I’m trying to do some now, but “working from home” is literally “working from home”.  Nothing is as productive as it can be, and nothing goes according to plan.

Sure, I have done some.  But it’s not quite the same.

Anyway.

I’ve had a request to show how to do the multiple Bézier curves I did earlier – that post also seems to be the most popular topics of the blog.  Lucky for some, I am currently trying to write a toolkit for the Renderer library, and being able to create fancy Bézier curves will feature in the near future.

For now, whilst I’m out of office, I’m looking at a few topics me and my supervisor have been meaning to touch upon.

Ninject

A tool used for dependancy injection, a form of Inversion of Control.  The traditional flow of programming is to use a central piece of code to control the flow; Inversion of Control takes away this design principle.  Dependancy injection introduces the notion of both high and low level modules independant of each other, and should only depend on their abstractions.

M.Spec

M.Spec is a testing framework, and as far as I’m aware, it uses a similar principle to BDD (Behaviour Driven Development) – it uses Given/When/Then statements.  I find these statements can be easily read as given initialState, when performing anAction, then newState.

Python

I’ve been meaning to try and get to grips with this new(ish) language for the past couple of months, but never really gave myself enough time.  A dynamic language, it looks to promise an increase in readability and productivity.

Fluent Interface

This is one thing I am most definately interested in.  Using a fluent interface increases the readability of code, trying to make it read like normal English.  To achieve this, an object may invoke a method, and return itself, allowing the client to invoke another straight afterwards.  Creating a fluent interface also takes the advantage of extension methods in C#.  Read this.

20.Minutes().Ago()

To achieve this, create an int extension Minutes(), returning a class representing time of x.minutes (this case 20).  To create the Ago(), add an extension to the time class (or add it as normal if the time class is self-written), and return an object of the same class, but representing the time now minus x.minutes.

Apparently it takes a rather lot of effort, but to achieve better readability, especially something something close to fluent English, is something I’m definately willing to spend time on.

Let’s hope I’m back soon.

Posted in Computing, Placement | Tagged: , , , , | Leave a Comment »