Making Hyperlinks and Dynamic RichTextBox Content Play Nice in WPF

I’ve been working on a WPF project for some time now, and one of the specifications required that the application be able to render web content without a full blown browser. This actually is a fairly non-trivial task, especially if you want to render the content in something simple like a RichTextBox control. Thankfully, Nigel Spencer has a great blog post about using Microsoft’s HtmlToXaml converter, which really makes this much simpler.

However, even after I had successfully converted the HTML content into a FlowDocument which rendered correctly in my RichTextBox control, I was left with one lingering issue: Hyperlinks didn’t work! After some research I found that this is actually a fairly common roadblock, with many different takes on the solution.

My personal approach is simple:

  1. Iterate through all of the elements of the RichTextBox.Document
  2. Ensure that the iteration happens whenever the RichTextBox content changes
  3. If a hyperlink is found, hook into an event handler to launch the link in an external browser

First, we need to decide upon an event in order to catch the RichTextBox content changes.  I chose RichTextBox.TextChanged as it fires when the initial content is set, as well as on all subsequent changes.  You must also ensure that the IsDocumentEnabled property of your RichTextBox control is set to true.

Next, in order to iterate the FlowDocument elements, I used a bit of the code found in a blog post by Dan Lamping.  I then combined that with a simple hook to the Hyperlink.RequestNavigate event.

public MainWindow()
{
	InitializeComponent();

	myRichTextBox.TextChanged += HookHyperlinks;
}

private void HookHyperlinks(object sender, TextChangedEventArgs e)
{
	FlowDocument doc = (sender as RichTextBox).Document;

	for (TextPointer position = doc.ContentStart;
		position != null && position.CompareTo(doc.ContentEnd) <= 0;
		position = position.GetNextContextPosition(LogicalDirection.Forward))
	{
		if (position.GetPointerContext(LogicalDirection.Forward) ==
			TextPointerContext.ElementEnd)
		{
			if (position.Parent is Hyperlink)
				(position.Parent as Hyperlink).RequestNavigate += HandleRequestNavigate;
		}
	}
}

private void HandleRequestNavigate(object sender, RequestNavigateEventArgs args)
{
	   System.Diagnostics.Process.Start(args.Uri.ToString());
}

At this point we have a functional setup.  Whenever the RichTextBox.TextChanged event fires, the content is parsed and any Hyperlink elements are hooked to our HandleRequestNavigate handler, which in turn simply uses Process.Start() to launch the default browser towards the given uri.

,

1 Comment

Internet Multiplayer Issues With August 2011 UDK Builds [Solved]

Quite a few people have noted that they are having multiplayer issues with recent UDK builds. They can connect to a server just fine over a LAN, but whenever they connect to a server hosted on the internet they get dropped. Since so many people are having this issue I decided to post a new thread instead of just posting my solution 7 pages deep in another one.

The output is similar to the following:

Client Log

[0058.77] DevNet: Browse: /TT-T_Sandbox1?Name=Player?Team=255
[0058.77] Init: WinSock: Socket queue 32768 / 32768
[0058.77] DevNet: Game client on port 7777, rate 10000
[0059.67] DevNet: Welcomed by server (Level: TT-T_Sandbox1, Game: Titan.TitanGame)
[0059.79] NetComeGo: Close TcpNetDriver_0 TcpipConnection_0 :7777 09/18/11 20:55:44
[0059.80] Log: Pending connect to '/TT-T_Sandbox1?Name=Player?Team=255?game=Titan.TitanGame' failed; Your connection to the host has been lost.
[0059.80] ScriptLog: (UTGameViewportClient_0) UTGameViewportClient::None:NotifyConnectionError Message:'Your connection to the host has been lost.' Title:'Connection Lost'
[0059.82] DevNet: URL: Adding default option Name=Player
[0059.82] DevNet: URL: Adding default option Team=255
[0059.82] DevNet: Browse: TT-T_Sandbox1?closed?Name=Player?Team=255
[0059.82] Log: Failed; returning to Entry
[0060.10] Log: LoadMap: TT-T_Sandbox1?closed?Name=Player?Team=255

Server Log

DevNet: NotifyAcceptingConnection: Server TheWorld accept
NetComeGo: Open TheWorld 09/18/11 22:24:04
DevNet: NotifyAcceptingChannel Control 0 server World TT-T_Sandbox1.TheWorld: Accepted
DevNet: Remote platform is 1
NetComeGo: Close TcpNetDriver_0 TcpipConnection_4 :59619 09/18/11 22:24:04
DevNet: NotifyAcceptingConnection: Server TheWorld accept
NetComeGo: Open TheWorld 09/18/11 22:24:04
NetComeGo: Close TcpNetDriver_0 TcpipConnection_5 :59619 09/18/11 22:24:04
DevNet: NotifyAcceptingConnection: Server TheWorld accept
NetComeGo: Open TheWorld 09/18/11 22:24:04

