Jump to content

  • Log In with Google      Sign In   
  • Create Account

Banner advertising on our site currently available from just $5!

1. Learn about the promo. 2. Sign up for GDNet+. 3. Set up your advert!


Member Since 23 Feb 2001
Offline Last Active Yesterday, 10:51 PM

#5141847 Debugging Graphics

Posted by slayemin on 24 March 2014 - 06:22 PM

I've run into tons of trouble with this exact problem. After spending hours and hours on trying to figure out why my "stuff" isn't rendering, I've come up with a comprehensive checklist of things to verify and check.

If you've never rendered a model or primitive to the screen before using your current API, you want to establish a baseline by trying to do the most basic thing you can: render the simplest model/primitive you can. This is akin to writing your first "hello world" program for graphics. If you can do this, then the rest of graphics programming is simply a matter of adding on additional layers of complexity. The general debugging step then becomes a matter of adding on each subsequent layer of complexity and seeing which one breaks.

At the core, debugging is essentially just a matter of isolating and narrowing the problem down to as few possibilities as possible, then focusing in on each possibility.


This is for the C# and XNA API, but you can generalize or translate these points to your own language and API.

Let's start with the comprehensive checklist for primitive rendering (triangle lists, triangle strips, line lists, line strips):
1. Base case: Can you render a triangle to the screen without doing anything fancy?

       -Are you setting vertex positions for the three corners of the triangle? Are they different from each other? Is it rendering a triangle which should be visible in the current view?

       -Are you actually calling the "DrawPrimitive()" method, or equivalent in your API?
       -Are you using vertex colors which contrast against the background color?
       -Are you correctly applying a shader? Is the shader the correct shader? Have all shader settings been set correctly before you call the draw call?
       -Are you using a valid view and projection matrix which would actually let you view the triangle?
       -Are you using a world matrix which is transforming the triangle off screen? (You shouldn't even need a world matrix yet)
      -Are you using the right primitive type in your DrawPrimitives call? (triangle list vs triangle strip, etc)
2. Indexed verticies: Are you using an index buffer to specify the vertex drawing order?
       -Is the vertex drawing order compatible with your current cull mode? To find out, either toggle your cull mode or change your drawing order.
       -Are you actually creating an index buffer? Are you copying an array of ints into your index buffer to fill it with data? Are the array values correct?
       -If your index buffer is created, are you actually setting the graphics cards active index buffer to your index buffer?
       -Are you using "DrawIndexedPrimitives()" or your API's equivalent draw call? Are you correctly specifying the correct number of primitives to draw?
      -Does the drawing order make sense with regard to the primitive type you're using? ie, the vertex order in a triangle strip is very different from a triangle list.
3. Vertex Data:
   -Are you using a custom vertex declaration? If yes, skip to #4.

   -Are you using a vertex buffer? If yes:
       -You must use a vertex array of some sort, at some point, to populate the vertex buffer. Verify that you're getting an array of verticies in your code. Using your IDE debugger, verify that the vertex data is correct.
      -Are you moving your vertex array data into a vertex buffer? Is the vertex buffer the correct size? Does the vertex buffer have the vertex data from your vertex array?
      -On the graphics card, are you setting the active vertex buffer before drawing? Is there an associated index buffer?
4. Custom Vertex Declarations: Are you using a custom vertex declaration?
  Yes: Then you must be defining your vertex in a Struct.
    -Does your vertex declaration include position information? If not, how are you computing the vertex position in your shader?
     -Does your vertex declaration include every field you want to use?
   -Are you creating a Vertex Declaration correctly?
       -Are your vertex elements being defined in the same order as they are in the struct fields? This is one of the few times declaration variable order really matters because it's specifying the order they appear in the struct memory block.
       -Are you correctly calculating the BYTE size of each variable in the vertex? Are you correctly calculating the field offset in bytes?

       -Are you correctly specifying the vertex element usage?

       -Are you correctly using the right usage index for the vertex element?
       -Are you specifying the correct total byte size for your custom vertex declaration?
 -Is your code correctly using the custom vertex data? ie, putting position information into a position variable.

5. High Level Shader Language (HLSL): Are you using a shader other than "BasicEffect"?
      -Are you actually loading the content for the shader and storing it in an "Effect" data structure?
      -Are you correctly initializing the effect?
      -Are you setting a "Current Technique" in your render call to one which exists in the shader?
      -Does the technique which you use include a vertex shader and a pixel shader? Are they supported by your API and graphics card?
      -Does the vertex shader require any global variables to be set? (ie, camera position, world matricies, textures, etc). Are they being set to valid data?
       -Does the vertex shader output valid data which the pixel shader can use?
       -Does the pixel shader actually output color information?
       -Does your vertex shader math and logic check out correctly? (If you don't know or aren't sure, it's time to use a shader debugger).

6. Shader debuggers:

    I'm using Visual Studio 2010, so I can't use the built-in shader debugger from VS2012. I have to use external tools. Here are the ones I've tried and my thoughts on them:
    NVidia FX Composer: It sucks. It is unstable and crashes frequently, has a high learning curve, and can't attach a shader debugger to an executable file (your game). You can't push custom vertex data into a shader and see how the shader handles it. This program is mostly useful for creating shaders for existing models.
   ATI's GPU PerfStudio: It doesn't work with DirectX 9.0, so if you're using XNA, you're out of luck. Sorry, ATI doesn't care enough. It's also a bit confusing to setup and get running.
    Microsoft PIX: It's a mediocre debugger, but is the best one I've found. It is included in the DirectX SDK. The most useful feature is being able to attach to an EXE and capturing a frame by pressing F12. You can then view every single method call used to draw that frame, along with the method parameters. This tool also lets you view every single resource (DX Surfaces, vertex buffers, index buffers, rasterizer settings, etc) on the graphics card, along with that resources data. This is the best way to see if your vertex data and index buffer data is legit. You can also debug a pixel in your vertex data. This lets you step through your shader code (HLSL or ASM) line by line and see what the actual variable values are being set to. It's an okay debugger, but it doesn't have any intellisense or let you mouse over a variable to see its values like the Visual Studio IDE debugger does. This is the debugger I currently use to debug my shaders. The debugging workflow is a bit cumbersome since you have to rebuild your project, start a new experiment, take a snapshot, find the frame, find the data object you want to see, step through the shader debugger to the variable you're interested in (~2 minutes). Here are a few "nice to know" notes on PIX:
  -If you're looking at the contents of a vertex buffer:

      -Each block is 32 bits, or 4 bytes in size. Keep this in mind if you're using a custom vertex declaration to pack data into a 4 byte block (such as with Color data).

      -0xFF is displayed as a funky value: -1.#Q0
     -Each 4-byte block is displayed in the order it appears in your custom vertex declaration. Each vertex data block is your vertex declaration size / 4. (ie, 36 bytes = 36 / 4 = 9 blocks per vertex)
     -The total size of the buffer is the blocks per vertex multiplied by the number of verticies you have (ie, 9 * 3 = 27 4-byte blocks)
      -Usage: If your vertex declaration byte offsets are off by a byte or more, you should expect to see funky data in the buffer.
  -Vertex Declaration should always match the vertex declaration in your custom vertex declaration struct.

-By selecting the actual draw call in the events list and then looking at the mesh, you can see the vertex information as it appears in the pre-vertex shader (object space), the post-vertex shader (world space), and Viewport (screen space). If the vertex data doesn't look right in any of these steps, you should know where to start debugging.
   *Special note: If you're creating geometries on the graphics card within your shader, you won't see much of value in the pre-vertex shader.
-The debugger includes an shader assembly language debugger. It's nice to have but not very useful.
-The shader compiler will remove any code which isn't used in the final output of a vertex. This is extra annoying when you're trying to set values to a variable and debug them.

Model Debugging:

The same principles from the primitive rendering apply, except you have to verify that you've correctly loaded the model data into memory and are calling the right method to render a model.

One handy tip which may help you for your project: Write down each step it takes to add and render a new model within your project (ie, your projects content creation pipeline & workflow). It's easy to accidentally skip a step as you're creating new assets and end up wasting time trying to isolate the problem to that missed step. An ounce of prevention is worth a pound of cure, right?

#5134613 C# Indexer overloading?

Posted by slayemin on 25 February 2014 - 07:41 PM

I'm trying to create a class which has three dictionaries, each of which store different types of objects. I want to be able to access those dictionary items by using the dictionary key via an indexer.

/// <summary>
/// This is the asset database for all assets being used in the game.
/// </summary>
public class AssetDB
	Dictionary<string, Texture2D> m_textureDB;
	Dictionary<string, Model> m_modelDB;
	Dictionary<string, Effect> m_effectDB;

	public enum AssetType

	public AssetDB()
		m_textureDB = new Dictionary<string, Texture2D>();
		m_modelDB = new Dictionary<string, Model>();
		m_effectDB = new Dictionary<string, Effect>();

	public Texture2D this[string Name]      //ambiguous overload: differs only by return type!
		get { return m_textureDB[Name]; }
		set { m_textureDB.Add(Name, value); }

	public Model this[string Name]      //ambiguous overload: differs only by return type!
		get { return m_modelDB[Name]; }
		set { m_modelDB.Add(Name, value); }

	public Effect this[string Name]      //ambiguous overload: differs only by return type!
		get { return m_effectDB[Name]; }
		set { m_effectDB.Add(Name, value); }

	public void Clear()

Ideally, I'd like to interact with this class by doing something like this:


AssetDB m_db = new AssetDB();

m_db[Texture, "Grass"] = Content.Load<Texture2d>("Textures\\Grass");
m_db[Model, "Sphere"] = Content.Load<Model>("Models\\Sphere");

But, I don't know how to overload my indexer to do this correctly.

#5134577 Voxel terrain move

Posted by slayemin on 25 February 2014 - 04:48 PM

Let's think about this.


Let's say you've got millions of voxels in your terrain environment. You realize that there's a performance issue with rendering them at a high level of detail, so you want to render the nearby voxels at a lower level of detail if they're far away from the camera. This is the gist of what we're trying to do. But we don't want to spend a huge amount of CPU time trying to figure out which level of detail we want to use for a voxel either! In the most brute force method for the algorithm, we'd calculate the distance from the camera position to the voxel position. If that distance exceeds a set threshold, you drop the LOD by one. However, if we used the brute force method, we'd be calculating the distance between the camera and all million voxels (which comes with an expensive square root) and any performance gains in switching to another LOD would be much lower. So, we want to keep the same idea for calculating distances with voxels, but try to use fewer distance computations.

Here's where Octreescome in handy, and that's why you are reading about them. You can divide your terrain into chunks of blocks, say, 16x16x16 (use powers of 2 if you can). Each chunk can be inserted into your octree. When you're going to calculate the camera distance, you could instead calculate the camera distance to the octree bounding regions and set the LOD of all contained objects to a preset value. This would help you reduce the number of distance checks, and would also scale very well with any number of game world objects (I assume you're going to have more than just terrain).

I don't know if its relevant to you or not, but there was a white paper a while back on rendering terrain using geomipmaps. The author had an interesting technique for deciding when to switch to a different LOD which was not based on camera distance, but rather on how much the terrain would pop if you transitioned it to a lower LOD (2.3.1). He basically measures the vertical change in "pop" between one LOD and another in screen space according to the camera viewing angle, and then switches the terrain LOD if the pop is below some acceptable threshold (ie, 2 pixels). I implemented a variation of this myself and I like the results.


Here is my code for that:

/// <summary>
/// This calculates the maximum amount of vertical error when switching from one level of detail to another.
/// </summary>
private void CalcError()
	for (int LoD = 0; LoD < 4; LoD++)
		int stepSize = (int)Math.Pow(2, LoD + 1);
		float d_max = 0;

		//traverse horizontally
		for (int z = 0; z < m_settings.TileCount; z++)
			for (int x = 0; x < m_settings.TileCount; x += stepSize)
				Vector3 p0 = m_verts[x + (z * (m_settings.TileCount + 1))].Position;
				Vector3 p1 = m_verts[(x + (stepSize / 2)) + (z * (m_settings.TileCount + 1))].Position;
				Vector3 p2 = m_verts[x + stepSize + (z * (m_settings.TileCount + 1))].Position;

				Vector3 P = (p0 + p2) / 2.0f;        //the phantom position of p1 is just the average of P0 and P2
				float d = (p1 - P).Length();         //find the error difference between p1 and the phantom point
				if (d > d_max)
					d_max = d;
		m_max_dy[LoD + 1] = d_max;            //this is the most error we'd get if we switched from LODX -> LODX+1

On screen and in the game, what ends up happening is that we try to use the lowest possible LOD we can get away with without getting unwanted popping artifacts. So, if you're pointing your camera straight down and you're viewing the terrain from above, the very bottom terrain chunk will be at a very low LOD, but you can't really tell since the vertical portions are not really coming into play based on your viewing angle.

#5133036 Game engine

Posted by slayemin on 20 February 2014 - 02:35 PM

Short answer: Yes.

A game engine can use any Application Programmer Interface (API), such as DirectX or OpenGL (these aren't the only available APIs though). All game engines are made using programming languages.

Game engine programming is very different from game design however. A game designer uses a much higher level of abstraction to create games. They're more interested in the game design itself, the game mechanics, the aesthetics, and any back end game systems. Game engines are more focused on building the foundation/workspace for these higher level game design decisions to be created within. That usually involves creating the backend infrastructure for drawing things, physics, collision detection, particle effects, sounds, asset management, etc.

#5129159 Rendering point sprites / textured quads purely on GPU using HLSL

Posted by slayemin on 05 February 2014 - 04:30 PM

D3D9 does support instancing.  You could make one vertex buffer that contains a single quad (either 4 verts + index buffer, or 6 verts), and then store the per-instance billboard information in another vertex buffer.


This is exactly what I'm trying to do. Thanks for giving me the direction I was looking for.

In case anyone else finds this thread in the future and wants to know how to instance a bunch of similar geometries on the graphics card, here are two articles which perfectly describes the technique: 
XNA 3.1: http://www.float4x4.net/index.php/2010/06/hardware-instancing-in-xna/

XNA 4.0: http://www.float4x4.net/index.php/2011/07/hardware-instancing-for-pc-in-xna-4-with-textures/


Blog post by Shawn Hargreaves: http://blogs.msdn.com/b/shawnhar/archive/2010/06/17/drawinstancedprimitives-in-xna-game-studio-4-0.aspx

#5105820 Trying to simulate the flamethrower from GTA2

Posted by slayemin on 30 October 2013 - 05:56 PM

You can do this by simply using a bunch of fire particles. Your player will have a particle emitter positioned a set distance away from the center of the player and based on the players orientation. There are a few things you'll want to think about when setting the properties for your emitter:
-The frequency/rate of particle emission

-The initial velocity of a particle (which should also factor in the current velocity of the emitter)

-The initial size of a particle

-etc. etc.


For your flame thrower, all you'd really have to do is create a flame particle every fraction of a second, give it an initial position and an initial velocity, and then let your particle system update all of the particles in its list of active particles. Once a particle has been emitted from the emitter, its position and velocity should be completely independent of the emitter.

It looks like the GTA2 flame thrower is shooting out flame particles at a high rate and the lifespan of each particle is quite short. I predict that if your character is initially stationary and shooting flames, then the distance of the farthest flame from the player should be at its standard length (let's call it 1 Flame Length). I also predict that if your character suddenly starts moving towards the direction of flames, the flame length should shorten for a brief period since the player is moving with the slower moving flame particles and the flame length may be 0.8 units of flame length until the first flame emitted with the player velocity reaches its lifespan. If the player moves backwards, then we should expect the flame length to extend (1.2 flame length?) for a brief moment (and we may even expect to see gaps between particles if the emitter frequency is too low).

Anyways, here are a few things you can try:
-You don't need to store the angle on a flame particle. Give it a velocity instead. Velocity is a 2D or 3D vector. The orientation of the vector contains the direction of movement. The magnitude of the velocity vector contains the speed. Every frame, all you have to do is add the velocity vector to the position coordinate.
-If you use spherical fire sprites, you don't have to rotate your flames. If you simply must use non-spherical sprites, you can still get the direction of travel by normalizing your velocity vector and using those normalized values to rotate your sprite. A normalized 2D velocity vector already contains [Cos(theta), Sin(theta)]
-I don't know if you're doing it already, but I'd recommend using a memory pool for your particles (you don't want to allocate and deallocate memory for each particle each time its created and dies).
-If you're feeling crazy, you can also store an "Acceleration" value in a particle. If you remember your calculus and physics, velocity is the change in position over time. Accelleration is the change in velocity over time. (And surge is the change in accelleration over time, such as a gas pedal on a car). For each frame and for every active particle, you'd do: Velocity += Accelleration; Position += Velocity; If you set a small negative number to the accelleration, your particle will gradually slow down as it travels.

#5001695 Which game engine.. an indie but experienced programmer?

Posted by slayemin on 16 November 2012 - 10:54 PM

Unity3D is my first recommendation. You can get something up and running pretty fast. Admitedly though, I'm not very experienced with Unity at the moment. I've spent about a week on it. I like that it supports C#, but the built in IDE just doesn't compare to Visual Studio.

If Unity3D isn't suitable, you could use XNA. With your time budget, I think you could reach your goal without too much pain. Though, you'd have to recreate engine features, like particle engines, which come out of the box with Unity and is quite powerful.

#4999452 Final Year Project

Posted by slayemin on 09 November 2012 - 04:12 PM

Considering your C++ background, I'd recommend picking up C# and going with XNA. You can have a simple game up and running in hours or a day (simple, like asteroids).

The net coding isn't too hard in C#, but it will take some planning and effort. Here are some questions to think about:
-What data do you want to send to other players? How are you going to organize it? (you're going to have to serialize and deserialize data off of a "stream")
-What happens if a player loses their connection?
-What if there is a data mismatch and your game states get out of synch?
-Are you going to use a peer-to-peer model or a client-server model? If client-server, how do you decide who is the server?

These are areas you shouldn't waste your time on:
-Shrinking the size of a data packet (you're on a LAN)
-Network and application security (This is a school project, not a public release)
-data validation (Use TCP/IP and just trust your clients)

My recommendation is to get something super simple up and running first. Then build the networking component, then make the game more complicated.
Example: Get two player controlled tanks to sit on flat terrain, each taking turns to shoot each other. Keep it simple. It should take a couple hours. Then, write the net code to get the games to connect and talk on a LAN, and then sharing game state data. You've now got a basic, networked, multiplayer game! Now, you can add features, update the network protocol, and see the changes in game play.

As far as network coding is concerned, most of the answers you're looking for a a google search away...
the basic outline is something like this:
1. Create a thread which listens for connections on a port
2. When a connection comes in, handle it and then wait for more connections
3. When a connection is established, think of both ends as reading and writing data from a file stream which can change under your feet. Before you write data out to the network stream, it has to be converted into an array of bytes (serialization). What those bytes mean is up to you to decide. When you get a stream of bytes, its up to you to decode and decipher their meaning as well. So, the common practice is to create a "header" which contains something to identify the type of data being sent, the byte length of the data, and then the data itself.
Trivial example:
suppose I have a "Mage" class like so:

class Mage
unsigned int ID = 1;
string Name;
If I want to send an instance of the Mage who has the name "Tim" to another computer, my serialized data would be:
(but all the data would be converted to bytes)

The receiving computer will get an array of bytes containing this data. It reads the first byte, which is the ID. Then it says, "Aha, I know that I'm going to be deserializing a Mage object! The next item will be the length!", and then it reads off the value "3". Then it says, "Aha! The next value will be the data and its length will be three bytes! This data is going to be the name of the mage, so I should read it as a string!" and then it reads the next three bytes and converts them into characters which form the name "Tim".

You can also add extra metadata to handle the basic C.R.U.D. principles of all your objects (create, read, update, delete). You're also going to have to decide how you want to handle weird shit, like you sent a "Create" command for an object, followed by an "Update" command, but the "Update" command gets there first, so its trying to update an object which doesn't exist yet (which suggests adding frame numbers to the packet meta data and storing actions in a queue, but that may be getting unnecessarily complicated). It's great fun :)

#4997628 OcTree For Randomly Generated Terrain Frustum Culling

Posted by slayemin on 05 November 2012 - 11:00 AM

Okay, let's back up a bit... what problem are you trying to solve, and why did you choose frustum culling as the solution to this problem?

#4996845 AI in RPG game

Posted by slayemin on 03 November 2012 - 06:52 AM

A lot of turn based strategy games can make good use of a minimax algorithm. This is good for deciding which action is the most effective one before executing it. Do you run away and heal your character? Or do you close in with the enemy and try to deal more damage? With the minimax tree, you can play out all the possible scenarios and responses to see which one is best. So, if the enemy is a warrior and you run away and heal, the warrior will have to chase you to attack the next turn. But, you can run out of his range, so this is a "good" move. If the enemy is a wizard and you run away and heal, he'll just cast a ranged fireball at you, dealing more damage than you'd heal. So, its more beneficial to just attack the wizard and do what damage you can.
If you build your game model correctly, you don't have to write pages of complicated If statements to capture this type of reasoning. Just give your minimax tree a list of the possible actions your character can do each turn, the possible responses, counter-responses, etc. and let the algorithm calculate the best move based on the scenario.
For complicated games like Chess, where there are dozens of possible moves each turn, your tree is going to get a lot of breadth. Since the essence of chess is thinking further ahead than your opponenet (and not making mistakes), breadth * depth will start to great very large trees. This will create some memory and processing limitations as the tree grows large. So, typically the tree depth will be limited to a set point. If the player chooses the easy difficulty setting, then the AI may only maintain a depth of 5 tree. If they choose medium, the AI will maintain depth 10 tree. If they choose hard, they'll get a depth 15 tree. The harder the AI is, the more time it will need to spend building deep and wide trees and evaluating the best branches to traverse. If you want to go insane, build a super computer with massive banks of CPU's and RAM and let the depth go really high, like 40. You'll get something like Deep Blue which can take on the worlds greatest chess players.
One technique you can use to save yourself some processing and RAM is to prune the tree a bit. If there is an obviously bad move (such as putting yourself into checkmate or losing your queen), you can stop traversing any subsequent moves down the tree. This is what people are really good at. The techniques for trimming and pruning your decision tree is where the specialized AI programmers differentiate themselves from the unspecialized programmers (I'm just a unspecialized programmer).

If your game is running in real time, you *may* be able to still get away with using this. If every ability has a cooldown time before it can be executed again, you can create a turn which is a set timespan in which actions can be performed, ie, you can swing your sword three times every five seconds, so a standard turn lasts for five seconds. Scripting complex if/else statements consisting of actions may also be a good way to go.

#4996294 If l want to draw a circle.How to do it?

Posted by slayemin on 01 November 2012 - 01:58 PM

Every point on a circle can be calculated by:

x = radius * cos(theta);
y = radius * sin(theta);

Where, theta is all values between 0 and 2PI, and radius is greater than zero.

So, to draw a circle, you can could either plot a bunch of pixels to the screen at the X,Y coordinates as you loop through every value of theta...
or you could draw line segments between each of the X/Y value pairs for all values of theta.

#4996270 Resolution ( full screen vs windowed )

Posted by slayemin on 01 November 2012 - 12:59 PM

I've experienced the mouse problem. What I do is place a graphic on the screen which represents the mouse cursor. Then, I update the mouse cursor position based off of the change in the mouse position relative to the last frame. I think there's even a function which will give you the dx, dy for mouse. Then, all you have to do is make sure that the mouse cursor is constrained to the screen dimensions. The part you're going to have to decide on is how you're going to handle the right edge of the screen -- do you let the mouse hot spot move all the way to the edge of the screen and clip a part of the graphic, or do you always display the entire cursor icon? What if you have a GUI element, like a scroll bar, on the far edge of the screen?

As for the UI offsets, it sounds like you're not finding the edges of the client rect correctly. You're going to have to step into the debugger to see exactly what's happening with your GUI element positioning.

#4995905 Looking for a code/desgin review of continous map implemention

Posted by slayemin on 31 October 2012 - 12:19 PM

Okay, I think I understand.

I didn't see this mentioned in your post or in your code, so I'll bring it up. If the player is on the edge of the map, how do you handle it? If you have a grid of 100x100 tiles, the view is always centered on the player, and the player is located at (0,0) (top left corner), what happens? Do you keep the player centered or does the player move to the top left corner of the screen?

(x).ToString() + "_" + (y).ToString();
You don't need to surround your variables with parentheses.

I think your whole approach is flawed, and I'm not saying that to be mean. Here is what I'd change:
1. Use a camera.
2. Store your tiles in a 2D array.
3. Use a quad tree for collision detection.
4. Use "layers" in your map (terrain, static terrain objects, creatures & items, etc).
5. Break your map class up into more objects.

Use a camera:
What you want to do is to create a camera viewing rectangle. If map objects are within the viewing rectangle of the camera, then they are rendered. If you treat your view as a viewing rectangle, you can do a lot more with it (panning, zooming in and out, centering on an object, tweening between points, etc). Rather than rendering everything relative to the character position, you render everything relative to the center position of the camera and, for the most part, keep the camera centered on the player. This makes it much easier to handle the map-edge cases. You could also do interesting features, where if your character is moving in a particular direction very quickly, you can adjust the veiwing area of the camera to show more of the world space in front of the character so that they have more time to react.

Store your tiles in a 2D array:
You can either store the tile objects directly, or just store an index in a 2D array. How you store your tiles should be independent of how you're moving on the tiles and viewing the tiles. Your character movement can be simplified into an X & Y position, and handled with requests to the map manager. Character tells the map "I am at this position. I want to move left one space", and the map manager reads the map array and says "Okay, that's a legal move! you can set your position there." or "Nope, that can't be done. There's a tree there!" or "Nope, you're on the edge of the map and you can't go left any further!"

Use a quad tree for collision detection:
Once I understood the concept, it didn't take me more than an hour or two to get a quad tree datastructure up and running. The idea is to put your spatial objects into the smallest box which will contain them, and keep dividing the box into fourths until its empty. Then, when you're doing collision detection, you only need to compare the objects in the largest box against all of its child cells. This changes your collision checks from O(N*N) to O(log N) (best case). The tiles which are being viewed would be all the tiles which collide with the camera viewing rectangle (don't necessarily need a quad tree for camera rect, you can also do a rect.Contains() call against all tiles in the game model which is more computationally expensive but works)

Use layers in your map:
Terrain is the first, bottom layer. This tends to make for boring maps because they're plain. So, create another layer and add trees, flowers, rocks, and any other terrain objects. These static terrain objects are non-moving, so this simplifies collision detection a bit (you're not checking if a tree is colliding with another tree every frame). Then, you'll also have another layer for moving objects (monsters, player characters, bullets, pick ups, etc). These objects may move every frame, so they can collide with other objects in their layer or objects in the static objects layer. By layering your map, you can be a bit more flexible. A tree can sit on a dirt tile or a grass tile, instead of creating a tree-dirt tile and tree-grass tile.

Break your map class up into more objects:
You're currently trying to do too much "stuff" in one class. Break it up a bit. You've currently got a class which contains map metadata, tile information, character information, character movement logic, screen resolution logic, and resource loading logic all in ONE class. This makes your class design VERY rigid and all of your object interactions are hardcoded. This makes your class have 430 lines of code. You want all of your objects to be as decoupled as possible and interacting with each other via class method calls. I like to use the model view controller design pattern. The model doesn't know about screen resolutions, it only cares about maintaining the game state and game logic, and updating it. The view doesn't care about the game logic, it only cares about correctly rendering the game state to the current rendering settings (resolution, anti-aliasing, shadows, etc). The controller doesn't care about rendering very much (except for getting its controls rendered, such as buttons and drop down menus), it only cares about interacting with the game model.
Some people like to break it out even further and add a data layer to handle data read/writes to and from a file or database. I generally include that in my game model objects.
So, I'd create at least the following classes:
-Player (inherits from character)
-Monster (inherits from character)
The map class would contain one or more 2D arrays of tiles, any meta data about the map (like map name, map size, etc), and methods for loading and saving to disk.
A tile class would contain tile specific information, such as the tile texture, tile dimensions, tile type, movement point costs, etc.
The character class would be an abstract game actor class which contains generic data about a character (hitpoints, name, position, dimensions, etc)
A player class would mostly have UI and controller specific methods
The monster class would be an extension of the character class, maybe with some added AI scripts to control it and do monster specific logic.
I like to keep a global class of loaded art resources (and call it a texture database, or TextureDB for short). Whenever I create a new object, I set its texture to point to one of those stored art assets. By doing this, I can centralize all of my resource loading into one object. Then, all I have to worry about is making sure that the TextureDB has all of the correct art assets loaded up. I can also load art assets into the TextureDB by reading a file for a list of needed art resources (art manifest), so if I load a game level, the level data would contain a list of all the art resources it uses. The textureDB would load those assets into memory, and off we go! :D

Warning: general hand waving to follow:

As for your rendering code, all you should be doing in the draw function is calling each object and telling it to render itself according to its current state. So, if you have a map object, your render code should be this:

Since the map contains a list of tiles which will know how to render themselves, it'll do the following:
//you'd also do a foreach for each layer, so you render terrain first, followed by static objects layer from top to bottom, followed by moving objects layer, etc.
foreach(Tile t in TileList)
	 t.draw(spriteBatch, position);

To move a character on a map, you'd make a request call to the map manager, something like this:
if(KeyboardInput == MoveLeft)
MyCharacter.Position = Map.MoveTo(MyCharacter.Position, new Vector2(-1,0));

And the map manager would get the request and handle it something like this:
public Vector2 MoveTo(Vector2 Pos, Vector2 Dir)
	 Vector2 RequestedTile = new Vector2(Pos.X + Dir.X, Pos.Y + Dir.Y);
	 if(Tile[RequestedTile.X][RequestedTile.Y].isPassable() and not Tile[RequestedTile.X][RequestedTile.Y].isOccupied() and blah blah blah conditions)
		  return new Vector(RequestedTile);
		  return Pos;

#4994385 Review of my code

Posted by slayemin on 27 October 2012 - 04:19 AM

I find the Model-View-Controller framework to be a helpful framework to keep in mind and to design to.

Your game is the "model". This would contain all of your data structures, game objects, game states, the state of your game objects, process the next frame, turn, etc. It's the guts of your application. It doesn't care at all about rendering stuff to the screen or collecting input to change the model*. It's very abstract.

Your "view" has the sole focus of representing the state of the "model" to the user. It doesn't do game logic! I like to think of it as the artistic manifestation of your model. Since it's "artistic", that means that you could interchange one view with another to get a totally different view of the same data. Real world example: I've got a database driven application. The model is the data and how it all interacts. The view can be rendered as either a windows application or a webpage. I wouldn't have to change any code in the model because its completely unconcerned about rendering.

The "controller" is how the user interacts with your model. Sometimes, it's intertwined closely with the view (use the mouse to click on a button!), but its not necessary (press "F1" key to fire torpedos!). A controller will send a command (better to think of it as a request) to the model and the model will decide if it wants to honor it and change its state accordingly ("okay! I've created a torpedo!" or "nope, you have no torpedos left or its not ready to fire again!"). Again, we are NOT putting game logic into the controller. We're using it as a way to interact with the model which contains the logic to do the requested action.

So, just by looking at your code, I can see that you have a single class which is concerned with rendering. This would fit within a "view" portion of the MVC framework. It's not enough to tell you anything about whether or not your classes are well architected because we can't see how they're interacting with each other.
One slightly worrisome thing I'm seeing though is your liberal use of public access for internal class variables. Do you do this with your other classes? It may not be a big deal for small projects, but you will start to run into problems with larger projects. I like to assume that I'm writing my classes to be used by the biggest idiot in the world (me). If there is a way someone (me) can completely screw it up, then it's only a matter of time before it happens (sleep deprivation, forgetfulness, laziness, sloppiness, etc). When that screw up happens, I have to waste time debugging to isolate the source of the problem ("OH! I'm getting errors because this completely unrelated class thinks it should be allowed to come into my class and muck around with its variables?! He wants to divide by zero?!). So, when you're designing your class, think of yourself as a miser who will only give access to your class if and only if there is a good reason to, and that access will be on your terms rather than the users terms. If something is public, it's free game for a legion of monkeys to use. Would you like a legion of monkeys twiddling with your class methods or class variables?

#4994170 Do's and Dont's of Recruiting a Volunteer Team?

Posted by slayemin on 26 October 2012 - 09:28 AM

From my experience, the greatest obstacle for your team will be motivation. You can pretty much plot the average team motivation level with the function: f(x) = 1/x, x > 0;
The y-axis is the motivation level and the x-axis is time. As you can see from the graph, it starts pretty high but it quickly dips and starts to taper off. Your people will have a hidden parameter which they don't know and you don't know, and it is their minimum required motivation to continue with the project.

if(currentMotivation <= randYVal)

There's also this weird phenomena where as a person's current motivation approaches their minimum motivation level, the amount of work they do decreases as well. The symptoms of this are flakeing out, laziness, lachrymose, etc.

As the project initiator (and presumed manager), the good news is that you've got control of this!! Your goal is to keep team morale as high as possible and lengthen the time it takes for it to taper off to project failure. Ideally, you'll have a project which has a completion time well before motivation failure. You can control when the project gets completed and when motivation failure occurs by ensuring that the size and scope of the project is attainable, by making significant progress on the project, by keeping personality conflicts to a minimum, by paying team members, by keeping poisonous personalities off the team, by setting a high standard and holding people accountable to it, and being realistic about current circumstances at all times. Eventually, the initial appeal and zest for the project fades away and everyone has to put their nose to the grind stone to complete it. It stops being "fun" and becomes "work", so when this happens, it becomes the true test of your project management skills, team cohesion, and the infrastructure you've put in place.

Ultimately, you need to take a realistic assessment of your team and its capabilities and pursue an achievable project which can be completed before morale failure occurs.