How to Copy a MS SQL 2005 Database

Problem: You want to make a copy of a Database to a Database on the same server. Useful if you want to run two sites that use the same database schema.

Solution: (Cleaned up version of http://skainsez.blogspot.com/2008/03/how-to-copy-sqlserver-2005-database.html)

Using Microsoft SQL Server Management Studio Express:

The first step I did was to create a new database on the server which would be the duplicate db.

For the purposes of this article let’s assume that my original db is called ‘Prod’ and my new db is called ‘Dev’.

So I right clicked on the ‘Databases’ folder in SSMSE (Sql Server Management Studio Express), chose ‘New Database . . .’ and created a new db called ‘Dev’.

Next up I right-clicked on the ‘Prod’ db (the one I want to duplicate) and chose ‘Tasks -> BackUp . . .’ I created a full backup of the db just to make sure I had the latest data. Once the backup had completed I then right-clicked on the ‘Dev’ database and chose ‘Tasks -> Restore -> Database . . .’

On the ‘General’ page I specified ‘Prod’ as my ‘From database’ and ‘Dev’ as my ‘To database’. Note that when you select the ‘From database’ the ‘To database’ value gets changed to that value. You need to make sure that the ‘To database’ value is actually the name of the duplicate database.

Next I clicked over to the Options page in the Restore dialog. Here I had to change the ‘Restore As’ names of the files in the file listing. By default they are the same as the ‘Original File Name’ values. But that would cause the backup to overwrite the original database.

What we want is to change the ‘Restore As’ names to be the names of the duplicate database’s files.

In this example I changed these two entries:

C:\Program Files\Microsoft SQL Server\MSSQL\data\Prod.mdf
C:\Program Files\Microsoft SQL Server\MSSQL\data\Prod_log.ldf

To:

C:\Program Files\Microsoft SQL Server\MSSQL\data\Dev.mdf
C:\Program Files\Microsoft SQL Server\MSSQL\data\Dev_log.ldf

Then, still on the Options page of the ‘Restore Database’ dialog, I checked the ‘Overwrite the existing database’ checkbox. Next just hit the ‘OK’ button and let it do its thing. The end result should be a duplicate of your original database.

No Comments

Elmo’s World: The Video Game

Elmo’s World: The Video Game is not licensed or endorsed by Sesame Street. All graphics and sounds are used without permission. It’s a homemade game that your small kids might enjoy.

Download Elmo’s World: The Video Game

System Requirements:
Windows XP/Vista
Microsoft XNA Framework Redistributable 3.0
Bluetooth Adapter
Nintendo Wii Remote
Wii Sensor Bar

Screenshots:

Installation:
Download and unzip to any folder you create. You will need to have a Wii Sensor Bar on top of your monitor. I recommend purchasing a wireless Wii Sensor Bar so you don’t have to fiddle with your Wii game system if you have one. If you don’t have one already you will also need a Wii Remote. Make sure your sensor bar and Wii Remote (also known as a Wiimote) are turned on.

How to Connect Your Wiimote to your PC

To allow your computer to use the Wiimote you will need a bluetooth adapter. To connect the Wiimote to your computer open up your bluetooth device manager. Hold down the 1 button and the 2 button on your Wiimote and then use the bluetooth device manager look for bluetooth devices. Click next to continue through the device manager. If you are asked to enter a pin or code to connect click “skip.” You may be asked which service to use from the Wiimote. Select the keyboard/mouse/HID service if prompted (you should only see one service available).

It seems complicated but once you get it working it’s easy to do again.

Make sure your Wii Sensor bar is turned on and double click on ElmosWorld.exe. If the game reports an error and fails to load your Wiimote is not connected.

Press the home button to quit a mini game and go back to the main title screen. All games simply require that you move the Wiimote to complete the tasks: Feed Dorothy, Catch Soccer Balls or Collect Letters.

No Comments

C Sharp Introduction

Microsoft Visual C# 2008 Express Edition is sufficient for using these tutorials. It is free from Microsoft.

The C# tutorials will cover various parts of Bunnies. You can download the complete source Here. This is the latest release from the Bunnies web-site. It’s ready to run so you can download it and try it out.

Rather than bore you with the same tutorials about plotting pixels and whatnot, I’m going to go through the Bunnies source and explain how it all works so you can take it and make it your own.

Java is great for writing software that will work on any platform. However, it has a number of quirks and is much slower than C# which makes it ultimately not suitable for what I want to do. One of the unintended consequences of doing Bunnies in Java first is that it was very easy to translate over. C# is not much different than Java. A lot of code could just be copy and pasted with a few minor changes. It’s then been mostly a matter of enchancing the code rather than rewriting it.

After the Java tutorials ended I started working on the Bunnies web-site which is where you can upload images and create your own maps. Now, rather than having to download a bunch of files there is a single download and the rest of the needed files are downloaded when you play the game. So now you use the web-site to make a map and load up the game to test it. So in addition to covering how Bunnies renders everything I will also be covering the protocol that it uses to communicate with the game server.

No Comments

C# Lesson 1: The Main Loop

Every game needs a main loop. Since C# is intended for applications and not games it doesn’t provide a very efficient way to create the main loop. Fortunatly, C# makes it possible to import the necessary DLLs to create a main loop the old fashioned way: the C way.

//found in bunny.cs

struct POINTAPI
{
	public Int32 x;
	public Int32 y;
}

struct MSG
{
	public Int32 hwmd;
	public Int32 message;
	public Int32 wParam;
	public Int32 lParam;
	public Int32 time;
	public POINTAPI pt;
}

[DllImport("user32.dll", SetLastError = true)]
private static extern bool PeekMessage(
				   ref MSG lpMsg,
				   Int32 hwnd,
				   Int32 wMsgFilterMin,
				   Int32 wMsgFilterMax,
				   PeekMessageOption wRemoveMsg);

[DllImport("user32.dll", SetLastError = true)]
private static extern bool TranslateMessage(ref MSG lpMsg);

[DllImport("user32.dll", SetLastError = true)]
private static extern Int32 DispatchMessage(ref MSG lpMsg);

private enum PeekMessageOption
{
	PM_NOREMOVE = 0,
	PM_REMOVE
}

private static Int32 WM_QUIT = 0x12;

...

public void Run()
{
	MSG msg = new MSG();
	...

	while (!done)
	{
		while (PeekMessage(ref msg, 0, 0, 0, PeekMessageOption.PM_REMOVE))
		{
			if (msg.message == WM_QUIT)
			{
				this.Close();
				break;
			}

			TranslateMessage(ref msg);
			DispatchMessage(ref msg);
		}
		...
		//game stuff goes here
	}
}

...
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
	done = true; //this makes sure everything exits properly
}