I noticed that this problem vanished when I tested with a teammate after cooking and packaging, and I believe I know why. After cooking and packaging a file appeared in my UDK//Binaries folder called UnSetup.Game.xml. This XML file contains two fields, GameUniqueID and MachineUniqueID. I noticed this file also was packaged with my installer. I decided to copy that file from package-created installation folder and place it in my development Binaries folder that is under source control which ensured all teammates had the identical file.

This seems to have solved the problem. My assumption is that the engine cares about the GameUniqueID when an internet multiplayer session is started, but it seems to ignore it for LAN games.

So to recap, if you are having this issue, please try the following.

  1. Using Unreal Frontend, fully recompile all scripts
  2. Cook all game packages
  3. Package your game into a UDK installer
  4. Install the game from that installer, and look in the Binaries folder in that new directory for UnSetup.Game.xml
  5. Copy that xml file back into the Binaries folder in your UDK development folder
  6. Ensure all teammates have an identical file

Best of luck to you!

,

2 Comments

Simple Class Serialization With JsonCpp

A recent project of mine necessitated that I find a way to share data between a client application written in C++ and a host application written in C#. After talking with the other programmer on the project, we decided that using Json to share data between the applications would be the best solution. This sent me on a search for a decent API for parsing Json data, which led to JsonCpp.

A cursory glance led me to conclude that this API would likely provide me with everything I would need for object serialization. The problem, however, was coming up with a decent design that would allow for full featured serialization. The goals were simple. I needed to be able to serialize and deserialze a class. I would also need access to all data members, including primitives, data structures, and nested classes.

JsonCpp provides us with the capability to do this with relative ease. As such, I hope to provide you all with a basic design to accomplish this. Luckily, we won’t need a deep understanding of JsonCpp to accomplish our goals. As such, I’m not going to overly explain much of the JsonCpp concepts, as the JsonCpp documentation is a good enough resource.

First, let’s consider a simple test class.

class TestClassA
{
public:
   TestClassA( void );
   virtual ~TestClassA( void );

private:
   int           m_nTestInt;
   double        m_fTestFloat;
   std::string   m_TestString;
   bool          m_bTestBool;
};

This class should provide us with a basic framework to test serialization.  We’re going to start with primitive data first (granted, std::string isn’t strictly primitive, but it’s primitive enough).

Now that we have a basic test case, lets design a basic interface that all of our serializable classes can inherit from.

class IJsonSerializable
{
public:
   virtual ~IJsonSerializable( void ) {};
   virtual void Serialize( Json::Value& root ) =0;
   virtual void Deserialize( Json::Value& root) =0;
};

This should be self explanitory. We obviously need to include json.h in order to have access to the Json::Value class. The Json::Value class is actually fairly complex, and as such we aren’t going to spent much time examining it. Suffice to say, we are going to treat it as a sort of map, mapping our metadata tags to the actual values we will be serializing. This will make much more sense once we work on the implementation of the Serialize() and Deserialize() methods in our classes.

So let’s update our updated test class definition.

class TestClassA : public IJsonSerializable
{
public:
   TestClassA( void );
   virtual ~TestClassA( void );
   virtual void Serialize( Json::Value& root );
   virtual void Deserialize( Json::Value& root);

private:
   int           m_nTestInt;
   double        m_fTestFloat;
   std::string   m_TestString;
   bool          m_bTestBool;
};

Now before we progress further on the C++ side of things, let’s cook up some test Json data to work with.

{
"testboolA" : true,
"testfloatA" : 3.14159,
"testintA" : 42,
"teststringA" : "foo"
}

Whether you know Json or not, this data structure should be completely self-explanatory.  The goal here is going to be to deserialize this data into our class.  However, we have one more thing to do.

The last class we need to design here is the actual serializer class.

class CJsonSerializer
{
public:
   static bool Serialize( IJsonSerializable* pObj, std::string& output );
   static bool Deserialize( IJsonSerializable* pObj, std::string& input );

private:
   CJsonSerializer( void ) {};
};

This is a simple little “static class”.  We’ll make the constructor private this way we can’t actually instantiate it.  We will simply deal with the methods directly.  This will let us add a second layer of abstraction to JsonCpp.

Alright, our basic design is done.  Let’s get into the implementation.  Let’s start with our test class.

void TestClassA::Serialize( Json::Value& root )
{
   // serialize primitives
   root["testintA"] = m_nTestInt;
   root["testfloatA"] = m_fTestFloat;
   root["teststringA"] = m_TestString;
   root["testboolA"] = m_bTestBool;
}

void TestClassA::Deserialize( Json::Value& root )
{
   // deserialize primitives
   m_nTestInt = root.get("testintA",0).asInt();
   m_fTestFloat = root.get("testfloatA", 0.0).asDouble();
   m_TestString = root.get("teststringA", "").asString();
   m_bTestBool = root.get("testboolA", false).asBool();
}

