Drawing FullScreen Quads with XNA 4.0


Quads are very important for numerous effects like all Image processing techniques (Bloom, Blur,Fog ….), Deferred Shading, Some particles system technics and others …..

In this short tutorial we will show how to draw a simple quad (and the theory behind it =P) using xna 4.0

If you dont want to know about the theory behind the quads, no problems =P, go to the code section directly.

Instead of showing how to create a Quad, i will talk about a specific case called FullScreenQuad, cause it is simpler and more easy to follow than the general case. (The concepts are the same in both case).

In simple words FullScreenQuad is just two triangles that fills the entire screen (imagine a rectangle in 2D that cover all the screen =P).

The importance of drawing FullScreen Quads is that we can run the pixel shader exactly once for each pixel of the render target (can be the back buffer or a texture). One example of this usefull property is the PostProcessing phase (or Image Process phase) where we recieve one quad and one texture as inputs, in GPU we change each texel of this texture and save the changes to the render target.

The magic is that the constructed quad will be perfect aligned to the screen borders (a rectangle covering all of it), when it is rasterized, the pixel shader will be called exactely once for each pixel of the screen, then you can access each corresponding texel of the associated texture, change it (process) and output  it in the render target in the same position it has in the original texture. (Remember that Render targets can be used as textures in another shader pass)

There are LOTS of ways of drawing fullscreen quads. We will use one that is simple and flexible enough =P (and can be used to draw arbitrary size quads, not only fullscreen).

Our choice is to create the vertices in CPU already in Projection Space and send them to a by-pass Vertex Shader.
In Projection space (after applying the world, view and projection matrix) , the borders of the screen (using the DirectX/XNA Projection matrix convention) are:  X: [-1,1], Y:[-1,1] and Z[0,1] (primitives which vertices is out of this range are clipped).  For example, a point with (-1,-1,0) will be in the down, left of you screen (The Z being 0 mean that it is VERY close to the camera). A point in (0,0,0) will appear in the midle of the screen. The following image shows the projection coordinates domain: (imagine the screen being the front square). Remember that we are in the normalized space, the rasterizator unit will convert it to the real screen coordinates (resolution dependent one)

DirectX Projection Coordinates space

So we will just create two triangles (to fill the quad) already in projection space, pass them to vertex shader, dont apply transformation (cause they are already in projection space) and send the vertices to the rasterization unit.

The vertice will contain the positions in Projection Space  and the Texture Coordinates. The up, left point of the quad will have the (0,0) texture coordinate and the lower, right will be (1,1).

The following code shows an easy way to do this in XNA 4.0:

internal sealed class QuadRender
    {
        private VertexPositionTexture[] verts;
        private GraphicsDevice myDevice;
        private short[] ib = null;

        ///
        /// Loads the quad.
        ///
        ///
The engine.
        public QuadRender(GraphicsDevice device)
        {

            myDevice = device;         

            verts = new VertexPositionTexture[]
                        {
                            new VertexPositionTexture(
                                new Vector3(0,0,0),
                                new Vector2(1,1)),
                            new VertexPositionTexture(
                                new Vector3(0,0,0),
                                new Vector2(0,1)),
                            new VertexPositionTexture(
                                new Vector3(0,0,0),
                                new Vector2(0,0)),
                            new VertexPositionTexture(
                                new Vector3(0,0,0),
                                new Vector2(1,0))
                        };

             ib = new short[] { 0, 1, 2, 2, 3, 0 };

        }             

        ///
        /// Draws the fullscreen quad.
        ///
        ///
The effect.
        public void RenderFullScreenQuad(Effect effect)
        {
            effect.CurrentTechnique.Passes[0].Apply();
            RenderQuad(Vector2.One * -1, Vector2.One);
        }

        public void RenderQuad(Vector2 v1, Vector2 v2)
        {          

            verts[0].Position.X = v2.X;
            verts[0].Position.Y = v1.Y;

            verts[1].Position.X = v1.X;
            verts[1].Position.Y = v1.Y;

            verts[2].Position.X = v1.X;
            verts[2].Position.Y = v2.Y;

            verts[3].Position.X = v2.X;
            verts[3].Position.Y = v2.Y;

            myDevice.DrawUserIndexedPrimitives
                (PrimitiveType.TriangleList, verts, 0, 4, ib, 0, 2);
        }
    }

