Is there a faster alternative to using textures in XNA? - c#

I am writing a map editing program for a 2D game using XNA. To create a Texture2D for all of the tiles that a map requires takes too long.
Are there any alternatives to using textures for drawing with XNA?
I attempted to create just one texture per tile set instead of a texture for every tile in a tile set, but there is a limit to the size of textures and I could not fit all the tiles of a tile set into one texture.
Currently the program contains all the would-be textures in memory as Bitmap objects. Is there a way to simply draw a Bitmap object to the screen in XNA? I have searched but I cannot find any information on this. This approach would avoid having to create textures altogether, however any tinting or effects I would have to do to the bitmap directly.

Is there any reason you haven't considered loading the image one time and then passing in x and y offset coordinates to the pixel shader?
You would basically set the C# up like this:
myGraphicsDevice.Textures[0] = whateverYourGiantMapTextureIs;
foreach(MapChunk chunk in mapChunks) {
myShader.Effect.Parameters["xOffset"] = chunk.XOffset;
myShader.Effect.Parameters["yOffset"] = chunk.YOffset;
myGraphicsDevice.DrawIndexedPrimitives( your chunk drawing code here );
}
And then the shader code like this:
float4x4 World;
float4x4 View;
float4x4 Projection;
float xOffset;
float yOffset;
sampler TextureSampler;
struct VS_INPUT {
float4 Position : POSITION0;
float4 Color : COLOR0;
};
VS_INPUT Transform(VS_INPUT Input) {
VS_INPUT Output;
float4 worldPosition = mul(Input.Position, World);
float4 viewPosition = mul(worldPosition, View);
Output.Position = mul(viewPosition, Projection);
Output.Color = Input.Color;
return Output;
}
float4 ColorTexture(VS_INPUT Input) : COLOR0{
return Input.Color.rgba * tex2D(TextureSampler, float2(xOffset, yOffset));
}
technique TransformColorTexture {
pass P0 {
VertexShader = compile vs_2_0 Transform();
PixelShader = compile ps_2_0 ColorTexture();
}
}
The shader code might need some fitting into your existing code but otherwise it should do the trick.

Using one texture per tile is not very efficient. Especially since it means you cannot do batching (in any real sense).
If you NEED to have them as separate textures in your content-project for some reason (easier to edit one tile, etc), you can quite easily compile them into tilemaps after loading.
How you do this is basicly:
1: Load a number of tiles (lets say 40 32*32 tiles for now)
2: Figure out a nice texture-size for the tilemap:
square root of 40 is 6.something, so we round up to 7. 7*32 is 224, which is nice, but 256 is nicer, so lets make the texture 256x256. (you can make code that figures out this on the fly)
3: Create a Rendertarget2D which is the desired size.
4: Activate rendertarget.
5: Render tiles on rendertarget:
int x, y = 0;
foreach (var tile in allTiles)
{
RenderTile(tile, x*32, y*32);
x++;
if (x >= 8)
{
x = 0;
y++;
}
}
To betch-render you have a vertex-buffer with 4 * 40 vertices. each set of 4 has a value indicating index of the quad it belongs to (0,1,2,etc...). In your shader you have an array of matrixes[40] for position of the tiles, as well as an array of tileIndex (int[40]) for knowing which tile to render from the tilemap.
I'm sorry, but I don't have time to write all the shader-code right now :s
An other trick I have used in our games is pre-rendering the level onto large tiles (640x360), which reduces the number of draw-calls by a great deal, especially when dealing with 5+ layers of tiles from different tilesets. Only thing is that it does not work with dynamic tiles (animated tiles, etc), but you can mark those and render them normally if you want...

