Software7

Personal Developer Notebook

Custom Shaders on Windows Phone 8

One of the exciting new features of Windows Phone 8 is the support of custom shaders. Something that was not possible on Windows Phone 7.

Basically adapting your existing shader code to MonoGame is a simple two step process:

  • replace POSITION0 by SV_POSITION
  • use vs_4_0_level_9_3 respective ps_4_0_level_9_3

The setup is a little bit more complicated, but don’t fear. There is a short video demonstrating the required steps.

Assumptions:

  • you have VS2010 installed – to use a feature of XNA called the Content Pipeline, a pre-compiler step for preparing assets to use at runtime
  • you have used the MonoGame installer, otherwise you have to adjust the paths accordingly.

We adapt a simple grayscale shader for use in MonoGame:

BTW the resulting grayscale shader:

float4x4 World;
float4x4 View;
float4x4 Projection;
texture BasicTexture;

sampler BasicTextureSampler = sampler_state {
	texture = <BasicTexture>;
	MinFilter = Anisotropic; 
	MagFilter = Anisotropic; 
	MipFilter = Linear; 
	AddressU = Wrap; 
	AddressV = Wrap; 
};

struct VertexShaderInput
{
    float4 Position : SV_POSITION;
    float2 UV : TEXCOORD0;
};

struct VertexShaderOutput
{
    float4 Position : SV_POSITION;
    float2 UV : TEXCOORD0;
};

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput output;
    float4 worldPosition = mul(input.Position, World);
    float4 viewPosition = mul(worldPosition, View);
    output.Position = mul(viewPosition, Projection);
    output.UV = input.UV;
    return output;
}

float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    float4 tex = tex2D(BasicTextureSampler, input.UV);
    tex.rgb = dot(tex.rgb, float3(0.3, 0.59, 0.11));
    return tex;
}

technique Technique1
{
    pass Pass1
    {
        VertexShader = compile vs_4_0_level_9_3 VertexShaderFunction();
        PixelShader = compile ps_4_0_level_9_3 PixelShaderFunction();
    }
}