Planning the Spontaneous

It's more than just a blueprint.

From Vision to Speech

Posted by Robert Chow on 23/10/2010

Vision

Wow.

It’s been a long year. Although it has also gone very fast indeed, I have now officially finished my term at IGI.

I have spent the last 14 months trying to get to grips with C#, OpenGL, WPF, Python, SVN, Kanban and all sorts of other technologies and methodologies.  I gave my final presentation at the user group meeting a fortnight ago, and, despite the length, it seemed to be very well received.  I showcased my demos that I tried to cram together to show the progress I had made throughout the year.

So that’s it for Renderer and Grapher on my behalf.  What did I think about the year?

Before joining, I was rather skeptical about it at first.  I had always said that for the duration of the year, I didn’t want to be a statistic; I wanted a responsibility, and to not just be doing the “little” jobs that I’ve heard a lot of other placement students undertake. IGI certainly did not fall into the latter – I was working in a team of 2.  That’s it.  Just my boss and I.  What if I didn’t get along with him?  What if he took the wrong end of the stick and had me “running” for him?  After all, this was his first time in management too.

I remember being sat at my desk at the end of the first day, and next to me was a pile of books he recommended I read.  I can’t say I was happy with this.  It’s not in everyone’s nature to be able to just read up on a topic as practical as programming and expect them to pick it up with enthusiasm.  In fact, I don’t think it’s in anyone’s.   Most certainly not mine.

But I managed to turn this lack of enthusiasm around.  I set myself little tasks.  To achieve and complete a new goal at the end of each day; and each goal had a new learning objective.  It’s not easy trying to teach yourself a new skill, especially when you don’t know what skills are out there, but the more I learnt, the more I wanted to learn.

I was rather glad with the set up I had at IGI.  As far as I’m aware, no other placement student on my course was so fortunate to get teaching at such a personal level.  I often do say that within the first 2 weeks of being at IGI, I had probably learnt more than I had in the first 2 years at university.  It was during the first few months that I was introduced to C# and an OpenGL implementation to accompany it.  It was exciting to learn from a professional and hands-on level about OpenGL, unlike the second-year course at university.  More exciting was learning C#.  Everyone’s said C# is Microsoft’s answer to Java.  I might agree, however, and also much to the similar views of other placement students working with the language, the Microsoft answer is also far superior.  Exploring the infinite avenues that lambda expressions, LINQ and extension methods offered was definitely something I particularly enjoyed learning about.  Renderer was born.

As much as it sounds so far, it wasn’t all perfect.  There were a number of issues I encountered during the latter half of the year.  Our approach for Grapher didn’t quite suit my working style for such a task.  Grapher can be seen as a large component, full of lots of smaller components.  However, take one of these smaller components away, and none of it would work.  Our original approach was to tackle it incrementally – build from the ground up, adding small sections at a time.  Alas, it didn’t seem to be the case.  Our switch to use the vertical stack – a skeleton made up of smaller skeletal sections – proved a lot more efficient.  Using the skeleton, I was able to “flesh” out the rest of the code incrementally, without have to change much of the base code.

Aside from the main objectives, I did enjoy sections of time spent on other projects.  It was agreed that I should learn a new programming language, of which it should be a dynamic language.  My language of choice was Python.  I started off with a few examples, and then managed to work my up towards near completing a very graphical version of minesweeper, implemented with IronPython and WPF.  I intend to finish that project sometime – I want to further my knowledge base of languages, technologies and methodologies.

If there is anything this year has taught me, it is about myself.   My hunger for knowledge has always been there, that I can already admit to.  However, combine this with creativity, an ambition to succeed and a thirst for problem solving, it has taught me that I really do enjoy working in the field of software development.  I am pretty sure that I want to do this for the rest of my career, and not only watch the world of software development evolve around me, but to also evolve with it.  Heck, if I could be a part of the evolution, then even better.

So what’s next?

Speech

Now I’m doing my final year at university, graduating in 2011.  My third year project title: Automatic Spoken Language Recognition.

For my third year project, I’ve particularly wanted to work in artificial intelligence and medicine.  However, due to the limited resources of the school, I’ve not been able to secure such a project, yet I think this does verge on it being similar.

During the first couple of weeks of term, I have spent learning about the anatomy of the human vocal system, and researching into how this is then transpired into and interpreted by a machine.  Next up is the introduction of the artificial intelligence, and to make the decision on whether or not take a model-based approach, or a data-driven approach.  I have a meeting with my supervisor next week, so hopefully I’ll be able to get some answers…

Advertisements

Posted in Automatic Spoken Language Recognition, Computing, Placement, University | Tagged: , , | Leave a Comment »

new Random().Update

Posted by Robert Chow on 06/07/2010

Just a quick message to let you know what’s been going on.

I’ve been quite busy lately, now coming to the end of my placement.

Since the last time I’ve blogged, I’ve had to try and complete Grapher to the best of my capabilities.  I did a 45 minute pressentation last week, which seemed to go rather well.  I’ve now got to build up on that and see if I can bring a good presentation to the user group meeting in October.

I also went to DDD South West 2.0 – a free conference held in Bristol for .NET developers.   It was very interesting to see the differing talks and all sorts of people developing in .NET.   I’m hoping that I can go again next year, providing my examinations don’t clash.

What’s next?  I’ve got to write a report concluding the year’s placement.  Watch this space.

I won’t be around much for the next month or so; I’m going travelling around Europe via interrailing.   I am however, coming back down to Devon afterwards to start a month or so of work here for the Summer.  Then it’s off to university for my finals.

As a side note, my brother is also doing a sponsered walk from Cheadle Hulme (Manchester) to London for Action For Kids.  I’m following his progress here on Twitter, and you can also sponser him here.

I’ll be back… soon…

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

DrawInside(Stencil);

Posted by Robert Chow on 26/05/2010

