XNA for C#
DirectX 9 for C#
DirectX 9 for C++
DirectX 9 for VB
Forum
   
My XNA Book
      
       Go to section on this site

Additional info


Latest Forum posts

 No download link for 2d series: shooter
  Posted by: zaboleq
  When: 07/05/2013 at 15:46:28

 Collision Class?
  Posted by: Anonymous
  When: 05/05/2013 at 19:03:59

 stack overflow
  Posted by: cityguy
  When: 07/04/2013 at 01:58:38

 Meshes looks strange.
  Posted by: ab_saratov
  When: 01/04/2013 at 04:31:08

 Lamppost Not loaded
  Posted by: Anonymous
  When: 22/03/2013 at 06:43:52

 Collision Class?
  Posted by: Da_Boom
  When: 21/03/2013 at 01:23:09

 Math boggles me
  Posted by: cityguy
  When: 17/03/2013 at 03:44:48

 Collision Class?
  Posted by: Da_Boom
  When: 16/03/2013 at 03:44:42

 Tree update
  Posted by: Anonymous
  When: 15/03/2013 at 21:11:22

 XNA 4.0
  Posted by: Anonymous
  When: 15/03/2013 at 19:43:57


Ads

Adding more detail close to the camera

When you look at the terrain from a distance, it looks pretty nice. But when you move the camera very close to the terrain, you値l see the individual pixels of each texture are spread out over quite a large area. This is bad, because in a game, the camera will most of the time be placed close to the terrain.

So how can we solve this? One easy approach would be to enlarge our texture coords, so much more of our textures would be put on our terrain, like this:

 terrainVertices[x + y * terrainWidth].TexCoords.Z = x / (float)10;
 terrainVertices[x + y * terrainWidth].TexCoords.W = y / (float)10;

Instead of:

 terrainVertices[x + y * terrainWidth].TexCoords.Z = x / (float)30;
 terrainVertices[x + y * terrainWidth].TexCoords.W = y / (float)30;

When running this, you値l see that this gives good results when the camera is close to the terrain, but when you move the camera further away, the textures will be too small so you see the repeating pattern. So the problem is now the other way around.

Instead of choosing one of these approaches, we値l combine both. This is done in our pixel shader: when the pixel is far away from our camera, we値l use the big textures. When the pixel is very close to the camera, we値l use the smaller, more detailed textures. For the region in between, we値l blend between these two. This whole operation can be done in the pixel shader, so the load on our CPU will remain the same.

As you can see, for each pixel we値l need the distance to our camera. So add this line to the struct MTVertexToPixel struct:

float    Depth            : TEXCOORD4;

This distance is nothing more than the z coordinate of the position in camera space. Remember, because this was the result of a 4x4 matrix multiplication, we first need to divide it by the w component before we can use it:

Output.Depth = Output.Position.z/Output.Position.w;

Now we can access this in the pixel shader, we know the distance between each pixel and the camera. Let痴 go to our pixel shader, where we値l define 2 values concerning the blending: the distance to the camera at which blending will begin, and the width of the blending border:

float blendDistance = 0.99f;
float blendWidth = 0.005f;
float blendFactor = clamp((PSIn.Depth-blendDistance)/blendWidth, 0, 1);

The last line is our blending function. All pixels will have a Depth value between 0 and 1, where 0 corresponds to the near clipping plane distance and 1 to the far clipping plane distance (as set in your projectionMatrix). Using this function, all pixels closer to the camera than 0.99 will get blendfactor 0, all pixel further than 0.99+0.005=0.995 will get blendfactor 1 and all pixels in between will get a linearly interpolated blendfactor. I have visualized this in the next image:



Where completely blue means blendfactor 0, and completely red blendfactor 1. Pixels with blendfactor 0 will use the highly detailed textures, and the red ones will use the standard textures.

First, we値l calculate both the high-detail color for each pixel as well as the standard color:

float4 farColor;
farColor = tex2D(TextureSampler0, PSIn.TextureCoords)*PSIn.TextureWeights.x;
farColor += tex2D(TextureSampler1, PSIn.TextureCoords)*PSIn.TextureWeights.y;
farColor += tex2D(TextureSampler2, PSIn.TextureCoords)*PSIn.TextureWeights.z;
farColor += tex2D(TextureSampler3, PSIn.TextureCoords)*PSIn.TextureWeights.w;
    
