Jump to content
  • Advertisement
Sign in to follow this  

2D - "Tileset" index to sub-rectangular position calculation

This topic is 2199 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hey forum of GameDev.net!
I'm stopping by for a quick question regarding how to calculate the sub-rectangle position for a tileset?
Say I have a tileset of 512x512 ( 256 worth of 32x32 tiles ) and that in my "map class" I have an array of integers that defines the array index of each tile in each cell.

Having a 1D Tileset is quite easy to work with, it's basically: tile_index * tile_width to get what the part of the whole tileset I should display. Once moving into a tileset of 2D I'm not sure how to go on about it.

I have found this snippet of code that works ( I have integrated it )
( Pseudo-Code )

int frame_col = tile_index % ( texture_width / tile_width );
int frame_row = tile_index / ( texture_width / tile_width );
subRect.setPos( frame_col * tile_width, frame_row * tile_height);

Could someone explain this to me a bit better, why does it work? and possible ( mostly because I'm very interested ) present another way to calculate it?

Share this post

Link to post
Share on other sites
You can index a linear array as if it were multidimensional by using a formula like x + y * width. i.e. Skip y rows of width elements, then x elements preceding the one you want on the row you want. Your code just reverses this. Where width is the number of tiles in the texture, and x < width: integer division truncates so (x + y * width) / width = y; % is the modulo operation, which effectively gives you the remainer: (x + y * width) % width = x.

Share this post

Link to post
Share on other sites
I'm not sure I follow, could someone please explain the concept a bit further? I feel that implementing a 2D tileset is somewhat complex? ( Not complex but I'm not sure how "new" people would approach this without that snippet of code ).

I'm having a hard time understanding the math behind it maybe?

Share this post

Link to post
Share on other sites
It's not complex - I'm not very good with math, but I find it easy once I understood it.

To convert a TileX and TileY to an 'index' into your array, you use this:
int index = (TileY * TilesetWidth) + TileX;

Let's pretend your tileset is 5 tiles wide and 7 tiles high, and you want to access the 2nd tile on the third row:



To reverse it (to go from the index to X,Y), we divide instead of multiply:
int TileX = (index % TilesetWidth);
int TileY = (index / TilesetWidth);

The numbers I'm using (x and y) are in tiles, not pixels. If you want the pixel location of a tile within your tileset, you have to multiply the x,y by the width and height of the tile.

int pixelX = (TileX * TileWidth);
int pixelY = (TileY * TileHeight);

Share this post

Link to post
Share on other sites
To further confuse the second image with more scribblings:


The reason we are starting to count at zero is because we are saying "How many cells beyond the first cell", If we are already on the first cell, then we are 0 cells beyond the first cell, so the first cell is cell 0.
This is why we start at zero for things like positions, but we don't start at zero for the widths and the heights. We already are at the first cell, and we need to know how many cells to move to go to where we want. When we actually want to first cell, we move 'zero' spaces. Edited by Servant of the Lord

Share this post

Link to post
Share on other sites

int TileX = (index % TilesetWidth);
int TileY = (index / TilesetWidth);

This line, I'm a bit confused, I get that it works, just the %-operator confuses me, how am I supposed to visualize this to myself how it works inside my head?

Also for a system that begins at 0, the formula ( Y * WIDTH ) + X works ( And I can see WHY it works ) but how would it work ( and bare with me since this is a bit important for me to actually understand why it works for the programming-0-first-style ) when everything starts at 1 and not 0?

The formula ( Y * WIDTH ) * X will no longer work for that kind of system, right? ( 0-first = 1,2 and 1-first = 2, 3 which will result in the 1-first to have a single index of 17? ( 3 * 5 ) + 2 = 17 )

Share this post

Link to post
Share on other sites
If for you, everything starts at one, then just subtract 1 before mutliplying.

If x and y start at 1 instead of zero, then you use:
int index = ((TileY-1) * TilesetWidth) + (TileX - 1);

The x and y we are wanting is, "Assuming you start at the first cell, how many steps do you need to move to get to where you want?".

If you want to think of the first cell as cell 1 instead of cell 0, you can think of it like this:
"I'm at cell 1, and I want to be at cell 4, so the difference between cell 1 and 4 is (4 - 1) which is 3, so I need to move 3 steps to get to cell 4"

The % operator is modulus. Think of it like this:
int TileY = (index / TilesetWidth); //Divide index by the width of the tileset. The result is Y, but save the remainder of the division!
int TileX = remainder;

If it helps you, you could mentally calculate it like this:
int TileY = (index / TilesetWidth);
int TileX = (index - TileY); //Whatever is left from the index, after TileY was calculated.

In the examples in the earlier posts, if the index is 11, we divide by the TilesetWidth (which is 5), so Y = (11 / 5) which is 2. But it's not an even division! There is still a remainder of 1, and that remainder goes to X. Edited by Servant of the Lord

Share this post

Link to post
Share on other sites
It's the difference between the place of origin (the cell), and the place you want to be (Third row, second column).

The difference between the second column and the first column is one column (2 - 1 = 1), so you need to move one column.
The difference between the third row and the first row is two rows (3 - 1 = 2), so you need to move two rows.