So a few things have changed since I last made a post.

My targets for the end of the year have been reduced.  Which I’m very glad about.  No, it’s not because I’m a slacker, but more importantly because there simply isn’t enough time.

What’s new?

As a result, the target is now very focused on getting an end product out to show for Grapher.  This end product will have rather minimal functionalities, yet will still be comprehensible enough to use as a Grapher component.  Of course, this target will not actually be used as a component without further work; like those functionalities.

Unfortunately, there are still hidden complexities.  There are always hidden complexities in any piece of software you write, in particular those which you have no prior knowledge about.  My supervisor said to me that you shouldn’t start coding until you have answered all those question marks.  Yet another downfall to my side of planning.  But I think I’m starting to learn.

Once again, Grapher threw up a hidden complexity in the way that layers would be drawn.  The idea was to draw the plot in its own viewport, eliminating everything outside of the view such as data points that do not lie in the visible range.  Of course, this is all fine with a rectangular plot – the natural OpenGl viewport is rectangular.  However, come to nonrectangular plots such as triplots or spiderplots, the story is rather different.

The first solution, would be to use a mask to hide away the data outside of the plot.  Unfortunately, this mask would also hide away any items lying underneath that has already been renderered there.

As a result, the next solution states that, because of the action caused by the first solution, some layers would have to be fixed; for example, the data plot will always be at the bottom to make sure the mask does not obscure anything underneath it.

At this point in the placement, I never did think that I’d be adding something major to Renderer;  the final solution, and arguably the best would be to use a stencil buffer.

Stencil me this

A stencil buffer allows for a nonrectangular viewport.  Primitvives, acting as the viewport is drawn to the stencil buffer; using this, only items drawn inside the viewport outlined by the stencil buffer is rendered.

Simple right?

Of course, there are hidden complexities.  Again.

The best thing for me to do would be to spike the solution, instead of coding it straight into Renderer.

First point of action I took was to visit the OpenGl documentation pages, and they provided me with a few lines of code.

Gl.glEnable(Gl.GL_STENCIL_TEST);

// This will always write to the corresponding stencil buffer bit 1 for each pixel rendered to
Gl.glStencilFunc(Gl.GL_ALWAYS, 1, 1);

// This will only render pixels if the corresponding stencil buffer bit is 0
Gl.glStencilFunc(Gl.GL_EQUALS, 0, 1);

Using these should result in items declared after the final call, to be only visible if it lies outside of the viewport declared after the second call.  I continue to claim that by all means, I am no expert on OpenGl, but that’s the rough idea I get from these calls.

I tried this, but to no avail, nothing happened.

My worry was that SimpleOpenGlControl, the rendering device provided by the Tao Framework did not support a stencil buffer; an earlier look notified me that it did not support an alpha channel.  Luckily, the stencil buffer bits can be changed without having to change the source code.  This should be done before initialising the control contexts.

SimpleOpenGlControl.StencilBits = 1;
SimpleOpenGlControl.InitializeContexts();

Once again, nothing happened.

I had a look around the Internet to try and find some source code that worked;  I noticed in one of them, one particular call was present, yet in mine, it was not.

// This specifies what action to take when either the stencil test or depth test succeeds or fails.
Gl.glStencilOp(Gl.GL_KEEP, Gl.GL_KEEP, Gl.GL_REPLACE);

Placing this at the start of the code appears to make use of the stencil buffer correctly.  I believe this is because when the stencil test succeeds, it will replace the current pixel with the resultant pixel, instead of keeping the old one.  Again, I am no expert; there is a lot more information on the documentation page (however useful, I cannot tell).

Drawing a conclusion

Below is the code and a screenshot of the application I used to spike using the stencil buffer.

public partial class Client : Form
{
public Client()
{
InitializeComponent();

SimpleOpenGlControl.StencilBits = 1;
SimpleOpenGlControl.InitializeContexts();

Gl.glEnable(Gl.GL_STENCIL_TEST);
Gl.glStencilOp(Gl.GL_KEEP, Gl.GL_KEEP, Gl.GL_REPLACE);
// Enable hinting

}

private void simpleOpenGlControl_Paint(object sender, PaintEventArgs e)
{
Gl.glClearColor(1, 1, 1, 1);
Gl.glClear(Gl.GL_COLOR_BUFFER_BIT | Gl.GL_STENCIL_BUFFER_BIT);

Gl.glMatrixMode(Gl.GL_PROJECTION);
Gl.glLoadIdentity();
Gl.glOrtho(0, SimpleOpenGlControl.Width, 0, SimpleOpenGlControl.Height, 10, –10);

Gl.glMatrixMode(Gl.GL_MODELVIEW);
Gl.glLoadIdentity();

// Draw to the stencil buffer
Gl.glStencilFunc(Gl.GL_ALWAYS, 1, 1);
// Turn off colour
Gl.glColorMask(Gl.GL_FALSE, Gl.GL_FALSE, Gl.GL_FALSE, Gl.GL_FALSE);
// Draw our new viewport
Gl.glBegin(Gl.GL_TRIANGLES);
Gl.glVertex2d(0, 0);
Gl.glVertex2d(SimpleOpenGlControl.Width, 0);
Gl.glVertex2d(SimpleOpenGlControl.Width / 2.0, SimpleOpenGlControl.Height);
Gl.glEnd();

// This has been changed so it will draw to the inside of the viewport
// To draw to the outside, use Gl.glStencilFunc(Gl.GL_EQUAL, 0, 1);

Gl.glStencilFunc(Gl.GL_EQUAL, 1, 1);
// Turn on colour
Gl.glColorMask(Gl.GL_TRUE, Gl.GL_TRUE, Gl.GL_TRUE, Gl.GL_TRUE);
// Draw triangles here

// Disable stencil test to be able to draw anywhere irrespective of the stencil buffer
Gl.glPushAttrib(Gl.GL_ENABLE_BIT);
Gl.glDisable(Gl.GL_STENCIL_TEST);
// Draw border here

Gl.glPopAttrib();

SimpleOpenGlControl.Invalidate();
}
}