Since you need to use a custom image format, if you want (for speed) you can attempt to write custom content pipeline importers and processors for XNA ( http://msdn.microsoft.com/en-us/library/bb447754.aspx ), but this may be overkill for what you need to do.
I see you want to design the GUI as easily as possible, even if these issues force you to use a language like C++ so you can use DirectX. In Visual C++ you should still be able to take advantage of visual Windows Forms layout if you are using Visual Studio.

Unfortunately, as far as I know, there is no way to directly draw a bitmap to the screen in XNA; it requires that everything is mapped to the Texture objects, which are by default buffered to the graphics card. It sounds like you're talking about a lot of tiles, though, if they won't all fit on the maximum allowed texture (I can't remember whether that was 1024 or 4096 square...) - have you tried having an unbuffered texture for speed purposes? Another alternative would be to lazy-load your tilesets into textures so the user didn't have to wait for them all to load - for an editor, using a bright pink fallback color is usually acceptable while it loads.
Also, is there anything inherently required to write your tool in XNA? Since it sounds like you're writing the tool separately from the game engine itself, you may find some very acceptable solutions in WPF, including drawing directly from BitmapSources and some utilities for your UI.

Assuming all the tiles that a map require existing images that are simply placing on a screen to lay out a tile map? Or are you making images in this map editor and want to save them out?
I read this, and your other post about textures - If they are all ready defined images that you want to use in your game couldnt you just include them in the content folder and reference them there? This allows XNA to compile the textures in the xnb format and you shouldn't have the problems you are explaining.
However if we are talking completely dynamic - or you are crafting one big image from the layout of the tiles (instead of doing something like a tile map) then I am not sure how to approach the issue.

If multiple tiles use the same texture, it will be enough to load it just once.
If the user includes textures in some file format, you could automatically convert it to a texture/image format which is faster for your needs.

Are you trying draw them all using a single thread of execution?
Try multi-threading your game. Threading in C# is quite easy and is supported by XNA.
Instead of looking at your screen as a whole, try splitting it into two (or more) portions. You may need to re-write the function you're using to Draw (I sure hope you didn't just dump everything directly in your Draw() method!!) to take in coordinates setting the boundaries of your draw regions.

Related

How to make my Monogame windows game compatible with every single screen type?

First of all, I posted this question here and not at game development because I just started my project and this question is not really about XNA or Monogame libraries.
So, i am trying to make my game compatible with every single screen type.
there are two aspects i need to pay attention to- ratio, and pixels size.
before i'm creating any graphics for my game, ill need to know the dimensions
of every single object in my game,(player,background, etc) and get the right dimensions to match the screen ratio, and change with it as well.
I searched the web looking for XNA/Monogame tutorials that show how to do that and i didn't find a single one. I tried basic fullscreen methods. but as you know, the object stand still and they wont move with the window. And as I mentioned before I need them to move and change size with the window to make my game compatible with every single screen type. (ratio and pixels(inch/cm))
I think the term you're looking for is resolution independence. I wrote a tutorial about it on my blog a while ago.
The way we do it in MonoGame.Extended is by scaling the entire sprite batch using a transformation matrix passed into the SpriteBatch.Begin method. We call them viewport adapters:
_spriteBatch.Begin(transformMatrix: _viewportAdapter.GetScaleMatrix());
What this does is transform everything rendered by a specified scale matrix.
The way it works is that you decide on what the virtual resoultion of your game and position everything relative to that. During the draw call you scale the graphics to match the actual resolution of your device.
For example, you might decide that your virtual resolution is 800x480 but you're rendering to an actual screen size of 1024x768 so the scale would be something like 1.28 x 1.6. Make sense? You can calculate a simple scale matrix like so:
var scaleX = (float)ActualWidth / VirtualWidth;
var scaleY = (float)ActualHeight / VirtualHeight;
var matrix = Matrix.CreateScale(scaleX, scaleY, 1.0f);
_spriteBatch.Begin(transformMatrix: matrix);
This will work as a basic approach. The only other thing you really need to know is that when you're dealing with actual screen coordinates, like the mouse position for example, you'll need to reverse the scaling back to your virtual resolution:
var invertedMatrix = Matrix.Invert(matrix);
virtualMousePosition = Vector2.Transform(new Vector2(x, y), invertedMatrix);
That's it for the basics. Of course, you can also get more sophisticated with letterboxing and pillar boxing approaches like I've described on my blog.

Remapping colours on textures dynamically in unity

I'm making a RTS game in Unity. In such games, players usually can determine the unit allegiance using the unit color markings. And I'm now trying to implement system, that will remap purple color on the unit owner's color.
One idea was to determine color that will be used as mask and then recoloured to any color. It could be done using some hue distribution function:
Solution 1
I used funtion based on max(). You can see the plot there.
hue = min(hue, pow(Math.abs(hue-MASK_HUE),8)*5000000+RESULT_HUE)
This solution has two big flaws:
Purple can't be used (I don't like it anyway)
Only full colours are applicable (no brown, black, white...)
What you see above is just my fiddling. The actual project would run on Unity engine in C#.
Solution 2
My friend proposed diferent approach: every image should use a map - either faded or just true/false array - to map where should the colours be applied. I didn't try this yet, as it's more complicated to test ad-hoc.
Altering textures in unity
It seems that texture for material can be easily altered in Unity, so the question is:
Q: How should I implement the dynamic texture coloring (generating) in Unity? Is any of my methods the good way? How should I produce the new textures, using what functions?
Rather than full code, I need information about what functions should I use. I hope other users will also profit from the general info.
To help you answering, I can guess the process will have 3 important parts:
Somehow get the texture of a model material (we know just the GameObject here)
If it hasn't been recolored already, use some algorithm to change the image properly. We'll need some pixel manipulation here
Apply the texture back to the model material
If you go the texture manipulation route, you'll need to make an additional copy of the texture stored in memory for each color, and this will increase the "loading" time of your scene. You can access the texture of a GameObject with renderer.material.mainTexture used on the GameObject that has the renderer component. Then you can use all sorts of pixel manipulation options such as SetPixel, or SetPixels to do it in batches for better performance.
There is, however, a third option that I would recommend. If you write/modify a custom shader, you can perform the color replacement at render time without significantly decreasing performance. This can be accomplished by adding a step where you convert your color output from RGB to HSV, change the Hue and Saturation, and then convert back to HSV.
By making the Hue and Saturation external parameters, you should be able to use a full range of colors including whatever you used for your marker color.
This post from the Unity forums should help with the hue shift shader.

