Archive

Archive for the ‘C/C++’ Category

Change GUI Label text colour on hover

November 14th, 2011 No comments

Hi,

Today I ran into a problem whereby I was drawing a GUI label that I want to have a different colour on hover to it’s normal state. Following the usual steps I altered the style in the GUI skin to have a different hover text colour expecting this to work. However it does not. The colour remaining the same even on hover. My draw code is fairly simple, akin to:

GUI.Label(rect,text,style);

So nothing wrong here. After playing around a bit I put in a background texture on the hover in the style to see if this made a difference and low and behold the text colour changed! I do not want a texture though so instead I created a 1×1 pixel texture which is completely alphaed out and used that as a background texture. Naff and pretty hidden behaviour but thats the workaround I found.

Also you need to change the drawing code to draw the item as a GUI.Button instead of a Label.

Categories: C/C++ Tags:

Update GUI Button text colour Unity

October 11th, 2011 No comments

I recently had a bit of text that I wanted to be able to click. This is easy to do, just make a GUI.Button with a custom style that has no background and use the text as the GUIContent parameter. However I wanted to change the colour of the text when you hover over the text, this proved trickier. I changed the hover text colour but nothing happened. I tried just putting in a background texture for the hover state in the GUI skin for a test and noticed that the text colour changed when I hovered over it!
So the solution that I found is to make a 1×1 transparent texture and use that as the background texture for the hover! Terrible I know but there is no other way I can see to fix it…

Categories: C/C++ Tags:

Changing GUI.Button text colour

October 11th, 2011 No comments

I recently had a bit of text that I wanted to be able to click. This is easy to do, just make a GUI.Button with a custom style that has no background and use the text as the GUIContent parameter. However I wanted to change the colour of the text when you hover over the text, this proved trickier. I changed the hover text colour but nothing happened. I tried just putting in a background texture for the hover state in the GUI skin for a test and noticed that the text colour changed when I hovered over it!
So the solution that I found is to make a 1×1 transparent texture and use that as the background texture for the hover! Terrible I know but there is no other way I can see to fix it…

Categories: C/C++ Tags:

Error from Debugger: Failed to launch simulated application: iPhone Simulator failed to install the application.

June 19th, 2011 No comments

I got the error below when attempting to Build and Go in XCode.

Error from Debugger: Failed to launch simulated application: iPhone Simulator failed to install the application.

My app wouldn’t launch in the iPhone Simulator and the console has little or no feedback.

I went through a few steps to fix this, firstly I tried to Clean All Targets but that didn’t work. What I did that worked was:

  • Close the iPhone Simulator
  • Open the terminal and execute
    sudo rm -Rfv ~/Library/Application\ Support/iPhone\ Simulator

Should work now when you Build and Go again.

Categories: C/C++ Tags:

A simple HashedString implementation

May 17th, 2011 No comments

Hi,

In my first forays into my engine development I’ve found it necessary to come up with my own simple hashed string implementation. I plan on using this in place of strings wherever possible for identifiers of objects or for storage. My requirements are fairly simple, I want to have an implementation that resolves a string to an unsigned integer. In debug I want to be able to identify the string in the debugger so I have a debug only char array that is used to store the original string when passed in.

For my hash functions I used the code from General Purpose Hash Functions. I haven’t looked at the hashing algorithms in much detail, a lot of the math looks above my head. I chose the DJB hash function as it is described as being one of the most efficient hashing algorithms ever produced.

One of the things I haven’t considered as of yet is that collisions may be possible. I’ll have to look at the various hashing implementations and pick the one that looks to be the best choice and come up with a system to cope with clashes. This will probably involve doing some tests on a wide range of strings, for now however I don’t have many strings and so my implementation will suffice.

Below are the header and implementation of my HashString along with the HashFunctions found at the link above. You may need to fiddle with them slightly to get them working for your purposes but they’re largely for illustration purposes anyway. These are provided as is, I may find bugs and will endeavour to reupload the fixes.

GeneralHashFunctions.c
HashedString.h
GeneralHashFunctions.h

Categories: C/C++ Tags:

Writing a game engine – Part 2

May 3rd, 2011 No comments

A quick one today, I’ve got a basic application up and running using the simple framework located here.

One interesting thing to note is that Nehe uses global variables for the active, fullscreen and keys variables. I don’t want to do this. I want to have these as members of an Application class to begin with and eventually I’ll create an input handler class and also a renderer that may hold onto these. However due to the way in which the windows are created only static non-member functions can be used to handle the callbacks from the window to handle messages like WM_NCCREATE, WM_ACTIVATE, WM_CLOSE, WM_KEYDOWN and so on. To allow a member function to be able to handle these messages you need to do perform some trickery. You need to define two static callback methods that will handle and messages from the window.