We use a “while” instead of an “if” when processing messages because we want to keep everything moving along. Say we use an “if” instead. Now imagine that the game, for whatever reason, is only able to run at 1 frame per second. We would only be able to handle one windows message per second. The windows message system is going to get backed up very quickly. By using a “while” we take a fraction of a second to clear out the messages and then the actual render can take as long as it wants. You can put the code from the Run() method directly into your C# form’s main method or call it from the main method. It really doesn’t matter. What this essentially does is get you an unmanaged main loop. This link has a discussion about setting up a main loop in C#. Specifically Tom Miller explains what the problem is with the standard C# main loop.

He gives 4 options for creating the main loop.

  • Set your form to have all drawing occur in WmPaint, and do your rendering there. Before the end of the OnPaint method, make sure you do a this.Invalidate(); This will cause the OnPaint method to be fired again immediately.
  • P/Invoke into the Win32 API and call PeekMessage/TranslateMessage/DispatchMessage. (Doevents actually does something similar, but you can do this without the extra allocations).
  • Write your own forms class that is a small wrapper around CreateWindowEx, and give yourself complete control over the message loop.
  • Decide that the DoEvents method works fine for you and stick with it.

The problem with the first method is that you’re relying on windows messaging to get the next frame rendered. A message has to be created, sent, received and translated before the next frame is rendered.

This is what Bunnies does. No messages are created, it just processes them as they come in. Bunnies doesn’t have to wait for a message to come in before it renders the next frame.

I havn’t played around with C# enough to know what he’s refering to exactly but it sounds dreadful.

This is the standard method that is used in the DirectX Tutorials by Microsoft. It does pretty much what Bunnies is doing but DoEvents allocates memory every time its called which slows things down.

You can stick with the version that has been implemented or try implementing one of the alternatives.

No Comments

Java Lesson 10: Finish Up the Game

Lesson 10 Source Files
Resource Files

This lesson adds in a robust light handler. lights.txt defines the light sources and map.lights.txt defines where those lights are positioned in the map. There are 7 values that define each light:

character,r,g,b,colored,global

Character is the single character that is used in the map file to indicate where the light is positioned. r,g and b are the color values from 0-255. colored is either 0 or 1. If a light is not colored then the color values are ignored. Otherwise the color value is applied to the pixel which is being lit up. If a light is global then walls are ignored when calculating the lighting of a pixel. When a light is not global the walls cast shadows. Although non-global lighting is allowed it is highly expensive and will cause a huge drop in the framerate.