Stencil Test.  This is created by first delaring the triangular viewport in the stencil buffer;  only primitives inside the stencil will be rendered.  The border was added on later, after disabling the stencil test.

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

MultiOpenGlControl Demo

Posted by Robert Chow on 16/04/2010

I’ve managed to grab some video capture software and also produce a small demo of using multiple SimpleOpenGlControls.  Each screen has it’s own camera, focusing on to the same scene.  Using lighting and picking, clicking a face of the cube will change the scene, and thus be reflected in all of the cameras.

I did have a little trouble with the picking at first – when I picked, I forgot to change the current camera, so it would register the mouse click on one screen whilst using the camera of another.  With that fixed, it was nice to be able to play around with Renderer again.

True, the videos not suppose to be a hit, but at least it’s showing what I want it to.

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

MultiOpenGlControl

Posted by Robert Chow on 14/04/2010

One thing I’ve only just come to tackle is the prospect of having more than one rendering context visible at any time.

Make Current

Using the Tao SimpleOpenGlControl, it’s a relatively simple feat.

MultiOpenGlControl.  Displaying two SimpleOpenGlControls in immediate mode is relatively easy.


The SimpleOpenGlControl class allows you to make the control as the current rendering context. Any OpenGl calls made after this will be applied to the most recently made current rendering context.

public void Init()
{
SimpleOpenGlControlA.InitializeContexts();
SimpleOpenGlControlB.InitializeContexts();
}

public void SimpleOpenGlControlAPaint(object sender, PaintEventArgs e)
{
SimpleOpenGlControlA.MakeCurrent(); // all code following will now apply to control A

Gl.glClearColor(1, 1, 0, 0);
Gl.glClear(Gl.GL_COLOR_BUFFER_BIT);

Gl.glMatrixMode(Gl.GL_PROJECTION);
Gl.glLoadIdentity();
Gl.glOrtho(-1, 1, –1, 1, 1, –1);

Gl.glMatrixMode(Gl.GL_MODELVIEW);
Gl.glLoadIdentity();

Gl.glColor3d(1, 0, 0);
Gl.glBegin(Gl.GL_POLYGON);
Gl.glVertex2d(-0.5, –0.5);
Gl.glVertex2d(0.5, –0.5);
Gl.glVertex2d(0, 0.5);
Gl.glEnd();

SimpleOpenGlControlB.Invalidate(); // I invalidate B so it gets refreshed – if I only invalidate A, B will never get drawn
}

public void SimpleOpenGlControlBPaint(object sender, PaintEventArgs e)
{
SimpleOpenGlControlB.MakeCurrent();  // all code following will now apply to control B

Gl.glClearColor(0, 1, 1, 0);
Gl.glClear(Gl.GL_COLOR_BUFFER_BIT);

Gl.glMatrixMode(Gl.GL_PROJECTION);
Gl.glLoadIdentity();
Gl.glOrtho(-1, 1, 1, –1, 1, –1); // NOTE: I have changed the projection to show the images differently

Gl.glMatrixMode(Gl.GL_MODELVIEW);
Gl.glLoadIdentity();

Gl.glColor3d(1, 0, 0);
Gl.glBegin(Gl.GL_POLYGON);
Gl.glVertex2d(-0.5, –0.5);
Gl.glVertex2d(0.5, –0.5);
Gl.glVertex2d(0, 0.5);
Gl.glEnd();

SimpleOpenGlControlA.Invalidate(); // I invalidate A so it gets refreshed – if I only invalidate B, A will never get drawn
}

Multiple Vertex Buffer Objects

I did run into a little trouble though. I found that when I was rendering in immediate mode, this worked fine.  However, when I came about to using vertex buffer objects and rendering in retained mode, I found the results were different.

MultiVertexBufferObjects.  Only one of the controls renders the image, despite making the exact same calls in each of the control’s paint methods.  You can tell the paint method of control A is called because the clear color is registered.


Only one of the rendering contexts shows an image, and the other did not, despite the obvious call to clear the color buffer.

int[] buffers = new int[3];
float[] vertices = new float[] { –0.5f, –0.5f, 0.5f, –0.5f, 0, 0.5f };
float[] colours = new float[] { 1, 0, 0, 1, 0, 0, 1, 0, 0 };
uint[] indices = new uint[] { 0, 1, 2 };

public void Init()
{
SimpleOpenGlControlA.InitializeContexts();
SimpleOpenGlControlB.InitializeContexts();

Gl.glGenBuffers(3, buffers);
Gl.glBindBuffer(Gl.GL_ARRAY_BUFFER, buffers[0]);
Gl.glBufferData(Gl.GL_ARRAY_BUFFER, (IntPtr)(vertices.Length * sizeof(float)), vertices, Gl.GL_STATIC_DRAW);
Gl.glBindBuffer(Gl.GL_ARRAY_BUFFER, buffers[1]);
Gl.glBufferData(Gl.GL_ARRAY_BUFFER, (IntPtr)(colours.Length * sizeof(float)), colours, Gl.GL_STATIC_DRAW);
Gl.glBindBuffer(Gl.GL_ELEMENT_ARRAY_BUFFER, buffers[2]);
Gl.glBufferData(Gl.GL_ELEMENT_ARRAY_BUFFER, (IntPtr)(indices.Length * sizeof(uint)), indices, Gl.GL_STATIC_DRAW);
}