Firstly, we need to alter the way in which the window is created. The first thing we need to do is the give the name of one of the static methods you defined as the initial callback i.e. called on creation of the window:

wc.lpfnWndProc		= &InitialWndProc;						// WndProc Handles Messages

The next thing you need to do is to alter the CreateWindowEx call and add change the last parameter from NULL to ‘this’. This last parameter is an optional extra data that is passed to the creation of the window. By passing this we are passing a pointer to the current Application class to the window creation callback.

So I mentioned two static methods earlier. The first method is to handle the creation of the window:

static LRESULT CALLBACK InitialWndProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) {
		if (Msg == WM_NCCREATE) {
			LPCREATESTRUCT create_struct = reinterpret_cast(lParam);
			void * lpCreateParam = create_struct->lpCreateParams;
			Application * theApp = reinterpret_cast< Application*>(lpCreateParam);
			SetWindowLongPtr(hWnd, GWLP_USERDATA, reinterpret_cast(theApp));
			SetWindowLongPtr(hWnd, GWLP_WNDPROC, reinterpret_cast(&StaticWndProc));
			return theApp->WndProc(hWnd, Msg, wParam, lParam);
		}
		return DefWindowProc(hWnd, Msg, wParam, lParam);
	}

Here we are taking the extra data that was passed into the CreateWindowEX, casting it to an Application pointer and then telling hWnd (the handle to the window) what the new user data (GWLP_USERDATA) will be and also WNDPROC will be that will handle messages from now on in. Essentially what this does is that it tells the window that all messages should be sent to the static method StaticWndProc with the user data being theApp (which is cast to a long pointer). Also note the call to theApp->WndProc, this is important later.

The second static method you need to define is the one that will pass on all messages that come to the window during runtime.

static LRESULT CALLBACK StaticWndProc(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam) {
		LONG_PTR user_data = GetWindowLongPtr(hWnd, GWLP_USERDATA);
		Application * theApp = reinterpret_cast< Application*>(user_data);
		return theApp->WndProc(hWnd, Msg, wParam, lParam);
	}

This is simple, all it does is take the user data from window that we setup earlier, cast it to the right Application* type and then pass along the callback to the class’s desired member.

So now we can have a member function on Application like so:

LRESULT CALLBACK Application::WndProc(	HWND	hWnd,			// Handle For This Window
											UINT	uMsg,			// Message For This Window
											WPARAM	wParam,			// Additional Message Information
											LPARAM	lParam)			// Additional Message Information
	{
		switch (uMsg)									// Check For Windows Messages
		{
			case WM_ACTIVATE:							// Watch For Window Activate Message
			{
				if (!HIWORD(wParam))					// Check Minimization State
				{
					m_active=TRUE;						// Program Is Active
				}
				else
				{
					m_active=FALSE;						// Program Is No Longer Active
				}

				return 0;								// Return To The Message Loop
			}

			case WM_SYSCOMMAND:							// Intercept System Commands
			{
				switch (wParam)							// Check System Calls
				{
					case SC_SCREENSAVE:					// Screensaver Trying To Start?
					case SC_MONITORPOWER:				// Monitor Trying To Enter Powersave?
					return 0;							// Prevent From Happening
				}
				break;									// Exit
			}

			case WM_CLOSE:								// Did We Receive A Close Message?
			{
				PostQuitMessage(0);						// Send A Quit Message
				return 0;								// Jump Back
			}

			case WM_KEYDOWN:							// Is A Key Being Held Down?
			{
				m_keys[wParam] = TRUE;					// If So, Mark It As TRUE
				return 0;								// Jump Back
			}

			case WM_KEYUP:								// Has A Key Been Released?
			{
				m_keys[wParam] = FALSE;					// If So, Mark It As FALSE
				return 0;								// Jump Back
			}

			case WM_SIZE:								// Resize The OpenGL Window
			{
				reSizeGLScene(LOWORD(lParam),HIWORD(lParam));  // LoWord=Width, HiWord=Height
				return 0;								// Jump Back
			}
		}

		// Pass All Unhandled Messages To DefWindowProc
		return DefWindowProc(hWnd,uMsg,wParam,lParam);
	}

And have achieved what I wanted, be able to have member variables and a member function be able to handle the various messages that come from the window.

Note: There is no error handling if the Application casting goes wrong, I might add that at some point.

Categories: C/C++ Tags:

Writing a game engine – Day 1

April 14th, 2011 2 comments