light_handler.java does all the heavy lifting with the lighting effects. You can trade off shadow accuracy with rendering speed if you want.

	dx = (sx-tx)/(dist*16.0);
	dy = (sy-ty)/(dist*16.0);
	for(j=0;j-1) { visible=false; j=dist;}
		tx+=dx;
		ty+=dy;
	}

dist is the map location. If you multiply by 1 the render speed is the fastest but the light appears to wrap around walls a bit. If you multiply by 64 (which converts it to pixel location) then you get pixel level accuracy. However you’re now doing 64 times as many checks for the light hitting a wall which really slows things down. 16 gives a decent accuracy and allows for a reasonable framerate with 1 non-global light source. Your results will vary based on the system you’re running.

Notice that we’re tracing the light from the light source to the pixel we’re rendering. This allows us to use less accurate tracing to improve speed. If we went the other way we may start off inside the wall we’re checking for illumination. There’s probably ways to fix that but going from the light to the destination I think makes more sense anyway. If we hit a wall before we get the the destination we set visible to false and the light source is ignored. And that’s how shadows are created. You may notice that it looks very similar to the raycasting code that renders the level. It’s the same concept except that instead of shooting a ray from the camera we shoot it from a light.

Global lighting is very fast since the most expensive calculation is a squareroot. On modern processors the squareroot is calculated by the CPU which is very fast. Back when Wolfenstein 3D came out the sqrt function was the bane of game programming because it was not a native instruction on the CPU. Carmack came up with a C function to do the calculation very fast but that is still much slower than a modern CPU.

And that concludes our real time software rendering tutorials using Java.

No Comments

Java Lesson 9: Finish Up the Game

Lesson 9 Source Files
Resource Files

We now have constants. Java doesn’t have global constants like languages like C. Instead you have to define a static class with static members. You can then reference those members without having to instantiate the static class. This allows us to use constants to define state values rather than having to remember that the title screen is state 1.

Since we now have an easy way to define states some files have been renamed to indicate they define a state. wolf5k.java is now state_wolf5k.java, etc. You’ll also find that there is no longer a thread running the game. Instead we’re using Java’s messaging system and the main loop is no longer a clearly defined loop. In the paint and update methods which were previously unused we call the run() method which does one game loop iteration as well as halts the main applet thread for a millisecond to let the CPU breathe. Once that method completes, the repaint() applet method is called which puts an event into Java which will trigger the paint or update method to be called. And that’s how our game loop is called until the applet exits. Of all the ways to get a language to loop, that is by far the most convoluted. But, with Java it actually gains us a few FPS and things just work more smoothly.

I say paint or update because that’s just how Java works. So, both those functions need to call the main method to render our game. There’s no way to determine which will be called on a repaint() event.

Now that we have a font that we can print to the screen we can finally display a timer. In doing so I discovered that the timer was running way too fast. Turns out I was calculating the time it took to render a frame the wrong way which sped up time. That is now corrected so 1 second of game time is 1 second of real time. Previously, one second of real time was several seconds of game time. We also now have a bunny counter so we can see how many of them are bouncing around. You’ve been able to shoot the bunnies. Now you can see how many you’ve killed.

There are four states currently. There’s the title screen, the game, the win and the lose. If you get the bunny counter down to 0 you win. If the bunny counter gets up to 100 you lose. How does the bunny counter go up you may ask. Bunnies multiply after 20 plus a random amount of seconds. After a bunny multiplies it will take longer and longer to multiply again until it reaches a certain age where it can’t multiply any longer. If you don’t shoot any bunnies the game will be over in a couple minutes which is pretty reasonable. Each bunny spawns one additional bunny at a time.

This tutorial would have been up sooner except for one minor detail: it was an applet that didn’t run in a browser. The reason it would not run in a browser was because it was loading resources using FILEs rather than URLs. That’s been fixed so now you can use the APPLET tag in an HTML document to load up Bunnies.

And so now you have a complete game in Java. In Lesson 10 my goal is to improve the rendering so things look better. Right now we have no lighting at all. We’re just plotting pixels with no consideration for any light source.

The tutorials end at Lesson 10 but I have more coming.

No Comments

Java Lesson 8: Titles and Text

Lesson 8 Source Files
Resource Files

This is a very important lesson. We finally can have a title screen and render text. To accomplish this I’ve added a simple blitter that renders an entire texture to a rectangular area. I’ve also reorganized the code to clean some things up. The video buffer class now handles all the pixel plotting and blitting functions.