public void SimpleOpenGlControlAPaint(object sender, PaintEventArgs e)
{
SimpleOpenGlControlA.MakeCurrent(); // all code following will now apply to control A

Gl.glClearColor(1, 1, 0, 0);
Gl.glClear(Gl.GL_COLOR_BUFFER_BIT);

Gl.glMatrixMode(Gl.GL_PROJECTION);
Gl.glLoadIdentity();
Gl.glOrtho(-1, 1, –1, 1, 1, –1);

Gl.glMatrixMode(Gl.GL_MODELVIEW);
Gl.glLoadIdentity();

Gl.glBindBuffer(Gl.GL_ARRAY_BUFFER, buffers[0]);
Gl.glVertexPointer(2, Gl.GL_FLOAT, 0, IntPtr.Zero);
Gl.glBindBuffer(Gl.GL_ARRAY_BUFFER, buffers[1]);
Gl.glColorPointer(3, Gl.GL_FLOAT, 0, IntPtr.Zero);

Gl.glEnableClientState(Gl.GL_VERTEX_ARRAY);
Gl.glEnableClientState(Gl.GL_COLOR_ARRAY);

Gl.glBindBuffer(Gl.GL_ELEMENT_ARRAY_BUFFER, buffers[2]);
Gl.glDrawElements(Gl.GL_POLYGON, indices.Length, Gl.GL_UNSIGNED_INT, IntPtr.Zero);

Gl.glDisableClientState(Gl.GL_VERTEX_ARRAY);
Gl.glDisableClientState(Gl.GL_COLOR_ARRAY);

SimpleOpenGlControlB.Invalidate(); // I invalidate B so it gets refreshed – if I only invalidate A, B will never get drawn
}

public void SimpleOpenGlControlBPaint(object sender, PaintEventArgs e)
{
SimpleOpenGlControlB.MakeCurrent(); // all code following will now apply to control B

Gl.glClearColor(0, 1, 1, 0);
Gl.glClear(Gl.GL_COLOR_BUFFER_BIT);

Gl.glMatrixMode(Gl.GL_PROJECTION);
Gl.glLoadIdentity();
Gl.glOrtho(-1, 1, –1, 1, 1, –1); // NOTE: I have changed the projection to show the images differently

// same code as above

SimpleOpenGlControlA.Invalidate(); // I invalidate A so it gets refreshed – if I only invalidate B, A will never get drawn
}

Multiple Vertex Buffer Objects

This is because if you are to generate buffers, the buffers only apply to the current rendering context – in this case, it is SimpleOpenGlControlB (it was the last one that was created).  If you are using buffers and want to render the same data in a different rendering context, you have to recreate the data buffers again under the different context.  It seems like a bit of a waste really – having to recreate the same thing twice just to view it in a different place.

public void Init()
{
SimpleOpenGlControlA.InitializeContexts();
SimpleOpenGlControlB.InitializeContexts();

SimpleOpenGlControlA.MakeCurrent();
// create bufferset

SimpleOpenGlControlB.MakeCurrent();
// repeat the same code to recreate the bufferset under a different rendering context
}

// Draw methods

Shared Vertex Buffer Objects

Fortunately, there is a small hack around. Wgl offers a method, wglShareLists, which allows for different rendering contexts to share, not only the same display lists, but also VBO, FBO and texture lists. To do this, you need to get the rendering context handles – unfortunately, you can only do this with a small hack around.

public void Init()
{
SimpleOpenGlControlA.InitializeContexts();
SimpleOpenGlControlB.InitializeContexts();

SimpleOpenGlControlA.MakeCurrent();
var aRC = Wgl.wglGetCurrent();
SimpleOpenGlControlB.MakeCurrent();
var bRC = Wgl.wglGetCurrent();

Wgl.wglShareLists(aRC, bRC);

// start creating vbos here – these will now be shared between the two contexts.
}

// Draw methods

Multiple Controls For Renderer

This now provides two solutions for Renderer – I can either have seperate lists for each control, or have them all share the same one.  There are advantages and disadvantages to both.

In terms of management, it would be a lot easier to have them share the same lists – there is an overhead in tracking what lists are part of which control.  It would also cause a problem when a user tries to draw a scene for a particular control, when the vertex buffer objects in the scene are assigned to a another.

It would also be advantageous to have shared lists when using heavy OpenGl operations, such as texture binding – it would have to bind a new texture each time a different control is refreshed.  Sharing a texture list would erase this problem.

In the short run, using seperate lists has its disadvantages; the memory use is rather inefficient because it has to create a new set of lists each time a control is created.  However, the memory story is a different matter when sharing lists becomes long term.   This is because once a control is destroyed, so too are its lists.  Sharing lists would mean the list will continue to accumulate more and more data until all the controls have been destroyed – that is entirely up to the user, and could take some time.

As a result, for the time being, I am going to go for the option of sharing lists – mainly because it does have its advantages in terms of not having to deal with the management side, and it also minimises the frequency of heavy OpenGl operations.  Not only this, but also because it would take some time to implement the management.  If  I do have time nearer the end of my placement, I may decide to come back and revisit it.

MultiOpenGlControl-3D.  Here is Renderer using 4 different SimpleOpenGlControls simultaneously.  I’ve tried to replicate a (very simple) 3D editing suite, whereby there are 3 orthogonal views, Front, Top and Side, and then the projection view.  It uses the same model throughout, but each control has differing camera positions.

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

Bright Break

Posted by Robert Chow on 13/04/2010

Easter was interesting.  And tiring.

Not to mention the fact that I’ve never really celebrated it as far as receiving a chocolate egg, this years was definitely to say the least, different.

Although working for a majority of the Easter break, I spent the Sunday entertained with my cousins and family who decided to come visit Devon for their holidays.  They come every year apparently, and always do the same thing – an Easter egg hunt.  Can’t say I’ve ever done one before, and it was a lot more fun than expected.

But it’s the week after Easter which is why I am so tired.  My girlfriend decided to take what very little break she has from university and spend it down south, and so too did one of my course friends.

