Creating a Custom Effect
Demonstrates how to create a custom effect that transforms an object and applies a texture.
Note
These steps create and use a custom effect using the Effect class. Custom shaders are not supported on Windows Phone. If you want to create an effect that works on all platforms, use a built-in effect. See this example, Creating a Basic Effect, which uses the BasicEffect class.
Complete Sample
The code in this topic shows you the technique for creating and applying special effects. You can download a complete code sample for this topic, including full source code and any additional supporting files required by the sample.
Download ApplyAnEffect_Sample.zip.
Creating a Custom Effect
To create a custom effect
Add the effect file to the Content directory of your XNA Framework game.
Right-click your Content node, point to Add, and then click Existing Item.
In the Files of type list, click All Files.
Navigate to your .fx file, and click Add.
Tip
To create a new .fx file, point to Add, click New Item, and then select the Effect File template.
Create a new Effect by using the ContentManager.Load method to load the .fx file.
effect = Content.Load<Effect>("ReallySimpleEffect");
The .fx file contains a parameter named WorldViewProj which is a matrix used by the vertex shader. The following code looks up the WorldViewProj parameter in Effect.Parameters, and calls EffectParameter.SetValue to initialize the value of the transform matrix.
effect.Parameters["WorldViewProj"].SetValue(worldViewProjection);
Set Effect.CurrentTechnique to a technique from the .fx file.
In this case, use the Effect.Techniques property to look up the technique named
TransformTechnique
from the .fx file.effect.CurrentTechnique = effect.Techniques["TransformTechnique"];
Use the GraphicsDevice.RasterizerState property to turn culling off so that all primitives will be drawn regardless of the order of the vertices.
Call EffectPass.Apply to apply the effect state before rendering.
Call DrawUserIndexedPrimitives to render the effect.
GraphicsDevice.Clear(Color.CornflowerBlue); RasterizerState rasterizerState = new RasterizerState(); rasterizerState.CullMode = CullMode.None; GraphicsDevice.RasterizerState = rasterizerState; GraphicsDevice.SetVertexBuffer(vertexBuffer); foreach (EffectPass pass in effect.CurrentTechnique.Passes) { pass.Apply(); GraphicsDevice.DrawUserIndexedPrimitives<VertexPositionColor>( PrimitiveType.TriangleList, vertices, 0, // vertex buffer offset to add to each element of the index buffer 24, // number of vertices to draw indices, 0, // first index element to read 12 // number of primitives to draw ); }