Planning the Spontaneous

It's more than just a blueprint.

One More Bite…

Posted by Robert Chow on 07/02/2010

I’ve been up in Manchester for the last few days, playing it out being a student again. And honestly, it’s felt rather good.

I signed for a house the first day I came back for the next academic year, and had a look around. It’s a pretty nice place; and thankfully, I didn’t have to do a single thing to find it! So I’m pretty grateful for all the hassle my future housemates went through to get the place – I’m sure I can find a lot more calming activities to do!

I’ve also just got back from the most amazing all-you-can-eat ever! It’s a Brazilian steakhouse called Bem Brazil in the northern quarter of Manchester. 12 different cuts of meat we managed to scoff down, ranging from the absolutely gorgeous beef fillet steak down to the little chicken hearts, which I wasn’t too particularly fond of.

I’m in Manchester because I’m going to a conference on Tuesday in Birmingham, and thought I’d take a long weekend at home since it’s only a couple of hours extra on the train. It’s a software developer’s conference about mapping software – hopefully something I’ll be touching upon later in my placement.  The link for anyone interested is http://www.esriuk.com/trainingevents/events/developerhub090210/.

The plans for the future are a bit up in the air for the time being.  Now with Renderer nearly finished, I am currently looking at spiking Grapher, and then after that, to possibly start on Mapper – hence the conference.  However, a lot of ideas have been proposed for Grapher, and it’s come to the point of it might be best for me to develope Grapher versions 1 and 2 during the rest of my placement and to do Mapper in the Summer if I am given the chance to come back.  My intentions are to try to do as much as possible – I want to, and if I don’t deliver, not only will I be annoyed and disappointed at myself, I’ll also think it’s a real shame that I am unable to bring to the table a good set of components usable in the next program.

The last few weeks I haven’t been blogging as often as I’d like, and that’s because things are just taking longer than the usual.  And it’s not like as if we have numerous time-consuming talks about health & safety to blame either.  Time after time after time, ideas come and go.  Try one out, and you end up in a dead-end, so you’re forced to try another.  It’s not until after 4-5 attempts do you quite get it right sometimes, and even then you’re not necessarily happy with the result because at the end of the day it’s not very good code.  So you have to try again.

My supervisor’s been telling me to come up with more than a few ideas before trying them out.  But I’m not much of a planner; I like to get stuck into it as soon as possible.  I guess I would like to become more of that planner type person – it’d also mean one more step in the right direction for personal development.  If you get it right and plan well, you do save yourself a lot of time from not having to implement all the wrong ideas.

Heck, even that bit of this blog wasn’t planned.

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

“{Binding OpenGl To WPF}” : Part 2

Posted by Robert Chow on 03/02/2010

This is the second part of my journey to creating an application using WPF, wrapping the Renderer demo I made earlier. You can find the first part here.

Subconscious Intentions

So, initially in this post, I was going to introduce the concept of the model-view-viewmodel, and code inline and code behind.  Or at least, how I understand them.  Yet due to recent activity, that will have to wait till the next post.

The great thing about writing these blog posts is that in order for me to seem like I know what I’m doing, I have to do the research.  I’ve always been taught that during an exam, always answer the question as if the examiner doesn’t know anything about the subject bar the basics.  This way, you should answer the question in a detailed and chronological order, thus making complete sense and gaining full marks.  In a way writing these posts are quite similar.  Sure, I may have broken the rule more than a few times, especially when I’m rushing myself, but I try to explain the topics I cover in enough detail for others than myself to understand it.  After all, although I am writing this primarily for myself to refer back to for when I get stuck, it’s nice to know that others are benefiting from this blog too.

It’s not because I haven’t done the research that I can’t bring to the table what I know (or seem to know) about the model-view-viewmodel, code inline and code behind.  It’s because during the research and much tinkering around, that I thought I should cover the main drive for using WPF in the first place, and that is to incorporate an OpenGl control.

From Scratch

So a couple of weeks ago, I did actually manage to create an OpenGl control, and place it inside a WPF form.  The way I did this was a bit long-winded compared to how I used to, by creating it in a Win32 form.  Instead of using the SimpleOpenGlControl provided by the Tao framework, I went about by creating the control entirely from scratch.