On the Wednesday, me and my girlfriend decided to borrow a couple of bicycles and cycle down the Tarka trail – something I’ve been meaning to do, but once again, like many other things, I’ve been putting off.  Instead of completing the Bideford-Barnstaple leg, we decided to go down the other way to Torrington, a place I’ve never been to.  It was rather interesting to see my girlfriend cycle for the first in 11 years – a few bumps and bruises were had!  And those seats weren’t the most comfortable either!  Yet, we finally made it in the end.

Tarka Trail House.


Tarka Trail River.


Puffing Billy.  We took this photo just to prove we had made it to Torrington (even though it wasn’t actually that far)!  We were recommended to try the food at the Puffing Billy, but unfortunately it was shut.


On Thursday we found ourselves at a leaving lunch for a couple of colleagues in Appledore.  We decided to stay around, but then realising there is absolutely nothing to do in Appledore, we decided to head towards Westward Ho! via Northam.  It only took about 50 minutes to walk and is quite nice, particularly if the weather is good.

Appledore To Instow.  This is the view from Appledore to Instow.  There’s not really much else.  They say that on the opposite of the river in Instow, the people are quite wealthy, and that those in Appledore are far less off.


Westward Ho!

My friend came round later that evening, and now with access to a car, we decided to go for a ‘nice’ walk near Saunton on Friday.  ‘Nice’ is a bit misleading.  The views were spectacular, and the route was quite enjoyable, but I think, it’s safe to say, we were a little unprepared. We took the coastal path to Woolacombe bay – that we were fine with.  We just didn’t quite realise how long it was, and unfortunately, we had to walk back to the car.   We resulted in going over the hills instead, on rather steep paths.  It sure was tiring, but it was a good (unplanned) 8.5 miles of exercise!  I’d recommend it to anyone who is willing enough for a struggle!

Coastal Rocks.

Croyde.

Cliffside.  It’s safe to say (or raher, unsafe) it’s quite steep!

Woolacombe Bay. Relief at last, until we realised we had to walk back.

Alien Saunton.  The view we had coming over the hills back to Saunton.  It had seemed as if we’d stepped into another world.

Coastal Walk.  This is the path that we took from Saunton to Woolacombe bay.  This image is taken from Google Maps.  You can find the map I’ve created at http://maps.google.co.uk/maps/ms?oe=utf-8&client=firefox-a&ie=UTF8&hl=en&msa=0&msid=107891036475706214108.000483e4e9b48ef32ebeb&ll=51.1317,-4.228878&spn=0.040181,0.090895&t=h&z=14

After the small break, it’s now back to work.  Me and my supervisor devised a (rather scary looking) timetable for me to try to stick to between now and the end of my placement.  It’s not too long now, only 3 more months!  A lot of work, and not a lot of time.  Hopefully, I’ll be pulling off a demo every single week – not necessarily anything particularly spectacular, but the by the end of the period, I should have a Grapher component done and polished.  I hope.

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

Linq me

Posted by Robert Chow on 07/04/2010

It’s been more than a few months into my placement now, and my grasp of C# has really gone further than just ‘beginner’ now.

There is a lot of material about Linq on the Internet, and because I should have posted about it a lot earlier, I’m only just going to touch upon a small problem I had yesterday.

Linq

Linq stands for language-intergrated query and consists of a small number of extension methods allowing users to query an IEnumerable collection.   The idea is to allow similar to SQL type queries be made on a collection and are very useful.

Invalid Operation Exception : Collection was modified;

The problem I had was taking a collection, applying a filter and then using the filter to alter the original collection.  Here’s an example of the code.

var toDelete = aCollection.Take(20).Skip(10);
foreach(CollectionItem collectionItem in toDelete)
{
aCollection.Remove(collectionItem);
}

This takes a collection, and applies a filter to it using Linq. The Take(20) will take the first 20 items in aCollection.   Apply Skip(10) will then filter the result to take the remaining items after skipping the first 10 items.  In the foreach loop, I then attempt to delete the items I have filtered from the original collection.

It works fine for the first iteration, yet on the second it throws a nasty error, “Invalid Operation Exception : Collection was modified”.  I know I am modifying the original collection, yet strangely enough it is throwing the exception, expressing that I have modified the toDelete collection.  Nowhere in the loop do I touch the toDelete collection at all.

So it seems

Unfortunately, I do. The reference held by toDelete is the same reference as aCollection – modifying aCollection will also modify toDelete.   This is because when I assign toDelete, it takes the same reference as aCollection, and then includes the filters.  My first impression of using Take and Skip was that it would return a new collection, with just the filtered elements, alas, it is not to be.

Knowing this, I realise I need to take the filtered elements and recreate the filter in a new collection.  Fortunately, Linq can also help me do this.

toDelete = toDelete.ToList();

Seems a bit of a pain that the filter doesn’t actually give a new collection item. I hope that after reading this, you can also avoid similar problems as I did.

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

OOP

Posted by Robert Chow on 01/04/2010

OOP.  Object-orientated-programming.  Something that every programmer should be able to do nowadays writing a 3rd gen language.  With dynamic languages, I’m not entirely sure on how different it is, but I’m guessing the principles are the same.

But that’s not what I’m here to blog about.  I’ve managed to whip up a demo of the toolkit, OOP, or I’d like to call it, Object-Orientated-Paint.

Object-Orientated-Paint

So for those that use Microsoft Paint (and I still do), many will know how annoying it is to only have one canvas, and that every single dash or pixel “painted” on to the canvas is essentially there to stay unless another splash of paint writes over it.  It’s quite frustrating, especially when only a few minutes down the line do you realise that you forgot to draw something and therefore have to edit the whole picture.  Once you’ve edited that picture, you’ve also no way of going back either (the undo command only has a history of 3, something that has frustrated me rather a lot over the years).