Floor draw method in isometric engine

Im working on isometric 2D tile engin for RTS game. I have two ways how can I draw floor. One option is one big image (for example 8000px x 8000px have about 10MB) and second option is draw images tile by tile only in visibly area.
My questin is what is better (for performance)?
Performance-wise and memory-wise, a tiled approach is better.
Memory-wise: If you can use a single spritesheet to hold the textures of every tile you need to render, then the amount of memory used would decrease tremendously - as opposed to redefining textures for tiles you want to render more than once. Also, on every texture there is an attribute called "pitch". This attribute tells us how much more memory is being used than the image actually needs. What? Why would my program be doing this? Back in the good old days, when Ben Kenobi was still called Obi Wan Kenobi, textures took up the memory they were supposed to. But now, with hardware acceleration, the GPU adds some padding to your texture to make it align with boundaries that it can process faster. This is memory you can reduce with the use of a spritesheet.
From a performance standpoint: Whenever you draw a regular sprite to the screen, the graphics hardware requires three main pieces of information: 1) The texture you want to render from. 2) What part of that texture you want to render from. 3) Where on the screen you want to render to. Repeat for every object you want to render. With a spritesheet, it only passes data once - a big performance increase because passing data from the CPU to the GPU (and vice-versa) is really slow.
And I disagree with the two comments, actually. Making a change of this caliber would be difficult when your program is mature.

The most efficient method of drawing multiple quads in OpenGL