For this, I could have done all the research, and become an expert at creating the control manually.  But that simply wasn’t my intention.  Luckily for me, the examples provided by Tao included the source code ,and a quick copy and paste, I more or less had the code ready and waiting to be used.

One thing I am more aware of now is that you need two things, a  rendering context and a device context.  The rendering context is where the pixels are rendered; the device context is the intended form for where the rendering context will sit inside.  Of course, the only way to interact with these are using their handles.

To create a device context in the WPF application, I am using a Windows Forms Host.  This allows you to host a windows control, which we will use as our device context.  The XAML code for this is relatively simple.  Inside the default grid, I have just inserted the WindowsFormsHost as the only child element.  However, for the windows control, I have had to take from a namespace other than the defaults provided.  To declare a namespace, declare the alias (in this case I have used wf, shorthand for windows forms) and then follow it with the namespace path.  Inside the control, we are also going to use the x namespace.  Using this, we can assign a name for the control, and thus allowing us to retrieve the handle to use as the device context.

<Window x:Class=“OpenGlControlInWPF.Client”
xmlns=“http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=“http://schemas.microsoft.com/winfx/2006/xaml”
xmlns:wf=“clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms”
Title=“Client” Height=“480″ Width=“640″ WindowStyle=“SingleBorderWindow”>
<Grid ClipToBounds=“True”>
<WindowsFormsHost ClipToBounds=“True”>
<wf:Control x:Name=“control”/>
</WindowsFormsHost>
</Grid>
</Window>

With the form done, we can now dive into the code in the C# file attached to the XAML file.  It is here where we create the rendering context, and attach it to the device context.  I’m not really an expert on OpenGl at all when it comes to this kind of thing, so I’m not going to show the full code.  If you’re really stuck, the best place I can point you to is to look at NeHe’s first lesson, making an OpenGl window.  If you’re using the Tao framework and you installed all the examples, the source code should come with it.

The WPF interaction in the C# code is very minimal.  All we need to do with the XAML file is to retrieve the handle associated with the control we declared beforehand.  This is done simply by using the name we gave it in the XAML and letting Tao do the rest.  We hook this up to retrive a rendering context, and then we show the form.

Gdi.PIXELFORMATDESCRIPTOR pfd = new Gdi.PIXELFORMATDESCRIPTOR();
// use this to create and describe the rendering context – see NeHe for details

IntPtr hDC = User.GetDC(control.Handle);
int pixelFormat = Gdi.ChoosePixelFormat(hDC, ref pfd);
Gdi.SetPixelFormat(hDC, pixelFormat, ref pfd);
IntPtr hRC = Wgl.wglCreateContext(hDC);
Wgl.wglMakeCurrent(hDC, hRC);

this.Show();
this.Focus();

All there is left to do is to go into the OpenGl loop of rendering the scene at each frame. Unfortunately, because I am used to the SimpleOpenGlControl provided by Tao, I’ve never needed to go into it whilst I’ve been on placement. All I had to do was to call simpleOpenGlControl.Invalidate() and the frame would automatically refresh for me.  As a result of this, I decided to place the draw scene method in a while(true) loop so the rendering would be continuous. And true to my thoughts, I knew this wouldn’t work.  As a result, the loop was “throttling” the application when running – I was unable to interact with it because all the runtime concentrated on rendering the scene – there was no interrupt handling so pressing a button or typing a key didn’t have any effect whatsoever.

I did try to look for answers to the throttling, and I stumbled across something else.  Another solution to hosting an OpenGl control in WPF.

The Better Solution

Going back to the first post of this multi-part blog, you might recall I am using a Canvas to host the OpenGl control.  I found this solution only a couple of days ago, due to a recent post on the Tao forums.  It uses this canvas in the C# code and assigns a WindowsFormsHost.  This in turn is assigned a SimpleOpenGlControl.  A SimpleOpenGlControl!  This means that I am able to use all the abstractions, methods and properties that the SimpleOpenGlControl has to offer without having to manually create my own.

First of we have to assign the canvas a name in the XAML code so we can reference it in the C# counterpart.

<Grid Background=“AliceBlue”>

