<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Gabriel Di Giorgio on Medium]]></title>
        <description><![CDATA[Stories by Gabriel Di Giorgio on Medium]]></description>
        <link>https://medium.com/@gabriel.enrique.digiorgio?source=rss-ca6ac1c33713------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*HlhN4-modLUOeM5s</url>
            <title>Stories by Gabriel Di Giorgio on Medium</title>
            <link>https://medium.com/@gabriel.enrique.digiorgio?source=rss-ca6ac1c33713------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 18:31:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@gabriel.enrique.digiorgio/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to create Water shader in Monogame/XNA]]></title>
            <link>https://medium.com/@gabriel.enrique.digiorgio/how-to-create-water-shader-in-monogame-xna-0a7e82092c85?source=rss-ca6ac1c33713------2</link>
            <guid isPermaLink="false">https://medium.com/p/0a7e82092c85</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[shaders]]></category>
            <category><![CDATA[gamedev]]></category>
            <dc:creator><![CDATA[Gabriel Di Giorgio]]></dc:creator>
            <pubDate>Sun, 19 May 2024 23:30:30 GMT</pubDate>
            <atom:updated>2024-05-27T14:53:31.174Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In this article we’ll cover the basics on creating a simple water shader in Monogame/XNA. This shader will make use of: <strong>planar reflections</strong>, <strong>refraction</strong>, <strong>Fresnel effect</strong> and <strong>specular highlights</strong>. At the time of writing, it was done with <strong>Monogame version 3.8.1</strong>. Here’s the <a href="https://github.com/gabdigiorgio/water"><strong>source code</strong></a> if you want to examine every aspect of it in detail.</p><h3>The Basics</h3><p>To better understand how our shader works we’re going to split it up in a few steps:</p><ul><li>Adding a <strong>quad</strong>/flat surface.</li><li>Adding a <strong>reflection </strong>and <strong>refraction </strong>texture (lerping between them using <strong>Fresnel </strong>effect).</li><li>Simulate small waves with a <strong>distortion map</strong>.</li><li>Adding a <strong>normal map</strong> for <strong>specular </strong>highlights.</li></ul><h3>Drawing</h3><p>The sequence of rendering steps is as follows:</p><ol><li>Drawing the <strong>refraction</strong></li><li>Drawing the <strong>reflection</strong></li><li>Drawing the <strong>water</strong></li><li>Drawing <strong>other objects</strong> in the scene</li></ol><p>This order ensures that each component is rendered in the correct sequence to achieve the desired visual effect.</p><h3>Setting up the Code</h3><p>In order to correctly achieve our water shader technique, we’ll need to set up some things in our code. To simplify the explanation I’ll use an already defined class calledQuadPrimitivethat will have a vertex buffer (sending information about Normals<strong> </strong>and texture coordinates) and, of course, an index buffer. I’ll also use a FreeCamera class to handle our camera movement, though we won&#39;t delve into its details as it&#39;s not the focus of this tutorial.</p><p>Firstly, we will <strong>create </strong>our <strong>quad</strong>, its <strong>world matrix</strong>,<strong> </strong>its <strong>height </strong>and the<strong> wave speed</strong>. We will use the wave speed later on in the shader parameters. Also, this height will be important when calculating the reflection and refraction. Additionally, we’ll declare our shader:</p><pre>// Camera<br>private FreeCamera _freeCamera;<br>private readonly Vector3 _cameraInitialPosition = new(0f, 50f, 300f);<br><br>// Water<br>private QuadPrimitive _quad;<br>private const float QuadHeight = 0f;<br>private const float WaveSpeed = 0.05f;<br>private Matrix _quadWorld;<br>private Effect _waterShader;</pre><p>And our Initialize method should look something like this:</p><pre>protected override void Initialize()        <br>{<br>  _graphicsDeviceManager.PreferredBackBufferWidth = <br>GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width - 100;<br>  _graphicsDeviceManager.PreferredBackBufferHeight = <br>GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height - 100;<br>  _graphicsDeviceManager.ApplyChanges();<br><br>  // Camera<br>  _freeCamera = new FreeCamera(GraphicsDevice.Viewport.AspectRatio, <br>_cameraInitialPosition);<br>  <br>  // Water<br>  _quad = new QuadPrimitive(GraphicsDevice);<br>  var quadPosition = new Vector3(0f, QuadHeight, 0f);<br>  _quadWorld = Matrix.CreateScale(3000f, 0f, 3000f) <br>* Matrix.CreateTranslation(quadPosition);<br>  <br>  base.Initialize();<br>}</pre><h3>Planar Reflections</h3><p>Before we continue with our code, we need to understand how planar reflections work. Here’s an example of what a planar reflection looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pEJeSfE49mYMTeTa1nhCRg.jpeg" /><figcaption>Planar reflection graphical example</figcaption></figure><p>In this example we can see that, given a <strong>reflective plane</strong>, a <strong>camera </strong>and some object, the <strong>reflection </strong>should look something like that.<br>To translate this later to code we need to calculate a new view matrix from the point of view of the <strong>Reflection Camera </strong>(the one under the reflective plane).</p><h4>Reflection Camera Position</h4><p>First, we’ll be calculating the <strong>Reflection Camera Position</strong>. We already know the <strong>Camera Position</strong>, the <strong>Plane Position</strong> and the <strong>Plane Normal</strong>, so if we subtract the Plane Position from the Camera position, we obtain the <strong>View Direction vector</strong>:</p><p>View Direction = Camera Position — Plane Position</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jYFHC1_5dbxGLLx6Zrb3xg.png" /><figcaption>View direction vector</figcaption></figure><p>As you can see I’ve also added another vector which is the <strong>Projection vector</strong>. Then we can use the <strong>length </strong>of that projection to find the distance to that point in the plane. <br>With that, we now have a rectangular triangle. The <strong>Projection Length </strong>should be equal to:</p><p>Projection Length = View Direction * cos(Angle)</p><p>The <strong>Angle</strong> refers as the angle between the Plane Normal and the View Direction</p><p>To simplify it we can rewrite it like this:</p><p>Projection Length = Dot Product(Plane Normal, View Direction)</p><p>Great, now we have the Projection Length. We can use that to obtain the <strong>Reflection Camera Position</strong>:</p><p>Reflection Camera Position = Camera Position — 2 * Plane Normal * Projection Length</p><h4>Reflection Camera View Matrix</h4><p>In order to achieve the Reflection Camera View Matrix, we’ll need to calculate the <strong>Reflection Camera Forward</strong>.<strong> </strong>We can use the function Reflect(vector, normal) to get the reflection of a vector off a surface that has the specified normal.</p><p>Reflection Camera Forward = Vector3.Reflect(Camera Forward, Plane Normal)</p><p>After calculating the Reflection Camera Forward, the next step is to compute the <strong>Reflection Camera Up</strong>. We’ll again use the Vector3.Reflect function to reflect the camera&#39;s up vector off the plane&#39;s normal.</p><p>Reflection Camera Up = Vector3.Reflect(Camera Up, Plane Normal)</p><p>With both the <strong>Reflection Camera Position</strong>, <strong>Reflection Camera Forward</strong> and <strong>Reflection Camera Up</strong> vectors calculated, we now have all the components necessary to construct the <strong>Reflection Camera View Matrix</strong>.</p><p>Reflection Camera View = Matrix.CreateLookAt(Reflection Camera Position, Reflection Camera Position + Reflection Camera Forward, Reflection Camera Position)</p><h3>Drawing the Reflection</h3><p>Now that we’ve calculated the necessary components for the Reflection Camera View Matrix, we can proceed to <strong>draw the reflection onto a texture</strong>, typically a RenderTarget2D. To accomplish this in our code, we can integrate the previously calculated values into our rendering process. The following snippet demonstrates how this can be achieved:</p><pre> private void DrawReflection(Matrix world, Matrix view, Matrix projection, <br>GameTime gameTime)<br> {<br>    // Set the render target to the Reflection Texture<br>    GraphicsDevice.SetRenderTarget(_reflectionRenderTarget);<br>    GraphicsDevice.Clear(ClearOptions.Target | <br>    ClearOptions.DepthBuffer, Color.CornflowerBlue, 1f, 0);<br>            <br>    var quadNormal = Vector3.Up;         <br>    var viewDirection = _freeCamera.Position - _quadWorld.Translation;       <br>    var projLength = Vector3.Dot(quadNormal, viewDirection);<br>    var reflectionCamPos = _freeCamera.Position - 2 * quadNormal * projLength;<br>    var reflectionCamForward = Vector3.Reflect(_freeCamera.FrontDirection, <br>    quadNormal);<br>    var reflectionCamUp = Vector3.Reflect(_freeCamera.UpDirection, quadNormal);  <br>    var reflectionCamView = Matrix.CreateLookAt(reflectionCamPos, <br>                reflectionCamPos + reflectionCamForward, reflectionCamUp);<br>    <br>    // Draw the scene from the reflection camera point of view<br>    DrawScene(reflectionCamView, projection, reflectionCamPos, <br>    _reflectionClippingPlane);<br>    <br>    // Reset the render target to the default (screen)<br>    GraphicsDevice.SetRenderTarget(null);<br>         <br>    // Draw the water<br>    DrawWater(world, view, projection, reflectionCamView, gameTime);<br>}</pre><p>In the DrawWatermethod we’ll pass the necessary parameters, which we’ll delve into in detail later.</p><h4>Clipping Planes</h4><p>If you’ve noticed, there’s a <strong>clipping plane</strong> _reflectionClippingPlanethat hasn’t been explained yet. Let’s dive into its purpose. This clipping plane is used to draw only objects above the water surface. This ensures that only the upper half of objects is reflected in the water, as is typically observed in realistic reflections. You can declare it like this:</p><pre>private readonly Vector4 _reflectionClippingPlane = new(0f, 1f, 0f, -QuadHeight);</pre><p>This plane is defined by a mathematical equation <strong>(Ax + By + Cz + D = 0)</strong>, where (A, B, C) represents the normal vector perpendicular to the plane, and D is the distance from the origin along that normal vector.</p><p>In our case, the water surface acts as a<strong> flat plane parallel to the XZ plane</strong>, with its <strong>normal vector</strong> pointing directly <strong>upwards (0, 1, 0)</strong>.</p><p>We utilize the value <strong>-QuadHeight</strong> in the reflection clipping plane equation specifically for the shader handling objects within the water. This value is later employed in the pixel shader using the clip function, where we’ll clip the pixels below the Reflection Plane. Here’s an example:</p><pre>// Uniforms<br>float4 ClippingPlane;<br><br>struct VertexShaderInput<br>{<br>    float4 Position : POSITION0;<br>    float4 Normal : NORMAL;<br>};<br> <br>struct VertexShaderOutput<br>{<br>    float4 Position : POSITION0;<br>    float3 WorldPosition : TEXCOORD0;<br>    float3 Normal : TEXCOORD1;<br>    float4 Clipping : TEXCOORD2;<br>};<br><br>VertexShaderOutput MainVS(VertexShaderInput input)<br>{<br>    VertexShaderOutput output = (VertexShaderOutput) 0;<br> <br>    float4 worldPosition = mul(input.Position, World);<br>    float4 viewPosition = mul(worldPosition, View);<br>    output.Position = mul(viewPosition, Projection);<br>    output.WorldPosition = worldPosition;<br>    output.Normal = mul(input.Normal, InverseTransposeWorld);<br>    /*<br>    Distance from the vertex to the clipping plane using dot product<br>    The resulting distance will be used to decide whether to discard <br>    the corresponding pixel in the pixel shader<br>    */<br>    output.Clipping = dot(worldPosition, ClippingPlane);<br> <br>    return output;<br>}<br><br>float4 MainPS(VertexShaderOutput input) : COLOR0<br>{<br>    clip(input.Clipping);<br>    <br>    // Rest of the pixel shader<br>}</pre><p>The clip function is responsible for discarding pixels based on a given condition. By utilizing -QuadHeight in our shader, we ensure that pixels representing objects below the water surface are discarded during rendering, effectively clipping them from the final reflection image.</p><p>Also, this works when we want to discard the pixels from above the water, in that case, for the refraction:</p><pre>private readonly Vector4 _refractionClippingPlane = new(0f, -1f, 0f, QuadHeight);</pre><h3>Refraction</h3><p>Drawing the refraction onto a render target is a straightforward process, especially when compared to rendering reflections. It involves rendering the scene from the perspective of the camera while utilizing the _refractionClippingPlane to discard pixels above the water surface.</p><pre>private void DrawRefraction()<br>{<br>    // Set the render target to the Refraction Texture<br>    GraphicsDevice.SetRenderTarget(_refractionRenderTarget);<br>    GraphicsDevice.Clear(ClearOptions.Target | ClearOptions.DepthBuffer, <br>Color.CornflowerBlue, 1f, 0);<br>            <br>    // Draw the scene normally but clipping the objects above the water<br>    DrawScene(_freeCamera.View, _freeCamera.Projection, _freeCamera.Position, <br>    _refractionClippingPlane);<br>            <br>    // Reset the render target to the default (screen)<br>    GraphicsDevice.SetRenderTarget(null);<br>}</pre><p>Great, now we can proceed to the <strong>actual water shader</strong> and see how all of this comes together.</p><h3>Water Shader</h3><p>First, we’ll declare the necessary uniforms and textures for our water shader. These include parameters for lighting, camera position, water movement, and texture samplers for the various maps we’ll use:</p><pre>float KSpecular;<br>float Shininess;<br>float3 LightPosition;<br>float3 LightColor;<br>float3 CameraPosition;<br><br>float MoveFactor;<br>float2 Tiling;<br>float WaveStrength;<br><br>float4x4 ReflectionView;<br>float4x4 Projection;<br>float4x4 WorldViewProjection;<br>float4x4 World;<br><br>texture RefractionTexture;<br>sampler2D refractionSampler = sampler_state<br>{<br>    Texture = (RefractionTexture);<br>    ADDRESSU = Clamp;<br>    ADDRESSV = Clamp;<br>    MINFILTER = Linear;<br>    MAGFILTER = Linear;<br>    MIPFILTER = Linear;<br>};<br><br>texture ReflectionTexture;<br>sampler2D reflectionSampler = sampler_state<br>{<br>    Texture = (ReflectionTexture);<br>    ADDRESSU = Clamp;<br>    ADDRESSV = Clamp;<br>    MINFILTER = Linear;<br>    MAGFILTER = Linear;<br>    MIPFILTER = Linear;<br>};<br><br>texture DistortionMap;<br>sampler2D distortionSampler = sampler_state<br>{<br>    Texture = (DistortionMap);<br>    ADDRESSU = WRAP;<br>    ADDRESSV = WRAP;<br>    MINFILTER = Linear;<br>    MAGFILTER = Linear;<br>    MIPFILTER = Linear;<br>};<br><br>texture NormalMap;<br>sampler2D normalMapSampler = sampler_state<br>{<br>    Texture = (NormalMap);<br>    ADDRESSU = WRAP;<br>    ADDRESSV = WRAP;<br>    MINFILTER = Linear;<br>    MAGFILTER = Linear;<br>    MIPFILTER = Linear;<br>};</pre><p>In this shader, the uniforms KSpecular, Shininess, LightPosition, LightColor, and CameraPosition define the lighting and viewing parameters. The MoveFactor, Tiling, and WaveStrength control the water&#39;s movement and appearance. The matrices ReflectionView, Projection, WorldViewProjection, and World are used for transforming coordinates. The texture samplers refractionSampler, reflectionSampler, distortionSampler, and normalMapSampler are used to sample the respective textures needed for rendering the water surface.</p><p>For the <strong>Distortion Map </strong>we’ll use a texture that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*AnT9-ODsyirYo7Ty_utX1w.jpeg" /><figcaption>Distortion Map Texture</figcaption></figure><p>By using this texture, we can <strong>distort </strong>the <strong>texture coordinates</strong>, creating the effect of small waves on the water surface. This distortion helps to simulate the dynamic and realistic appearence of water.</p><p>For the <strong>Normal Map </strong>we’ll use another texture, like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*mZ-hRslDcrHZ5ADZjfxeig.jpeg" /><figcaption>Normal Map Texture</figcaption></figure><p>This map contains information about the<strong> surface normals</strong>, which are essential for simulating the way light interacts with the water. Unlike the distortion map, which is used to manipulate texture coordinates, the normal map is used for light-related calculations.</p><h4>Vertex Shader</h4><p>In our vertex shader, we transform the vertex data to prepare it for the pixel shader. Here’s a breakdown of the process:</p><pre>struct VertexShaderInput<br>{<br>    float4 Position : POSITION0;<br>    float4 Normal : NORMAL;<br>    float2 TextureCoordinates : TEXCOORD0;<br>};<br><br>struct VertexShaderOutput<br>{<br>    float4 Position : SV_POSITION;<br>    float2 TextureCoordinates : TEXCOORD0;<br>    float4 WorldPosition : TEXCOORD1;<br>    float4 Normal : TEXCOORD2;<br>    float4 ReflectionPosition : TEXCOORD3;<br>    float4 RefractionPosition : TEXCOORD4;<br>};<br><br>VertexShaderOutput MainVS(in VertexShaderInput input)<br>{<br>    VertexShaderOutput output = (VertexShaderOutput) 0;<br><br>    // Transform the vertex position to clip space<br>    output.Position = mul(input.Position, WorldViewProjection);<br>    <br>    // Transform the vertex position to world space<br>    output.WorldPosition = mul(input.Position, World);<br>    <br>    // Pass the vertex normal without any changes<br>    output.Normal = input.Normal;<br>    <br>    // Adjust texture coordinates by the tiling factor<br>    output.TextureCoordinates = input.TextureCoordinates * Tiling;<br>    <br>    // Calculate the reflection position and world matrix<br>    float4x4 reflectProjectWorld = mul(ReflectionView, Projection);<br>    reflectProjectWorld = mul(World, reflectProjectWorld);<br>    output.ReflectionPosition = mul(input.Position, reflectProjectWorld);<br>    <br>    // The refraction position is the same as the clip space position<br>    output.RefractionPosition = output.Position;<br>    <br>    return output;<br>}</pre><p>Excellent, with this, we’ve finished the vertex shader part, and we can move on to the pixel shader.</p><h3>Pixel Shader</h3><h4>Projective Texture Mapping</h4><p>Firstly, we transform the refraction and reflection texture coordinates to <a href="https://learnopengl.com/Getting-started/Coordinate-Systems"><strong>Normalized Device Coordinates</strong> (<strong>NDC</strong>)</a> space. Then, we scale and offset the <strong>XY</strong> coordinates appropriately to ensure accurate sampling of a DirectX (DX) texture.</p><p><strong>Why do we need our texture coordinates to be in NDC?</strong> If we use our current texture coordinates, which are in <strong>clip space</strong>, their values may exceed the range of (-1, -1) to (1, 1). Which means we can’t use it directly to a map texture. Therefore, we need to convert the coordinates to NDC first.</p><pre>float4 MainPS(VertexShaderOutput input) : COLOR<br>{     <br>    // Refraction<br>    float4 refractionTexCoord;<br>    refractionTexCoord = input.RefractionPosition;<br><br>    // Normalized device coordinates<br>    refractionTexCoord.xy /= refractionTexCoord.w;<br><br>    // Adjust offset<br>    refractionTexCoord.x = 0.5f * refractionTexCoord.x + 0.5f;<br>    refractionTexCoord.y = -0.5f * refractionTexCoord.y + 0.5f;<br>    <br>    // Reflection<br>    float4 reflectionTexCoord;<br>    reflectionTexCoord = input.ReflectionPosition;<br><br>    // Normalized device coordinates<br>    reflectionTexCoord.xy /= reflectionTexCoord.w;<br><br>    // Adjust offset<br>    reflectionTexCoord.x = 0.5f * reflectionTexCoord.x + 0.5f;<br>    reflectionTexCoord.y = -0.5f * reflectionTexCoord.y + 0.5f;<br><br>    // Rest of the shader<br>}</pre><p>By converting to NDC coordinates, our coordinate system now ranges from (-1, -1) to (1, 1).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*S1ihb4IY6xc6sQnQN5cEvg.png" /><figcaption>Normalized Device Coordinates</figcaption></figure><p>But we need it to range from (0, 0) to (1, 1) in order to map the texture correctly. So we do this simple conversion:</p><pre>refractionTexCoord.x = 0.5f * refractionTexCoord.x + 0.5f;<br>refractionTexCoord.y = -0.5f * refractionTexCoord.y + 0.5f;<br><br>reflectionTexCoord.x = 0.5f * reflectionTexCoord.x + 0.5f;<br>reflectionTexCoord.y = -0.5f * reflectionTexCoord.y + 0.5f;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*4D3DJNk4ZK1tMgeQB7yd5Q.png" /><figcaption>Texture Coordinates</figcaption></figure><p>Now, our texture should accurately map on the water surface, ensuring that the texture is displayed <strong>consistently</strong>,<strong> </strong>regardless of the camera position or perspective.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*oz4kOzHpO5zde2hM4ogvVQ.gif" /><figcaption>Projective Texture Mapping</figcaption></figure><p>Recapitulating, we first transform the refraction and reflection texture coordinates to Normalized Device Coordinates (NDC) space. Additionally, we adjust the coordinates to range from (0, 0) to (1, 1) using a simple conversion, allowing for correct texture mapping.</p><h4>Distortion Map / DuDv Map</h4><p>Now, we are going to sample both the reflection and refraction textures using the Distortion Map shown above.</p><p>This map is represented by <strong>red and green </strong>colors, a float2.</p><p>However, these values are always going to be positive in this Distortion Map, so our distortions <strong>would always be positive values</strong>, the values are between (0.0,0.0) and (1.0,1.0). We want to be able to have <strong>both positive and negative</strong> distortions for this to look realistic.</p><p>To convert these values to be between (-1.0,-1.0) and (1.0,1.0) we simply multiply by 2 and subtract 1. With that, we use that to distort the <strong>Reflection and Refraction texture coordinates</strong> by simply adding the distortion onto those texture coordinates.</p><pre>float2 distortion = (tex2D(distortionSampler, Input.TextureCoordinates)).rg <br>                    * 2.0 - 1.0) * WaveStrength;<br><br>reflectionTex += distortion;<br>refractionTex += distortion;</pre><p>This distortion might be a little strong by default so we’ll use the uniform we previously declared as WaveStrength in order to reduce the distortion.</p><h4>Moving the Waves</h4><p>To get the water to look like it’s moving, we achieve this by <strong>using an offset</strong> for where we sample the Distortion Map. We have already declared that, which is the MoveFactor and we’re going to change this offset over time.</p><p>To achieve this effect, we add the <strong>MoveFactor</strong> to the <strong>X </strong>component of the texture coordinates and sample the distortion map. Afterward, we perform a <strong>second sampling</strong> for the <strong>Y</strong> component, applying an additional distortion in a <strong>different direction</strong>. This process enhances the realism of the distortion effect, creating a more dynamic appearance.</p><pre>float2 distortedTexCoords = tex2D(distortionSampler, <br>float2(input.TextureCoordinates.x + MoveFactor, input.TextureCoordinates.y)) <br>* 0.01;<br>distortedTexCoords = input.TextureCoordinates + <br>float2(distortedTexCoords.x, distortedTexCoords.y + MoveFactor);<br>float2 totalDistortion = (tex2D(distortionSampler, distortedTexCoords).rg <br>* 2.0 - 1.0) * WaveStrength;<br><br>reflectionTex += totalDistortion;<br>refractionTex += totalDistortion;<br><br>// Sample both textures using the distorted texture coordinates<br>float4 reflectionColor = tex2D(reflectionSampler, reflectionTex);<br>float4 refractionColor = tex2D(refractionSampler, refractionTex);</pre><p>I’ve multiplied the first line by 0.01 to slightly adjust the intensity of the distortion applied in the initial sample.</p><h4>Fresnel</h4><p>If you don’t know what the <strong>Fresnel </strong>Effect is, here’s <a href="https://www.dorian-iten.com/fresnel/"><strong>a very good explanation</strong></a> by <strong>Dorian</strong>.</p><p>To implement this effect, we need to use the View Direction and the Normal from the water like this:</p><pre>float3 viewDirection = normalize(CameraPosition - input.WorldPosition.xyz);<br>float refractiveFactor = dot(viewDirection, normalize(input.Normal.xyz));</pre><p>And the output would be a <strong>linear interpolation </strong>between the reflectionColorand refractionColorwith a value of refractiveFactor which we previously calculated.</p><pre>float4 finalColor = lerp(reflectionColor, refractionColor, refractiveFactor);</pre><p>But we’re not done yet! The last thing we need to do is add Normal Maps and Lighting.</p><h4>Normal Maps</h4><p>We can use a <strong>normal map</strong> to indicate the normal at different points on the water surface. The pixel color at any point on the normal map can indicate the <strong>3D normal vector</strong> of the water at that point. (R, G, B) → (X, Y, Z). The normal map I’ve shown above is mostly a blue color, because the <strong>blue</strong> value represents the <strong>up axis</strong> and in our case, that’s the <strong>Y axis</strong>.</p><p>So, we’ll use the <strong>blue component</strong> of the normal map color to be the <strong>Y component</strong> in the normal vector, the red and green components of the normal map can then be used as the <strong>X</strong> and <strong>Z</strong> components of the normal vector. <strong>(R, G, B) -&gt; (R, B, G)</strong>.</p><p>The only problem here, is that because you can never have a negative color, the components of the normal vector are also going to be positive. That’s <strong>not a problem</strong> for the <strong>Y</strong> component, because we would always want our surface normal to be <strong>pointing upwards</strong> to some extent. But we <strong>don’t necessarily want the normal to always be pointing in the positive X and Z directions.</strong> It should also be able to point in the negative <strong>X</strong> and <strong>Z directions</strong> as well.</p><p>To do this, we’re going to use the same conversion we’ve used for the distortion map. <strong>Multiplying by 2 and subtracting 1</strong>. That way, we can extract the normal vectors from the normal map like so:</p><pre>float4 normalMapColor = tex2D(normalMapSampler, distortedTexCoords);<br>float3 normal = float3(normalMapColor.r * 2.0 - 1.0, <br>normalMapColor.b, normalMapColor.g * 2.0 - 1.0);<br>normal = normalize(normal);</pre><p>Now, utilizing these extracted normal vectors, we proceed to calculate the lighting effects.</p><h4>Lighting</h4><p>The lighting technique we are going to use is basically the <strong>Blinn–Phong reflection model</strong>, to learn more about it <a href="https://learnopengl.com/Advanced-Lighting/Advanced-Lighting"><strong>click here</strong></a>. The uniforms involved here are: KSpecular, Shininess, LightPosition and LightColor.</p><p>First, we obtain the <strong>light direction</strong> and the <strong>half vector</strong> by normalizing the vectors representing the light position, and the sum of the light and view directions, respectively:</p><pre>float3 lightDirection = normalize(LightPosition - input.WorldPosition.xyz);<br>float3 halfVector = normalize(lightDirection + viewDirection);</pre><p>With these vectors, we compute the dot products <strong>NdotL</strong> and <strong>NdotH</strong>, which represent the <strong>angle between the normal and the light direction</strong>, and between the <strong>normal and the half vector</strong>, respectively:</p><pre>float NdotL = saturate(dot(normal, lightDirection));<br>float NdotH = saturate(dot(normal, halfVector));</pre><p>Using these dot products, we calculate the <strong>specular lighting</strong> contribution by applying the <strong>Phong </strong>reflection model equation:</p><pre>float3 specularLight = sign(NdotL) * KSpecular * LightColor * pow(NdotH, Shininess);</pre><p>Finally, we combine the specular lighting with the previously calculated reflection and refraction colors to determine the final color output:</p><pre>// Final calculation<br>float4 finalColor = lerp(reflectionColor, refractionColor, refractiveFactor) <br>+ float4(specularLight, 0.0);</pre><p>And that’s it. We have completely made our water shader successfully! You can tweak it in any way you want the parameters. I did it like this:</p><pre>private void DrawWater(Matrix world, Matrix view, Matrix projection, <br>Matrix reflectionView, GameTime gameTime)<br>{<br>    _waterShader.CurrentTechnique = _waterShader.Techniques[&quot;Water&quot;];<br><br>    _waterShader.Parameters[&quot;World&quot;].SetValue(world);<br>    _waterShader.Parameters[&quot;WorldViewProjection&quot;]<br>.SetValue(world * view * projection);<br>    _waterShader.Parameters[&quot;ReflectionView&quot;].SetValue(reflectionView);<br>    _waterShader.Parameters[&quot;Projection&quot;].SetValue(projection);<br>            <br>    _waterShader.Parameters[&quot;ReflectionTexture&quot;]<br>.SetValue(_reflectionRenderTarget);<br>    _waterShader.Parameters[&quot;RefractionTexture&quot;]<br>.SetValue(_refractionRenderTarget);<br>    _waterShader.Parameters[&quot;DistortionMap&quot;].SetValue(_distortionMap);<br>    _waterShader.Parameters[&quot;NormalMap&quot;].SetValue(_normalMap);<br>    _waterShader.Parameters[&quot;Tiling&quot;].SetValue(Vector2.One * 20f);<br>            <br>    _waterShader.Parameters[&quot;MoveFactor&quot;]<br>.SetValue(WaveSpeed * (float)gameTime.TotalGameTime.TotalSeconds);<br>    _waterShader.Parameters[&quot;WaveStrength&quot;].SetValue(0.01f);<br>            <br>    _waterShader.Parameters[&quot;CameraPosition&quot;].SetValue(_freeCamera.Position);<br>    _waterShader.Parameters[&quot;LightPosition&quot;].SetValue(_lightPosition);<br>    _waterShader.Parameters[&quot;LightColor&quot;].SetValue(Color.White.ToVector3());<br>    _waterShader.Parameters[&quot;Shininess&quot;].SetValue(25f);<br>    _waterShader.Parameters[&quot;KSpecular&quot;].SetValue(0.3f);<br>            <br>    _quad.Draw(_waterShader);<br>}</pre><p>And in my case it looks something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aP6ogdZBeuWqWZYcCmNtEA.png" /><figcaption>A cube, A Teapot and A Torus on the Water.</figcaption></figure><p>I do hope this article has helped you to both understand, and implement this effect in your Monogame graphical application.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0a7e82092c85" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create a simple triangle in Monogame/XNA]]></title>
            <link>https://medium.com/@gabriel.enrique.digiorgio/how-to-create-a-simple-triangle-in-monogame-xna-ae2f2c0222dc?source=rss-ca6ac1c33713------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae2f2c0222dc</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[xna]]></category>
            <category><![CDATA[monogame]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[Gabriel Di Giorgio]]></dc:creator>
            <pubDate>Fri, 29 Mar 2024 15:31:27 GMT</pubDate>
            <atom:updated>2024-05-26T22:06:15.316Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In this tutorial, we’ll cover one of the <strong>fundamental</strong> building blocks of 3D and 2D graphics: creating a simple triangle. Whether you’re a beginner eager to dive into the realm of game programming or an experienced developer seeking to refresh your skills, understanding how to generate basic shapes like a triangle lays a solid foundation for more complex designs.</p><h3>Setting Up the Game Environment</h3><p>Before we dive into creating our triangle, let’s set up our game environment. In the Initialize method, we initialize our view and projection matrices, which are essential for rendering objects in a 3D space.</p><pre>private Matrix _view;<br>private Matrix _projection;<br><br>protected override void Initialize()<br>{<br>    // Set up view and projection matrices<br>    _view = Matrix.CreateLookAt(Vector3.One * 5, Vector3.Zero, Vector3.Up);<br>    _projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, GraphicsDevice.Viewport.AspectRatio, 0.1f, 25000f);<br><br>    // Adjust the back buffer size<br>    _graphics.PreferredBackBufferWidth = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Width - 100;<br>    _graphics.PreferredBackBufferHeight = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode.Height - 100;<br>    _graphics.ApplyChanges(); <br>}</pre><h3>Vertices</h3><p>In order to create a triangle we’ll need to declare our vertices. To do this, we’ll simply create an array to store them in the Initialize method.</p><pre>protected override void Initialize()<br>{<br>    var vertices = new VertexPosition[]<br>    {<br>        new VertexPosition(new Vector3(-1, 0, -1)),<br>        new VertexPosition(new Vector3(-1, 0, 1)),<br>        new VertexPosition(new Vector3(1, 0, -1)),<br>    };<br><br>    base.Initialize();<br>}</pre><p>In this example I’ve used VertexPositionto only send information about the position of the vertex, but you can also use VertexPositionColor(where you can also send information about color), VertexPositionColorNormal, etc.</p><h3>Vertex Buffer</h3><p>To begin with, we need to set up a vertex buffer. This structure is responsible for storing a large number of vertices in the GPU’s memory.</p><pre>private VertexBuffer _vertexBuffer;<br><br>protected override void Initialize()<br>{<br>    var vertices = new VertexPosition[]<br>    {<br>        new VertexPosition(new Vector3(-1, 0, -1)),<br>        new VertexPosition(new Vector3(-1, 0, 1)),<br>        new VertexPosition(new Vector3(1, 0, -1)),<br>    };<br><br>    _vertexBuffer = new VertexBuffer(GraphicsDevice, VertexPosition.VertexDeclaration, 3, BufferUsage.None);<br>    _vertexBuffer.SetData(vertices);<br><br>    base.Initialize();<br>}</pre><p>In the provided code snippet, we initialize the vertex buffer _vertexBuffer with an array of VertexPosition objects. Each VertexPosition specifies a position in 3D space using a Vector3 coordinate. For simplicity, we define a triangle with three vertices positioned at (-1, 0, -1), (-1, 0, 1), and (1, 0, -1) respectively.</p><p>Once the vertex data is defined, we create the VertexBuffer object using the GraphicsDevice and specify the vertex declaration (VertexPosition.VertexDeclaration). The buffer is allocated with enough space to store three vertices (3 in this case), and the vertex data is set using the SetData method.</p><h3>Drawing the Triangle</h3><p>Now, let’s proceed with rendering our triangle. In the code snippet below, we’ll integrate our basic shader and define how the triangle will be drawn.</p><p>Firstly, we need to have a shader and load it, using the LoadContent method. We’ll create a “BasicShader” which is a straightforward shader that defines basic transformations and coloring for our vertices. It consists of a vertex shader and a pixel shader.</p><pre>public const string ContentFolderEffects = &quot;Effects/&quot;;<br>private Effect _effect;<br><br>protected override void LoadContent()<br>{<br>    _effect = Content.Load&lt;Effect&gt;(ContentFolderEffects + &quot;BasicShader&quot;);<br>}</pre><p>And this will be our “BasicShader”:</p><pre>float4x4 World;<br>float4x4 View;<br>float4x4 Projection;<br><br>float3 DiffuseColor;<br><br>struct VertexShaderInput<br>{<br>    float4 Position : POSITION0;<br>};<br><br>struct VertexShaderOutput<br>{<br>    float4 Position : SV_POSITION;<br>};<br><br>VertexShaderOutput MainVS(in VertexShaderInput input)<br>{<br>    VertexShaderOutput output = (VertexShaderOutput)0;<br><br>    float4 worldPosition = mul(input.Position, World);<br>    float4 viewPosition = mul(worldPosition, View);<br>    output.Position = mul(viewPosition, Projection);<br><br>    return output;<br>}<br><br>float4 MainPS(VertexShaderOutput input) : COLOR<br>{<br>    return float4(DiffuseColor, 1.0);<br>}<br><br>technique BasicColorDrawing<br>{<br> pass P0<br> {<br>  VertexShader = compile VS_SHADERMODEL MainVS();<br>  PixelShader = compile PS_SHADERMODEL MainPS();<br> }<br>};</pre><p>Now, let’s move on to drawing the triangle in the Draw method:</p><pre>protected override void Draw(GameTime gameTime)<br>{<br>    GraphicsDevice.Clear(Color.Black);<br><br>    // Set shader parameters<br>    _effect.Parameters[&quot;World&quot;].SetValue(Matrix.Identity);<br>    _effect.Parameters[&quot;View&quot;].SetValue(_view);<br>    _effect.Parameters[&quot;Projection&quot;].SetValue(_projection);<br>    _effect.Parameters[&quot;DiffuseColor&quot;].SetValue(Color.Red.ToVector3());<br><br>    // Set rasterizer state<br>    var rasterizerState = RasterizerState.CullNone;<br>    GraphicsDevice.RasterizerState = rasterizerState; <br><br>    // Set vertex buffer<br>    GraphicsDevice.SetVertexBuffer(_vertexBuffer);<br>    <br>    // Begin drawing<br>    foreach (var pass in _effect.CurrentTechnique.Passes)<br>    {<br>        pass.Apply();<br><br>        // Draw the triangle<br>        GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, 1);<br>    }<br><br>    base.Draw(gameTime);<br>}</pre><p>In this Draw method, we start by clearing the screen with a black color. Then, we set up our shader parameters such as the world, view, and projection matrices, along with the diffuse color. We also configure the rasterizer state to ensure proper rendering.</p><p>Next, we set the vertex buffer to define the geometry we want to draw. Finally, within the loop iterating over each pass of our shader technique, we apply the shader and use DrawPrimitives to render the triangle defined by our vertex buffer.</p><p>In this method call, PrimitiveType.TriangleList specifies the type of primitive being drawn, which in this case is a triangle. The second parameter, 0, indicates the starting index in the vertex buffer from which vertices will be fetched for drawing. Lastly, 1 specifies the number of primitives to draw. Here, we&#39;re drawing a single triangle, but this number can be increased to draw multiple primitives. This method is crucial for converting vertex data into visual geometry on the screen.</p><p>With this setup, our triangle should now be displayed on the screen using the specified shader and parameters.</p><figure><img alt="Red triangle" src="https://cdn-images-1.medium.com/max/1024/1*Y0PRqffPsUNJ3LlYjaIshA.png" /><figcaption>Red Polygon Triangle</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae2f2c0222dc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>