Ok so I’ve decided to write my own engine. I’m doing this not to make a game or anything but to learn from it. I’ve read the articles where people say ‘make a game not an engine’ but I think it is very important to actually learn by doing. I’ve been reading a lot recently and feel like a lot of the stuff almost goes in one ear and out the other, mainly because I’m not actually doing anything to follow up my learnings.
So I’m going to begin creating an C++ Open GL based engine (over my lunchtime). The main aims are:

  • Minimise the use of virtual functions and inheritance
  • Minimise the use of STL
  • Have modular and heavily configurable sub-systems
  • Aim for deferred rendering in my scene
  • Implement a simple data-based GUI that includes an in-game editor (possibly haven’t decided on this yet)
  • Incorporate scripting
  • Make use of threading/multi cores

Today I’m not really doing anything in particular, just reading. I’d imagine I’ll be doing this for a while before I even write a line of code.

I’ve read the excellent Game Engine Architecture by Jason Gregory but will start again looking at it taking real note and actually sketching out some designs. I like the idea of the way Unity do things with Entities and a property system.

I intend to revisit this post during the coming months and amend, laugh and update it… will be an interesting challenge ahead. It’s certainly going to take a long time given that I can only give it about 45 minutes a day!

Categories: C/C++ Tags:

Visual Studio filters disappear

April 4th, 2011 1 comment

Recently I had a project in VS2008 whereby all my filters disappeared and all files appeared unfiltered. Very annoying when trying to locate files, I thought something was borked with the vcproj or even the solution. The fix is actually really simple, somehow (I have no idea how) the ‘Show All Files’ option had been toggled. To untoggle it go and click Project->Show All Files. Very simple I know but it had me perplexed for a couple of minutes!

Categories: C/C++, Visual Studio Tags:

Perforce with C# (p4 dotnet)

March 25th, 2011 No comments

I’ve found a need to use Perforce with C# recently. The first step was to get the right DLLs for the job. I got the P4 API DLL from SourceForge here

Extracting it, I think you actually only need the p4API dll in the bin/CLR_2.0 directory, I took the whole directory just in case.

In your project right click on the References directory and ‘Add Reference’ and navigate to the p4api.dll.

// Load up the API
using P4API;
...

// Create the connection
P4Connection p4 = null;
            try
            {
                p4 = new P4Connection(); // Uses the default connection to Perforce
                p4.Connect();

                // Don't throw an exception on a Perforce error.  We handle these manually.
                p4.ExceptionLevel = P4ExceptionLevels.NoExceptionOnErrors;
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

I want to delete a file from the repository so to do this I needed to just put through the right call. From what I’ve gathered you can run any P4 command that can be run via the command line, all you need to do is

try
{
       if (p4 != null)
       {
             p4.RunUnParsed("delete", selectedItemPath);
       }
}
catch (System.Runtime.InteropServices.COMException ex)
{
        MessageBox.Show(ex.Message);
}

Done!

Categories: C/C++ Tags: ,

C# Npgsql tutorial

March 24th, 2011 No comments

Hi,

I’ve just started using C# for the first time and decided to chuck up a little intro on how to connect with a Postgres database. This is a very stripped down tutorial, does the basics and doesn’t really handle exceptions, error states and the like. Firstly you need to get a few DLLs, Npgsql.dll, policy.2.0.Npgsql.dll and MonoSecurity.dll. You can get them from PgFoundry here.

I’ve put these in the same folder as the project. Go to Solution Explorer and locate the ‘References’ section under your project. Right click that and Add Reference. Click the ‘Browse’ tab and select the Npqsql dll only.
Firstly you need to load up the package/namespace (I’m not sure of the correct terminology here). Then you’re ready to connect to the database using the correct name, port, username and so on. This is simple.

using System;
...
using Npgsql;

....

NpgsqlConnection dbConnection = new NpgsqlConnection("Server=myServer;Port=xxxx;User Id=xyz;Password=xyz;Database=myDB;");

try
 {
        dbConnection.Open();
 }
catch
{
        //Handle error states here
}

That’s it! You’re now ready to execute queries and updates on the database.

I’ve included a very simple select statement below, it selects all from a hypothetical animal table and extracts the name and type column values from the results. The GetOrdinal is a useful helpful function to return you the integer that represents the index of the named column. It is more robust to changes in the database as indices may change but you need to check for NULLs as it won’t work (I’ve found out!)

NpgsqlCommand Command = new NpgsqlCommand("select name,type from animals", dbConnection);
NpgsqlDataReader result = Command.ExecuteReader();

while (result.Read())
{
      String animalName = result.GetString(result.GetOrdinal("name"));
      String animalType = result.GetString(result.GetOrdinal("type"));
      ... (Do something here)
}

Finally when you’re done with your database you need to close down the connection

dbConnection.Close();
dbConnection = null;

Thats it’s some very simple DB manipulations in very few lines of code, impressed with C# so far I must say!
Next step do things in transactions and handle exceptions!

Categories: C#, C/C++ Tags: , ,