The reason we start counting at zero alot of times in programming, is because we are always at some location in memory, wanting to move to another location in memory. If the place where we are at is also the place we want to be, then we just move "zero" places. Once you understand this, so you know why it makes sense, then you can just keep that information in the back of your head, and take the much much easier mental shortcut of saying, "We start counting at zero", and cut out the "we're here, we want to be there, the difference is thus.", because the end result always just to subtract one from the "there" location anyway. We work with relative positions, not absolute positions, so our "here" is always 1, so we can just shortcut by always subtracting 1 from our "there".

We always work with relative positions instead of absolute positions because we never can be sure about what actual physical location of memory we're at. Our memory address might be 0x45FF34A4 at one run, or 0x33C63A3D the next run - but it doesn't matter, because we know we have a tileset at [whatever location in memory], and whatever that location is, it doesn't effect us, because we know that 4 steps beyond that location is the specific tile we want. So, (absolute location of memory) + 4 steps = Our tile.
Instead of complicating math unnecessarily and saying "0x45FF34A4 + 4", we move the problem domain to be relative to zero (for ease of mental problem solving), and say, "0 + 4", and then add 0x45FF34A4 to the final result. (Note that '4' is moving '4' steps to get to the 5th tile, because the first tile is located at location 0x45FF34A4 itself, but since we moved the problem domain to be relative to zero, then the first tile is located at position zero. Unnecessarily large numbers that are our location in memory can be shortcutted out of our math since it's irrelevant to our final result.

That was really confusing. If I'm doing a crappy job of explaining this, just let me know. If someone more skilled in explanations is reading this, you are most welcome to step in any time you want to undo any damage I may be causing! smile.png

If you are just born, you are in your first year of life. You aren't 1 year old (1 year old = you are in your second year of life).
If I'm 5 years old, that means I've already moved 5 years from my place of origin (my birth at zero years old). It means I am now in my sixth year of life.
If it is 12:05 am, you are 5 minutes into the first hour of the day. The first hour is hour 'zero', it hasn't yet reached hour '1' which is the second hour of the day.

Taking the age thing further: If I was born in 2010, nobody stops and thinks that "Your age is now at time-location 2012 minus 2". They say, "You are now 2". Everyone understands that my birth was in 2010, so my "2" is relative to 2010. Even though I was born in 2010, that year doesn't tell anyone information that they want, but my age relative to that year is what is important.
It doesn't matter that the tileset starts at memory location 0x45FF34A4 in a piece of RAM somewhere. But the location of the tile in the tileset relative to the origin is the information we want. If we want the tile, we can just eliminate the '0x45FF34A4 ' information entirely, and work from a problem domain of 'zero' (memory location 0x00). Edited by Servant of the Lord

Share this post

Link to post
Share on other sites
More confusion!
[source lang="csharp"]int sy = ((tile_index - 1) / tileset_width);
int sx = ((tile_index - 1) - (sy * tileset_width)) * tile_width;
sy = sy * tile_height;[/source]

Tile index to source rect huh.png

Share this post

Link to post
Share on other sites
The code is trying to do two things at once, and instead of doing them in order, are mixing the two together in what looks like a poor programmer's attempt at "optimizing code" (and are instead obfuscating code, making it harder to maintain).

1) They are converting from a tile index, to the tile location in tiles.
2) They are converting from the tile location in tiles, to the tile location in pixels.
...But they are intermingling the two at one time, which is what is causes the confusion.

If you do things neatly, it might look like this:
//Step one: Go from index to tile location in tiles.
int tileX = (tileIndex % TilesetWidthInTiles);
int tileY = (tileIndex / TilesetWidthInTiles);

//Step two: Go from location in tiles, to location in pixels.
int tilePixelX = (tileX * TileWidth);
int tilePixelY = (tileY * TileHeight);

If you want to mix them together in one line that's also fine:
int tilePixelX = (tileIndex % TilesetWidthInTiles) * TileWidth;
int tilePixelY = (tileIndex / TilesetWidthInTiles) * TileHeight;

It's still broken into two logical steps (step 1: within the parenthesis, step 2: the multiplication), even if you have it on one line, and is easier to understand.

The other one intermingles the two steps, I'm not sure why, probably to save the cost of using the modulus operator or something. rolleyes.gif
But (since it's just a tiny snippet of code) it's really not as bad as I'm making it sound - I'm just an idealist when it comes to clean code. laugh.png
Though even in my own projects, clean code isn't always possible, it's still one of the top goals to shoot for (Much more important than running fast, but I digress).

Here's how it works:
[hr]We'll start by assigning some test values, to help us walk through it. It'll work for any sane values you choose, but for figuring out what a piece of code does, it's always good to pick some test values and walk through the code mentally in the same way the computer will walk through it.
int tile_index = 12;
int tileset_width = 5; //The tileset is 5 _tiles_ wide.
int tile_width = 32; //Our tiles are 32 _pixels_ wide and high.

Line one:
int sy = ((tile_index - 1) / tileset_width);
int sy = ((12 - 1) / 5);
int sy = ((11) / 5);
int sy = (2);

Line two:
int sx = ((tile_index - 1) - (sy * tileset_width)) * tile_width;
int sx = ((12 - 1) - (2 * 5)) * 32;
int sx = ((11) - (10)) * 32;
int sx = (1) * 32;
int sx = 32;

Line three:
sy = sy * tile_height;
sy = 2 * 32;
sy = 64;

sx = 32 pixels
sy = 64 pixels
Edited by Servant of the Lord

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!