Search code examples
c#toolkittexture2dsharpdxmipmaps

How to create MipMaps in SharpDX Toolkit (2.5)


i am using the SharpDX-Toolkit and can not create mimaps on a Texture2D. If i load a texture by the content manager and try to call GenerateMipMaps() i receive a NotSupportedException:

Cannot generate mipmaps for this texture (Must be RenderTarget and ShaderResource and MipLevels > 1

Code (in LoadContent-Method of the Game-Class):

Texture2D texture = this.Content.Load<Texture2D>("MyTexture");
texture.GenerateMipMaps(this.GraphicsDevice); <- Exception thrown in this line

I don't know what to do and i hope anyone can help me with this issue. Thanks.


Solution

  • Using:

     Texture2D texture = this.Content.Load<Texture2D>("MyTexture");
    

    Will default texture usage to "Immutable" and will only allow binding as Shader View.

    In order to generate MipMaps, usage needs to be Default and Binding as both ShaderView/RenderView.

    Now you have a few options:

    1/Preprocess your textures as dds with mipmaps, loader would take this into account.

    TexConv can do that for you. (use -m to specify level count).

    2/Load your texture as above, create a second texture using

     Texture2D texturewithmips = Texture2D.New(device, texture.Width, texture.Height, MipMapCount.Auto, texture.Format,
     TextureFlags.ShaderResource | TextureFlags.RenderTarget,
     1,Direct3D11.ResourceUsage.Default);
    

    Now you need to copy the first mip, using :

    device.Copy(texture, 0, null, t2, 0);
    

    You can now use :

    t2.GenerateMipMaps(this.GraphicsDevice);
    

    3/Since with method above you kinda lose the content manager (with auto caches for you).

    You can modify the TextureContentReader class to do that for you, by adding more options for texture loading.

    If you need more help feel free.