I've been producing this 2d tile-based game engine to be used in several projects.
I have a class called "ScreenObject" which is mainly composed of a
Dictionary<Point, Tile>
The Point key is to show where to render the Tile on the screen, and the Tile contains one or more textures to be drawn at that point. This ScreenObject is where the tiles will be modified, deleted, added, etc..
My original method of drawing the tiles in the testing I've done was to iterate through the ScreenObject and draw each quad at each location separately. From what I've read, this is a massive waste of resources. It wasn't horribly slow in the testing, but after I've completed the animation classes and effect classes, I'm sure it would be extremely slow.
And one last thing, if you wouldn't mind..
As I said before, the Tile class can contain multiple textures to be drawn at the Point location on the screen.
I recognize possibly two options for me here. Either add a quad at that location for each texture to be drawn, or, somehow.. use a multiple texture for the same quad (if it's possible). Even if each tile contained one texture only, that would be 64 quads to be drawn on the screen. Most of the tiles will contain 2-5 textures, so the number of total quads would increase dramatically with this method. Would it be feasible to add a quad for each new texture, or am I ignoring a better way to do this?
I'd suspect using a Dictionary would be slower than just using a straight array. If your world consists of 512x512 tiles then you allocate an array 512x512 (262144) in length. YTou can get any given tile in that array by using "array[x + (y * 512)]".
You know how many tiles there are so store an array where each either points to the tile at that position or has an index to the tile in a list (you will likely save memory this way as you can probably keep all your tiles in an array less than 65536, or maybe even 256, in size and thus store the index as a 16-bit.
You then find the area of your array you want to render. To do this optimally you want to avoid switching textures as much as possible. So first thing I'd check to see how big your tiles are I'd then try and combine as many of the texture into 1 big texture. Then set your UVs to sample a sub portion of this large texture. This way you should be able to limit the number of textures in use with a few big textures. Of course you will probably find that a given tile set (lets say rocky ground, for example) will use the same groups of textures. There may also be some blending across to grass somewhere so it may well be worth holding the grass textures in BOTH big texture to avoid doing so many texture swaps. ie sacrifice video memory for speed.
You then iterate over the visible portion of the array and draw all the tiles using texture 1 and then all tiles using texture 2 and so on.
I would recommend to use single VAO object composed from triangles + indices. Calculate position on client side and just update it on each frame (streaming).
Use texture atlas to store everything in single texture (to avoid switching states). You can use texture packer tool.
Render in one shot (if you have depth buffer enabled). Otherwise render first objects that opaque and then render everything that should be blended.

Displaying "broken" sprites?

I'm quite new to the world of 2D-Engines. I figured out how to load images and display those as sprites and stuff, but theres one question that bugs me.
For instance, when a "rocket" hits an object it will deal damage to it and leave a crater behind. I'd like to have the crater shown on that object. That would require "skipping" some of the pixels of that image when rendering, doesn't it?
My question is, how would you do such a thing? What data strcture would you use to save this? How to display a "broken" sprite?
Create a sprite sheet.
This will contain all the spirites your object, in this case the rocket. Some of these images would be of the rocket smashing into many pieces, fire etc...
Then when your object hits, you play the collision animation. Your method would technically work, but it's overkill. Using a sprite sheet is simple, rather than drawing a massive image, you just draw a portion of the sheet, and to play the animation increment in the X an Y axis of the sheet. This naturally requires the sheet to be layed out even, but it's not too much work.
For some situations, you can simply draw another sprite on top of the original sprite. Alternatively, you can switch between different sprites depending on the state of the object.
I see you have tagged this with XNA, so assume that is your API (though this answer could well be applied to any OpenGL/D3d approach with appropriate calls). If you want to do this in an elegant fashion, I suggest using a temporary RenderState. You would switch to the new RenderState and draw your original background texture, then draw crater sprites over the top (you can modify the AlphaSourceBlend and AlphaDestinationBlend properties of the RenderState to create the subtractive effect you are looking for).
Once you have finished drawing, you can retrieve the RenderState as a texture easily using the GetTexture() function.
Keep in mind that if you are changing the blend modes, your SpriteBatch should be performing in the "immediate" mode (I forget the XNA term, but the one where it doesn't do ordering of sprites for efficiency) else it will be reset unexpectedly.
View this: http://www.riemers.net/eng/Tutorials/XNA/Csharp/Series2D/Adding_craters.php
Slow, but probably fast enough.
public static void Fill(this Texture2D t, Func<int, int, Color> perPixel)
{
var data = new Color[t.Height * t.Width];
for (int y = 0; y < t.Height; y++)
for (int x = 0; x < t.Width; x++)
{
data[x + (y * t.Width)] = perPixel(x, y);
}
t.SetData(data);
}
I was working on something like this on a mobile Java game, a worms/scorched earth clone (actually based on GunBound).
You don't "skip" the pixels in order to leave a crater. You change the pixels in your planet's bitmap, so the crater is now a permanent part of your planet. I assume you know all about bitmaps, blitting transparent, and hit testing.
To create a crater I used a circle-fill algorithm and filled the "explosion area" with the background or transparent color.
So when doing hit-testing you have to do it twice. A bounding-box hit test for speed, then a per-pixel hit test when then bounding boxes overlap.

Categories

Resources