Remember when I said we were going to look at the Json::Value class like a map?  That should make more sense now.  The Serialize() method should make sense.  We are simply adding the values to our root object as if it was a map.  The keys we are using map directly to the metadata in the Json data.  The Deserialize() method is only slightly more complex.  We need to use the get() method in order to retrieve our data.  The get() method takes two parameters: get( <key>, <defaultvalue>).  Knowing that, the method should make sense.  We simply call get() with each key and place the values from the Json into our members.

Now let’s move on to the CJsonSerializer class implementation.

bool CJsonSerializer::Serialize( IJsonSerializable* pObj, std::string& output )
{
   if (pObj == NULL)
      return false;

   Json::Value serializeRoot;
   pObj->Serialize(serializeRoot);

   Json::StyledWriter writer;
   output = writer.write( serializeRoot );

   return true;
}

bool CJsonSerializer::Deserialize( IJsonSerializable* pObj, std::string& input )
{
   if (pObj == NULL)
      return false;

   Json::Value deserializeRoot;
   Json::Reader reader;

   if ( !reader.parse(input, deserializeRoot) )
      return false;

   pObj->Deserialize(deserializeRoot);

   return true;
}

It should be obvious now why we wanted a second level of abstraction from JsonCpp.

Let’s look at the Serialize() method here.  We need to pass two parameters, a pointer to the IJsonSerializable object to be serialized, and a reference to a std::string.  That string is going to hold the serialized Json data from our class.  This is very rudimentary.  We simply create an instance of a Json::Value object to act as our root, and pass it to the Serialize() method of the object in question.  That Serialize() method will fill the Json::Value object with all of the serialized data.  We then create an instance of Json::StyledWriter, and use it to write the Json data to the empty std::string we originally passed.

As for the Deserialize() method, it’s not terribly different aside from the fact that the std::string we pass is going to contain Json instead of being empty.  We will create an instance of Json::Reader and use it to parse our input string and fill a Json::Value object for us.  We will then use that new Json::Value object and pass it to the IJsonSerializable objects Deserialze() method, which will set the data members based on the Json::Value object’s values.

As you can see, this is all pretty simple.  We can now create a simple test case.

TestClassA testClass;
std::string input = "{ \"testintA\" : 42, \"testfloatA\" : 3.14159, \"teststringA\" : \"foo\", \"testboolA\" : true }\n";
CJsonSerializer::Deserialize( &testClass, input );

std::cout << "Raw Json Input\n" << input << "\n\n";

std::string output;
CJsonSerializer::Serialize( &testClass, output);

std::cout << "testClass Serialized Output\n" << output << "\n\n\n";

If everything went according to plan, you should see the following:

Raw Json Input
{ "testintA" : 42, "testfloatA" : 3.14159, "teststringA" : "foo", "testboolA" : true }

testClass Serialized Output
{
   "testboolA" : true,
   "testfloatA" : 3.14159,
   "testintA" : 42,
   "teststringA" : "foo"
}

Essentially our test case simply created an “empty” TestClass object.  It then deserialized a string of input Json data into the class, filling it’s members.  We then create a new empty output string, and deserialize our TestClass object into that string.  If the outut is what we expect, then we can assume that basic serialization and deserialization is working!

,

18 Comments

C++ Vector2D & Rectangle classes

I’n my current C++ class we’ve been playing with the Allegro C++ library to create some 2D games.  While Allegro is a fairly powerful library, it’s shortcomings made me miss the Microsoft XNA Framework quite a bit.  I suppose I cannot fault Allegro in this regard, but I have grown so accustomed to using Microsoft’s implementation of 2D vectors and rectangles that learning new variants seems convoluted.

Now, before anyone judges me for not wanting to learn a new API, consider this.  Allegro has a plethora of 2D methods, but the only vector methods I am able to find are 3D.  Fine you say, just zero the Z element and be done with it.

Well sure.  But would I rather use a non OOP implementation like this:

float x = <someXValue>;
float y = <someYValue>;
float z = 0.0f;
void normalize_vector_f(float *x, float *y, float *z);

Or would I rather take an OOP approach:

Vector2D vec( <someXValue>, <someYValue> );
vec.Normalize();

Call me crazy, but I prefer the later.  As such, I’m going to go ahead and post my Vector2D class here, as well as the Rectangle class I am using.  Normally I would cite sources I used for help in writing these classes.   However, in the case of the Vector2D class most of the methods used are fairly standard and there is nothing really out of the ordinary.

As for the Rectangle class, there are some cool static methods I added that Microsoft released in their RectangleExtensions class (released under the MSPL).  I ported these methods over from C# to C++,and they seem to work correctly, however I haven’t tested them thoroughly and they may have a bug or two.

Anyway, enough ranting.  Here’s the code.

Vector2D.h

#ifndef _VECTOR2D_H
#define _VECTOR2D_H
#pragma once

#include <math.h>

class Vector2D
{

public:
	Vector2D(float x = 0, float y = 0);
	~Vector2D() {};