So why better it by encapsulating each shape/splash of paint as an object?  It’s essentially what Microsoft Powerpoint uses.  True, you dont’ get the same precision and granularity to edit a particular shape as you would in Paint, but it’s a heck of a lot easier to use.  Although my knowledge is very limited in the area, I’m guessing you could make the same connection with C and C#.  C is a language (correct me if I’m wrong here) that is not designed for OOP, yet it allows you to reach the gutsy insides of a computer.  C# on the other-hand is designed to be used in OOP, and although it’s a lot harder to get to the lower-levels of computation, it is a lot faster, and ultimately easier to use.

Now jumping the gun a bit, it’s similar to Renderer and the toolkit.  Renderer is just a wrapper around OpenGl – it can do everything it wants, providing OpenGl supports it (although I haven’t wrapped around every single OpenGl call – that would be insane).  Yet if I were to use Renderer indirectly, via the toolkit, I am unable to do everything that Renderer supports – the toolkit limits my actions, yet makes the more commonly used functions of Renderer a lot easier to deal with.

Demo

Enough rambling.  I’ve implemented basic shapes in the toolkit, as well as very basic shape control.

Shapes.  Using the toolkit, I am able to ask for basic shapes.  Each shape has a fill colour, line colour and line width property.


Shapes Select.  I’ve also added picking functionality and shape control too.  When a user selects a fill/border of a shape, it will recognise it as a shape.  This is then decorated with a shape control.  This shape control has handles – these too are shapes.


Shapes Resize.  Clicking on a handle requires a couple of steps first before allowing to interact with it.  Although clicking on a border/fill will return the shape representing the handle, the handles act differently and need to be tested for.  Once this is done, we can notify the application that a handle is selected, not a shape.  This is important because if it was a shape, then the shape control will try to decorate the handle – clearly something that needs to be avoided.

Shapes Move.  clicking on a shape not only decorates it with a shape control, but it also allows you to drag and drop the shape too.


OOPhilosophy

Before this demo, I’ve had a lot of trouble creating similar objects. I’ve created bézier curves for the toolkit too, but I haven’t shown them because I ‘ve never been to happy with them.

If you recall from DrawCurve(Bézier);, near the end I was able to draw a master curve, encapsulating the bézier sub-curves.  To incorporate this into a scene graph, I needed an anchor, a node.  I did this by using a get property for the root of the curve.

public class Bezier : IRootNode
{
public Bezier()
{
RootNode = new Node(Matrix.Identity());
}

public INode RootNode { get; private set; }

private void CreateSubCurve()
{
var subCurve = new SubCurve();
RootNode.AddChild(subCurve.RootNode);
}

}

The problem with this is that once the Rootnode of the bézier curve is accessed, anything can be done with it.  A renderable can be assigned, all the children cleared, random children added.  It wasn’t very safe, and I never really did like it.

Why I never thought of simply inheriting from a model node in the first place, I’ll never know.  Not only does it allow me to change the node contents a lot easier, but it also means that I can change the interface, so that only a few select items can be modified.

public interface IShape
{
Colour FillColour { get; set; }
Colour BorderColour { get; set; }
double BorderThickness { get; set; }
}

internal class Shape : Node, IShape
{
public Shape(IFill fill, IBorder border) : base(Matrix.Identity())
{
Fill = fill;
Border = border;

base.AddChild((INode)Fill);
base.AddChild((INode)Border);
}

public Colour FillColour { get {…} set {…} }
public Colour BorderColour { get {…} set {…} }
public double BorderThickness { get {…} set {…} }

public IFill Fill { get; private set; }
public IBorder Border { get; private set; }

}

The only problem is that I have to cast from an IShape to an INode for when I want to add it to a graph, but at least the internals are protected from modification.  I suppose you could say someone could take an IShape and cast it into an INode and use it from there.  I guess there’s no stopping that.

Regardless, I’m finding it a lot easier to use the latter method than the former.  It took me only a week to create the shapes demo, but around two to get the bézier curves in the toolkit working.

Out of shape

Has anyone seen the statue designed for London 2012?  I thought I’d try and recreate it.  And if you ask me, I can’t say I’m particularly fond of it either.

Kapoor 2012.  Winning design for the London 2012 statue.  Apparently, it’s designed to stay.  No thanks.


OOP Kapoor 2012.  It might as well look like this.

As a side note, a couple of guys have released a rather nifty free tool, Paint.NET.  It’s a lightweight application that’s pretty much paint, but similar in the style and functionalities of Adobe Photoshop.  So those who can’t afford the extortionate prices of designer tools, well, I’d highly recommend giving it a try.   Did I also mention it’s free?

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

290310

Posted by Robert Chow on 29/03/2010

I haven’t really focused much on music, but I’ve always loved it.  From listening to it when I was a kid, to picking up the guitar and whacking some tunes in my teens, to going to gigs in the current (although there’s been a lot less of the latter in Devon).

Anyway.  I’m excited.

Posted in Music | Tagged: , , , | Leave a Comment »

Because testing_isnt_all_bad

Posted by Robert Chow on 26/03/2010

I took a course module last year that didn’t end so well. My results were fine, but the teaching was plain appalling.  One of our assignments wanted us to try testing, yet the lesson hadn’t been covered at the time – it was covered after the assignment deadline. The reason behind this was so we had to do the research ourselves instead of being taught it textbook style.  I guess that way does work better – most of the stuff I’m doing now is all research I’ve done myself.  Still, it doesn’t excuse them for the time they handed an assignment out 2 days before the deadline, despite it being a 2 week workload.

My point is, testing is important.  As mundane as it is, it’s necessary.  We all try to avoid it.  We all seem to think we’re already doing it.  But that’s a lie. Unless we are actually devoting time and effort into it, we’re not actually doing it.  And fortunately for myself, I found this the easy way.

First glance tells me it’s fine

I have 3 methods, each an extension method for an integer.  These are:

bool IsPowerOf2();

int NextPowerOf2Up();

int NextPowerOf2Down();