<Border Grid.Row=“0″ Grid.Column=“0″ Background=“Black” BorderThickness=“1″ BorderBrush=”Navy” CornerRadius=“5″ Margin=“6, 6, 3, 3″>
<Canvas ClipToBounds=“True” Margin=“2″/ x:Name=“canvas”>
</Border>
</Grid>

The C# code for creating the SimpleOpenGlControl is short and sweet.  We create the WindowsFormsHost, attach a newly created SimpleOpenGlControl and attach the whole thing to the Canvas.  Here is the entire code for creating this.

namespace OpenGlWPFControl
{
using System.Windows;
using System.Windows.Forms.Integration;
using Tao.Platform.Windows;

/// <summary>
/// Interaction logic for Client.xaml
/// </summary>
public partial class Client : Window
{
public Client()
{
InitializeComponent();

this.windowsFormsHost = new WindowsFormsHost();
this.simpleOpenGlControl = new SimpleOpenGlControl();
this.simpleOpenGlControl.InitializeContexts();
this.windowsFormsHost.Child = this.simpleOpenGlControl;
this.canvas.Children.Add(windowsFormsHost);
}

private WindowsFormsHost windowsFormsHost;
private SimpleOpenGlControl simpleOpenGlControl;
}
}

Now we have the SimpleOpenGlControl set up, we simply just add the event for rendering and we’re nearly done. There is one problem however, and that is the windows forms host does not know what size to take. We add an event for when the canvas is resized to update the windows forms host size too.

public Client()
{

this.simpleOpenGlControl.Paint += new PaintEventHandler(simpleOpenGlControl_Paint);
this.canvas.SizeChanged += new SizeChangedEventHandler(canvas_SizeChanged);
}

void simpleOpenGlControl_Paint(object sender, PaintEventArgs e)
{
// do your normal opengl drawing here
this.simpleOpenGlControl.Invalidate();
}

void mainCanvas_SizeChanged(object sender, SizeChangedEventArgs e)
{
this.windowsFormsHost.Width = this.canvas.ActualWidth;
this.windowsFormsHost.Height = this.canvas.ActualHeight;
}

A Revelation To An Even better Solution

So I said I was going to talk about other topics before delving into my journey of placing an OpenGl control inside a WPF application, and that’s because of what I found myself accomplishing last night.  In the first blog post of this multi-part series, I found myself using a Canvas to hold a Windows Forms Host, and in turn, to parent a SimpleOpenGlControl.  Yet with further understanding of WPF,  a revelation came.  The reason I was unable to insert a SimpleOpenGlControl directly into the application beforehand was because I wasn’t entirely aware of namespaces in XAML.  Soon after finding more about them, I find I am able to access the SimpleOpenGlControl by referencing Tao, and hence solving all the background work the C# had to do.

<Window
xmlns:tao=“clr-namespace:Tao.Platform.Windows;assembly=Tao.Platform.Windows”
…>
<Grid Background=“AliceBlue”>

<Border Grid.Row=“0″ Grid.Column=“0″ Background=“Black” BorderThickness=“1″ BorderBrush=“Navy” CornerRadius=“5″ Margin=“6, 6, 3, 3″>
<WindowsFormsHost Margin=“2″ ClipToBounds=“True”>
<tao:SimpleOpenGlControl x:Name=“simpleOpenGlControl”/>
</WindowsFormsHost>
</Border>
</Grid>

So the only thing extra that to add to this is the event for rendering, which I included before. I can omit the need for having to resize the canvas, partially because there is now no canvas, and also because the WindowsFormsHost ClipTobounds property is true.

In the next part of this series I will hopefully be touching upon what I intended on touching upon in the first place, the model-view-viewmodel pattern.

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

“{Binding OpenGl To WPF}” : Part 1

Posted by Robert Chow on 02/02/2010

I’ll admit, it’s been a while.  But since I’ve been back, I’ve been working on a fair few things simultaneously, and they’ve taken a lot longer than planned.  But alas, here is one of them, in a multi-part blog.

Windows Presentation Foundation

Remember where I mention WPF a few times, but never really got into it?  Here’s a statement from the Microsoft website:

Windows Presentation Foundation was created to allow developers to easily build the types of rich applications that were difficult or impossible to build in Windows Forms, the type that required a range of other technologies which were often hard to integrate.”

Ha.