	void Rotate( const float angle );
	float Magnitude() const;
	float Normalize();
	float DotProduct( const Vector2D& v2 ) const;
	float CrossProduct( const Vector2D& v2 ) const;

	static Vector2D Zero();
	static float Distance( const Vector2D& v1, const Vector2D& v2);

	Vector2D& operator= ( const Vector2D& v2 );

	Vector2D& operator+= ( const Vector2D& v2 );
	Vector2D& operator-= ( const Vector2D& v2 );
	Vector2D& operator*= ( const float scalar);
	Vector2D& operator/= ( const float scalar);

	const Vector2D operator+( const Vector2D &v2 ) const;
	const Vector2D operator-( const Vector2D &v2 ) const;
	const Vector2D operator*( const float scalar ) const;
	const Vector2D operator/( const float scalar ) const;

	bool operator== ( const Vector2D& v2 ) const;
	bool operator!= ( const Vector2D& v2 ) const;

public:
	float x, y;
};
#endif

Vector2D.cpp

#include "Vector2D.h"

//-----------------------------------------------------------------------------
// Purpose:	Constructor
//-----------------------------------------------------------------------------
Vector2D::Vector2D( float x, float y )
{
	this->x = x;
	this->y = y;
}

//-----------------------------------------------------------------------------
// Purpose:	Rotate a vector
//-----------------------------------------------------------------------------
void Vector2D::Rotate( const float angle )
{
	float xt = (x * cosf(angle)) - (y * sinf(angle));
	float yt = (y * cosf(angle)) + (x * sinf(angle));
	x = xt;
	y = yt;
}

//-----------------------------------------------------------------------------
// Purpose:	Get vector magnitude
//-----------------------------------------------------------------------------
float Vector2D::Magnitude() const
{
	return sqrtf(x * x + y * y);
}

//-----------------------------------------------------------------------------
// Purpose:	Convert vector to a unit vector and return previous magnitude
//-----------------------------------------------------------------------------
float Vector2D::Normalize()
{
	float mag = Magnitude();

	if(mag != 0.0)
	{
		x /= mag;
		y /= mag;
	}

	return mag;
}

//-----------------------------------------------------------------------------
// Purpose:	Dot Product
//-----------------------------------------------------------------------------
float Vector2D::DotProduct( const Vector2D &v2 ) const
{
	return (x * v2.x) + (y * v2.y);
}

//-----------------------------------------------------------------------------
// Purpose:	Cross Product
//-----------------------------------------------------------------------------
float Vector2D::CrossProduct( const Vector2D &v2 ) const
{
	return (x * v2.y) - (y * v2.x);
}

//-----------------------------------------------------------------------------
// Purpose:	Return an empty vector
//-----------------------------------------------------------------------------
Vector2D Vector2D::Zero()
{
	return Vector2D(0, 0);
}

//-----------------------------------------------------------------------------
// Purpose:	Get distance between two vectors
//-----------------------------------------------------------------------------
float Vector2D::Distance( const Vector2D& v1, const Vector2D& v2)
{
	return sqrtf( pow((v2.x - v1.x), 2 ) + pow((v2.y - v1.y), 2) );
}

Vector2D& Vector2D::operator= ( const Vector2D& v2 )
{
	if (this == &v2)
		return *this;

	x = v2.x;
	y = v2.y;

	return *this;
}

Vector2D& Vector2D::operator+= ( const Vector2D& v2 )
{
	x += v2.x;
	y += v2.y;

	return *this;
}

Vector2D& Vector2D::operator-= ( const Vector2D& v2 )
{
	x -= v2.x;
	y -= v2.y;

	return *this;
}

Vector2D& Vector2D::operator*= ( const float scalar )
{
	x *= scalar;
	y *= scalar;

	return *this;
}

Vector2D& Vector2D::operator/= ( const float scalar )
{
	x /= scalar;
	y /= scalar;

	return *this;
}

const Vector2D Vector2D::operator+( const Vector2D &v2 ) const
{
	return Vector2D(*this) += v2;
}

const Vector2D Vector2D::operator-( const Vector2D &v2 ) const
{
	return Vector2D(*this) -= v2;
}

const Vector2D Vector2D::operator*( const float scalar ) const
{
	return Vector2D(*this) *= scalar;
}

const Vector2D Vector2D::operator/( const float scalar ) const
{
	return Vector2D(*this) /= scalar;
}

bool Vector2D::operator== ( const Vector2D& v2 ) const
{
	return ((x == v2.x) && (y == v2.y));
}

bool Vector2D::operator!= ( const Vector2D& v2 ) const
{
	return !((x == v2.x) && (y == v2.y));
}

Rectangle.h

#ifndef _RECTANGLE_H
#define _RECTANGLE_H
#pragma once

#include "Vector2D.h"

class Rectangle
{
public:
	Rectangle( int x = 0, int y = 0, int w = 0, int h = 0 );
	~Rectangle( void ) {};

