I noticed that at least two terrain engine examples in XNA are reading heightmap images into 4 channel textures instead of single channel textures.
To create a custom content processor that will permit you to convert any Texture2D compatible input format into an Alpha8 format texture, do the following:
Right click your game solution -> add new item
Under XNA 3.1 select Custom Content Pipeline, and replace the default class in this solution with this code:
using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework.Content.Pipeline;
using Microsoft.Xna.Framework.Content.Pipeline.Processors;
using Microsoft.Xna.Framework.Content.Pipeline.Graphics;
using Microsoft.Xna.Framework.Graphics.PackedVector;
using Microsoft.Xna.Framework;
using System.ComponentModel;
namespace ContentPipelineExtension1
{
[ContentProcessor]
[DesignTimeVisible(true)]
class HeightMapTextureProcessor : ContentProcessor
{
///
/// Process converts displacement maps to Alpha8 textures.
///
public override TextureContent Process(TextureContent input,
ContentProcessorContext context)
{
// Convert to data that we can work with:
input.ConvertBitmapType(typeof(PixelBitmapContent));
// Select first mipmap, there should only be one:
MipmapChain mipmapChain = input.Faces[0];
// There should only be one bitmap, but it doesnt hurt to write this loop:
foreach (PixelBitmapContent bitmap in mipmapChain)
{
for (int x = 0; x < bitmap.Width; x++)
{
for (int y = 0; y < bitmap.Height; y++)
{
Vector4 pixel = bitmap.GetPixel(x, y);
// Move R channel to A channel:
bitmap.SetPixel(x, y, new Vector4(0, 0, 0, pixel.X));
}
}
}
// Alpha8 contains values from 0 - 1 in the W channel.
input.ConvertBitmapType(typeof(PixelBitmapContent));
input.GenerateMipmaps(false);
return input;
}
}
}
Now add a reference to your CustomContentPipeline1 solution in the “Content” module in your game solution.
Right click on the heightmap file(s) that you wish to be converted to Alpha8 and select the HeightMapTextureProcessor as the content processor.
That’s it!