Along with title screens comes the notion of “states.” Each state has a loading process and an execution process. When the state changes all the resources for that state are loaded in. While the state continues the same we just process the logic for that state. Garbage collection takes care of clearing out the unneeded resources. The trick is keeping track of what states are what number and which state can go to what other states and how. To get from the title screen to the game hit enter. To get back to the title screen press escape. To halt the program, press esc from the title screen.

To simplify some things we really should be using constants. Java doesn’t have constants. We’ll take care of how to get around that in Lesson 9.

The major advance that this lesson brings is being able to write text to the screen. The font_gen class is currently quite simple. It finds all the fonts that the current system supports and then generates a bitmap containing all the printable characters rendered at 36 pixels in height using the color red and the font “Ariel.” Needless to say, in Lesson 9 we’ll be abstracting this class a little more so we can adjust the font properties at load time and maybe add in the ability to have more than one font. The really nice thing about letting the language handle rendering a bitmap font rather than doing it yourself with a paint program is that we can let the language tell us the location and size of each character. You don’t need to go one letter at a time and tell the program how large each character is.

For no particular reason the generated font map is saved to a PNG file so you can see what it looks like. Keep in mind that this font generator will only work with Java. Other languages have other ways of doing this task. I’ve personally done it with C++ using the Windows API.

Our video_buffer class now has a “Print” function which takes the font class, the text and the height (in pixels) of the text. It then takes care of everything else. We’ll be improving that later as well.

Believe it or not you now have all the basic tools you need to make a complete game. In lesson 9 we’ll finally turn this tutorial into a complete game. In Lesson 10 we’ll start to push the limits with some fancy rendering.

No Comments

Java Lesson 7: Map Files and Beach Balls

Lesson 7 Source Files
Resource Files

Prior to this lesson everything was just randomly placed. Now we’ve added a “levels” directory with numbered sub-directories for each level. In those directories are the files which define the graphics we’ll be using for walls and objects. We also define the level itself. A maximum of 256 graphics can be used for objects and 256 graphics can be used for wall, floors and ceilings. Each level can define different graphics to use so we’re not too restricted.

  • tile.txt – this file defines our wall, floor and ceiling textures as well as what character is used in the map file to reference them. The format is texture number, character code, texture, mask. The character codes must be a single character. The mask is optional.
  • obj.txt – this file defines our object textures, floor and ceiling textures. You only need to load the textures for the objects you’ll be using in the level but the texture number must always be the same. Those are hard coded in the object’s class file. The format is texture number, texture, mask. The mask is optional but objects should always have a mask.
  • obj.map.txt – this file defines our object character codes. There is a hash map in the object handler that associates an object type number with an object type string. This file associates a character code with the object type string. Currently we have “bunny,” “player,” and “tree.” When the map is loaded the player object is returned to the wolf5k class which needs to know what object is the player. There should only be one player character code per map. If there are multiple player codes in the map the last one will be used as the real player object. All others will do nothing. The format for this file is character code, object type string.
  • map.*.txt – We have four files which define the map; wall, floor, ceil and obj. The wall, floor and ceil files all use the tile.txt codes. The obj file uses the obj.map.txt codes. The wall file defines the size of the map. The dimensions of the map are determined by the size of the last row and the size of the total map string. Line returns are ignored. “.”‘s indicate that the default texture or object is used which is usually no texture or object at all. Only the floor is set to have a default texture which is grass. You files should all have the same dimensions and every line should be the same length. If not, things won’t render correctly.

I’ve also fixed the hopping code. It’s much simpler now. Also I determined that the distance calculation was off by a multiple of 64 when using it to render sprites. 64 pixels is now 64 pixels at 64 pixels from the player and 32 pixels when 128 pixels from the player like it should be. The tree has been replaced by a bouncing beach ball.

One of the problems that shows up when doing time based movement is that things don’t always collide like they should because objects move too fast. I’ve improved the collision detection to track the movement from the previous location to the new location using time slices equal to 1/50th of the time difference from the previous frame. The collision detection is now essentially running at 50 times the frame rate of the game itself. Nothing is moving particularly fast in this game so it’s accurate enough.

This isn’t perfect. The real way to do it is to first figure out if the two object collide using simple alegbra and the line formula. Then you calculate the time it takes for both objects to get to that point (distance to the point divided by the render time) and if they both get there at the same time, there’s a collision. That only checks for them being at the exact same point however. It’s a little more complex when you take into account a collision radius around the objects. We’ll stick to the simple way for now. Maybe in lesson 8 I’ll improve it. The current way does hurt the frame rate noticably.

