November 11, 2013

XNA Hack: Create RenderTarget2D greater than 4096x4096


XNA's HiDef profile has a maximum Texture2D size of 4096x4096.  RenderTarget2D has a backing Texture2D object, and this limitation is enforced at time of construction.


Time to get a bit tricky with reflection.  Limitations in XNA are all stored in Microsoft.Xna.Framework.Graphics.ProfileCapabilities, an internal class.  Fortunately, they aren't constants...

In your Initialize() function...

Assembly xna = Assembly.GetAssembly(typeof(GraphicsProfile));
Type profileCapabilities = xna.GetType("Microsoft.Xna.Framework.Graphics.ProfileCapabilities"true);
if (profileCapabilities != null)
     FieldInfo maxTextureSize = profileCapabilities.GetField("MaxTextureSize"BindingFlags.Instance | BindingFlags.NonPublic);
     FieldInfo hidefProfile = profileCapabilities.GetField("HiDef"BindingFlags.Static | BindingFlags.NonPublic);
     if (maxTextureSize != null && hidefProfile != null)
         object profile = hidefProfile.GetValue(null);
         maxTextureSize.SetValue(hidefProfile.GetValue(null), MaxTextureSize);

Replace MaxTextureSize in the last line with whatever you feel your maximum size should be. Ideally, you'll be querying DirectX 9 and setting the value to the maximum value allowed by D3D9Caps.


PhilTech said...

Hello Michael,

Can this solution be applied to a standard Texture2D or be used to eliminate the 4096x4096 restriction altogether? If so what changes would need to be made?

Michael Russell said...

This most likely could get rid of the Texture2D size limitation as well, but the downside is that you wouldn't be able to load oversized textures through the current content pipeline.