If you dont want to draw a full screen quad, you can change the border values passed as function parameter

The Vertex Shader to process the FullScreen quad is:

texture colorMap;
sampler colorSampler = sampler_state
{
    Texture = (colorMap);
    AddressU = CLAMP;
    AddressV = CLAMP;
    MagFilter = LINEAR;
    MinFilter = LINEAR;
    Mipfilter = LINEAR;
};

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

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

float2 halfPixel;
VertexShaderOutput VertexShaderFunction(VertexShaderInput input)
{
    VertexShaderOutput output;
    input.Position.x =  input.Position.x - 2*halfPixel.x;
    input.Position.y =  input.Position.y + 2*halfPixel.y;
    output.Position = float4(input.Position,1);
    output.TexCoord = input.TexCoord ;
    return output;
}

 

XNA 4.0 works under DirectX9.0. In this environment, we have to make a “somehow strange correction” to the position of our vertices in the Vertex Shader (subtract the halfPixel size) when processing quads. The reason for this is the algorithm used in the rasterization unit (More info about this is Here).

The Pixel Shader is where you process the image. For this sample i just multiply each texel by 0.7f. (make them darker):

float4 PixelShaderFunctionNormal(VertexShaderOutput input) : COLOR0
{
	float4 process = tex2D(colorSampler,input.TexCoord);
        return process * 0.7f;
}

Its done =P quite simple. The PostProcess samples (the simple ones) are just “diferent” pixel shaders that process the recovered color in diferent ways.

 

