How do I pack a group of Texture2Ds into a larger Texture2D during Runtime with the UV Coordinates?

I’m currently trying to make a class which packs a group of Texture2Ds which are loaded from a file during runtime into a larger Texture2D, being a sprite atlas, and a list/array of UV locations. I’m doing this as I want the user to customize my game to an extent where s/he can add their own textures to the game. I want a single Texture2D for performance reasons for 3D rendering.

SpriteBatch. Render into a RenderTarget (the bigger texture) should do the trick

(you could do it also by hand by making a buffer and copying the data over and then Texture2D.SetData again - but I think SpriteBatch is easier to handle and faster)

How am I to get the resolution for the RenderTarget? Because if I use 1024x1024 sized textures, the atlas’ size will be different if the user uses 2048x2048 sized textures instead. The textures are all found in one directory, and are to be packaged by the game.

You should be able to load a texture from a file at runtime like that:

Texture2D myTexture = Texture2D.FromStream(graphicsDevice, filestream);

Texture2D exposes properties for the image size, so you could work out your atlas’ size

Is there any formula I should use when calculating the dimensions of the atlas? Because I’m unsure of how to calculate the dimensions only now.

There is too little information about your target. The naiv approach would be to equally subdivide and make an atlas of equally sized tiles making sure (by scaling), the atlas is in some sort of max dimensions.

width/height = Math.Ceil(count_images / 2) * tilesize

or something like that (may be wrong just mockup) - all squares

If you have smaller and bigger textures, you’d need some sort of weighting to decide which parts should be bigger and which should be smaller.