	inline int Left( void ) const { return x; }
	inline int Right( void ) const { return x + w; }
	inline int Top( void ) const { return y; }
	inline int Bottom( void ) const { return y + h; }

	bool Contains( Vector2D& vVec ) const;
	bool Contains( int x, int y ) const;

	static Rectangle Empty();

	// Static methods below are derived from the RectangleExtensions class
	// written in C#, released under the MSPL
	static Vector2D GetIntersectionDepth( const Rectangle& rectA, const Rectangle& rectB );
	static Vector2D GetBottomCenter( const Rectangle& rect );
	static Vector2D GetCenter( const Rectangle& rect );
	static float GetDistance( const Rectangle& rectA, const Rectangle& rectB);
	static Vector2D GetDirection( const Rectangle& rectA, const Rectangle& rectB);

	Rectangle& operator= ( const Rectangle& r2 );

	bool operator== ( const Rectangle& r2 ) const;
	bool operator!= ( const Rectangle& r2 ) const;

public:
	int x, y, w, h;
};

#endif

Rectangle.cpp

#include "Rectangle.h"
#include <stdlib.h>

//-----------------------------------------------------------------------------
// Purpose:	Constructor
//-----------------------------------------------------------------------------
Rectangle::Rectangle( int x, int y, int w, int h )
{
	this->x = x;
	this->y = y;
	this->w = w;
	this->h = h;
}

//-----------------------------------------------------------------------------
// Purpose:	Check if rectangle contains a 2D vector
//-----------------------------------------------------------------------------
bool Rectangle::Contains( Vector2D& vVec ) const
{
	if ( ( vVec.x >= x )&&
		 ( vVec.x <= x + w ) &&
		 ( vVec.y >= y ) &&
		 ( vVec.x <= y + h ) )
	{
		return true;
	}
	else
		return false;
}

//-----------------------------------------------------------------------------
// Purpose:	Check if rectangle contains a set of coords
//-----------------------------------------------------------------------------
bool Rectangle::Contains( int x, int y ) const
{
	if ( ( x >= this->x )&&
		( x <= this->x + this->w ) &&
		( y >= this->y ) &&
		( x <= this->y + this->h ) )
	{
		return true;
	}
	else
		return false;
}

//-----------------------------------------------------------------------------
// Purpose:	Return an empty rectangle
//-----------------------------------------------------------------------------
Rectangle Rectangle::Empty()
{
	return Rectangle();
}

//-----------------------------------------------------------------------------
// Purpose:	Get intersection depth between two rectangles
//-----------------------------------------------------------------------------
Vector2D Rectangle::GetIntersectionDepth( const Rectangle& rectA, const Rectangle& rectB )
{
	// Calculate half sizes.
	float halfWidthA = rectA.w / 2.0f;
	float halfHeightA = rectA.h / 2.0f;
	float halfWidthB = rectB.w / 2.0f;
	float halfHeightB = rectB.h / 2.0f;

	// Calculate centers.
	Vector2D centerA(rectA.x + halfWidthA, rectA.y + halfHeightA);
	Vector2D centerB(rectB.x + halfWidthB, rectB.y + halfHeightB);

	// Calculate current and minimum-non-intersecting distances between centers.
	float distanceX = centerA.x - centerB.x;
	float distanceY = centerA.y - centerB.y;
	float minDistanceX = halfWidthA + halfWidthB;
	float minDistanceY = halfHeightA + halfHeightB;

	// If we are not intersecting at all, return (0, 0).
	if ( abs(distanceX) >= minDistanceX || abs(distanceY) >= minDistanceY )
		return Vector2D::Zero();

	// Calculate and return intersection depths.
	float depthX = distanceX > 0 ? minDistanceX - distanceX : -minDistanceX - distanceX;
	float depthY = distanceY > 0 ? minDistanceY - distanceY : -minDistanceY - distanceY;
	return Vector2D(depthX, depthY);
}

//-----------------------------------------------------------------------------
// Purpose:	Gets the position of the center of the bottom edge of the rectangle.
//-----------------------------------------------------------------------------
Vector2D Rectangle::GetBottomCenter(const Rectangle& rect)
{
	return Vector2D( (float)(rect.x + rect.w / 2.0f), (float)(rect.y + rect.h) );
}

//-----------------------------------------------------------------------------
// Purpose:	Gets the position of the center point of a rectangle
//-----------------------------------------------------------------------------
Vector2D Rectangle::GetCenter(const Rectangle& rect)
{
	return Vector2D( (float)(rect.x + rect.w / 2.0f), (float)(rect.y + rect.h / 2.0f) );
}

//-----------------------------------------------------------------------------
// Purpose:	Gets the floating point distance between the center point
//			of one rectangle and the center point of another.
//-----------------------------------------------------------------------------
float Rectangle::GetDistance( const Rectangle& rectA, const Rectangle& rectB )
{
	return Vector2D::Distance(GetCenter(rectA), GetCenter(rectB));
}