, , ,

  1. #1 by WINTER FUN on 22 de julho de 2017 - 11:20 am

    Wonderful story, reckoned we could combine a couple of unrelated data, nevertheless seriously worth taking a search, whoa did one particular understand about Mid East has got far more problerms too

  2. #2 by TOP RATED SLED on 22 de julho de 2017 - 11:24 am

    Wonderful story, reckoned we could combine a few unrelated information, nonetheless truly really worth taking a search, whoa did 1 master about Mid East has got more problerms also

  3. #3 by http://cottageofgrace.com/CLshoes.asp on 22 de julho de 2017 - 1:57 pm

    The supplement was in such a ideal rates I do not believe your grade is therefore exceptional. It’s breathtaking. It mother may enjoy they on top of Xmas early morning when she opens up gift and it appearance as though I invested far more, although cost had been just awesome!!

  4. #4 by cartier love bracelet replica on 22 de julho de 2017 - 3:17 pm

    This particular product is at such a awesome expense I never attention all excellent would be therefore excellent. It’s beautiful. It mama is going to enjoy this concerning Christmas time day when she opens present and it looks like I invested alot more, although cost is just great!!

  5. #5 by go to this website on 22 de julho de 2017 - 7:15 pm

    below youll uncover the link to some websites that we assume it is best to visit

  6. #6 by Wholesale Jerseys From China on 22 de julho de 2017 - 9:05 pm

    An example of one such instance on my site is a horse called Ameeq. It will help to toughen them up mentally. Several of these merchandise is made with cold temperatures taken into account, as well as others, as an example the classy tote and also other handbags, are great for any kind of weather. Find free articles in our dofollow article directory, get free website content and submit your own articles for free. In 1994, Woods was a national star, and he jointly entered for the only time the SCGA Amateur and State Amateur.
    Wholesale Jerseys From China http://www.empsuccess.com/

  7. #7 by sasha grey deepthroat on 22 de julho de 2017 - 9:14 pm

    The details talked about within the article are a number of the most beneficial obtainable

  8. #8 by click here for info on 22 de julho de 2017 - 10:27 pm

    that would be the finish of this post. Right here you will find some websites that we think you will enjoy, just click the links over

  9. #9 by cartier juste un clou replica on 22 de julho de 2017 - 10:32 pm

    I’ve purchased that brand concerning bracelet some instances. Every single one is ultra cute, done very well, cannot tarnish as well as meaningful based on what any you purchase plus which your bring things towards.

  10. #10 by the magic wand massager on 22 de julho de 2017 - 10:32 pm

    we like to honor quite a few other net web pages around the web, even though they arent linked to us, by linking to them. Underneath are some webpages worth checking out

  11. #11 by BrvCat on 22 de julho de 2017 - 10:33 pm

    lendup cash now all payday loan companies [url=https://paydayloans365vra.org/]best online payday loans[/url] ’

  12. #12 by cheapest homeowners insurance on 22 de julho de 2017 - 10:46 pm

    Hiya very nice blog!! Guy .. Excellent .. Superb .. I will bookmark your web site and take the feeds also?KI am glad to search out so many helpful info here in the publish, we need work out more strategies on this regard, thank you for sharing. . . . . .

  13. #13 by cheap nike roshe run on 23 de julho de 2017 - 2:43 am

    The system ended up being at that ideal pricing I do not thought that the top quality would be quite excellent. Its pretty. This mother does like they upon Xmas early morning where she starts present therefore seems like I invested more, and yet pricing is really very good!!

  14. #14 by cheap louboutin shoes replica on 23 de julho de 2017 - 7:56 am

    This particular system had been in such a great expense I do not idea the high quality would be so that exceptional. It is pretty. This one mama will really like that upon Xmas day once she opens up present therefore appearances as though I invested a great deal more, however rates was just very good!!

  15. #15 by cheap nike roshe run on 23 de julho de 2017 - 7:57 am

    That goods ended up being in such a great amount I by no means believed ones excellence is so exceptional. It’s striking. The mom will likely appreciate this at Xmas early morning once she opens gift and it styles as though I invested even more, and yet rates had been exclusively ideal!!

  16. #16 by boxes on 23 de julho de 2017 - 7:58 am

    although internet websites we backlink to below are considerably not associated to ours, we really feel they may be essentially worth a go through, so possess a look

  17. #17 by hermes h bracelet replica on 23 de julho de 2017 - 8:50 am

    I have bought this particular brand name concerning bracelet a few times. Every a person is ultra cute, made well, does not tarnish and also significant based on which kind of someone you buy additionally just who people promote things at.

  18. #18 by link building local seo on 23 de julho de 2017 - 10:26 am

    the time to read or stop by the subject material or web pages we have linked to beneath the

  19. #19 by why not find out more on 23 de julho de 2017 - 10:39 am

    check beneath, are some entirely unrelated sites to ours, nevertheless, they are most trustworthy sources that we use

  20. #20 by http://www.julianhans.com/wp-price.php on 23 de julho de 2017 - 12:59 pm

    I have bought your brand concerning bracelet various times. Every single one is very attractive, created well, cannot tarnish additionally significant based on which kind of one particular you buy and/or that shoppers present it on.

  21. #21 by cheap nike roshe run on 23 de julho de 2017 - 1:52 pm

    We have bought your brand name of bracelet a number of circumstances. Every single one is extremely cute, created well, does not tarnish and also important based on which any you purchase then which a person provide that it to.

  22. #22 by http://www.aspkucyl.org/files/shoesmen.asp on 23 de julho de 2017 - 1:52 pm

    We have purchased this particular brand out of bracelet a number of instances. Every one is very pretty, manufactured well, cannot tarnish as well as important depending on which an you purchase plus that people give it in order to.

  23. #23 by worktop protection on 23 de julho de 2017 - 2:12 pm

    here are some links to web sites that we link to since we believe they’re worth visiting

  24. #24 by Lahpram on 23 de julho de 2017 - 5:48 pm

    all online payday loans – https://cashadvance300nty.org/ direct lender payday loans [url=https://cashadvance300nty.org/]cash advance loan[/url] ’

  25. #25 by http://www.bmx-saintquentin.com/flats.asp on 23 de julho de 2017 - 6:04 pm

    Our device had been at that awesome price tag I did not thought ones excellence would be so that exceptional. Its awesome. This particular mama will likely really like that it on Xmas day after she opens present therefore styles as though I spent a great deal more, and yet rates had been just ideal!!

  26. #26 by BedcVeld on 23 de julho de 2017 - 6:57 pm

    payday loan installment – https://personalloan365ergh.org/ business loan [url=https://personalloan365ergh.org/]quick personal loans bad credit[/url] ’

  27. #27 by more tips here on 23 de julho de 2017 - 6:59 pm

    Here is a great Weblog You may Obtain Exciting that we Encourage You

  28. #28 by LmnPak on 23 de julho de 2017 - 7:15 pm

    bad credit debt consolidation internet payday loan – https://loansbadcredit24hvm.org/ cash advance credit cards [url=https://loansbadcredit24hvm.org/]bad credit loans[/url] ’

1 740 741 742
(não será publicado)