I think from the names they’re pretty much self-explanatory.

When writing these methods, they worked the way they should do.

2.IsPowerOf2(); // returns true

7.IsPowerOf2(); // returns false

5.NextPowerOf2Up(); // returns 8

21.NextPowerOf2Down(); // returns 16

Or at least that’s the way I thought.

I’ve learnt over the few years of my experience that if you’re not thinking testing, then you’re not thinking outside the box.  All you see are the cases that work, and that should work.  Fine.  But then what if someone else thinks outside of the box?

(-1).NextPowerOf2Down();

Logically, no power of 2 should ever exist less than zero, and no integer power of 2 should exist less than 1.  Lucky for me, I already thought of this case, so I had it covered by throwing an exception.  And that’s basically it.

Second glance tells me different

Around Christmas time, I remember blogging that I wanted to look into using a tool called Machine.Specifiations, more commonly known as M.Spec.  M.Spec provides a handy library designed for writing and implementing tests in a fluent manner.  My supervisor asked me to write some of my own tests to cover the extension methods I’ve written, and that was when I started to think testing.

The idea behind testing is to try to cover every single case, without actually testing every single case.  Taking NextPowerOf2Up(), I can identify the different cases; these are values less than 1, and values equal to or greater than 1.  This is because the pivotal point in this method is 1 itself – it’s is the smallest possible power of 2.  We expect that any case less than 1 will result in 1, and any case that is equal to or greater than 1 will run as expected.  I can also split the latter into two more sections – those that are already a power of 2, and those that are not.  This is to ensure that the result does end in the next power of 2 and not the current one.

Sounds fairly simple.  But I did find one case that actually forced me to change the method code. This case covers all numbers equal to and greater than the highest possible power of 2 supported by an integer value.   Trying to ask for a power of two greater than that supported by int should throw an exception.

It was because of this case that I really saw the benefit of testing.  I knew it was important, but just not entirely how.  Sure I knew it was beneficial to see if your method works as expected.  But that’s pretty much really.  No one expects to use the corner cases, but it still needs to be covered.  And it’s using testing that’s helped me to do that.

M.Spec

Anyway, here’s the M.Spec code that I used to write my tests.  Like I said, it’s fairly fluent – M.Spec provides types and extension methods to aid this.

Note: SpecWithResult<> and FailingSpec are very simple containers designed by my supervisor.  SpecWithResult<> holds a result, and FailingSpec holds an exception.

[Subject(typeof(Magpie.Core.Extensions.Int32Extensions), “.NextPowerOf2Up”)]
public class when_given_0 : SpecWithResult<int>
{
Because of = () => result = 0.NextPowerOf2Up();
It should_equal_1 = () => result.ShouldEqual(1);
}

[Subject(typeof(Magpie.Core.Extensions.Int32Extensions), “.NextPowerOf2Up”)]
public class when_given_1 : SpecWithResult<int>
{
Because of = () => result = 1.NextPowerOf2Up();
It should_equal_2 = () => result.ShouldEqual(2);
}

[Subject(typeof(Magpie.Core.Extensions.Int32Extensions), “.NextPowerOf2Up”)]
public class when_given_2 : SpecWithResult<int>
{
Because of = () => result = 2.NextPowerOf2Up();
It should_equal_4 = () => result.ShouldEqual(4);
}

[Subject(typeof(Magpie.Core.Extensions.Int32Extensions), “.NextPowerOf2Up”)]
public class when_given_3 : SpecWithResult<int>
{
Because of = () => result = 3.NextPowerOf2Up();
It should_equal_4 = () => result.ShouldEqual(4);
}

[Subject(typeof(Magpie.Core.Extensions.Int32Extensions), “.NextPowerOf2Up”)]
public class when_given_4 : SpecWithResult<int>
{
Because of = () => result = 4.NextPowerOf2Up();
It should_equal_8 = () => result.ShouldEqual(8);
}

[Subject(typeof(Magpie.Core.Extensions.Int32Extensions), “.NextPowerOf2Up”)]
public class when_given_5 : SpecWithResult<int>
{
Because of = () => result = 5.NextPowerOf2Up();
It should_equal_8 = () => result.ShouldEqual(8);
}

[Subject(typeof(Magpie.Core.Extensions.Int32Extensions), “.NextPowerOf2Up”)]
public class when_given_negative_1 : SpecWithResult<int>
{
Because of = () => result = (-1).NextPowerOf2Up();
It should_equal_1 = () => result.ShouldEqual(1);
}

[Subject(typeof(Magpie.Core.Extensions.Int32Extensions), “.NextPowerOf2Up”)]
public class when_given_127 : SpecWithResult<int>
{
Because of = () => result = 127.NextPowerOf2Up();
It should_equal_128 = () => result.ShouldEqual(128);
}

[Subject(typeof(Magpie.Core.Extensions.Int32Extensions), “.NextPowerOf2Up”)]
public class when_given_128 : SpecWithResult<int>
{
Because of = () => result = 128.NextPowerOf2Up();
It should_equal_256 = () => result.ShouldEqual(256);
}

[Subject(typeof(Magpie.Core.Extensions.Int32Extensions), “.NextPowerOf2Up”)]
public class when_given_129 : SpecWithResult<int>
{
Because of = () => result = 129.NextPowerOf2Up();
It should_equal_256 = () => result.ShouldEqual(256);
}

[Subject(typeof(Magpie.Core.Extensions.Int32Extensions), “.NextPowerOf2Up”)]
public class when_given_negative_128 : SpecWithResult<int>
{
Because of = () => result = (-128).NextPowerOf2Up();
It should_equal_1 = () => result.ShouldEqual(1);
}

[Subject(typeof(Magpie.Core.Extensions.Int32Extensions), “.NextPowerOf2Up”)]
public class when_given_min_value : SpecWithResult<int>
{
Because of = () => result = int.MinValue.NextPowerOf2Up();
It should_equal_1 = () => result.ShouldEqual(1);
}