It’s not easy to develop on at all, especially for a developer just starting their first WPF project.  Not compared to creating a Win32 Form with a visual editor to say the least.

But it does allow you to build very rich applications that appeal to many by their look and feel alone.  And they look a lot better than Win32 forms too.

Remember that demo for Renderer?  I originally said I was going to try and incorporate fonts into it, but that’s still one bridge I have yet to cross.  Instead, I decided to learn a bit of WPF instead.  What do you think?

Demo In WPF.  Here I have incorporated the demo into a WPF form, and included panels on the right and bottom.  The right panel depicts the current state of the game, and allows the user to change the camera position and change the texture used when a cube face is picked.


Demo in Win32 Forms Mock.  I have included a mock of the original in a Win32 Form.  I think it’s fair to say the least that you would all rather use the WPF version.


XAML

The language of WPF is XAML, extensible-application-markup-language, and is very similar to XML.  It uses the open/close tag notation – one which I’m not particularly fond of, but it does mean that everything is explicit, and being explicit is good. Like all other languages, it’s very useful to know your ins and outs and what is available to use, and using XAML is no exception to this rule either. As a result, there are many ways, some better, some far worse, ways of creating the form I have made.  As I am no expert in this at all, I am going to leave it as it is, and take a look at the code I have generated for creating the form base.

To create this, I used Visual C# 2008 Express Edition.  This has proved rather handy as it updates the designer view as the code is changed.

Starting a WPF project gives you a very empty template.  With this comes 2 pieces of code, one in XAML and the other in C#.  For the time being, we are just going to concentrate on the XAML file.  This is where we create our layout.  The initial piece of XAML code is very simplistic, and doesn’t really mean too much.

<Window x:Class=“OpenGlWPFControl.Client”
xmlns=“http://schemas.microsoft.com/winfx/2006/xaml/presentation”
xmlns:x=“http://schemas.microsoft.com/winfx/2006/xaml”
Title=“Client” Height=“665″ Width=“749″>
<Grid>
</Grid>
</Window>

The first few lines relate to the namespaces being used within the XAML file. The tags marked Grid relate to the box inside the window. This is a new concept different to the panels in a Win32 Form. Instead of having top, bottom, left and right panels, the grid can be split into a number of columns and rows using definitions.

Here I have split the grid into 4 components using 2 rows and 2 colums.  The code is relatively easy to deal with.  It also allows you to specify minimum, maximum and default dimensions.

<Grid Background=“AliceBlue”>
<Grid.RowDefinitions>
<RowDefinition Height=“*” MinHeight=“200″/>
<RowDefinition Height=“100″/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width=“*” MinWidth=“200″/>
<ColumnDefinition Width=“200″/>
</Grid.ColumnDefinitions>
</Grid>

Here, I have specified the default heights for each row and the default widths of each column.  The “*” is simply a marker to take what space is left.  As an extra,  I have also set the grid background colour.

Now that we have split the initial grid, we can now start to populate it.  This can be with other layout panels, like the grid, or a stackpanel or dockpanel and so forth to add extra layout details.  It can also be filled with more meaningful objects such as a label or a text box.

Starting off, I want to place the OpenGl control in the top-left panel.  For the time being, we are going to mock this using a Canvas.  This item will be used later in the C# code to attach the OpenGl control, but for the time being we are only handling XAML.  In addition, I have also decorated the canvas with a border.  Using a combination of the canvas and border properties, I have managed to achieve the rounded edges, making it more aesthetically appealing.

<Grid Background=“AliceBlue”>

<Border Grid.Row=“0″ Grid.Column=“0″ Background=“Black” BorderThickness=“1″ BorderBrush=“Navy” CornerRadius=“5″ Margin=“6, 6, 3, 3″>
<Canvas ClipToBounds=“True” Margin=“2″/>
</Border>
</Grid>

This piece of code stays within the Grid tags, as it is a grid child.  For where in the grid it sits, I have explicitly stated which row and column of the grid it sits inside the Border tag.

The bottom panel is done in a similar fashion, only this time the border decorates a textblock.  In order to scroll a textblock, this itself needs to be decorated using a scroll viewer.

<Grid Background=“AliceBlue”>

