<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Sgt. Conker &#187; Shaders</title>
	<atom:link href="http://www.sgtconker.com/category/xna/shaders/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.sgtconker.com</link>
	<description>We are &#34;absolutely fine&#34;</description>
	<lastBuildDate>Thu, 09 Sep 2010 19:48:45 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.2</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Article: Derived Effect Classes in XNA 4</title>
		<link>http://www.sgtconker.com/2010/08/article-derived-effect-classes-in-xna-4/</link>
		<comments>http://www.sgtconker.com/2010/08/article-derived-effect-classes-in-xna-4/#comments</comments>
		<pubDate>Sat, 14 Aug 2010 05:04:58 +0000</pubDate>
		<dc:creator>Absolutely Fine Tutorial Contest</dc:creator>
				<category><![CDATA[2010 Contest Entries]]></category>
		<category><![CDATA[Articles]]></category>
		<category><![CDATA[Contest]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[Shaders]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[Absolutely Fine Tutorial Contest]]></category>
		<category><![CDATA[Content Pipeline]]></category>
		<category><![CDATA[Dave Carlile]]></category>
		<category><![CDATA[Derives Effects]]></category>
		<category><![CDATA[Effects]]></category>
		<category><![CDATA[XNA 4.0]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/?p=1569</guid>
		<description><![CDATA[by Dave Carlile

One of the nice API changes in XNA 4.0 is the simplified syntax used when drawing with an Effect. In previous versions you would draw things like this:

effect.Begin();
foreach (EffectPass pass in effect.CurrentTechnique.Passes)
{
        pass.Begin();
        // draw your stuff
   [...]]]></description>
			<content:encoded><![CDATA[<h4 style="text-align: center;">by Dave Carlile</h4>
<p style="text-align: center;"><img class="aligncenter" title="Derived Effects" src="http://www.sgtconker.com/wp-content/uploads/contest/2010/derivedEffects.png" alt="" width="484" height="305" /></p>
<p>One of the nice API changes in XNA 4.0 is the simplified syntax used when drawing with an Effect. In previous versions you would draw things like this:</p>
<pre class="brush: csharp;">
effect.Begin();
foreach (EffectPass pass in effect.CurrentTechnique.Passes)
{
        pass.Begin();
        // draw your stuff
        pass.End();
}
effect.End();
</pre>
<p>Now you can draw things like this, with EffectPass.Apply handling all the magic:</p>
<pre class="brush: csharp;">
foreach (EffectPass pass in effect.CurrentTechnique.Passes)
{
        pass.Apply();
        // draw your stuff
}
</pre>
<p>Related to this is the new Effect.OnApply virtual method which gets called by EffectPass.Apply. By overriding this method in a derived class you can do things like perform pre-shader calculations and set shader parameters from properties. This is how BasicEffect and the other new standard shaders work, and it would be nice to be able to duplicate that functionality in our own derived effects.<br />
Ideally we would like to be able to do something like this:</p>
<pre class="brush: csharp;">
        MyEffect effect = Content.Load&lt;MyEffect&gt;(“myeffect”);
        effect.World = Matrix.Identity;
        effect.Color = Color.Blue;
        ...
        effect.Apply();
        ...
</pre>
<p>The first line is where we begin running into issues. In order to load a derived class using the content pipeline you have to write your own content processor, reader, and writer, for every single class.  You might think that you could load an Effect instance using the content manager, then create an instance of your derived Effect class and pass in the code. Unfortunately, there is no way to get at the code in the Effect instance (okay, that is <a href="http://blogs.msdn.com/b/shawnhar/archive/2010/05/07/effect-compilation-and-content-pipeline-automation-in-xna-game-studio-4-0.aspx">not entirely true</a>, but this solution requires the full Game Studio install).<br />
If you want to store the class properties (e.g. MyEffect.World, MyEffect.Color) as content then extending the content pipeline for each class is your best option.  But what if you don't need to store the properties?  What if you just want a cleaner interface to your shaders?  Extending the pipeline each time for these cases seems like a lot of unnecessary work.</p>
<h1>A Solution</h1>
<p>This remainder of this tutorial will show you how to load any derived Effect class from the content pipeline without having to extend the pipeline for each class.  To accomplish this we're going to create a content pipeline extension library that will compile the effect into an intermediate object that will let us get at the compiled code. We will also create a game library that will define the intermediate class so we can get to it at run time.  And finally we’ll add an extension method that will do the work of loading our derived Effect class.<br />
<span id="more-1569"></span></p>
<h1>Setup</h1>
<p>Let's start by opening Microsoft Visual Studio 2010 Express for Windows Phone and setting some things up. It’s important that you name things correctly, so make sure you use the names given while you follow these steps:</p>
<ul>
<li>Create a new Windows Game (4.0) project, call it DerivedEffectsTutorial.</li>
<li>Add a new Windows Game Library (4.0) project to the solution, call it DerivedEffects.</li>
<li>Add a new Content Pipeline Extension Library (4.0) project, call it DerivedEffects.Pipeline.</li>
<li>Reference the DerivedEffects game library in both the DerivedEffects.Pipeline and DerivedEffectsTutorial projects.</li>
<li>Reference the DerivedEffects.Pipeline in the DerivedEffectsTutorialContent project which Visual Studio generated for you.</li>
</ul>
<p>Make sure you can build the solution. All three projects should compile with no errors.</p>
<h1>Extend the Pipeline</h1>
<p>Now that everything is set up, the first thing we're going to do is extend the content pipeline so we can compile a shader in such a way as to provide us access to the compiled code at run time. This requires these steps:</p>
<ul>
<li>Create an intermediate class to store compiled shader code.</li>
<li>Implement a ContentProcessor to compile the code and store it an instance of the intermediate class. Note that we don't need to define a content importer because we can use the existing effect importer.</li>
<li>Implement a ContentTypeWriter to write out the intermediate class at compile time.</li>
<li>Implement a ContentTypeReader to read the intermediate class at run time.</li>
</ul>
<h1>Intermediate Class</h1>
<p>First we need to create an intermediate class to hold the effect code after it's compiled by the content processor. Some types of content require a different class at compile time versus run time for various reasons. But in this case the same class will work for both. Since this class is used at both compile time and run time it needs to live in the DerivedEffects game library.<br />
Visual Studio created a Class1.cs file when we added the game library project. Right click on the file in Solution Explorer, select Rename, and change the name to DerivedEffect.cs.  You should be prompted to change the name of the class to match, click “Yes”.<br />
Now open the file.  You should see the empty DerivedEffect class defined in the DerivedEffects namespace. Make the class public so it looks like this:</p>
<pre class="brush: csharp;">
namespace DerivedEffects
{
        public class DerivedEffect
        {
        }
}
</pre>
<p>Now add a private member to store the compiled code.</p>
<pre class="brush: csharp;">
        private byte[] compiledCode;
</pre>
<p>Add a constructor which accepts the code as a parameter and stores it in the private member.</p>
<pre class="brush: csharp;">
public DerivedEffect(byte[] compiledCode)
{
        this.compiledCode = compiledCode;
}
</pre>
<p>And finally add a public property to provide access to the code.</p>
<pre class="brush: csharp;">
public byte[] CompiledCode { get { return compiledCode; } }
</pre>
<p>The final class should look like this:</p>
<pre class="brush: csharp;">
namespace DerivedEffects
{
        public class DerivedEffect
        {
                private byte[] compiledCode;

                public DerivedEffect(byte[] compiledCode)
                {
                        this.compiledCode = compiledCode;
                }

                public byte[] CompiledCode { get { return compiledCode; } }
        }
}
</pre>
<p>Make sure everything still compiles before moving on to the next step.</p>
<h1>Content Processor</h1>
<p>The content processor's job is to compile the shader code and return an instance of our intermediate DerivedEffect class.  Since it is used at compile time it lives in the DerivedEffects.Pipeline project. Visual Studio created a ContentProcessor1.cs file for us when we added the pipeline extension project. Right click on the file in Solution Explorer, select Rename, and change the name to DerivedEffectProcessor.cs.  You should be prompted to change the name of the class to match, click “Yes”.<br />
Now open the file and you should see the empty DerivedEffectProcessor class defined in the DerivedEffects.Pipeline namespace. The class should look like this (with generated comments removed for brevity):</p>
<pre class="brush: csharp;">
using TInput = System.String;
using TOutput = System.String;

namespace DerivedEffects.Pipeline
{
        [ContentProcessor(DisplayName = &quot;DerivedEffects.Pipeline.ContentProcessor1&quot;)]
        public class DerivedEffectProcessor : ContentProcessor&lt;TInput, TOutput&gt;
        {
                public override TOutput Process(TInput input, ContentProcessorContext context)
                {
                        throw new NotImplementedException();
                }
        }
}
</pre>
<p>The Process method takes an input type and returns out output type. The input type in our case is the EffectContent class which is output by the default effect importer (this is the “Effect - XNA Framework” content importer you see when you select an .fx file in solution explorer and look at the file properties).</p>
<p>The output type is the intermediate DerivedEffect class we defined earlier.</p>
<p>Change the TInput and TOutput aliases to the fully qualified names of our input and output types.</p>
<pre class="brush: csharp;">
using TInput = Microsoft.Xna.Framework.Content.Pipeline.Graphics.EffectContent;
using TOutput = DerivedEffects.DerivedEffect;
</pre>
<p>Alternatively you can remove the aliases and replace all instances of TInput with EffectContent, and all instances of TOutput with DerivedEffect.</p>
<p>Change the ContentProcessor attribute to give the processor a better name.  This is the name that shows up in the Content Processor property when you select an .fx file in Solution Explorer.</p>
<pre class="brush: csharp;">
[ContentProcessor(DisplayName = &quot;Effect – Derived Effects&quot;)]
</pre>
<p>Now, replace the contents of the Process method with this code to compile the effect.</p>
<pre class="brush: csharp;">
EffectProcessor compiler = new EffectProcessor();
CompiledEffectContent compiledContent = compiler.Process(input, context);
</pre>
<p>This creates an EffectProcessor instance, passes the EffectContent input to the Process method to compile the effect, and returns a CompiledEffectContent instance which will allow us access to the compiled code.<br />
Now we need to create an instance of our intermediate content class, passing it the compiled effect code – remember TOutput is the alias we defined previously for our DerivedEffect class.</p>
<pre class="brush: csharp;">
return new TOutput(compiledContent.GetEffectCode());
</pre>
<p>And that's it for the content processor. The final code should look like this (again, with the generated comments removed):</p>
<pre class="brush: csharp;">
using TInput = Microsoft.Xna.Framework.Content.Pipeline.Graphics.EffectContent;
using TOutput = DerivedEffects.DerivedEffect;

namespace DerivedEffects.Pipeline
{
        [ContentProcessor(DisplayName = &quot;Effect – Derived Effects&quot;)]
        public class DerivedEffectProcessor : ContentProcessor&lt;TInput, TOutput&gt;
        {
                public override TOutput Process(TInput input, ContentProcessorContext context)
                {
                        EffectProcessor compiler = new EffectProcessor();
                        CompiledEffectContent compiledContent = compiler.Process(input, context);
                        return new TOutput(compiledContent.GetEffectCode());
                }
        }
}
</pre>
<p>Now make sure everything still builds before continuing on. If there are problems, double check that you've set up the references correctly.</p>
<h1>Content Writer</h1>
<p>Next up is the content writer.  This class is responsible for writing an instance of the DerivedEffect class to an .xnb file during compile time.  Since the content writer is executed at compile time, where does it go?  That's right, the pipeline extension library.  Right click on the DerivedEffects.Pipeline project and select Add/New Item. Make sure XNA Game Studio 4.0 is selected in the Installed Templates list on the left, then choose Content Type Writer, name it DerivedEffectWriter.cs, and press the Add button.<br />
In the DerivedEffectWriter class, start by changing the TWrite alias to our DerivedEffect class.</p>
<pre class="brush: csharp;">
using TWrite = DerivedEffects.DerivedEffect;
</pre>
<p>Remove all of the code from the Write method and replace it with this:</p>
<pre class="brush: csharp;">
output.Write(value.CompiledCode.Length);
output.Write(value.CompiledCode);
</pre>
<p>These two lines write out the length of the compiled code array, followed by the code itself. Later on when we implement the content reader it will be able to read in the length first so it  knows how many bytes of code to read.<br />
Next, replace all the code in the GetRuntimeReader method with this:</p>
<pre class="brush: csharp;">
return typeof(DerivedEffectReader).AssemblyQualifiedName;
</pre>
<p>This line returns the name space, class name, and assembly name for the DerivedEffectReader class. It basically tells the pipeline which content reader to use when it needs to read in our DerivedEffect class.<br />
Note that we haven't defined our content reader class yet, so there will be errors if we try to compile at this point. That will be taken care of next, but first, here is what the final content writer should look like:</p>
<pre class="brush: csharp;">
using TWrite = DerivedEffects.DerivedEffect;

namespace DerivedEffects.Pipeline
{
        [ContentTypeWriter]
        public class DerivedEffectWriter : ContentTypeWriter&lt;TWrite&gt;
        {
                protected override void Write(ContentWriter output, TWrite value)
                {
                        output.Write(value.CompiledCode.Length);
                        output.Write(value.CompiledCode);
                }

                public override string GetRuntimeReader(TargetPlatform targetPlatform)
                {
                        return typeof(DerivedEffectReader).AssemblyQualifiedName;
                }
        }
}
</pre>
<h1>Content Reader</h1>
<p>We can compile an effect and write the code out to an .xnb file.  Now we need to be able to read it back from the file, which is the content reader's job.  The content reader is used at run time, which means it goes into the game library.  Right click on the DerivedEffects project and select Add/New Item. Make sure XNA Game Studio 4.0 is selected in the Installed Templates list on the left, then choose Content Type Reader, name it DerivedEffectReader.cs, and press the Add button.<br />
Change the TRead alias to our DerivedEffect class.</p>
<pre class="brush: csharp;">
using TRead = DerivedEffects.DerivedEffect;
</pre>
<p>Now replace the contents of the Read method with this code:</p>
<pre class="brush: csharp;">
int size = input.ReadInt32();
byte[] code = input.ReadBytes(size);
</pre>
<p>Recall that the content writer first wrote out the length of the code, then the code.  The reader first reads in the length of the code so it knows how many bytes to read, after which it proceeds to read that many bytes into an array.<br />
And finally, the read method needs to return a new instance of our DerivedEffect class – remember that TRead is the alias we defined for our DerivedEffect class.</p>
<pre class="brush: csharp;">
return new TRead(code);
</pre>
<p>The final content reader looks like this:</p>
<pre class="brush: csharp;">
using TRead = DerivedEffects.DerivedEffect;

namespace DerivedEffects
{
        public class DerivedEffectReader : ContentTypeReader&lt;TRead&gt;
        {
                protected override TRead Read(ContentReader input, TRead existingInstance)
                {
                        int size = input.ReadInt32();
                        byte[] code = input.ReadBytes(size);
                        return new TRead(code);
                }
        }
}
</pre>
<p>Now you should be able to compile successfully again. Make sure that is the case before moving on.</p>
<h1>Testing the Content Pipeline Changes</h1>
<p>That brings us to the end of the content pipeline extension. We've created a content processor to compile the effect, a content writer to save it out to an .xnb file at compile time, and a content reader to read it back in at run time.<br />
Allegedly we can now compile an effect file and load it into a DerivedEffect instance at run time using the content manager.  Let's make sure everything is working so far.<br />
To start with we need an .fx file. Right click on the DerivedEffectsTutorialContent project and select Add/New Item. Choose Effect File, name it MyEffect.fx, and press the Add button. You don't need to change anything in the file.<br />
Select the file in Solution Explorer. Find the Content Processor property in the file properties; click the down arrow to show the available content processors. You should see our new content processor “Effect – Derived Effects” - select it. If you don't see it, verify that you've correctly referenced the DerivedEffects.Pipeline project in the DerivedEffectsTutorialContent project (refer back to the Setup section for instructions on setting up all of the references).<br />
Open the Game1 class in the DerivedEffectsGame project. Add a using statement.</p>
<pre class="brush: csharp;">
using DerivedEffects;
</pre>
<p>Declare a new member in the Game1 class.</p>
<pre class="brush: csharp;">
DerivedEffect myEffectCode;
</pre>
<p>And a line to the LoadContent method in order to load the derived effect.</p>
<pre class="brush: csharp;">
myEffectCode = Content.Load&lt;DerivedEffect&gt;(&quot;myeffect&quot;);
</pre>
<p>Now comes the big moment – compile the project. If everything compiles then the compile time part of the content manager is working correctly. If not, you'll need to go back through the tutorial and find out what you missed.<br />
Now we need to test the run time – go ahead and run the game. If it works you'll see the beautiful cornflower blue window appear. If the content manager has a problem, such as not being able to locate the content reader for DerivedEffect, it will throw an exception.<br />
You can also set a breakpoint and examine myEffect.CompiledCode to see that it is indeed loaded with what you can assume is compiled shader code.<br />
At this point we could create an Effect object by passing the CompiledCode to the Effect constructor, like this:</p>
<pre class="brush: csharp;">
Effect effect = new Effect(GraphicsDevice, myEffect.CompiledCode);
</pre>
<p>And that is why we've done everything we have up to this point – the need to get access to the compiled code so we can pass it to the Effect constructor.  If the existing Effect class would expose a property like this we could do what we're trying to do without involving the content pipeline at all.  I'm sure the powers that be have a good reason for not exposing it, but it makes things a little awkward.<br />
Now we need to work on loading our own effect descendent. Based the previous line of code, you've probably already figured out what we need to do.</p>
<h1>Derived Effect Class</h1>
<p>Let's start by creating our derived effect class.  Right click on the DerivedEffectsTutorial game project, select Add/Class, name it MyEffect.cs, and press the Add button.<br />
You'll need to add a couple of using statements.</p>
<pre class="brush: csharp;">
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
</pre>
<p>You'll also need to have the class descend from Effect, and create one of the Effect constructors. It should look like this:</p>
<pre class="brush: csharp;">
using System;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace DerivedEffectsTutorial
{
        class MyEffect:Effect
        {
                public MyEffect(GraphicsDevice graphicsDevice, byte[] effectCode)
                        : base(graphicsDevice, effectCode)
                {
                }
        }
}
</pre>
<p>Now back in the Game1 class, add a new class member.</p>
<pre class="brush: csharp;">
MyEffect effect;
</pre>
<p>And add a line to LoadContent to create a MyEffect instance.</p>
<pre class="brush: csharp;">
effect = new MyEffect(GraphicsDevice, myEffectCode.CompiledCode);
</pre>
<p>The LoadContent method should look like this:</p>
<pre class="brush: csharp;">
protected override void LoadContent()
{
        myEffectCode = Content.Load&lt;DerivedEffect&gt;(&quot;myeffect&quot;);
        effect = new MyEffect(GraphicsDevice, myEffectCode.CompiledCode);
}
</pre>
<p>And there you have it, an instance of your very own shader class derived from Effect! It will work anywhere you would normally use an effect.  You can override OnApply and have it do things when EffectPass.Apply is called, add your own properties, and so on.<br />
But, now we need to kick it up a notch.</p>
<h1>BAM!</h1>
<p>In the beginning we decided we'd like to be able to do this.</p>
<pre class="brush: csharp;">
MyEffect effect = Content.Load&lt;MyEffect&gt;(“myeffect”);
</pre>
<p>Well, we can't do that using this solution, but how about this instead?</p>
<pre class="brush: csharp;">
MyEffect effect = Content.LoadDerivedEffect&lt;MyEffect&gt;(&quot;myeffect&quot;);
</pre>
<p>We can accomplish this by adding an extension method to the ContentManager class, so let's get started.<br />
Add a new class to the DerivedEffects game library, call it ContentManagerExtensions.  Make sure the class is static and public.</p>
<pre class="brush: csharp;">
public static class ContentManagerExtensions
{
}
</pre>
<p>Add some using statements.</p>
<pre class="brush: csharp;">
using System.Reflection;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Content;
</pre>
<p>Add the LoadDerivedEffect extension method to the class.  Notice the use of generics, and that the allowed classes must be derived from Effect.</p>
<pre class="brush: csharp;">
public static T LoadDerivedEffect&lt;T&gt;(this ContentManager content, string assetName)
  where T:Effect
{
}
</pre>
<p>Inside the function, we need to be able to get to the graphics device. We can do that by finding the graphics device service.</p>
<pre class="brush: csharp;">
IGraphicsDeviceService graphicsDeviceService =
    (IGraphicsDeviceService)content.ServiceProvider.GetService(typeof(IGraphicsDeviceService));
</pre>
<p>This uses the content manager's ServiceProvider property to look for the graphics device service.<br />
Next we load the compiled effect code.</p>
<pre class="brush: csharp;">
DerivedEffect effect = content.Load&lt;DerivedEffect&gt;(assetName);
</pre>
<p>This is the same code we used before to load the DerivedEffect instance, but we're now using the asset name that was passed to LoadDerivedEffect.<br />
Now comes the interesting part. It would be nice if we could do this:</p>
<pre class="brush: csharp;">
return new T(graphicsDeviceService.GraphicsDevice, effect.CompiledCode);
</pre>
<p>Unfortunately, you can't do that with generics – you can only create objects with parameterless constructors. But, we can use reflection to find and call the constructor we want.</p>
<pre class="brush: csharp;">
Type classType = typeof(T);

ConstructorInfo classConstructor = classType.GetConstructor(
                BindingFlags.Instance | BindingFlags.Public, null,
                new Type[] { graphicsDeviceService.GraphicsDevice.GetType(),
                        effect.CompiledCode.GetType() },
                null);
</pre>
<p>This code first gets the type for the generic class (e.g. MyEffect). It then uses that to locate the constructor that takes GraphicsDevice and byte[] parameters.  Once we have that we can create and return and instance of the class by calling the constructor and passing the graphics device and compiled code.</p>
<pre class="brush: csharp;">
return (T)classConstructor.Invoke(new object[]
    { graphicsDeviceService.GraphicsDevice, effect.CompiledCode });
</pre>
<p>The final code should look like this:</p>
<pre class="brush: csharp;">
namespace DerivedEffects
{
        public static class ContentManagerExtensions
        {
                public static T LoadDerivedEffect&lt;T&gt;(this ContentManager content, string assetName)
                        where T : Effect
                {
                        IGraphicsDeviceService graphicsDeviceService =
                                (IGraphicsDeviceService)content.ServiceProvider.GetService(
                                        typeof(IGraphicsDeviceService));

                        DerivedEffect effect = content.Load&lt;DerivedEffect&gt;(assetName);

                        Type classType = typeof(T);
                        ConstructorInfo classConstructor = classType.GetConstructor(
                                BindingFlags.Instance | BindingFlags.Public, null,
                                new Type[] { graphicsDeviceService.GraphicsDevice.GetType(),
                                        effect.CompiledCode.GetType() }, null);

                        return (T)classConstructor.Invoke(new object[]
                                { graphicsDeviceService.GraphicsDevice,
                                        effect.CompiledCode });
                }
        }
}
</pre>
<p>Now to make sure it's working, go back to the Game1 class, remove the DerivedEffect member and replace all of the code in LoadContent with:</p>
<pre class="brush: csharp;">
effect = Content.LoadDerivedEffect&lt;MyEffect&gt;(&quot;myeffect&quot;);
</pre>
<p>The project should compile and run with no errors, and you now have an instance of your derived effect class.</p>
<h1>What Next?</h1>
<p>The downloadable code included with this tutorial extends the example with a more fully implemented MyEffect class, including OnApply and pre-shader calculations, as well as some drawing code that uses it. Going through all of that here would make a long tutorial prohibitively long.<br />
It was mentioned earlier that the DerivedEffects and DerivedEffects.Pipeline libraries are reusable. All you need to do in your new game projects is reference DerivedEffects.Pipeline in your game's content project, and DerivedEffects in your game project, and make sure the run time library is distributed with your game.  That's all there is to it.</p>
<h1>Finale</h1>
<p>This was a lot of work to do something that should be simple. If the Effect class exposed the compiled effect code this would boil down to just the content manager extension method. But since it doesn't, we can leverage the content pipeline to help us out by providing the data we need.<br />
Implementing derived effects can really improve code readability and reuse, especially with the latest Effects API changes. Hopefully this method of loading your derived classes through the content pipeline makes it that much easier to use them.  Happy sub-classing!</p>
<p><strong>Download sample code:</strong> <a href="http://www.sgtconker.com/wp-content/uploads/contest/2010/DerivedEffectsTutorial.zip">DerivedEffectsTutorial.zip</a> (<a href="http://www.sgtconker.com/wp-content/uploads/contest/2010/dave_license.txt">license</a>)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2010/08/article-derived-effect-classes-in-xna-4/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Brute Force 2D Shadows</title>
		<link>http://www.sgtconker.com/2010/07/brute-force-2d-shadows/</link>
		<comments>http://www.sgtconker.com/2010/07/brute-force-2d-shadows/#comments</comments>
		<pubDate>Sat, 10 Jul 2010 14:25:58 +0000</pubDate>
		<dc:creator>Captain ZSquare</dc:creator>
				<category><![CDATA[2D]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[News]]></category>
		<category><![CDATA[Shaders]]></category>
		<category><![CDATA[2D Shadows]]></category>
		<category><![CDATA[Charles Humphrey]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/?p=1514</guid>
		<description><![CDATA[Because he is a much less busy man (it would seem), Charles Humprey made his own implementation for shader-based dynamic 2D shadows and posted it for everyone to see. You can read about it here.
]]></description>
			<content:encoded><![CDATA[<p>Because he is a much less busy man (it would seem), Charles Humprey made his own implementation for shader-based dynamic 2D shadows and posted it for everyone to see. You can read about it <a href="http://xna-uk.net/blogs/randomchaos/archive/2010/06/25/brute-force-2d-shadows-well-sort-of.aspx">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2010/07/brute-force-2d-shadows/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Article : Sun- and Lens Flare as a Post Process</title>
		<link>http://www.sgtconker.com/2010/04/article-sun-and-lens-flare-as-a-post-process/</link>
		<comments>http://www.sgtconker.com/2010/04/article-sun-and-lens-flare-as-a-post-process/#comments</comments>
		<pubDate>Wed, 21 Apr 2010 12:12:01 +0000</pubDate>
		<dc:creator>NemoKrad</dc:creator>
				<category><![CDATA[3D]]></category>
		<category><![CDATA[Articles]]></category>
		<category><![CDATA[MVP Watch]]></category>
		<category><![CDATA[Post Processing]]></category>
		<category><![CDATA[Shaders]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[Blacksun]]></category>
		<category><![CDATA[Charles Humphrey]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[Lens flare]]></category>
		<category><![CDATA[Post Process]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/?p=1407</guid>
		<description><![CDATA[by ]]></description>
			<content:encoded><![CDATA[<h4 style="text-align: center;">by <a href="<a href="http://xna-uk.net/blogs/randomchaos/">Charles Humphrey</a></h4>
<p><img class="alignright" src="http://sgtconker.com/wp-content/uploads/2010/04/sunpostprocess.png" alt="" width="264" height="206" /></p>
<p>Now this sample has come from my current XNA toy which is the Blacksun engine I am currently writing in XNA 3.1. It uses deferred lighting, instancing and a post processing framework that I found on a great site <a href="http://graphicsrunner.blogspot.com/2008/06/post-process-framework-sample.html">here</a>, all I had to do was make it engine ready.</p>
<p>If you want to have a look at the effect in the engine you can see it <a href="http://www.youtube.com/watch?v=DrhF2Bp-95I">here</a>.</p>
<p>This sample is just one of the elements from the post processing framework in the engine, there are none of the other goodies in this sample, just the Sun post process. This sample has also been created using the XNA 4.0 CTP, so I only had one render target to work with at the time. This means that you can't see the sun being culled behind objects in the scene as I can't create a depth map as well as the rendered scene, to be honest, I still don't have that bit of the shader 100% anyway <img src='http://www.sgtconker.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
<p><span id="more-1407"></span></p>
<p>So, what do you get in this sample, well, the sun shader and the lens flare effect all in one post process and done in XNA 4.0. It's a pretty simple effect really, taking the suns position in the world, then just finding its screen coordinates on the render target and render the sun flare texture, then render the texture again over a set of offset texture coordinates to give the lens flare effect.</p>
<p>Lets take a look at the code...</p>
<p><strong>Sun.fx</strong></p>
<p>We have a few variables we can pass to the shader to control this effect, the names I hope are quite self explanatory, well most of them</p>
<pre class="brush: csharp;">
float3 cameraPosition;

float SunSize = 1500;

float Density = 3;
float Exposure = -.1;
float Weight = .25;
float Weight2 = .125;
float Decay = .5;

float3 lightPosition;

float lightIntensity = 10.0f;
float3 Color = float3(1,1,1);

texture flare;
sampler Flare = sampler_state
{
    Texture = (flare);
    AddressU = CLAMP;
    AddressV = CLAMP;
};

sampler BackBuffer : register(s0);

//depth
texture depthMap;
sampler depthSampler = sampler_state
{
    Texture = (depthMap);
};

struct VertexShaderInput
{
    float3 Position : POSITION0;
    float2 texCoord : TEXCOORD0;
};

struct VertexShaderOutputToPS
{
    float2 texCoord : TEXCOORD0;
};
</pre>
<p>Those that I guess are not that obvious are Density to Decay and these relate the the lens flare part of the shader and control the number of texture samples to display, density of those samples etc..</p>
<p>So onto the lane flare function that is used in the shader to give the lens flare effect.</p>
<pre class="brush: csharp;">
float4 DoLenseFlare(float4 ScreenLightPosition,float2 texCoord,bool fwd)
{
    // Calculate vector from pixel to light source in screen space.
    float2 deltaTexCoord = (texCoord - ScreenLightPosition.xy);// Divide by number of samples and scale by control factor.
    deltaTexCoord *= 1.0f / 3 * Density;

    // Store initial sample.
    float3 color = 0;

    // Set up illumination decay factor.
    float illuminationDecay = 1.0f;

    for (int i = 0; i &amp;lt; 3 ; i++)
    {
        // Step sample location along ray.
        if(fwd)
            texCoord -= deltaTexCoord;
        else
            texCoord += deltaTexCoord;

        // Retrieve sample at new location.
        float3 sample = tex2D(Flare, texCoord);

        // Apply sample attenuation scale/decay factors.
        if(fwd)
            sample *= illuminationDecay * Weight;
        else
            sample *= illuminationDecay * Weight2;

        // Accumulate combined color.
        color += sample;

        // Update exponential decay factor.
        illuminationDecay *= Decay;
    }

    return float4(color,1);
}
</pre>
<p>I can take very little credit for this bit of the code, as I got it from GPU Game 3 Chapter 13 Volumetric Light Scattering as a Post Process, not exactly using it as it was intended, but is does the job I wanted here well enough <img src='http://www.sgtconker.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p>So the pixel shader itself that pulls this all together looks like this</p>
<pre class="brush: csharp;">
float4 PixelShaderFunction(VertexShaderOutputToPS input) : COLOR0
{
    // Get the scene
    float4 col = tex2D(BackBuffer,input.texCoord);// Find the suns position in the world and map it to the screen space.
    float4 ScreenPosition = mul(lightPosition - cameraPosition,VP);
    float scale = ScreenPosition.z;
    ScreenPosition.xyz /= ScreenPosition.w;
    ScreenPosition.x = ScreenPosition.x/2.0f+0.5f;
    ScreenPosition.y = (-ScreenPosition.y/2.0f+0.5f);

    // get the depth from the depth map
    //float depthVal = 1- tex2D(depthSampler, input.texCoord).r;

    // Are we lokoing in the direction of the sun?
    if(ScreenPosition.w &gt; 0)
    {
        float2 coord;

        float size = SunSize / scale;

        float2 center = ScreenPosition.xy;

        coord = .5 - (input.texCoord - center) / size * .5;

        //if(depthVal &gt; ScreenPosition.z-.0003)
        col += (pow(tex2D(Flare,coord) * float4(Color,1),2) * lightIntensity) * 2;

        // Lens flare
        col += ((DoLenseFlare(ScreenPosition,input.texCoord,true) + DoLenseFlare(ScreenPosition,input.texCoord,false)) * float4(Color,1) * lightIntensity) * 5;
    }

    return col;
}
</pre>
<p>You will see in here that I have left in the code for detecting the depth of objects in the scene for sun culling and just commented it out, when you have a full release XNA 4.0 you will be able to create and pass in the depth map, but it’s not possible in the current CTP.</p>
<p>So what am I doing in the pixel shader, first off we grab the current scene’s color, I then get the position of the light in screen space by multiplying its position by the camera position and then doing the homogeneous divide (ScreenPosition.xyz / ScreenPosition.w) to get the position of the sun (see the Get2DCoords method below for my inspiration for this). Then, if we are looking in the direction of the sun (ScreenPosition.w &gt; 0) then we need to render the sun and or lens flare. I then calculate the size of the sun and find the tex coords required to get the texture from the Flare sampler and then add this with the sun color and raise it to the power of 2, this lightens the light bits and darkens the dark bits, this is then multiplied by the light intensity and the final values doubled again. Then we come to the lens flare, I call this twice: once for each direction of the flare (you will see in the clip there are two) and again tint this to the sun color and multiply by intensity.</p>
<p>Now please feel free to pick my dodgy math’s apart here I know I suck, but it is working and I have not thought much more abut it since writing it <img src='http://www.sgtconker.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' /> </p>
<p><strong>Game Code</strong></p>
<p>First thing we will do is set up a render target and and effect so we can apply our sun as a post process.</p>
<pre class="brush: csharp;">
RenderTarget2D rt;
Effect effect;
</pre>
<p>Also some way of representing the sun’s position, color intensity and size</p>
<pre class="brush: csharp;">
Vector3 sunPosition = new Vector3(100, 200, -1000);
Color sunColor = Color.White;
float sunIntensity = 1f;
float sunSunSize = 1500;
</pre>
<p>Now we have these variable lined up and ready to use we can initialize both the render target and the effect shader</p>
<pre class="brush: csharp;">
rt = new RenderTarget2D(GraphicsDevice, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height);

effect = Content.Load&lt;Effect&gt;(&quot;Shaders/PostProcessing/Sun&quot;);
effect.Parameters[&quot;flare&quot;].SetValue(Content.Load&lt;Texture2D&gt;(&quot;Textures/PostProcessing/flare&quot;));
effect.Parameters[&quot;Color&quot;].SetValue(sunColor.ToVector3());
effect.Parameters[&quot;lightIntensity&quot;].SetValue(sunIntensity);
effect.Parameters[&quot;SunSize&quot;].SetValue(sunSunSize);
effect.Parameters[&quot;lightPosition&quot;].SetValue(sunPosition);
</pre>
<p>Now we need to make sure the shader/effect is updated with the required variables. So in our update method we set the following parameters</p>
<pre class="brush: csharp;">
effect.Parameters[&quot;VP&quot;].SetValue(camera.View * camera.Projection);
effect.Parameters[&quot;cameraPosition&quot;].SetValue(camera.Position);
//effect.Parameters[&quot;depthMap&quot;].SetValue(depthBuffer);
</pre>
<p>And now for the render, keep in mind that this is all done just for this sample, you will want to encapsulate all this in its own class deriving from DrawableGameComponent or in a post processing framework as shown in the link above.</p>
<pre class="brush: csharp;">
    GraphicsDevice.SetRenderTargets(rt);
    GraphicsDevice.Clear(&lt;Color.Black);
    base.Draw(gameTime);

    // Post Processing.
    GraphicsDevice.SetRenderTargets(null);

    GraphicsDevice.Textures[0] = rt;
    spriteBatch.Begin(SpriteSortMode.Immediate, BlendState.AlphaBlend);
    effect.Techniques[0].Passes[0].Apply();
    spriteBatch.Draw(rt, new Rectangle(0, 0, rt.Width, rt.Height), Color.White);
    spriteBatch.End();
</pre>
<p>So, we setup the render target, allow the scene to be drawn (nothing gets drawn in this sample), then we resolve the render target and then apply our effect to the newly captured render target.</p>
<p>As mentioned earlier I have a method I use to get screen coordinates from a 3D screen position, this method I am 99% sure I got (or at least the nuts and bolts of it) from Rocket Commander which was written by <a href="http://exdream.com/Games/Default.aspx?Game=RocketCommander&amp;Category=Open%20Source">Benjamin Nitsche</a></p>
<pre class="brush: csharp;">
public Vector2 Get2DCoords(Vector3 myPosition, Base3DCamera Camera)
{
    Matrix ViewProjectionMatrix = Camera.View * Camera.Projection;
    Vector4 result4 = Vector4.Transform(myPosition, ViewProjectionMatrix);

    if(result4.W &lt;= 0)
        return new Vector2(Camera.Viewport.Width, 0);

    Vector3 result = new Vector3(result4.X / result4.W, result4.Y / result4.W, result4.Z / result4.W);

    Vector2 retVal = new Vector2((int)Math.Round(+result.X * (Camera.Viewport.Width / 2)) + (Camera.Viewport.Width / 2), (int)Math.Round(-result.Y * (Camera.Viewport.Height / 2)) + (Camera.Viewport.Height / 2));

    return retVal;
}
</pre>
<p>As you can see it transforms the position by the ViewProjection matrix to then get the screen position if the result4.W &gt;= 0.</p>
<p><a href="http://www.sgtconker.com/Downloads/articles/RandomchaosSunPostProcess.zip">Download the sample project here</a><br />
Well that’s abut it, and this is my first post on Sgt Conker, hope it’s not my last one <img src='http://www.sgtconker.com/wp-includes/images/smilies/icon_razz.gif' alt=':P' class='wp-smiley' />  Hope you find this useful, if not in it’s own right, then I hope it gives you some ideas for your own shaders…..</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2010/04/article-sun-and-lens-flare-as-a-post-process/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
		<item>
		<title>XNA 4.0 MultiEffect</title>
		<link>http://www.sgtconker.com/2010/03/xna40multieffect/</link>
		<comments>http://www.sgtconker.com/2010/03/xna40multieffect/#comments</comments>
		<pubDate>Mon, 15 Mar 2010 21:15:11 +0000</pubDate>
		<dc:creator>CorporalX</dc:creator>
				<category><![CDATA[3D]]></category>
		<category><![CDATA[Shaders]]></category>
		<category><![CDATA[WP7]]></category>
		<category><![CDATA[XNA]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/?p=1289</guid>
		<description><![CDATA[X-Tatic has created a wrapper for all 4 built in effect types in XNA 4.0
What this means is that you can store a single type of effect yet have it be any one of the four included effect types, while still having access to all of the properties that any of the underlying effects expose.
The [...]]]></description>
			<content:encoded><![CDATA[<p>X-Tatic has created a wrapper for all 4 built in effect types in XNA 4.0</p>
<p>What this means is that you can store a single type of effect yet have it be any one of the four included effect types, while still having access to all of the properties that any of the underlying effects expose.</p>
<p>The reason for MultiEffect is that its useful to use an effect without trying to figure out which of the 4 types it is and which properties/methods to call. You can call any of them, regardless of whether the effect implements them.</p>
<div>How To Use:</div>
<pre class="brush: csharp;">
// to create a MultiEffect
MultiEffect effect = new MultiEffect(); // this defaults to BasicEffect

// or via any one of the built in effects
MultiEffect effect = builtInEffect.ToMultiEffect();

// you can access the underlying Effect
Effect effect = multiEffect.Effect;

// or explicitly cast it
Effect effect = (Effect)multiEffect;

// Finally, you can query the type
MultiEffectType effectType = multiEffect.CurrentType;
</pre>
<p>Download the binaries: <a href="http://www.xtaticware.com/downloads/XNA4MultiEffect.zip">http://www.xtaticware.com/downloads/XNA4MultiEffect.zip</a></p>
<p>or the source: <a href="http://www.xtaticware.com/downloads/XNA4MultiEffectSource.zip">http://www.xtaticware.com/downloads/XNA4MultiEffectSource.zip</a> (MS-PL)</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2010/03/xna40multieffect/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Distance field based decal rendering</title>
		<link>http://www.sgtconker.com/2010/03/distance-field-based-decal-rendering/</link>
		<comments>http://www.sgtconker.com/2010/03/distance-field-based-decal-rendering/#comments</comments>
		<pubDate>Thu, 04 Mar 2010 14:28:28 +0000</pubDate>
		<dc:creator>Captain boki</dc:creator>
				<category><![CDATA[2D]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[News]]></category>
		<category><![CDATA[Shaders]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[Distance Field]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/2010/03/distance-field-based-decal-rendering/</guid>
		<description><![CDATA[Rim van Wersch shares an XNA Framework implementation of the Valve paper Improved Alpha-Tested Magnification for Vector Textures and Special Effects, presenting “[a] simple and efficient method […] which allows improved rendering of glyphs composed of curved and linear elements. A distance field is generated from a high resolution image, and then stored into a [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.xnainfo.com/">Rim van Wersch</a> shares an <a href="http://www.xnainfo.com/content.php?content=44">XNA Framework implementation</a> of the <a href="http://www.valvesoftware.com/publications/2007/SIGGRAPH2007_AlphaTestedMagnification.pdf">Valve paper <em>Improved Alpha-Tested Magnification for Vector Textures and Special Effects</em></a>, presenting <q>“[a] simple and efficient method […] which allows improved rendering of glyphs composed of curved and linear elements. A distance field is generated from a high resolution image, and then stored into a channel of a lower-resolution texture.”</q></p>
<p><a href="http://www.xnainfo.com/content.php?content=44"><img style="border-right-width: 0px; margin: 8px auto 0px; display: block; float: none; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Distance Field Based Rendering" border="0" alt="Distance Field Based Rendering" src="http://www.sgtconker.com/wp-content/uploads/2010/03/dfcsmall.png" width="200" height="150" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2010/03/distance-field-based-decal-rendering/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Post Processing Trick from MJP</title>
		<link>http://www.sgtconker.com/2009/12/post-processing-trick-from-mjp/</link>
		<comments>http://www.sgtconker.com/2009/12/post-processing-trick-from-mjp/#comments</comments>
		<pubDate>Tue, 15 Dec 2009 16:17:47 +0000</pubDate>
		<dc:creator>Captain ZSquare</dc:creator>
				<category><![CDATA[Graphics]]></category>
		<category><![CDATA[News]]></category>
		<category><![CDATA[Shaders]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[MJP]]></category>
		<category><![CDATA[MVP]]></category>
		<category><![CDATA[Shader]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/?p=699</guid>
		<description><![CDATA[Matt Pettineo took a crack at a trick used in Killzone 2 for Lens Flare, and decided to share his new shader with the world.

]]></description>
			<content:encoded><![CDATA[<p>Matt Pettineo took a crack at a trick used in Killzone 2 for Lens Flare, and decided to <a href="http://mynameismjp.wordpress.com/2009/12/15/more-post-processing-tricks-lens-flare/">share his new shader with the world</a>.</p>
<p><a href="http://mynameismjp.wordpress.com/2009/12/15/more-post-processing-tricks-lens-flare/"><img class="alignnone" title="Lens Flare Trick" src="http://mynameismjp.files.wordpress.com/2009/12/screen.png" alt="" width="500" height="282" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2009/12/post-processing-trick-from-mjp/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Two Samples For The Price Of One at MJP&#8217;s XNA Danger Zone</title>
		<link>http://www.sgtconker.com/2009/12/two-samples-for-the-price-of-one-at-mjps-xna-danger-zone/</link>
		<comments>http://www.sgtconker.com/2009/12/two-samples-for-the-price-of-one-at-mjps-xna-danger-zone/#comments</comments>
		<pubDate>Sun, 06 Dec 2009 05:04:58 +0000</pubDate>
		<dc:creator>Captain boki</dc:creator>
				<category><![CDATA[3D]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[News]]></category>
		<category><![CDATA[Shaders]]></category>
		<category><![CDATA[Shader]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/2009/12/two-samples-for-the-price-of-one-at-mjps-xna-danger-zone/</guid>
		<description><![CDATA[Over at MJP’s XNA Danger Zone Matt J. Pettineo writes:
Today I have two XNA samples fresh out of the oven: a Motion Blur Sample, and Depth Of Field Sample. I figure all of the kids these days wanna add fancy post-processing tricks to their games, right?

Read more
 
]]></description>
			<content:encoded><![CDATA[<p>Over at <a href="http://mynameismjp.wordpress.com/">MJP’s XNA Danger Zone</a> <a href="http://mynameismjp.wordpress.com/about-me/">Matt J. Pettineo</a> writes:</p>
<blockquote cite="http://mynameismjp.wordpress.com/2009/12/05/two-samples/"><p>Today I have two XNA samples fresh out of the oven: a <a href="http://mynameismjp.wordpress.com/samples-tutorials-tools/motion-blur-sample/">Motion Blur Sample</a>, and <a href="http://mynameismjp.wordpress.com/samples-tutorials-tools/depth-of-field-sample/">Depth Of Field Sample</a>. I figure all of the kids these days wanna add fancy post-processing tricks to their games, right?</p>
</blockquote>
<p><a href="http://mynameismjp.wordpress.com/2009/12/05/two-samples/">Read more</a></p>
<p style="text-align: center"><a href="http://mynameismjp.wordpress.com/samples-tutorials-tools/motion-blur-sample/"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="motionblur" border="0" alt="Motion Blur" src="http://www.sgtconker.com/wp-content/uploads/2009/12/motionblur.png" width="240" height="132" /></a> <a href="http://mynameismjp.wordpress.com/samples-tutorials-tools/depth-of-field-sample/"><img style="border-right-width: 0px; display: inline; border-top-width: 0px; border-bottom-width: 0px; border-left-width: 0px" title="Depth of Field" border="0" alt="dof" src="http://www.sgtconker.com/wp-content/uploads/2009/12/dof.png" width="235" height="132" /></a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2009/12/two-samples-for-the-price-of-one-at-mjps-xna-danger-zone/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Instanced Deferred Render</title>
		<link>http://www.sgtconker.com/2009/11/instanced-deferred-render/</link>
		<comments>http://www.sgtconker.com/2009/11/instanced-deferred-render/#comments</comments>
		<pubDate>Fri, 27 Nov 2009 06:14:09 +0000</pubDate>
		<dc:creator>Captain ZSquare</dc:creator>
				<category><![CDATA[3D]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[News]]></category>
		<category><![CDATA[Shaders]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[Deferred Rendering]]></category>
		<category><![CDATA[Instancing]]></category>
		<category><![CDATA[MVP]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/?p=585</guid>
		<description><![CDATA[Nemo Krad (of RandomChaos) continues to tease us with yet another video of his Deferred Render Instancing sample.

Let's hope he releases the code soon, because what he's doing there definitely looks sweet, and there can never be too many samples about deferred rendering, or instancing!
See all his posts about this so far, here.
]]></description>
			<content:encoded><![CDATA[<p>Nemo Krad (of RandomChaos) continues to <a href="http://xna-uk.net/blogs/randomchaos/archive/2009/11/26/last-post-of-the-month.aspx">tease us</a> with yet another video of his Deferred Render Instancing sample.<br />
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" width="425" height="344" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,40,0"><param name="allowFullScreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="src" value="http://www.youtube.com/v/Jeh4wQw0jUQ&amp;hl=en_US&amp;fs=1&amp;" /><param name="allowfullscreen" value="true" /><embed type="application/x-shockwave-flash" width="425" height="344" src="http://www.youtube.com/v/Jeh4wQw0jUQ&amp;hl=en_US&amp;fs=1&amp;" allowscriptaccess="always" allowfullscreen="true"></embed></object></p>
<p>Let's hope he releases the code soon, because what he's doing there definitely looks sweet, and there can never be too many samples about <a href="http://www.catalinzima.com/?page_id=14">deferred rendering</a>, or <a href="http://creators.xna.com/en-US/sample/meshinstancing">instancing</a>!</p>
<p>See all his posts about this so far, <a href="http://xna-uk.net/blogs/randomchaos/archive/tags/Deferred+Render/default.aspx">here</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2009/11/instanced-deferred-render/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Scrolls from the Past: Crash Course in HLSL</title>
		<link>http://www.sgtconker.com/2009/11/scrolls-from-the-past-crash-course-in-hlsl/</link>
		<comments>http://www.sgtconker.com/2009/11/scrolls-from-the-past-crash-course-in-hlsl/#comments</comments>
		<pubDate>Wed, 18 Nov 2009 21:50:46 +0000</pubDate>
		<dc:creator>Captain ZSquare</dc:creator>
				<category><![CDATA[Graphics]]></category>
		<category><![CDATA[Scrolls from the past]]></category>
		<category><![CDATA[Shaders]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[Shader]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/?p=526</guid>
		<description><![CDATA[Greetings again, good sirs and ladies.
This week, we will have a different kind of scoll to look at. Instead of looking into the archives for scrolls written by other people in times past, I will show you something that I accidentally found in my own archives today.
This was written many moons ago, as a sample [...]]]></description>
			<content:encoded><![CDATA[<p>Greetings again, good sirs and ladies.<br />
This week, we will have a different kind of scoll to look at. Instead of looking into the archives for scrolls written by other people in times past, I will show you something that I accidentally found in my own archives today.<br />
This was written many moons ago, as a sample for a book that was to be written for a great library together with some other wizards of XNA land. Even though the library keepers liked my writing, their plans for that book changed, and it never got written.<br />
Alas, I decided to not let those scrolls be forgotten, so I blew the dust off of them, made some corrections, and decided to bring them to your attention. In them, I talked about a detailed introduction into the magic of HLSL, and the basic elements needed to understand and use this wonderful kind of magic. You can find it <a href="http://www.sgtconker.com/2009/11/crash-course-in-hlsl/">here</a>.</p>
<p>Have a nice reading, and I wholeheartedly hope it helps at least some of my usual readers.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2009/11/scrolls-from-the-past-crash-course-in-hlsl/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Article: Crash Course in HLSL</title>
		<link>http://www.sgtconker.com/2009/11/crash-course-in-hlsl/</link>
		<comments>http://www.sgtconker.com/2009/11/crash-course-in-hlsl/#comments</comments>
		<pubDate>Wed, 18 Nov 2009 21:50:27 +0000</pubDate>
		<dc:creator>Captain ZSquare</dc:creator>
				<category><![CDATA[Articles]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[Shaders]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[Shader]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/?p=521</guid>
		<description><![CDATA[by Catalin Zima
What does HLSL stand for? Why was it created? How does an HLSL effect file look like? What can you do with HLSL? What do float4x4, TEXCOORD0 or compile ps_3_0 mean? The answer to the first question is simple: HLSL means High Level Shader Language. This answer by itself might raise a few [...]]]></description>
			<content:encoded><![CDATA[<h4 style="text-align: center;">by <a href="http://www.catalinzima.com/">Catalin Zima</a></h4>
<p>What does HLSL stand for? Why was it created? How does an HLSL effect file look like? What can you do with HLSL? What do <span style="font-family: Courier New;">float4x4</span>, <span style="font-family: Courier New;">TEXCOORD0</span> or <span style="font-family: Courier New;">compile ps_3_0</span> mean? The answer to the first question is simple: HLSL means High Level Shader Language. This answer by itself might raise a few questions. The answers for these and a few other questions will be found in this article.<br />
<span id="more-521"></span><br />
You will first learn about the history of HLSL and why it came to existence. After that, you will see the basic structure of an HLSL effect file, and learn about the different elements of the language. Finally, after looking over the language’s basics, you will see the template effect file that XNA gives to us.</p>
<h2>History of HLSL</h2>
<p>In more than one way, HLSL is for GPU programming as C is for CPU programming. You can use them both well without caring much about what was before them. However, just like with C, knowledge about what was before it will bring better understanding of what makes it special, and similar to computer science students who learn about CPU history, next you will see a brief history of GPUs.</p>
<p>As you probably know already, a GPU (Graphics Processing Unit) is the component inside your PC or console which has a single purpose: process and display computer graphics. The ancestors of modern GPUs are graphics chips present in 80’s PCs that has special circuits dedicated to combining two or more bitmaps into one image. However, the history of interest starts with the release of the first 3D hardware accelerator, in 1996. This was the 3dfx Voodoo card, which was a separate hardware component that had 3D functions implemented into it. The 3D functionality was soon integrated with the classic 2D video cards, to produce a single chip, the grandfather of current GPUs. The most popular video cards in that generation were the Voodoo, TNT, GeForce and Radeon series.</p>
<p>Another step towards current GPUs was the appearance of hardware support for Transform and Lighting, which meant that the video card could handle transformation of geometry in 3D space, clipping and lighting of the polygons, all in hardware. At this moment in time, all 3D capabilities were implemented as fixed-functions (thus called the Fixed Function Pipeline), which meant that you could only use the transformations and lighting models provided by the card. This caused many games of that time to look very similar.</p>
<p>To further enhance the realism and flexibility of computer graphics, the video card manufacturers could take one of two possible paths. One would have been to simply add more and more fixed-function functionality, to cover the many features that programmers desired. This would have needed an exponential growth in the number of circuits on the board, as well as the number of variables and states in the APIs. The second option, which is fortunately what was chosen, was to allow small programs to be written, which were to be executed for each vertex, or for each pixel that is processed by the video cards. This would give a lot of flexibility to developers to process graphics in any way they wanted (in the limits of the hardware, of course).</p>
<p>These small programs are called shaders, and were introduced in DirectX 8.0. A set of specifications, called Shader Model 1 detailed their possible functionality. In this version of Direct3D, programmers had to write shaders in a language similar to assembly and you can see an example of a vertex shader written in assembly language below.</p>
<pre class="brush: csharp;">vs_1_1
dcl_position v0
dcl_color v0
m4x4 oPos, v0, c0
mov oD0, v1
</pre>
<p>Shaders written in assembly were hard to read, understand and maintain. Besides this, Shader Model 1 allowed for very few instructions, and limited functionality. And just like CPU programming was blessed with higher level programming languages to make programming easier, DirectX 9.0 brought Shader Model 2.0, and together with it the High Level Shading Language.</p>
<p>HLSL is the language used to write shaders for GPUs in DirectX. It is syntactically similar to C, but has its own data types and program structure. It makes the graphics programmer’s life easier by allowing the elements of high level programming languages, such as named variables, functions, expressions, statements, standard and user-defined data types, and preprocessor directives. This makes it easier to write, read, understand and debug.</p>
<p>Before we dive into HLSL syntax and structure, you need to look at the graphics-processing pipeline.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2009/11/crash-course-in-hlsl/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
	</channel>
</rss>