[Subject(typeof(Magpie.Core.Extensions.Int32Extensions), “.NextPowerOf2Up”)]
public class when_given_max_value : FailingSpec
{
Because of = () => exception = Catch.Exception(() => int.MaxValue.NextPowerOf2Up());
It should_throw_an_exception = () => exception.ShouldBeOfType<ArgumentException>();
It should_throw_an_exception_with_an_inner_exception = () => exception.InnerException.ShouldBeOfType<OverflowException>();
}

Here are the results after running the library with M.Spec

Int32Extensions .NextPowerOf2Up, when given 0
» should equal 1

Int32Extensions .NextPowerOf2Up, when given 1
» should equal 2

Int32Extensions .NextPowerOf2Up, when given 2
» should equal 4

Int32Extensions .NextPowerOf2Up, when given 3
» should equal 4

Int32Extensions .NextPowerOf2Up, when given 4
» should equal 8

Int32Extensions .NextPowerOf2Up, when given 5
» should equal 8

Int32Extensions .NextPowerOf2Up, when given negative 1
» should equal 1

Int32Extensions .NextPowerOf2Up, when given 127
» should equal 128

Int32Extensions .NextPowerOf2Up, when given 128
» should equal 256

Int32Extensions .NextPowerOf2Up, when given 129
» should equal 256

Int32Extensions .NextPowerOf2Up, when given negative 128
» should equal 1

Int32Extensions .NextPowerOf2Up, when given min value
» should equal 1

Int32Extensions .NextPowerOf2Up, when given max value
» should throw an exception
» should throw an exception with an inner exception

Contexts: 13, Specifications: 14

Oh, and for the record, we managed a petition against that particular course and got over 75% backing from the students who took it, including some who took it in previous years too.

[Subject(typeof(Magpie.Core.Extensions.Int32Extensions), “.NextPowerOf2Up”)]
public class when_given_0 : SpecWithResult<int>
{
Because of = () => result = 0.NextPowerOf2Up();
It should_equal_1 = () => result.ShouldEqual(1);
}

[Subject(typeof(Magpie.Core.Extensions.Int32Extensions), “.NextPowerOf2Up”)]
public class when_given_1 : SpecWithResult<int>
{
Because of = () => result = 1.NextPowerOf2Up();
It should_equal_2 = () => result.ShouldEqual(2);
}

[Subject(typeof(Magpie.Core.Extensions.Int32Extensions), “.NextPowerOf2Up”)]
public class when_given_2 : SpecWithResult<int>
{
Because of = () => result = 2.NextPowerOf2Up();
It should_equal_4 = () => result.ShouldEqual(4);
}

[Subject(typeof(Magpie.Core.Extensions.Int32Extensions), “.NextPowerOf2Up”)]
public class when_given_3 : SpecWithResult<int>
{
Because of = () => result = 3.NextPowerOf2Up();
It should_equal_4 = () => result.ShouldEqual(4);
}

[Subject(typeof(Magpie.Core.Extensions.Int32Extensions), “.NextPowerOf2Up”)]
public class when_given_4 : SpecWithResult<int>
{
Because of = () => result = 4.NextPowerOf2Up();
It should_equal_8 = () => result.ShouldEqual(8);
}

[Subject(typeof(Magpie.Core.Extensions.Int32Extensions), “.NextPowerOf2Up”)]
public class when_given_5 : SpecWithResult<int>
{
Because of = () => result = 5.NextPowerOf2Up();
It should_equal_8 = () => result.ShouldEqual(8);
}

[Subject(typeof(Magpie.Core.Extensions.Int32Extensions), “.NextPowerOf2Up”)]
public class when_given_negative_1 : SpecWithResult<int>
{
Because of = () => result = (-1).NextPowerOf2Up();
It should_equal_1 = () => result.ShouldEqual(1);
}

[Subject(typeof(Magpie.Core.Extensions.Int32Extensions), “.NextPowerOf2Up”)]
public class when_given_127 : SpecWithResult<int>
{
Because of = () => result = 127.NextPowerOf2Up();
It should_equal_128 = () => result.ShouldEqual(128);
}

[Subject(typeof(Magpie.Core.Extensions.Int32Extensions), “.NextPowerOf2Up”)]
public class when_given_128 : SpecWithResult<int>
{
Because of = () => result = 128.NextPowerOf2Up();
It should_equal_256 = () => result.ShouldEqual(256);
}

[Subject(typeof(Magpie.Core.Extensions.Int32Extensions), “.NextPowerOf2Up”)]
public class when_given_129 : SpecWithResult<int>
{
Because of = () => result = 129.NextPowerOf2Up();
It should_equal_256 = () => result.ShouldEqual(256);
}

[Subject(typeof(Magpie.Core.Extensions.Int32Extensions), “.NextPowerOf2Up”)]
public class when_given_negative_128 : SpecWithResult<int>
{
Because of = () => result = (-128).NextPowerOf2Up();
It should_equal_1 = () => result.ShouldEqual(1);
}

[Subject(typeof(Magpie.Core.Extensions.Int32Extensions), “.NextPowerOf2Up”)]
public class when_given_min_value : SpecWithResult<int>
{
Because of = () => result = int.MinValue.NextPowerOf2Up();
It should_equal_1 = () => result.ShouldEqual(1);
}

[Subject(typeof(Magpie.Core.Extensions.Int32Extensions), “.NextPowerOf2Up”)]
public class when_given_max_value : FailingSpec
{
Because of = () => exception = Catch.Exception(() => int.MaxValue.NextPowerOf2Up());
It should_throw_an_exception = () => exception.ShouldBeOfType<ArgumentException>();
It should_throw_an_exception_with_an_inner_exception = () => exception.InnerException.ShouldBeOfType<OverflowException>();
}

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