float4 nearColor;
float2 nearTextureCoords = PSIn.TextureCoords*3;
nearColor = tex2D(TextureSampler0, nearTextureCoords)*PSIn.TextureWeights.x;
nearColor += tex2D(TextureSampler1, nearTextureCoords)*PSIn.TextureWeights.y;
nearColor += tex2D(TextureSampler2, nearTextureCoords)*PSIn.TextureWeights.z;
nearColor += tex2D(TextureSampler3, nearTextureCoords)*PSIn.TextureWeights.w;

Where the first block of code is taken straight from the previous chapter. For the near color, we multiply our texture c0ords by 3, so the textures a 3 times smaller, and thus 3 times more detailed.

Now we have both our near and far colors for the pixel, we need to mix them according to the blendfactor:

Output.Color = lerp(nearColor, farColor, blendFactor);
Output.Color *= lightingFactor;

This is simple linear interpolation, useful when the blendfactor is between 0 and 1. When you multiply this with the lighting factor, you should get the same result as below:




DirectX Tutorial 5 - Adding detail

If you appreciate the amount of time I spend creating and updating
these pages, feel free to donate -- any amount is welcome !



Click here to go to the forum on this chapter!

Or click on one of the topics on this chapter to go there:
  • XNA 4.0
           ******************************** **************...
  • adding really near detail does not work
          Hello. I tried to add a third level of detail t...
  • Problem with adding detail to multitex
          Hello, these tutorials are great and really excele...
  • Warning compiling HLSL file
          After copying the text, I get this warning in the ...


    The chapter is the last one of this series that will handle the texturing of our terrain. Next chapter we could start with the water technique, but this will yield poor results because we don稚 have any clouds yet that can be reflected in the water. So first we値l load a skysphere and decorate it with a cloud texture.

    You can try these exercises to practice what you've learned:
  • Try playing around with the blendDistance and blendWidth values
  • Try adding a 3rd level of detail for the textures
    //----------------------------------------------------
    //-- --
    //-- www.riemers.net --
    //-- Series 4: Advanced terrain --
    //-- Shader code --
    //-- --
    //----------------------------------------------------

    //------- Constants --------
    float4x4 xView;
    float4x4 xProjection;
    float4x4 xWorld;
    float3 xLightDirection;
    float xAmbient;
    bool xEnableLighting;

    //------- Texture Samplers --------
    Texture xTexture;

    sampler TextureSampler = sampler_state { texture = <xTexture> ; magfilter = LINEAR; minfilter = LINEAR; mipfilter=LINEAR; AddressU = mirror; AddressV = mirror;};Texture xTexture0;

    sampler TextureSampler0 = sampler_state { texture = <xTexture0> ; magfilter = LINEAR; minfilter = LINEAR; mipfilter=LINEAR; AddressU = wrap; AddressV = wrap;};Texture xTexture1;

    sampler TextureSampler1 = sampler_state { texture = <xTexture1> ; magfilter = LINEAR; minfilter = LINEAR; mipfilter=LINEAR; AddressU = wrap; AddressV = wrap;};Texture xTexture2;

    sampler TextureSampler2 = sampler_state { texture = <xTexture2> ; magfilter = LINEAR; minfilter = LINEAR; mipfilter=LINEAR; AddressU = mirror; AddressV = mirror;};Texture xTexture3;

    sampler TextureSampler3 = sampler_state { texture = <xTexture3> ; magfilter = LINEAR; minfilter = LINEAR; mipfilter=LINEAR; AddressU = mirror; AddressV = mirror;};
    //------- Technique: Textured --------
    struct TVertexToPixel
    {
    float4 Position     : POSITION;
    float4 Color        : COLOR0;
    float LightingFactor: TEXCOORD0;
    float2 TextureCoords: TEXCOORD1;
    };

    struct TPixelToFrame
    {
    float4 Color : COLOR0;
    };

    TVertexToPixel TexturedVS( float4 inPos : POSITION, float3 inNormal: NORMAL, float2 inTexCoords: TEXCOORD0)
    {
        TVertexToPixel Output = (TVertexToPixel)0;
        float4x4 preViewProjection = mul (xView, xProjection);
        float4x4 preWorldViewProjection = mul (xWorld, preViewProjection);

        Output.Position = mul(inPos, preWorldViewProjection);
        Output.TextureCoords = inTexCoords;

        float3 Normal = normalize(mul(normalize(inNormal), xWorld));
        Output.LightingFactor = 1;
        if (xEnableLighting)
            Output.LightingFactor = saturate(dot(Normal, -xLightDirection));

        return Output;
    }

    TPixelToFrame TexturedPS(TVertexToPixel PSIn)
    {
        TPixelToFrame Output = (TPixelToFrame)0;

        Output.Color = tex2D(TextureSampler, PSIn.TextureCoords);
        Output.Color.rgb *= saturate(PSIn.LightingFactor + xAmbient);

        return Output;
    }

    technique Textured_2_0
    {
        pass Pass0
        {
            VertexShader = compile vs_2_0 TexturedVS();
            PixelShader = compile ps_2_0 TexturedPS();
        }
    }

    technique Textured
    {
        pass Pass0
        {
            VertexShader = compile vs_1_1 TexturedVS();
            PixelShader = compile ps_1_1 TexturedPS();
        }
    }

    //------- Technique: Multitextured --------
    struct MTVertexToPixel
    {
        float4 Position         : POSITION;
        float4 Color            : COLOR0;
        float3 Normal            : TEXCOORD0;
        float2 TextureCoords    : TEXCOORD1;
        float4 LightDirection    : TEXCOORD2;
        float4 TextureWeights    : TEXCOORD3;

         float Depth                : TEXCOORD4;

    };

    struct MTPixelToFrame
    {
        float4 Color : COLOR0;
    };

    MTVertexToPixel MultiTexturedVS( float4 inPos : POSITION, float3 inNormal: NORMAL, float2 inTexCoords: TEXCOORD0, float4 inTexWeights: TEXCOORD1)
    {    
        MTVertexToPixel Output = (MTVertexToPixel)0;
        float4x4 preViewProjection = mul (xView, xProjection);
        float4x4 preWorldViewProjection = mul (xWorld, preViewProjection);

        Output.Position = mul(inPos, preWorldViewProjection);
        Output.Normal = mul(normalize(inNormal), xWorld);
        Output.TextureCoords = inTexCoords;
        Output.LightDirection.xyz = -xLightDirection;
        Output.LightDirection.w = 1;    
        Output.TextureWeights = inTexWeights;

         Output.Depth = Output.Position.z/Output.Position.w;


        return Output;
    }

    MTPixelToFrame MultiTexturedPS(MTVertexToPixel PSIn)
    {
        MTPixelToFrame Output = (MTPixelToFrame)0;        
        
        float lightingFactor = 1;
        if (xEnableLighting)
            lightingFactor = saturate(saturate(dot(PSIn.Normal, PSIn.LightDirection)) + xAmbient);

             
         float blendDistance = 0.99f;
         float blendWidth = 0.005f;
         float blendFactor = clamp((PSIn.Depth-blendDistance)/blendWidth, 0, 1);
             
         float4 farColor;
         farColor = tex2D(TextureSampler0, PSIn.TextureCoords)*PSIn.TextureWeights.x;
         farColor += tex2D(TextureSampler1, PSIn.TextureCoords)*PSIn.TextureWeights.y;
         farColor += tex2D(TextureSampler2, PSIn.TextureCoords)*PSIn.TextureWeights.z;
         farColor += tex2D(TextureSampler3, PSIn.TextureCoords)*PSIn.TextureWeights.w;
         
         float4 nearColor;
         float2 nearTextureCoords = PSIn.TextureCoords*3;
         nearColor = tex2D(TextureSampler0, nearTextureCoords)*PSIn.TextureWeights.x;
         nearColor += tex2D(TextureSampler1, nearTextureCoords)*PSIn.TextureWeights.y;
         nearColor += tex2D(TextureSampler2, nearTextureCoords)*PSIn.TextureWeights.z;
         nearColor += tex2D(TextureSampler3, nearTextureCoords)*PSIn.TextureWeights.w;
     
         Output.Color = lerp(nearColor, farColor, blendFactor);
         Output.Color *= lightingFactor;

        
        return Output;
    }

    technique MultiTextured
    {
        pass Pass0
        {
            VertexShader = compile vs_1_1 MultiTexturedVS();
            PixelShader = compile ps_2_0 MultiTexturedPS();
        }
    }


    Google
     
    Webwww.riemers.net


    If you appreciate the amount of time I spend creating and updating
    these pages, feel free to donate -- any amount is welcome !



    - Website design & XNA + DirectX code : Riemer Grootjans -
    ©2003 - 2011 Riemer Grootjans
  • Translations

    This site in English
    This site in Korean
    This site in Czech

    Microsoft MVP Award



    2007 - 2011 MVP Award
    DirectX - XNA

    Contents

    News
    Home
    Forum
    XNA 2.0 Recipes Book (8)
    Chapter 1
    Chapter 2
    Chapter 3
    Chapter 4
    Chapter 5
    Chapter 6
    Chapter 7
    Chapter 8
    XNA 3.0 Recipes Book (8)
    Chapter 1
    Chapter 2
    Chapter 3
    Chapter 4
    Chapter 5
    Chapter 6
    Chapter 7
    Chapter 8
    Downloads
    Extra Reading (3)
    Matrices: geometrical
    Matrix Mathematics
    Homogenous matrices
    Community Projects (1)
    Team Project (1)
    News
    Tutorials (160)
    XNA 4.0 using C# (89)
    2D Series: Shooters (22)
    Starting a project
    Drawing fullscreen images
    Positioning images
    SpriteBatch.Draw()
    Rotation
    Keyboard input
    Writing text
    Angle to Direction
    Direction to Angle
    Smoke trail
    Manual texture creation
    Random terrain
    Texture to Colors
    Coll Detection Overview
    Coll Detection Matrices
    Putting CD into practice
    Particles
    Additive alpha blending
    Particle engine
    Adding craters
    Sound in XNA
    Resolution independency
    3D Series 1: Terrain (13)
    Starting a project
    The effect file
    The first triangle
    World space
    Rotation - translation
    Indices
    Terrain basics
    Terrain from file
    Keyboard
    Adding colors
    Lighting basics
    Terrain lighting
    VertexBuffer & IndexBuffer
    3D Series 2: Flightsim (14)
    Starting point
    Textures
    Loading the floorplan
    Creating the 3D city
    Loading a Model
    Ambient and diffuse
    Quaternion camera
    Flight kinematics
    Collision detection
    Adding targets
    Point sprites
    Alpha blending
    Skybox
    Camera delay
    3D Series 3: HLSL (18)
    Starting point
    HLSL introduction
    Vertex format
    Vertex shader
    Pixel shader
    Per-pixel colors
    Textured triangle
    Triangle strip
    World transform
    World normals
    Per-pixel lighting
    Shadow map
    Render to texture
    Projective texturing
    Real shadow
    Shaping the light
    Preshaders
    3D Series 4: Adv. terrain (19)
    Starting code
    Mouse camera
    Textured terrain
    Multitexturing
    Adding detail
    Skydome
    The water technique
    Refraction map
    Reflection map
    Perfect mirror
    Ripples
    The Fresnel term
    Moving water
    Specular highlights
    Billboarding
    Region growing
    Billboarding renderstates
    Perlin noise
    Gradient skybox
    Short Tuts (3)
    Run XNA on older pcs
    MessageBox in XNA
    Normal generation
    DirectX using C# (54)
    Series 1:Terrain (14)
    Opening a window
    Linking to the Device
    Drawing a triangle
    Camera
    Rotation - Translation
    Indices
    Terrain creation
    Terrain from file
    DirectInput
    Importing bmp files
    Colored vertices
    DirectX Light basics
    Mesh creation
    Mesh lighting
    Series 2: Flightsim (19)
    Starting code
    Textures
    The floorplan
    Creating the 3D City
    Meshloading from file
    Ambient light
    Action
    Flight kinematics
    Collision detection
    Skybox
    Texture filtering
    Adding targets
    Point sprites
    Alpha blending
    DirectSound
    Sounds in 3D
    Playing MP3 files
    Displaying text
    Going fullscreen
    Series 3: HLSL (19)
    Starting point
    HLSL Introduction
    Vertex Shader
    Shaded triangle
    Pixel Shader
    Textured Triangle
    Triangle Strip
    World transform
    Adding normals
    The first light
    Shadow mapping
    Render To Texture
    Projective texturing
    The first shadow
    Shaping the light
    Preshaders
    Multiple lights
    Adjusting Z values
    Finishing touch
    Short Tuts (2)
    Resizing problem
    Checking Device caps
    DirectX using C++ (15)
    Series 1: Terrain (15)
    Opening a window
    Ending the game loop
    Linking to the Device
    Clearing your window
    Drawing a triangle
    Culling
    Camera
    Rotation - Translation
    Indices
    Terrain creation
    Terrain from file
    DirectInput
    Importing .bmp files
    Adding colors
    DirectX Light basics
    DirectX using VB (2)
    Series 1: Intro (2)
    The first triangle
    Rotation - translation
    -- Tree view --


    Thank you!

    Support this site --
    any amount is welcome !

    Stay up-to-date

    I don't have the time to keep a News section, so stay informed about the updates by clicking on this RSS file!