//-----------------------------------------------------------------------------
// Purpose:	Gets the unit vector from one rectangle to another
//-----------------------------------------------------------------------------
Vector2D Rectangle::GetDirection( const Rectangle& rectA, const Rectangle& rectB )
{
	Vector2D direction = GetCenter(rectA) - GetCenter(rectB);
	direction.Normalize();
	return direction;
}

Rectangle& Rectangle::operator= ( const Rectangle& r2 )
{
	if (this == &r2)
		return *this;

	x = r2.x;
	y = r2.y;
	w = r2.w;
	h = r2.h;

	return *this;
}

bool Rectangle::operator== ( const Rectangle& r2 ) const
{
	return ((w == r2.w) && (h == r2.h));
}

bool Rectangle::operator!= ( const Rectangle& r2 ) const
{
	return !((w == r2.w) && (h == r2.h));
}

,

8 Comments

Project Daedalus Update 4/10

It’s been some time since my last progress update, and I have sort of fallen out of the groove.  As such, this is going to be a short post to sort of get back into the swing of things.

I spent a good while last night working out a good solution to adding rotating gear platforms into the Boilerworks.  The initial idea was simple.  I was going to simply convert the gear texture into a set of vertices and load them up as a collision volume.  However, I realized this solution was not going to be viable as I have been using SAT collision, and a single gear polygon would have been a concave polygon (not supported by SAT implementation).  I decided to try Distance Grid collision instead of SAT, but the difference was noticeable and caused some big headaches.

It doesn’t look like the good folks at Farseer will be implementing concave polygon decomposition until Farseer 3.0 is released, so I had to take an alternate route.

The end result was simply generating multiple convex geometries programmatically that matched mt gear texture.  This ended up working perfectly, and as such we now have some really nice gear platforms ready to be added to levels.  A screenshot of the testbed is below.

Hopefully I’ll start updating this a bit more often as development continues.

, ,

No Comments

Developing a simple plugin architecture in C#

Once my editor officially began being used for two different, completely unrelated games, I had a few decisions to make.  The main problem was the fact that an RPG needs very specific helper functions (NPC editing, scripting, etc) whereas a platformer would need things like event scripting.  Rather than make additional tools to handle these functions, having them combined would be ideal.  However, I didn’t want to combine functions into an editor that would be useless for the other game.

The solution: a very simple plugin architecture.  By very simple, I mean that the actual Map classes would not be changed at all, in fact the XML map that the editor exported would not be changed in the slightest.  The plugin would not so much be given access to the Map in any way, but more so it would be given a place to run.  Essentially (at this point anyway) the plugin would be aesthetic.  It would allow level designers to use additional functionality within the level editor, which would already be running on the system.

But enough about that, the reason for this post is that I wanted to share a bit of code that let this happen.  After doing some research, I came across an old post by Shawn Walcheske called “Implementing a Plug-In Architecture in C#” (located here: http://www.ddj.com/cpp/184403942).  My implementation is, basically, identical, however the source download on that page is down, and he doesn’t really explain the System.Activator class which leaves the reader hanging. Update from a reader. Apparently the source is still available here: ftp://ftp.cuj.com/sourcecode/cuj/2003/cujjan2003.zip. Thanks!

So with that, I thought I’d show how I went about doing things, and basically explain the few loose ends that Shawn leaves out.  I think it goes without saying that if you really want to understand this entire concept, read his article as well.

The first thing we need to do is create a simple interface for our plugin.  This interface needs to be in it’s own assembly, for example I created ParadigmCommon.dll for plugins to reference in order to have access to this interface.  As the plugin system I am developing is very simple, the interface only provides an ActivatePlugin() method, as all we want to do is be able to launch new plugins from the main editor.

    public interface IParadigmPlugin
    {
        /// <summary>
        /// Activates the plugin, showing it's main form
        /// </summary>
        void ActivatePlugin();
    }

Next we need to define some custom attributes.  These attributes will hold some metadata for our class, this way our main application can reference that data.  We are, for this example, going to create a custom DisplayName attribute, and a custom Description attribute.  They are fairly self explanatory.

    /// <summary>
    /// This class defines the custom attribute for plugin display names
    /// </summary>
    [AttributeUsage(AttributeTargets.Class)]
    public class ParadigmPluginDisplayNameAttribute : System.Attribute
    {
        private string displayName;
 
        public ParadigmPluginDisplayNameAttribute(string displayName)
            : base()
        {
            this.displayName = displayName;
        }
 
        public override string ToString()
        {
            return displayName;
        }
    }
    /// <summary>
    /// This class defines the custom attribute for plugin descriptions
    /// </summary>
    [AttributeUsage(AttributeTargets.Class)]
    public class ParadigmPluginDescriptionAttribute : System.Attribute
    {
        private string description;
 
        public ParadigmPluginDescriptionAttribute(string description)
            : base()
        {
            this.description = description;
        }
 
        public override string ToString()
        {
            return description;
        }
    }