<Border Grid.Row=“1″ Grid.Column=“0″ Grid.ColumnSpan=“2″ Background=“White” BorderThickness=“1″ BorderBrush=“Navy” CornerRadius=“5″ Margin=“6, 3, 6, 6″>
<ScrollViewer Margin=“2″>
<TextBlock/>
</ScrollViewer>
</Border>
</Grid>

There is only small change which we have to do so the panel is not confined to one grid space. This is done using the Grid.ColumnSpan property.

Now with only one panel left, I have decided to make my life that little easier by adding in extra grids.  These are done in the exact same way as the initial grid.  Using what I have done already, and combining it with new elements, the last panel is added.

<Grid>

<Border Grid.Row=“0″ Grid.Column=“1″ Background=“White” BorderThickness=“1″ BorderBrush=“Navy” CornerRadius=“5″ Margin=“3, 6, 6, 3″>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height=“Auto”/>
<RowDefinition Height=“Auto”/>
<RowDefinition Height=“*”/>
<RowDefinition Height=“30″/>
<RowDefinition Height=“30″/>
<RowDefinition Height=“60″/>
</Grid.RowDefinitions>
<Grid Grid.Row=“0″>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Label Grid.Row=“0″ HorizontalAlignment=“Left” VerticalAlignment=“Bottom” FontSize=“36″ Content=“Score:”/>
<Label Grid.Row=“1″ HorizontalAlignment=“Right” VerticalAlignment=“Top” FontSize=“48″ Content=“0″/>
</Grid>
<Grid Grid.Row=“1″>
<Grid.RowDefinitions>
<RowDefinition Height=“50″/>
<RowDefinition Height=“Auto”/>
<RowDefinition Height=“Auto”/>
</Grid.RowDefinitions>
<Label Grid.Row=“1″ HorizontalAlignment=“Left” VerticalAlignment=“Bottom” FontSize=“24″ Content=”Lives:”/>
<Label Grid.Row=“1″ HorizontalAlignment=“Right” VerticalAlignment=“Bottom” FontSize=“24″ Content=“0″/>
<Label Grid.Row=“2″ HorizontalAlignment=“Left” VerticalAlignment=“Bottom” FontSize=“24″ Content=“Level:”/>
<Label Grid.Row=“2″ HorizontalAlignment=“Right” VerticalAlignment=“Bottom” FontSize=“24″ Content=“0″/>
</Grid>
<Label Grid.Row=“3″ HorizontalAlignment=“Center” VerticalAlignment=“Bottom” Content=“Camera Position”/>
<Grid Grid.Row=“4″>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Button Grid.Column=“0″ Margin=“15,0,15,0″ Content=“&lt;&lt;”/>
<Button Grid.Column=“1″ Margin=“15,0,15,0″ Content=“>>”/>
</Grid>
<Button Grid.Row=“5″ Margin=“15,15,15,15″ Content=“Change Texture”/>
</Grid>
</Border>
</Grid>

As a result, we achieve a form created entirely from XAML.

Unfortunately however, there is no logic behind this. In part 2, we start looking at the other parts of the code and insert an OpenGl control into the application.

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

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

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 »

Time For A Break

Posted by Robert Chow on 25/12/2009

So I haven’t been posting recently, and that’s because I’m back in Manchester for Christmas.

Lo and behold, recently it’s started to chuck it down with snow – bringing many much delight, but also many to much despair.

Travelling has been the main problem, and thankfully, I myself have not been greatly affected. The icy roads and paths have made it hard for anyone to travel – train, plane, car, even walking. I do believe that the only time it should snow is when you’re on a mountain with a board strapped to your feet, but what do I know – the last time I did that, I broke a wrist and dislocated a collarbone. But it’s not all doom and gloom.

The scenery’s definately brightened up.

First Glimpse Of Snow And Sunset.

Snow Through The Trees.

Bridge Snowed Over.

I may make one another post every now and then, but for now, I’m putting my feet up.

Merry Christmas and have a Happy New Year.

Posted in Placement | Tagged: , | 1 Comment »

Renderer: Demo

Posted by Robert Chow on 16/12/2009

So now that I’ve got a lot of my functionality going for me in this component, I thought I’d try and create a snazzy demo.

