<?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; Shader</title>
	<atom:link href="http://www.sgtconker.com/tag/shader/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.sgtconker.com</link>
	<description>We are &#34;absolutely fine&#34;</description>
	<lastBuildDate>Wed, 06 Jul 2011 13:29:44 +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>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>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; title: ;">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>10</slash:comments>
		</item>
		<item>
		<title>Article : Realistic Soft Edged Water In XNA</title>
		<link>http://www.sgtconker.com/2009/11/article-realistic-soft-edged-water-in-xna/</link>
		<comments>http://www.sgtconker.com/2009/11/article-realistic-soft-edged-water-in-xna/#comments</comments>
		<pubDate>Tue, 03 Nov 2009 18:40:06 +0000</pubDate>
		<dc:creator>CorporalX</dc:creator>
				<category><![CDATA[3D]]></category>
		<category><![CDATA[Articles]]></category>
		<category><![CDATA[Graphics]]></category>
		<category><![CDATA[Shaders]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[RenderTarget]]></category>
		<category><![CDATA[Shader]]></category>

		<guid isPermaLink="false">http://www.sgtconker.com/?p=436</guid>
		<description><![CDATA[by X-Tatic

Still water bodies are a powerful distinguishing factor for identifying an outdoor scene. The nature of this water, such as a lake, makes it challenging to render efficiently while still maintaining a believable sense of realism. There are several factors that need to be considered when rendering such a water body and in this [...]]]></description>
			<content:encoded><![CDATA[<h4 style="text-align: center;">by <a href="http://www.x-tatic.net/">X-Tatic</a></h4>
<p style="text-align: center;"><a href="http://xtaticware.com/images/WaterArticle/ZWArtSampleProg4_7_9.jpg"><img class="aligncenter" src="http://xtaticware.com/images/WaterArticle/ZWArtSampleProg4_7_9.jpg" alt="" width="467" height="273" /></a></p>
<p style="text-align: left;">Still water bodies are a powerful distinguishing factor for identifying an outdoor scene. The nature of this water, such as a lake, makes it challenging to render efficiently while still maintaining a believable sense of realism. There are several factors that need to be considered when rendering such a water body and in this article I will cover each one while presenting the technical details.</p>
<p><span id="more-436"></span><br />
There is a sample download link at the end of the article, however I strongly suggest you follow the article in order to understand the progression of the effect.</p>
<h3 style="text-align: justify;"><strong>Introduction</strong></h3>
<p>Many games seem to now have a higher occurrence of outdoor scenes, or even elements of outdoor scenes. Many outdoor elements are significantly difficult to implement, such as large terrain, believe vegetation, or atmospheric scattering. Fortunately one such element can be implemented easily with spectacular results. Here I present an implementation to represent calm and slow flowing flat water bodies, such as lakes. The technique will implement varying intensity and color over depth, as well as fading intensity of color, transparency, and ripple at the shoreline. Lighting will consist of phong specular and a Fresnel factor for varying transparency between reflection and refraction.</p>
<p><strong>Rendering a Scene</strong></p>
<p>One of the best ways to contrast the rendering of your water, showing reflection and refraction is with terrain. A terrain implementation is beyond the scope of this article, however you can find multiple articles about this subject throughout the web. For this article and sample, I will start with the XNA Creators Club Sample titled “Lens Flare”. You can download it from here: <a href="http://creators.xna.com/downloads/?id=138" target="_blank">http://creators.xna.com/downloads/?id=138</a> (you may need to upgrade the solution to XNA 3.1).</p>
<p>The first thing I am going to do with this sample is to re-factor the terrain drawing into its own method. The reason for this is that we will need to draw it more than once a frame, and do not want a lot of redundant code.</p>
<p>Move the terrain drawing code into a method like this:</p>
<pre class="brush: csharp; title: ;">protected void DrawTerrain(ref Matrix view, ref Matrix projection)
{
    // Draw the terrain.
    GraphicsDevice.RenderState.CullMode = CullMode.None;

    foreach (ModelMesh mesh in terrain.Meshes)
    {
        foreach (BasicEffect effect in mesh.Effects)
        {
            effect.World = Matrix.Identity;
            effect.View = view;
            effect.Projection = projection;

            effect.LightingEnabled = true;
            effect.DiffuseColor = new Vector3(1f);
            effect.AmbientLightColor = new Vector3(0.5f);

            effect.DirectionalLight0.Enabled = true;
            effect.DirectionalLight0.DiffuseColor = Vector3.One;
            effect.DirectionalLight0.Direction = lensFlare.LightDirection;

            effect.FogEnabled = true;
            effect.FogStart = 200;
            effect.FogEnd = 500;
            effect.FogColor = Color.CornflowerBlue.ToVector3();
        }

        mesh.Draw();
    }
}</pre>
<p>Then call the draw where it used to be in the Games Draw method:</p>
<pre class="brush: csharp; title: ;">this.DrawTerrain(ref view, ref projection);</pre>
<p><strong>Drawing the Water Plane</strong></p>
<p>To get something representing the water surface, we will draw some geometry covering the same area as the terrain; since we are doing this step by step we will draw this plane geometry white for now. What we will need is: Vertex/Index Buffers for the planar geometry and an Effect to draw it with. For convenience, we will place this in its own class called PlanarWater.</p>
<p>Right click in the project in the solution explorer window and choose Add&gt;New Item, the pick Class, calling it PlanarWater.cs.</p>
<p>Add the following code to the file:</p>
<pre class="brush: csharp; title: ;">using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;

namespace LensFlare
{
    public class PlanarWater
    {
        private VertexBuffer PlaneVB;
        private VertexDeclaration PlaneVD;

        private Effect WaterEffect;

        ///
        /// A tesselation factor to balance the texture read cache.
        ///
        private const int Tesselation = 10;

        private const int TesselationN1 = Tesselation - 1;

        ///
        /// Static world matrix that will match our water grid up to terrain
        ///
        private static Matrix World;

        static PlanarWater()
        {
            PlanarWater.World = Matrix.CreateScale(600f, 1f, 600f) * Matrix.CreateTranslation(25f, 23f, 25f);
        }

        public PlanarWater(GraphicsDevice device, Effect waterEffect)
        {
            const int vertexCount = 6 * TesselationN1 * TesselationN1;

            this.WaterEffect = waterEffect;
            this.PlaneVB = new VertexBuffer(device, typeof(VertexPositionTexture), vertexCount, BufferUsage.WriteOnly);
            this.PlaneVD = new VertexDeclaration(device, VertexPositionTexture.VertexElements);

            VertexPositionTexture[] vertices = new VertexPositionTexture[vertexCount];

            // Space between grid cells
            const float delta = 1f/Tesselation;

            // Offset to position around origin in object space
            const float halfLength = 0.5f;

            // current index into vertices
            int index = 0;

            for (int x = 0; x &amp;lt; Tesselation-1; x++)
            {
                // positions for current and next along X
                float column1 = (delta * x) - halfLength;
                float column2 = column1  + delta;

                // texcoords for current and next along U
                float uCoord1 = column1 + 0.5f;
                float uCoord2 = column2 + 0.5f;

                for (int z = 0; z &amp;lt; Tesselation-1; z++)
                {
                    // positions for current and next along Z
                    float row1 = (delta * z) - halfLength;
                    float row2 = row1 + delta;

                    // texcoords for current and next along V
                    float vCoord1 = row1 + 0.5f;
                    float vCoord2 = row2 + 0.5f;

                    /// Triangle 1
                    {
                        vertices[index].TextureCoordinate = new Vector2(uCoord1, vCoord1);
                        vertices[index++].Position = new Vector3(column1, 0, row1);

                        vertices[index].TextureCoordinate = new Vector2(uCoord2, vCoord1);
                        vertices[index++].Position = new Vector3(column2, 0, row1);

                        vertices[index].TextureCoordinate = new Vector2(uCoord2, vCoord2);
                        vertices[index++].Position = new Vector3(column2, 0, row2);
                    }

                    /// Triangle 2
                    {
                        vertices[index].TextureCoordinate = new Vector2(uCoord2, vCoord2);
                        vertices[index++].Position = new Vector3(column2, 0, row2);

                        vertices[index].TextureCoordinate = new Vector2(uCoord1, vCoord2);
                        vertices[index++].Position = new Vector3(column1, 0, row2);

                        vertices[index].TextureCoordinate = new Vector2(uCoord1, vCoord1);
                        vertices[index++].Position = new Vector3(column1, 0, row1);
                    }
                }
            }

            this.PlaneVB.SetData(vertices);
        }

        public void Draw(GraphicsDevice device, Matrix view, Matrix projection)
        {
            device.VertexDeclaration = this.PlaneVD;
            device.Vertices[0].SetSource(this.PlaneVB, 0, VertexPositionTexture.SizeInBytes);
            device.Indices = null;

            RenderState renderState = device.RenderState;

            renderState.DepthBufferEnable = true;
            renderState.AlphaTestEnable = false;
            renderState.AlphaBlendEnable = false;

            this.WaterEffect.Begin();

            this.WaterEffect.Parameters[&quot;World&quot;].SetValue(PlanarWater.World);
            this.WaterEffect.Parameters[&quot;View&quot;].SetValue(view);
            this.WaterEffect.Parameters[&quot;Projection&quot;].SetValue(projection);

            this.WaterEffect.Techniques[0].Passes[0].Begin();

            const int primitiveCount = 2 * (TesselationN1*TesselationN1);
            device.DrawPrimitives(PrimitiveType.TriangleList, 0, primitiveCount);

            this.WaterEffect.Techniques[0].Passes[0].End();
            this.WaterEffect.End();
        }
    }
}</pre>
<p>This creates a grid mesh of type triangle list, and draws it in the world so that it intersects the terrain. However, first it needs an effect to draw with.</p>
<p>Right click your content project and choose Add&gt;New Item. Choose Effect File, and call it Water.fx.</p>
<p>Add the following HLSL code to the .fx file:</p>
<pre class="brush: csharp; title: ;">float4x4 World;
float4x4 View;
float4x4 Projection;

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

struct VertexShaderOutput
{
    float4 Position : POSITION0;
    float2 TexCoord : TEXCOORD0;
};

VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput output;

    float4 worldPosition = mul(float4(input.Position, 1), World);
    float4 viewPosition = mul(worldPosition, View);
    output.Position = mul(viewPosition, Projection);

    output.TexCoord  = input.TexCoord;

    return output;
}

float4 PixelShaderFunction(VertexShaderOutput input) : COLOR0
{
    return float4(input.TexCoord.x, input.TexCoord.y, 0, 1);
}

technique Technique1
{
    pass Pass1
    {
        VertexShader = compile vs_2_0 VertexShaderFunction();
        PixelShader = compile ps_2_0 PixelShaderFunction();
    }
}</pre>
<p>Now we can draw the planar water mesh, showing its texture coordinates. First we need to create an instance of PlanarWater and pass it the effect. Add a new field:</p>
<pre class="brush: csharp; title: ;">private PlanarWater water;</pre>
<p>Inside the LoadContent method, initialize the water field:</p>
<pre class="brush: csharp; title: ;">water = new PlanarWater(graphics.GraphicsDevice, Content.Load(&quot;Water&quot;));</pre>
<p>Now finally, call draw on the water right after the terrain is drawn, inside the Games Draw method:</p>
<pre class="brush: csharp; title: ;">this.water.Draw(graphics.GraphicsDevice, view, projection);</pre>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2009/11/article-realistic-soft-edged-water-in-xna/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Article: Simply Rendertargets</title>
		<link>http://www.sgtconker.com/2009/10/simply-rendertargetsplaceholder/</link>
		<comments>http://www.sgtconker.com/2009/10/simply-rendertargetsplaceholder/#comments</comments>
		<pubDate>Wed, 14 Oct 2009 01:21:58 +0000</pubDate>
		<dc:creator>Sgt. Conker</dc:creator>
				<category><![CDATA[2D]]></category>
		<category><![CDATA[Articles]]></category>
		<category><![CDATA[Shaders]]></category>
		<category><![CDATA[XNA]]></category>
		<category><![CDATA[RenderTarget]]></category>
		<category><![CDATA[Shader]]></category>
		<category><![CDATA[SpriteBatch]]></category>

		<guid isPermaLink="false">http://sgt.conkerjo.com/?p=23</guid>
		<description><![CDATA[This article describes how to use RenderTargets to draw a portion of the screen or an image using SpriteBatch.]]></description>
			<content:encoded><![CDATA[<h4 style="text-align: center;">by <a href="http://www.conkerjo.com/">Conkerjo</a></h4>
<p>This article describes how to use RenderTargets to draw a portion of the screen or an image using SpriteBatch.<br />
<span id="more-23"></span><br />
Here's an image of our game.</p>
<p><a href="http://conkerjo.files.wordpress.com/2009/05/background.png"><br />
<img style="display:inline;border-width:0;" title="background" src="http://conkerjo.files.wordpress.com/2009/05/background_thumb.png" border="0" alt="background" width="244" height="184" /></a></p>
<p>And here is how we want the result to look</p>
<p><a href="http://conkerjo.files.wordpress.com/2009/05/pieview.jpg"><img style="display:inline;border-width:0;" title="pieview" src="http://conkerjo.files.wordpress.com/2009/05/pieview_thumb.jpg" border="0" alt="pieview" width="244" height="192" /><br />
</a></p>
<p>What you see here is the game scene drawn, with a triangle portion visible and the rest not so much. My favourite way to achieve this is to use 2 RenderTargets, A VERY simple Effect(shader) and good old SpriteBatch.<br />
So what do we use all this for?</p>
<p>First we need to draw the game scene. There is a way around this but to make things easier to understand we will draw this to a RenderTarget. Simply put, a RenderTarget is an imaginary “screen” to draw to which you can specify the size of.<br />
Then once done, you can use the texture like any normal Texture2D you might load from the Content Pipeline.</p>
<p>To draw the scene we first want to set the correct RenderTarget, then use spritebatch just like you would to draw any other sprite. Like this.</p>
<pre class="brush: csharp; title: ;">
    GraphicsDevice.SetRenderTarget(0, _gameRT);
    //Clear the RT screen
    GraphicsDevice.Clear(Color.Black);
    spriteBatch.Begin();
    //Draw the game
    spriteBatch.Draw(
        _gameBackground,
        Vector2.Zero,
        Color.White);

    spriteBatch.End();
</pre>
<p>Simple uh?</p>
<p>Now we need to create another RenderTarget, and Draw a triangle to it. This will never be displayed in the final scene. Although with the RenderTarget it allows you to if you so desire, maybe for debugging purposes?</p>
<pre class="brush: csharp; title: ;">

            GraphicsDevice.SetRenderTarget(0, _lightRT);
            //Clears the screen transparent.
            GraphicsDevice.Clear(Color.TransparentBlack);
            spriteBatch.Begin();

            spriteBatch.Draw(
                _triangle,
                Vector2.Zero,
                Color.White);

            spriteBatch.End();
</pre>
<p>This code is almost identical to the last except we draw the _triangle Texture which looks like this.</p>
<p><a href="http://conkerjo.files.wordpress.com/2009/05/triangle.png"><img style="display:inline;border-width:0;" title="triangle" src="http://conkerjo.files.wordpress.com/2009/05/triangle_thumb.png" border="0" alt="triangle" width="244" height="124" /></a></p>
<p>And we use the color transparent black.</p>
<p>The final thing we need to do now is draw it to the scene.</p>
<p>If we just draw the triangle on top of the game scene you will see the game scene with a white triangle on top.<br />
This isnt what we want. So we use a shader to take the game scene, and change the alpha channel corresponding to the white triangle.<br />
Wherever there is a solid non transparent color pixel, this will be set to a fully non transparent pixel in the game result, however, a transparent pixel in the triangle image will result in a completely transparent pixel in the final result.<br />
Resulting in you not being able to see that pixel. The final result is like this.</p>
<p><a href="http://conkerjo.files.wordpress.com/2009/05/pieview.jpg"><br />
<img style="display:inline;border-width:0;" title="pieview" src="http://conkerjo.files.wordpress.com/2009/05/pieview_thumb.jpg" border="0" alt="pieview" width="244" height="192" /><br />
</a></p>
<p>The shader code is very simple. It is a pixel shader which takes a AlphaTexture parameter which is the texture taken from the triangle RT.<br />
It takes the alpha from that texture, and sets the coresponding pixel on the final image to be the same.</p>
<pre class="brush: csharp; title: ;">
    float4 PixelShader(float2 texCoord: TEXCOORD0) : COLOR
    {
	    float4 Color = tex2D(ScreenS, texCoord);
        float alphaLayerAlpha = tex2D(AlphaSampler, texCoord).a;
	    Color.a=alphaLayerAlpha;
        return Color;
    }
</pre>
<p>Cool?</p>
<p>To use this we just create a new Effect variable and load it in LoadContent. Call Begin/End in the appropriate places, set the parametar and hey presto. A RESULT!!!</p>
<pre class="brush: csharp; title: ;">
    _myEffect.Parameters[&amp;quot;AlphaTexture&amp;quot;].SetValue(_lightRT.GetTexture());

	spriteBatch.Begin(SpriteBlendMode.AlphaBlend, SpriteSortMode.Immediate, SaveStateMode.None);
	_myEffect.Begin();
    _myEffect.CurrentTechnique.Passes[0].Begin();

    spriteBatch.Draw(_gameRT.GetTexture(),
        Vector2.Zero,
        Color.White);

    _myEffect.CurrentTechnique.Passes[0].End();
    _myEffect.End();
    spriteBatch.End();
</pre>
<p>To get a better grasp of the code you can download the sample project here.</p>
<p><a href="http://www.sgtconker.com/Downloads/articles/SimplyRenderTargets.zip" target="_blank">DOWNLOAD</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.sgtconker.com/2009/10/simply-rendertargetsplaceholder/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