Here we have an actual plugin.  As you can see, we need to use the ParadigmCommon namespace, as well as reference the DLL from the project.  The plugin itself merely implements the IParadigmPlugin interface and as such implements the ActivatePlugin() method, which only serves to open a new form for the plugin.  Simple enough.  Similar in implementation to the way Program.cs would launch the main form in a Windows application.  As you can see, we are also using our custom attributes.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms; // referencing System.Windows.Forms is obviously needed for form usage, make sure to reference it in the project as well
using ParadigmCommon; // you must reference the ParadigmCommon namespace to access the needed attributes and interface
 
namespace TestPlugin
{
    /// <summary>
    /// This is an example of a paradigm plugin
    /// </summary>
    [ParadigmPluginDisplayName("Test Plugin")] // you must provice a display name
    [ParadigmPluginDescription("Test Plugin")] // as well as a description
    public class TestPlugin : IParadigmPlugin  // Your main class must implement the IParadigmPlugin interface
    {
        public void ActivatePlugin() // by implementing the interface, you must implement an ActivatePlugin method
        {
            TestPluginMainForm mainForm = new TestPluginMainForm();
            mainForm.Show();
            mainForm.Activate();
        }
    }
}

In our host applciation, we need to define a few things.  First, we need a wrapper class. This class will hold a reference to an object implementing our IParagidmPlugin interface (ie: any plugin we create), as well as the metadata for the plugin (in our case, name and description). In this case we also implement an Activate() method that will call the actual plugin’s ActivatePlugin() method.

    /// <summary>
    /// This class wraps our plugins
    /// </summary>
    public class ParadigmPlugin
    {
        #region Fields
        private IParadigmPlugin plugin;
        private string name;
        private string description;
        #endregion
 
        #region Attributees
        public string Name
        {
            get { return name; }
        }
 
        public string Description
        {
            get { return description; }
        }
        #endregion
 
        /// <summary>
        /// Constructs a plugin wrapper
        /// </summary>
        public ParadigmPlugin(IParadigmPlugin plugin, string name, string description)
        {
            this.plugin = plugin;
            this.name = name;
            this.description = description;
        }
 
        /// <summary>
        /// Activate Plugin
        /// </summary>
        public void Activate()
        {
            plugin.ActivatePlugin();
        }

We also need to define a quick custom exception, which we will use later on. There is really no implementation here in the example, but you can handle the exception however you wish.

    class PluginNotValidException : ApplicationException
    {
        public PluginNotValidException(Type type, string param1)
        {
        }
    }

First, we need to define a list to contain all of the plugins we load at runtime.  Next, we need a LoadPlugins() method.  This method uses reflection to handle plugin loading.  Essentially, it steps through our plugin directory looking for any file that matches the *.dll file name mask.  When it finds a DLL, it attempts to load the assembly.  If it fails, it will throw an exception and alert the user.

If it succeeds in loading the assembly, and looks for our IParadigmInterface.  If it finds it, it then gets our custom attributes.

Next, the System.Activator class comes into play.  This wasn’t mentioned in Shawn’s article as I said before.  Basically, we are going to create an object of a specific type, which in this case our type is going to be pulled from the loaded assembly, this way we create the correct type of object.

Next, we create an instance of our wrapper class.  Upon constructing, we are going to make sure to cast the object returned by System.Activator as IParadigmPlugin.  We will then add it to our list of loaded plugins.  Thats it.

The last part of this function is optional, but pretty cool and may be helpful.  Basically, we want our loaded plugins to show up dynamically on a menu strip.  So, we will iterate through our list of loaded plugins, and for each one we will add a new item to a toolstrip menu dropdown list.  We will set the name and text to the plugin display name, and the tool tip to the plugin description (see, we used the metadata for something afterall).  Then, we will set the new items Click event to be a delegate referencing the plugin’s Activate() method.  Simple right?  When this method executes, our tool strip will be dynamically populated by the plugins, and clicking them will launch them.

private List<ParadigmPlugin> loadedPlugins = new List<ParadigmPlugin>();
        private void LoadPlugins()
        {
            // search plugin directory for dlls
            string[] files = Directory.GetFiles("Plugins", "*.dll");
 
            // check each file in plugin direction
            foreach (string file in files)
            {
                try
                {
                    // load the assembly and get types
                    Assembly assembly = Assembly.LoadFrom(file);
                    System.Type[] types = assembly.GetTypes();
 
                    // look for our interface in the assembly
                    foreach (System.Type type in types)
                    {
                        // if we found our interface, verify attributes
                        if (type.GetInterface("IParadigmPlugin") != null)
                        {
 
                            if (type.GetCustomAttributes(typeof(ParadigmPluginDisplayNameAttribute), false).Length != 1)
                                throw new PluginNotValidException(type, "Plugin display name is not supported!");
 
                            if (type.GetCustomAttributes(typeof(ParadigmPluginDescriptionAttribute), false).Length != 1)
                                throw new PluginNotValidException(type, "Plugin description is not supported");
 
                            // get custom attributes from plugin
                            string name = type.GetCustomAttributes(typeof(ParadigmPluginDisplayNameAttribute), false)[0].ToString();
                            string description = type.GetCustomAttributes(typeof(ParadigmPluginDescriptionAttribute), false)[0].ToString();
 
                            // create the plugin using reflection
                            Object o = Activator.CreateInstance(type);
 
                            ParadigmPlugin plugin = new ParadigmPlugin(o as IParadigmPlugin, name, description);                                                               
 
                            loadedPlugins.Add(plugin);
                        }
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show(e.Message, "Plugin Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
 
            // iterate through list and add them to our form control
            for (int i = 0; i < loadedPlugins.Count; i++)
            {
                ParadigmPlugin plugin = loadedPlugins[i];
 
                pluginsToolStripMenuItem.DropDownItems.Add(plugin.Name);
                pluginsToolStripMenuItem.DropDownItems[i].Click += delegate { plugin.Activate(); };
                pluginsToolStripMenuItem.DropDownItems[i].Text = plugin.Name;
                pluginsToolStripMenuItem.DropDownItems[i].ToolTipText = plugin.Description;
            }
        }

You could easily expose much more via the interface and make some complicated plugins, but that isn’t needed in this scenario.  However, I hope this helps to illuminate the basics of plugin architecture in C#.

, ,

3 Comments

Upcoming level editor updates

After switching gears and looking at my editor from an RPG standpoint instead of a sidescrolling standpoint, I’ve noticed a few shortcomings in my editor and engine design.

As such, a few changes are planned.

  1. Shadow mapping.  I have a few different ideas on to how create shadows with a decent degree of alpha transparency.  More than likely I will go with a separate B&W image that stores that shadow textures and have the engine draw them as needed with alpha transparency.
  2. Layers, layers, LAYERS.  Three layers, simply, is not enough.  As such, I’m going to transition from the current 3 layer system to an unlimited layer system.
  3. Zooming.  RPG maps are going to be somewhat large.  I think zooming in and out of the editor will be a very helpful addition.
  4. Advanced entity spawning system.  I’m on the fence with this one.  I may or may not implement this in the editor.  Part of me thinks creating an NPC editor would be smarter.  We’ll see how this pans out though.

That is all for now.

, ,

No Comments

Tile Based Level Editor Progress

Well it’s about time isn’t it?  I finally got around to writing this blog post regarding my tile editor.  I recently joined a team to produce an RPG in C# using XNA Studio 3.1, so I figured now would be a good time to put some more work into the tile engine / editor and showcase what is working so far.

As it stands, the editor is pretty robust.  Currently it supports three tile layers, a rear, mid, and foreground layer.  The rear layer is self explanatory.  The mid layer renders over the rear layer to add details, and the foreground layer renders over NPCs, the player, particles, etc (as long as your engine supports it).  The foreground layer is currently tinted yellow so it can be distinguished.

Tiles can be drawn in as single tiles and regions.  You can also choose to fill an entire layer with a single tile if you so choose.

The editor supports multiple collision types such as impassible, platform, slopes, etc.  These are basically just flags that your engine needs to interpret correctly.

The editor also supports spawn points.  Any entity your engine supports can be dumped into a plain text file and the editor will parse it.  The spawn points can be added dynamically to the map.

It also supports a portal layer which allows for areas of the map to be flagged as a portal.  This allows for your engine to do a check against those regions and load a new map as needed.

We also support terrain effects which are regions of the map that will be processed with some sort of effect.  My demo shows this being used with a simple water shader I wrote.

You can set the background color of the map to any of the predefined .NET colors, as well as a custom color using the color wheel.  You can resize the map dynamically as well as specify the tile size to match your tile set.

The next iteration of this editor will support more layers, likely unlimited using just a list of layers.  In addition I plan to implement a sort of multilayer occlusion so that the foreground layer is more or less dynamic.  Different layers will occlude other layers, so on and so forth.  This is not really needed for a platformer, but will be pretty useful in RPG world building.

Videos:

(My apologies as the audio goes out of sync near the end of part 1 and into part 2, blame Camstudio.)

, ,

No Comments

Level Editor Progress

I’ve been hard at work on the level editor for my game engine and I figured I’d get something up here showing current progress. It is currently near completion actually. It allows for editing of 3 tile layers, background, midground, and foreground. It also allows for world hazards, spawn points, portals, and multiple collision types. The editor renders using the XNA framework within a normal WinForms application. Output is serialized using the XNA intermediate serializer into an XML file that can be directly loaded into the game itself.

Basically, pretty sweet.

Here is a screenshot for the time being.

Level Editor Alpha

Level Editor Alpha

, ,

No Comments

Added Flamethrower to Sidescroller

I know I said the last update would be the last before new assets and a level, but I just finished the flamethrower weapon and it turned out really well. I figured I’d share it. Enjoy!

, ,

3 Comments