My supervisor’s obsessed with it. It’s like a little game – there is a rotating cube, and the challenge is you have to click on each face before you pass on to the next level. As you progress, the cube rotates just that little bit faster, making it harder to complete the challenge. Clicking on a face will turn that face on. Clicking on a face that is already on will turn it off – you can only progress when all 6 faces are switched on.

So you can automatically see that this little demo already involves the concept of vertex buffer objects (drawing of the cube), the scene graph (rotating cube), the camera (viewing the cube, using the scene graph) and picking (turning faces on/off). But what about the others?

Well, lets place the scene into dark surroundings – we’re going to need lights to see our cube – that’s lighting handled. So where does texturing fit in?

Switching the faces on/off need an indicator to show what state they are in.  We can easily do this by simply changing the colour of a face.  But that’s kinda boring.  So instead, we’re going to take the rendering to texture example, and slap that on a face which is on.  So that’s textures included.

Here are some screenshots of this demo.

Demo Setup. From left to right: initial scene – just a white cube; let’s dim the lighting to, well, none; include some lights: green – centre, red – bottom, blue – left; create a texture.

Demo Rotate. The demo in motion – the camera is stationary, whereas the cube is rotating, and the lights are rotating independantly around it.

Demo Play.  The first and second images show what happens when a face is clicked – the texture replaces the blank face.  Once all the faces are replaced with the texture, the demo advances to the next level.

Demo Camera.  This shows added functionality of how a camera can be fixed on to a light, thus the camera is rotating around the cube too.  Here it is fixed on to the blue light.  This is done with ease by manipulating the scene graph.

I guess you can’t really get a grasp of how this demo works in its entirety – sanpshots don’t really do it much justice.  I might try and upload a video or so – how, I’m unsure of – I’m sure I can probably find screen capture software around on the net.

And unfortunately, there is no score involved. Yet. That will come when fonts come.

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

Renderer: Lighting

Posted by Robert Chow on 15/12/2009

So these are tricky too.

OpenGL only allows 8 lights at any one time, and should you need more, they suggest you ought to reconsider how you draw your model.

As it is not just one light available, we need to be able to differentiate between each light.  We do this by declaring an enum.

public enum LightNumber
{
GL_LIGHT0 = Gl.GL_LIGHT0,
GL_LIGHT1 = Gl.GL_LIGHT1,
..
..
GL_LIGHT7 = Gl.GL_LIGHT7
}

An enum, like classes, can be used as parameters, with one restriction – the value of the parameter must be equal to one of the values decalered within the enum.  In the context of lights, the LightNumber can only be either GL_LIGHT0, GL_LIGHT1, GL_LIGHT2 and so forth until GL_LIGHT7; giving us a maximum of 8 lights to choose from.  For an enum, the values on the left-hand side are names.  These names can be referred to.  However, you can then assign these names values, as I have done – in this case, it is their correspondant OpenGL value.

So now we can set our lights, and attach them to a node, similar to the camera.  Kind of.  Unlike the camera, these lights can either be switched on or off, and have different properties to one another – going back to the lighting post, the ambient, diffuse and specular properties of a light can be defined. We could do this using two methods.

Renderer.SwitchLightOn(LightNumber lightNumber, bool on);
Renderer.ChangeLightProperty(LightNumber lightNumber, LightProperty lightProperty, Colour colour);

We could.

But we shouldn’t.

I’ve been reading a lot lately about refactoring – cleaning up code, making it better, more extensible, and easier to read. A few months ago, I stumbled across this guide to refactoring. A lot of things were simple and made a lot of common sense. But it was intelligent. Something which, everyone becomes every now and then.  And it’s definately worth a read.  Another one I’ve ben reading of late is this book on clean code.  How good really is your code?

The Only Valid Measurement Of Code Quality.  This image has been taken from http://sayamasihbelajar.wordpress.com/2008/10/24/

Naming conventions are rather important when it comes to something like this, and using a bool as a parameter – doesn’t exactly mean much.  Once there is a bool, you will automatically know that the method does more than one thing – one thread for true, and another for false.  So split them.

Renderer.SwitchLightOn(LightNumber lightNumber);
Renderer.SwitchLightOff(LightNumber lightNumber);

There a lot of wrongs and rights, but no concrete answer – just advice that these books can give you.  So I’m not going to trip up on myself and try and give you some more advice – I’m only learning too.

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