We’re also only checking the x and y position. Bunnies can’t hop over your beach balls at this time.

The main thing in the next lesson will be to finally render title screens and status bars.

No Comments

Java Lesson 6: Optimizations and Ceilings

Lesson 6 Source Files
Resource Files

In the last lesson I added in floors but didn’t want to assume anything about ceilings. I’m actually glad I waited because adding ceilings and floors caused the framerate to plummet. This lesson I was then able to use to get my framerate back up and finish up floors and ceilings.

The map now has three arrays of equal size. One for the walls, one for the ceiling and one for the floor. This allows us to texture anything however we want. I also added in transparency to the floors so players can see through the floor to the background texture. I also removed the default fence around the parimeter. That stopped working when I optimized the raycaster. Now that I think about it, I’ll probably remove the transparent walls. They don’t really work except on the outer edge anyway.

The original Wolf5K based everything on 64 pixels which resulted in a lot of excess math once we stopped working in pixels and started working in percentages. I’ve removed all that now and the raycaster works in map coordinates instead of pixels. All the multiply and divide by 64s are now gone. Before the optimization 320×240 ran at about 15fps. Now it runs at about 21fps. That’s pretty much the same speed it was running when only walls/objects were being rendered.

One of the things I’ve been wanting to do since I deobfuscated the Wolf5K javascript code was rename all the variables back to something meaningful. I’ve done that now with most of the raycasting code. It makes a lot more sense now and I was able to find some minor optimizations.

For the most part our raycaster is complete. We have walls, floors, and ceilings which is more than most raycasters out there. The only component missing is lighting. We’ll also be enhancing our 2D graphics capabilities. All games need title screens and menus as well as status bars. There’s no shortage of things that go into a rendering engine.

No Comments

Java Lesson 5: Noisy Bunnies and Floors

Lesson 5 Source Files
Resource Files

I have been banging my head against the wall trying to render floors. There’s a standard equation floating around the internet that I had previously tried using but for some reason it would just not work with the Wolf5K raycaster. The solid bright green floor in previous tutorials was the most I could get the work. If you look closely the green gets darker towards the edges of the map.

There were two key mistakes I was making in my previous attempts. The big giant one was currentDist. The scale was wrong. currentDist was calculating the map distance. Not the pixel distance. f is the pixel distance from the camera to the wall slice that was hit. All I had to do was multiply by 64.0 and I had floors that moved the same speed as the player. One of the things I like to see in tutorials is what happens when you do it wrong. In this case, if currentDist is calculating based on a different scale than f, the floor moves way out of sync with the camera. It moves in the correct direction, it just moves significantly faster.

Now that the scale was right the second problem was the texture location. The original code was using a simple multiply and mod. That works great when you’re working with integers. You may notice the equation I use is the same format as the equation used in the wall rendering. That equation is a quick way to mod a double. It leaves you with a value between 0 and 64. We then divide by 64 to get a value between 0 and 1 which is what we use to stretch textures.

I highly recommend messing around with the floor equations because they are a big pain and I think it would help you to see what goes wrong when you start changing things around. Once I got it right I saw pretty clearly what I was doing wrong to get the various effects I was running into earlier.

In the next tutorial we’ll show how to render the ceiling and define a floor and ceiling map so we don’t have to use a single repeating texture. The grass texture is a large grass texture I found at Gamasutra.com.

The other big addition is the ability to play sound effects. Currently no fancy formats are being used, just simple wav files. You can load all the sound effects at once at the beginning and then play any number of sounds at the same time just by calling the play method with the file name. No need to keep track of numbers. The bunny object now has a sound_effect string. When that is set, the sound handler attempts to play the referenced sound effect. The sound is started every frame so make sure that sound_effect is set to null the frame after the sound effect is set. In the bunny code you will see that the sound effect is defaulted to null (not an empty string) and only set to the file name when the bunny first initializes the hop.

I’m using some basic math to adjust the volume of the sound effect based on distance from the camera. The balance is also supposed to be adjusted but that seems to not actually work. If it did, the sound effect would play mostly out of the left speaker when the bunny is to the left of you and the right speaker if the bunny is to the right of you.

All in all this a good start with sound and floors. The next tutorial will finish up the floor and ceiling rendering and maybe have some more advanced sound playing. I’d like to use Ogg but I’m not sure what is available to do that. The way the sound effect code is organized it should be rather easy to modify the sound effect loading code without affecting anything else.

No Comments