<?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 Valerio Marty on Medium]]></title>
        <description><![CDATA[Stories by Valerio Marty on Medium]]></description>
        <link>https://medium.com/@valeriomarty?source=rss-2f2b66929564------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*nafoHWBzwONjnuNI</url>
            <title>Stories by Valerio Marty on Medium</title>
            <link>https://medium.com/@valeriomarty?source=rss-2f2b66929564------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 20:44:23 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@valeriomarty/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[Coloring Raymarched Volumetric Light as it passes through Stained Glass (Part 2)]]></title>
            <link>https://valeriomarty.medium.com/coloring-raymarched-volumetric-light-as-it-passes-through-stained-glass-a19846def1cd?source=rss-2f2b66929564------2</link>
            <guid isPermaLink="false">https://medium.com/p/a19846def1cd</guid>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[shaders]]></category>
            <category><![CDATA[scriptablerendererfeature]]></category>
            <category><![CDATA[volumetric-light]]></category>
            <category><![CDATA[raymarching]]></category>
            <dc:creator><![CDATA[Valerio Marty]]></dc:creator>
            <pubDate>Tue, 06 Jul 2021 15:34:06 GMT</pubDate>
            <atom:updated>2021-07-12T13:09:50.762Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2XvQ5Be6ICBdcjBKFmrs7Q.jpeg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*sO8xw5sb-OrepuJIDCEcUw.gif" /></figure><p>In the <a href="https://valeriomarty.medium.com/raymarched-volumetric-lighting-in-unity-urp-e7bc84d31604">previous tutorial</a>, we learned how to do raymarched volumetric light, in this article we will pick it up where we left off and add support for stained glass.</p><p>Shortcomings of this implementation:</p><ul><li>Previous shortcomings.</li><li>It is in no way physically accurate. The color-specific raymarching is hugely simplified and has edge cases.</li><li>Tinting is a screen space effect, if the glass is not visible, the light will not be colored.</li><li>If you are watching stained glass through another panel of stained glass, only the closest one will actually tint light. Pretty minor.</li><li>Colors at the furthest edge of the stained glass will be more powerful than the rest</li><li>It is a performance sink, for each step of the previous raymarching we are doing another raymarch. We can get away with 4–8 samples, but the performance hit is very noticeable.</li></ul><p>This tutorial assumes that you are familiar with the previous tutorial, and there are some variables like _SunDirection that aren’t mentioned here, if you intend to use this code, need an explanation on raymarching in general or my specific implementation, I encourage you to <a href="https://valeriomarty.medium.com/raymarched-volumetric-lighting-in-unity-urp-e7bc84d31604">read it</a> first.</p><h3>The Complete Algorithm</h3><ul><li>For every pixel in the screen we cast a ray in the direction of the camera view, effectively towards higher depth (but still the same screen space coordinate).</li><li>This ray is divided into a limited number of steps, each one at a different distance from the camera.</li><li>We ask Unity if that point in space is in light or shadow of the main light, this is possible because we can sample the Shadow Map.</li><li>IF a step is lit we calculate light scattering</li><li>Also, if the step is in light, we cast a second world-space ray from the step position towards the light.</li><li>This ray is also divided into a limited number of steps, each one not just at a different distance from the camera, but in a different screen space coordinate from where it started.</li><li>IF the second ray depth intersects the depth at that position, we can say the ray is touching something, but because this is only happening if the ray is in light, it can only be a non-shadow-casting object.</li><li>We calculate the average light scattering in that pixel by dividing the sum of the steps between the number of steps.</li></ul><p>Of course, just checking if the distance from the camera to the ray is greater than the distance from the camera to that pixel is not an accurate intersection check, the ray could always just be behind something from the camera perspective without ever intersecting it, but that is not a problem because we are going to use custom depth.</p><h3>Custom Depth</h3><p>Our algorithm uses depth to check if we are intersecting non-shadow-casting objects, but transparent materials do not write depth by default. We still do not want to force write depth because that will have unintended results. The solution is to have a custom depth pass where only the objects we want are rendered, which won’t affect regular transparent rendering.</p><p>This way we can also filter which objects will actually tint the rays, preventing regular objects from tinting our light because of the simplified intersection method, otherwise, every depth discontinuity would tint nearby light.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/934bd55f2a7f5b6d87ab05238a9c3e53/href">https://medium.com/media/934bd55f2a7f5b6d87ab05238a9c3e53/href</a></iframe><p>This script, which is based on the render feature of this <a href="https://alexanderameye.github.io/notes/edge-detection-outlines/">Alexander Ameye tutorial</a>, will let us create a ScriptableRendererFeature that will filter the visible objects by LayerMask, override their material and render them into a custom buffer. By using a material that writes custom depth, we have a custom depth buffer.</p><p>Some notes:</p><ul><li>In line 48, I am clearing to white, which is very important for our algorithm.</li><li>Using R8 encoding is completely fine for this purpose.</li><li>I am outputting to a global texture called “_CameraDepth2Texture”, which is not a great name.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*QWyFGq16yqGDe00OrDoD2w.png" /><figcaption>Make sure that the custom depth is above the volumetric light, your setting will look different than mine</figcaption></figure><p>We can’t actually use the same depth pass regular materials use for our custom depth, or at least I don’t know how to. What I do know is that in the volumetric shader I will calculate distance from the camera, so we can write a depth shader that outputs that as well. Regular depth is encoded using non-linear scaling for better precision near the camera, but to save on some calculations in the shader nested loop (which would mean converting to linear depth hundreds of times), I decided to directly write linear depth. For our purpose, the lower precision won’t have any impact.</p><p>The shader we are using is the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d62d0c2b4eb9ef4eaeae5e4a9bda95d8/href">https://medium.com/media/d62d0c2b4eb9ef4eaeae5e4a9bda95d8/href</a></iframe><p>This shader outputs distance from the camera, divided by the far plane value (_ProjectionParams.z) so it is a value from 0 to 1. Keep in mind that this shader is not a screen space effect, but the actual shader that will render some of the objects, that we are outputting to a render texture.</p><h3>The Shader</h3><p>Let’s jump directly into the shader and compare it with the one we had before.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88eba228bcd361b0397928bc7c28c1dd/href">https://medium.com/media/88eba228bcd361b0397928bc7c28c1dd/href</a></iframe><p>First, let’s talk about the least obvious difference. Before, we were working in monochrome, but we can no longer do that. Now, every pass outputs a real3 and every color is defined as real3. Apart from that, the blur, compositing, and Low Res passes are identical.</p><p>The raymarching differences start at line 192, where we define the constant variables for every color ray. This time the distance is constant, so we can calculate the step vector outside the loop.</p><p>The next stage starts at line 210, where we declare a nested loop when the ray is in light. We calculate the distance from the camera to the ray position and then that position in screen space coordinates, which we will use as UVs to sample our custom depth.</p><p>We don’t want to continue if the ray exited the screen view, so we break the loop in line 216 if that is the case.</p><p>In line 220 we sample our custom depth using DX10+ nomenclature and using SampleLevel(), which will sample the mipmap of our choice. The reason for this is that the regular sample uses derivatives to select the appropriate mipmap level, but to do that in a loop, the compiler needs to unroll it, which isn’t possible in our nested loop. This being a screen space effect, we don’t need mipmaps anyway, so we just sample from mipmap 0. We multiply by the far plane value to bring it back to proper units.</p><p>If the distanceToDepthRay is greater than the depth in that specific point of the screen, the ray is either behind or intersecting that point, so we sample its color. The tex2dlod nomenclature is equivalent to SampleLevel, you can use either one, DX10+ nomenclature is more modern and separates the sampler from the texture, but for a screen space effect, we don’t care about that.</p><p>The color value is multiplied by the scattering and then by 2, to not lose luminosity, I also added a _Boost parameter for stylistic effect.</p><p>Once we have sampled, we don’t need to continue the ray, so we break out of the inner loop. If we didn’t intersect, we continue the ray.</p><h3>The ScriptableRendererFeature</h3><p>We need to update our feature with RBG encoding for our render textures and passing the new parameters. Apart from that, it is identical to the previous one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18a885cf64892c7f323cb507cd327e3d/href">https://medium.com/media/18a885cf64892c7f323cb507cd327e3d/href</a></iframe><p>As a final note, my actual shader uses a _COLORED_ON keyword to switch between the previous one and this one, changing color variables and frag functions from real to real3 and enabling the second raymarching loop. In the scriptable renderer feature, I switch between the encodings too.</p><h3>The Result</h3><p>For the coloring to work, make sure to select a layer in your Custom Depth LayerMask and assign it to some objects. STAINED GLASS MUST HAVE SHADOWS DISABLED or it will not work properly.</p><p>For the best quality, I am using 40 normal raymarching steps at half resolution with 250 jitter and 8 colored samples with 2 jitter and 28 color max distance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*gc8bSv7lqQQ0QhfY_Wfvhg.png" /></figure><p>The same result can be obtained with 25 normal raymarching steps and just 4 colored samples at a minimal loss, any fewer samples than that will become noticeably noisy.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F9RG0SptJHkY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D9RG0SptJHkY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F9RG0SptJHkY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/bd1ebbfcb782ae779dea06c85c44fdd9/href">https://medium.com/media/bd1ebbfcb782ae779dea06c85c44fdd9/href</a></iframe><h3>Conclusion</h3><p>If you want more shader and game dev content be sure to follow me on Twitter: <a href="https://twitter.com/ValerioMarty">@ValerioMarty</a></p><p>You can also check my itch.io page for finished projects.</p><p><a href="https://valeriomarty.itch.io/">https://valeriomarty.itch.io/</a></p><h3>Additional resources used for this effect</h3><ul><li>Filtering and writing to a custom buffer <a href="https://alexanderameye.github.io/notes/edge-detection-outlines/">https://alexanderameye.github.io/notes/edge-detection-outlines/</a></li><li>The ones on the first article.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a19846def1cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Raymarched Volumetric Lighting in Unity URP (Part 1)]]></title>
            <link>https://valeriomarty.medium.com/raymarched-volumetric-lighting-in-unity-urp-e7bc84d31604?source=rss-2f2b66929564------2</link>
            <guid isPermaLink="false">https://medium.com/p/e7bc84d31604</guid>
            <category><![CDATA[raymarching]]></category>
            <category><![CDATA[shaders]]></category>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[scriptablerendererfeature]]></category>
            <category><![CDATA[volumetric-light]]></category>
            <dc:creator><![CDATA[Valerio Marty]]></dc:creator>
            <pubDate>Sat, 03 Jul 2021 12:34:26 GMT</pubDate>
            <atom:updated>2022-10-22T15:15:24.306Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ObPEAMXQWUOuDVR47VJ08A.png" /></figure><p>There are a lot of resources on raymarched volumetric lighting on the internet, but in this article, I am going to show you step by step everything you need to know about my own implementation and my modifications over the resources. This includes not just the basic concept, but how to make it performant with good visual quality, using downsampling, randomized sampling, bilateral blur, and near-depth upsampling. In a <a href="https://valeriomarty.medium.com/coloring-raymarched-volumetric-light-as-it-passes-through-stained-glass-a19846def1cd">later article</a>, we will learn how to modify this algorithm so it supports tinting when passing through stained glass.</p><p>Shortcomings of this implementation:</p><ul><li>Only supports a single directional light, no other lights.</li><li>No local density volumes or density textures</li></ul><p>These cons are not inherent to the implementation and can be added at a later stage, I just haven’t needed to do it, but if I do I will write about it :)</p><p>If you want to see the full code you can just scroll to the end, it is not the precise code I am running because I have cleaned it up a bit for this tutorial/breakdown so there may be easy to fix compile errors.</p><p>This effect is a screen space post-process, which means it takes place after everything else is rendered, and we work with limited information on a single quad that takes up the whole screen. To implement this in URP (I live on the edge and at the time of writing I am using the latest beta Unity 2021.2b) we need to use a:</p><h3>Scriptable Renderer Feature</h3><p>The basic concept is that we need to pass a render texture containing everything we have rendered until this point (we are going to do this just before regular post-processing) to our shader and then back to the screen, effectively injecting our code in the middle.</p><p>To do this, we need to write a ScriptableRendererFeature:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8af916ef3d376ccf94223892121898a/href">https://medium.com/media/d8af916ef3d376ccf94223892121898a/href</a></iframe><p>Most of this code can be reused for all your renderer features. A ScriptableRendererFeature overrides Create() which will allow us to create our feature in the Renderer Settings. Here we set the name of our feature and the settings that will show up in the inspector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/385/1*5_YuL_fBhcMrshA7etezHw.png" /></figure><p>It also overrides AddRenderPasses, which lets us inject our own code at certain points in the pipeline, passing our own ScriptableRenderPass. Keep in mind that the AddRenderPasses (and Setup because of that), Configure, and Execute methods are called every frame, even in the scene view.</p><p>In Configure() we get a temporary render texture which will be the target of our shader, we are using an R16 render texture, which only has a red channel, this is a simplification I am making because I only support a single light, so I don’t need its color until the very end, in our compositing pass, and we can work in black and white.</p><p>In Execute() we queue our own commands in the CommandBuffer which will run our code.</p><p>cmd.Blit(source, target) takes the source render texture, in this case containing the image the camera just rendered, and copies it into the target render texture, if the target render texture has a different resolution, it handles the downsampling for you.</p><p>cmd.Blit(source, target, material, passIndex) does the same but it runs the downsampled source render texture through a material of your choosing, using the pass you want. This means that we can write a single shader that can perform raymarching, blur, upsample, and compositing all in a single file but divided into different stages and we select which one we want to perform.</p><p>Make sure to ALWAYS run CommandBufferPool.Release(…) or you will have a huge memory leak that will crash not just Unity but your whole computer. I am putting all the code that can potentially fail while we are writing this feature inside a try-catch block. This way, the execution of this method doesn’t stop if it encounters an error, in that case, it will run the code in the catch block and continue properly.</p><p>We also included a RenderPassEvent in our settings, make sure to set it to Before Post Processing.</p><p>The code we just wrote will only handle the raymarching pass, but we will add more to it, you can scroll down to the end for the complete version. Also, we are passing our screen into the _MainTex of our raymarching pass, which isn’t necessary, but it will when we change this shader to support stained glass.</p><h3>Raymarching Pass</h3><h4>The concept</h4><p>The algorithm we are going to use works this way:</p><ul><li>For every pixel in the screen, we cast a ray in the direction of the camera view, effectively towards higher depth.</li><li>This ray is divided into a limited number of steps, each one at a different distance from the camera.</li><li>We ask Unity if that point in space is in light or shadow of the main light, this is possible because we can sample the Shadow Map (we need to use #pragma multi_compile _ _MAIN_LIGHT_SHADOWS_CASCADE to be able to sample the shadow map).</li><li>IF a step is lit we calculate light scattering and add its contribution</li><li>We calculate the average light scattering in that pixel by dividing the sum of the steps between the number of steps.</li></ul><p>The light scattering we are interested in occurs when light bounces with dust particles and aerosols in the atmosphere, the physics around this phenomenon is already known and there are equations that model to certain degrees various aspects of it. I have chosen to use a simplified Mie scattering because I am not looking for a realistic effect but a pleasant and performant one.</p><h4>The requisites</h4><p>Being a screen space effect, we are limited by the amount of information we have, but we have just enough. We have access to the depth information using _CameraDepthTexture, which we must enable in the pipeline settings.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/392/1*wRN50NMuPJWyiiS9fqx6XA.png" /></figure><p>The following include already declares this texture in our code and gives us a couple of functions.</p><pre>#include &quot;Packages/com.unity.render-pipelines.universal/ShaderLibrary/DeclareDepthTexture.hlsl&quot;</pre><p>We can reconstruct world position from the depth texture, which you can explore in-depth (pun intended) in this Cyan article (<a href="https://www.cyanilux.com/tutorials/depth/">https://www.cyanilux.com/tutorials/depth/</a>), luckily Unity already provides us with a function to do just that.</p><pre>ComputeWorldSpacePosition(uv, depth, UNITY_MATRIX_I_VP);</pre><p>The last external piece of information we need is the main light direction, to which we will need to add a script that will set a global variable we can read from every shader.</p><pre>using System.Collections;<br>using System.Collections.Generic;<br>using UnityEngine;</pre><pre>[ExecuteAlways]<br>public class MoonDirection : MonoBehaviour<br>{<br>    void Update()<br>    {<br>        Shader.SetGlobalVector(&quot;_SunDirection&quot;, transform.forward);<br>    }<br>}</pre><p>Note the [ExecuteAlways], which is necessary if you want this effect to update in the scene view.</p><p>You will also need the “_SunMoonColor”, which you can set up as a global variable just like “_SunDirection”, using Shader.SetGlobalVector(“_SunMoonColor”, /*your color*/);</p><p>With that, we have all we need to start writing our shader, which will be written in code because even if we used Shader Graph or Amplify Shader Editor we would need to write plenty of custom code.</p><h4>The code</h4><p>A couple of notes before we start if you have written shader code in BIRP (Built-In Render Pipeline) or followed old tutorials:</p><ul><li>We are using HLSLPROGRAM instead of CGPROGRAM, you can still use CGPROGRAM in URP, but Unity has moved into HLSL for URP and chances are that you want to include Unity functions in your code. Including both UnityCG and URP libraries will result in redefinition issues. Don’t worry, because there are replacements for every UnityCG function.</li><li>The included Unity files define ‘real’ as float or half depending on the platform, and that’s what I use.</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3ff36eeba1501de25daff2c95df78811/href">https://medium.com/media/3ff36eeba1501de25daff2c95df78811/href</a></iframe><p>Our actual code starts at line 104, in our fragment pass. First, we calculate the world space position of the pixel using GetWorldPosition(i.uv), which is defined in line 64. This function samples the depth texture and then uses a Unity function to reconstruct the depth position. If you want to see how it looks you can return its value after calculating it.</p><pre>real3 worldPos = GetWorldPos(i.uv);<br>return frac(worldPos);</pre><p>Colors in shaders go from 0 to 1, any more than that will only contribute to HDR bloom, but won’t actually be visible, if we want to analyze higher values we can use frac, which returns the decimal part of a number.</p><p>The fragment pass we’ve written outputs a single float (real), so if you want to properly see what you are doing, you can temporarily change it to a real3, if you still see a single color, use an RGB format in your render texture in the scriptable renderer feature.</p><p>From lines 110 to 128 we calculate the ray direction, its length, and the length of each step. The ray starts from the camera and we can use the global variable _WorldSpaceCameraPos to get the position. The end position is the world space position we just calculated. We then clamp the maximum ray length because it affects our precision, it is recommended you don’t reinvent the wheel and use the available functions, so I should probably use the following code instead.</p><pre>rayLength = min(rayLength,_MaxDistance);<br>worldPos= startPosition+rayDirection*rayLength;</pre><p>In line 132 starts the real deal of the shader, the for loop. Loops aren’t great in shaders as they benefit poorly from the parallel power of a GPU, but for a raymarching approach, it is the only way.</p><p>In line 134 we sample the light value in that position, which is essentially a mask for light and shadow. If the value is greater than zero we calculate light scattering, sum its value and advance the loop. We then average the result and return its value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VNTGXmabWCy2OyKGkl5kww.png" /></figure><p>If we return to Unity we will see a monochrome screen with our volumetric light. If you are checking the FPS meter you can see this effect is costing a very sizeable amount of performance and the result isn’t that great, because there is a very noticeable banding issue. If we reduce the number of steps we can clearly see the shadow silhouette. If we use more steps, it will be less noticeable but it will consume much more.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*VQZVEm4Ruh9ZA7eD5RpdzA.png" /><figcaption>There is clear banding and it is not even a single ray</figcaption></figure><p>Banding occurs because we are sampling at discrete points, and for a given portion of the screen, every step of each ray is mostly at asimilar depth, effectively reproducing the shadow map pixel by pixel, if we somehow randomize the sampling points, the pattern will not be recognizable. This technique is inspired by Interleaved Sampling, used in Lords of the Fallen, but with huge simplification and, in my opinion, improvement.</p><p>If we randomize the starting point of each ray, instead of just starting in the camera position, we are also randomizing each subsequent step position. To get a random number we can either sample a blue noise texture or use the famous:</p><pre>frac(sin(dot(p, float2(41, 289)))*45758.5453 );</pre><p>, which gives us a pseudo-random value from 0 to 1 depending on an input variable p. If we add it to the starting position, randomizing in the direction of the ray, and add a new variable to control its influence, we can get rid of any patterns, albeit very noisy, but that will be solved when we blur everything out.</p><pre>real rayStartOffset= random01( i.uv)*stepLength *_JitterVolumetric/100;<br>real3 currentPosition = startPosition + rayStartOffset*rayDirection;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0pCjOp4R08soS5DDBWgrqA.png" /><figcaption>Noisy, but looking good</figcaption></figure><p>If you want to easily play around with the values, like the max distance and step amount, you can add new variables to the ScriptableRendererFeature settings.</p><pre>        public float intensity = 1;<br>        public float scattering = 0;<br>        public float steps = 25;<br>        public float maxDistance=75;<br>        public float jitter = 250;</pre><p>And send them to our shader just before the blit.</p><pre>settings.material.SetFloat(&quot;_Scattering&quot;, settings.scattering);                settings.material.SetFloat(&quot;_Steps&quot;, settings.steps);                settings.material.SetFloat(&quot;_JitterVolumetric&quot;, settings.jitter);                settings.material.SetFloat(&quot;_MaxDistance&quot;, settings.maxDistance);                settings.material.SetFloat(&quot;_Intensity&quot;, settings.intensity);                </pre><p>Now you can play with them!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/375/1*t2TTD83dICC9a6D9vuxqGA.png" /></figure><p>If you ignore the noise, you will notice that we can get away with fewer steps if we increase the jitter but, even then, it is pretty performance heavy. To get a good result, we are using between 25 and 50 steps for every single pixel of the screen. But what if we don’t do that and work on a lower resolution version of the screen instead?</p><h3>Downsample</h3><p>Blit can downsample for us, but chances are that you want to downsample to half or quarter resolution depending on your quality settings, and you may also want to experiment on the fly and check how it looks with or without downsampling without recompiling, so we are gonna add a new variable to our settings.</p><pre>public enum DownSample { off = 1, half = 2, third = 3, quarter = 4 };<br>public DownSample downsampling;</pre><p>Notice that I’ve overwritten the values of the enum, otherwise, it would start at zero, and you will see immediately why we don’t want that. In the Configure method of our ScriptableRenderPass, where we get a temporary render texture, we can further customize its properties.</p><pre>cameraTextureDescriptor.width /= settings.downsampling;<br>cameraTextureDescriptor.height /= settings.downsampling;</pre><p>Now we have a dropdown to select downsample.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/165/1*XxQpIfrRKgLzXGWR8wlcng.png" /></figure><p>If at any time from now on you notice that the downscaling works differently in the scene view, with even lower resolution, you will have to use the following code. I don’t know if it is a bug or version dependent, or the expected behavior, but just in case.</p><pre>if (Camera.current != null){<br>    cameraTextureDescriptor.width = (int)Camera.current.pixelRect.width / divider;<br>    cameraTextureDescriptor.height = (int)Camera.current.pixelRect.height / divider;<br>}<br>else{<br>    cameraTextureDescriptor.width /= divider;<br>    cameraTextureDescriptor.height /= divider;<br>}</pre><p>In URP, Camera.current only works in the scene view.</p><p>Now it works everywhere but, of course, it has less quality. When we eventually composite this render texture with the camera view, it will be obvious the rays were rendered in another resolution. The answer is a bilateral blur (which will get rid of the noise too) and depth-aware upsample.</p><h3>Bilateral Blur</h3><p>Blur works by averaging the color value of the surrounding pixels of a given pixel. But here is the problem, shaders are run in parallel, and the information a single pixel has of the rest is very limited. How do we access the surrounding color values of our raymarch? The answer is writing the raymarch pass into a render texture and passing it into another pass, this way we are just sampling a texture and we can offset our UVs.</p><p>A bilateral blur works like a regular Gaussian blur but takes depth into account to try not to blur hard edges in the depth texture. It also blurs to a higher degree pixels that are very close and gradually reduces the blur weight of further pixels.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lc6DaXyIUbltDWnpBjAl4Q.png" /><figcaption>Gaussian Blur</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LFLbimugbpj6PLOoLOlTcw.png" /><figcaption>Bilateral Blur, probably not the best implementation</figcaption></figure><p>Our blur is gonna be composed of two different passes, in the first one we will blur in the X-axis, write to a texture, and blur in the Y-axis in another pass. This implementation is almost 1:1 to the <a href="https://fr.slideshare.net/BenjaminGlatzel/volumetric-lighting-for-many-lights-in-lords-of-the-fallen">Lords of the Fallen</a> one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/254acedde84821616aaa1237ff851da0/href">https://medium.com/media/254acedde84821616aaa1237ff851da0/href</a></iframe><p>The comments in the code are self-explanatory. You will notice we are sampling _MainTex, which takes the value of whatever source we blit into this shader, in our case, our volumetric pass. This blur pass only accounts for the X-axis, to blur the Y-axis you can copy and paste this whole pass and change the UV offset from</p><pre>real2 uv= i.uv+real2(  index*_GaussAmount/1000,0);</pre><p>to</p><pre>real2 uv= i.uv+real2( 0, index*_GaussAmount/1000);</pre><p>Or you can pass the axis through a variable and run the blit using the same Pass but changing the axis. I’ve opted for the former.</p><p>In our ScriptableRenderPass our Blits should be looking like this:</p><pre>cmd.Blit(source, tempTexture.Identifier(), settings.material, 0);<br>cmd.Blit(tempTexture.Identifier(), tempTexture2.Identifier(), settings.material, 1);<br>cmd.Blit(tempTexture2.Identifier(), source, settings.material, 2);</pre><p>As you can see, we change the index in each Blit because we are using a different pass. There is also a new render texture, we need two to keep passing info from one pass to the next. Add a</p><pre>RenderTargetHandle temptexture2;</pre><p>to the ScriptableRenderPass variables and the following lines in the Configure method right next to the other render texture.</p><pre>temptexture2.id = 1;<br>cmd.GetTemporaryRT(temptexture2.id, cameraTextureDescriptor);<br>ConfigureTarget(temptexture2.Identifier());</pre><p>Both render textures use the same description, we only have to make sure to change the id of the second one (zero by default).</p><p>We now need to pass our blur settings (samples and intensity) to the shader. We can add the following variables to the settings:</p><pre>[System.Serializable]        <br>public class GaussBlur{<br>   public float amount;<br>   public float samples;<br>}<br>public GaussBlur gaussBlur = new GaussBlur();</pre><p>I’ve chosen to create a small class so it can be expanded and minimized in the editor without writing a custom inspector.</p><pre>settings.material.SetFloat(&quot;_GaussSamples&quot;, settings.gaussBlur.samples);<br>settings.material.SetFloat(&quot;_GaussAmount&quot;, settings.gaussBlur.amount);</pre><p>And we pass them to our shader in the Execute method. If we return to Unity and play around with our values we will now have something close to this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KxjDaVFAQ4ruKhiJiUS33g.png" /></figure><h3>Upsampling and Compositing</h3><p>We just need to composite! Almost! If we use the downsampled render texture as it is, and composite it into our scene, the pixels will be noticeable, even after blurring, because we blurred on a downsample resolution. The trick is to use <a href="https://eleni.mutantstargoat.com/hikiko/on-depth-aware-upsampling/">Depth-Aware Upsampling</a>, which uses depth information to select the closest-in-depth downsampled pixel adjacent to a full resolution one, leaving our hard edges cleaner, where the downsampling is more noticeable.</p><p>To use this technique we need both a full resolution depth texture, which we already have as _CameraDepthTexture, and a downsampled one. Because the compositing pass works at full res, we will need to pass the downsampled version ourselves. There are probably multiple, more elegant methods than mine, but I chose to add yet another pass (fourth in my case, compositing is the third, the order doesn’t matter).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b007fb5e972da1848afaa31bbe445dbd/href">https://medium.com/media/b007fb5e972da1848afaa31bbe445dbd/href</a></iframe><p>The code is nothing special, it literally just returns depth, but because we are going to use a low res target in the blit, the downsampling is automatic.</p><p>We don’t need a new render texture for this, as we can reuse one of the previous ones:</p><pre><em>//raymarch<br></em>cmd.Blit(source, tempTexture.Identifier(), settings.material, 0);<br><em>//bilateral blur X<br></em>cmd.Blit(tempTexture.Identifier(), tempTexture2.Identifier(), settings.material, 1);<br><em>//bilateral blur Y<br></em>cmd.Blit(tempTexture2.Identifier(), tempTexture.Identifier(), settings.material, 2);<br><em>//downsample depth<br></em>cmd.Blit(source, tempTexture2.Identifier(), settings.material, 4);<br>cmd.SetGlobalTexture(&quot;_LowResDepth&quot;, tempTexture2.Identifier());<br>cmd.SetGlobalTexture(&quot;_volumetricTexture&quot;, tempTexture.Identifier());</pre><p>Notice that we are writing both the downsampled depth texture and our blurred raymarch to textures because our future compositing blit needs the camera render as its source, so the other inputs need to be passed as separate textures.</p><p>Let’s add the final blit even though we still haven’t written the compositing pass.</p><pre><em>//upsample and composite<br></em>cmd.Blit(source, tempTexture3.Identifier(), settings.material, 3);<br>cmd.Blit(tempTexture3.Identifier(), source);</pre><p>Add yet another render texture to our custom pass, adding:</p><pre>RenderTargetHandle tempTexture3;</pre><p>This time around the render texture will not be like the others, as it will need all channels and full resolution, leaving our Configure method like this:</p><pre>public override void Configure(CommandBuffer cmd, RenderTextureDescriptor cameraTextureDescriptor){</pre><pre>var original = cameraTextureDescriptor;<br>int divider = (int)settings.videoSettings.currentSettings.volumetricSettings.downsampling;</pre><pre>if (Camera.current != null){<br>    cameraTextureDescriptor.width = (int)Camera.current.pixelRect.width / divider;<br>    cameraTextureDescriptor.height = (int)Camera.current.pixelRect.height / divider;<br>    original.width = (int)Camera.current.pixelRect.width;<br>    original.height = (int)Camera.current.pixelRect.height;<br>}<br>else{<br>    cameraTextureDescriptor.width /= divider;<br>    cameraTextureDescriptor.height /= divider;<br>}<br>cameraTextureDescriptor.msaaSamples = 1;<br>cameraTextureDescriptor.colorFormat = RenderTextureFormat.R16;</pre><pre>tempTexture2.id = 1;<br>tempTexture3.id = 2;</pre><pre>cmd.GetTemporaryRT(tempTexture.id, cameraTextureDescriptor);<br>ConfigureTarget(tempTexture.Identifier());<br>cmd.GetTemporaryRT(tempTexture2.id, cameraTextureDescriptor);<br>ConfigureTarget(tempTexture2.Identifier());<br>cmd.GetTemporaryRT(tempTexture3.id, original);<br>ConfigureTarget(tempTexture3.Identifier());</pre><pre>ConfigureClear(ClearFlag.All, Color.black);<br>}</pre><p>Let’s write the compositing pass:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a286f778250e64fffbe73d1cded1f21/href">https://medium.com/media/9a286f778250e64fffbe73d1cded1f21/href</a></iframe><p>Branching in shaders is not great, especially in this case, where each pixel uses a different branch, but the results speak for themselves.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ol09OFRBZHhGkxakCGF03g.png" /></figure><p>If you examine hard edges and try regular upsampling the difference is obvious.</p><p>We are done!</p><h3>Final Code</h3><p>The final ScritableRendererFeature should be looking similar to this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22d5763acb457ab4cf5013dcdb396d09/href">https://medium.com/media/22d5763acb457ab4cf5013dcdb396d09/href</a></iframe><p>I have added a switch in the Execute method so I can choose to run specific stages for debugging purposes.</p><p>And our final shader should look similar to this.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/871d523bc45a97b921359fa95b6d7cf9/href">https://medium.com/media/871d523bc45a97b921359fa95b6d7cf9/href</a></iframe><h3>Project example</h3><p>You can find a project with slightly updated code <a href="https://github.com/ValerioMarty/VolumetricLightExample"><strong><em>here</em></strong></a>.</p><h3>Next Article</h3><p><a href="https://valeriomarty.medium.com/coloring-raymarched-volumetric-light-as-it-passes-through-stained-glass-a19846def1cd">In the next article, we will learn how to modify this effect to support stained glass.</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_py9m6FpGiySivzneVamzQ.png" /></figure><h3>Other Possible Upgrades</h3><ul><li>Epipolar Sampling, for performance</li><li>Density volumes, for local fog</li><li>Point lights</li><li>Spotlights</li></ul><h3>Conclusion</h3><p>If you want more shader and game dev content be sure to follow me on Twitter: <a href="https://twitter.com/ValerioMarty">@ValerioMarty</a></p><p>You can also check my itch.io page for finished projects.</p><p><a href="https://valeriomarty.itch.io/">https://valeriomarty.itch.io/</a></p><h3>Resources</h3><p>This implementation is loosely based on a combination of different techniques and concepts taken from a variety of resources:</p><ul><li>Basic concept: <a href="http://www.alexandre-pestana.com/volumetric-lights/"><em>http://www.alexandre-pestana.com/volumetric-lights/</em></a></li><li>Interleaved sampling and bilateral blur: <a href="https://fr.slideshare.net/BenjaminGlatzel/volumetric-lighting-for-many-lights-in-lords-of-the-fallen"><em>https://fr.slideshare.net/BenjaminGlatzel/volumetric-lighting-for-many-lights-in-lords-of-the-fallen</em></a></li><li>Depth-aware upsampling: <a href="https://eleni.mutantstargoat.com/hikiko/on-depth-aware-upsampling/"><em>https://eleni.mutantstargoat.com/hikiko/on-depth-aware-upsampling/</em></a></li><li>Scriptable Renderer Feature: <a href="https://samdriver.xyz/article/scriptable-render">https://samdriver.xyz/article/scriptable-render</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e7bc84d31604" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a Card Shader with 3D content]]></title>
            <link>https://valeriomarty.medium.com/creating-a-card-shader-with-3d-content-f3324ca8ffdc?source=rss-2f2b66929564------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3324ca8ffdc</guid>
            <category><![CDATA[shaders]]></category>
            <category><![CDATA[amplify]]></category>
            <category><![CDATA[stencil]]></category>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[card-foil]]></category>
            <dc:creator><![CDATA[Valerio Marty]]></dc:creator>
            <pubDate>Sun, 25 Apr 2021 16:27:34 GMT</pubDate>
            <atom:updated>2021-10-04T18:58:13.056Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*DV9_pKYScGBniaSzbM1k4w.gif" /></figure><p>This is a breakdown of a couple of shaders I made for Harry Alisavakis’ Technically Speaking Discord Challenge, with the theme of Trading Card Foil. I used Unity (URP) and Amplify Shader Editor to author these shaders, but if you are following this breakdown to replicate some aspects of it, you can perfectly use Shader Graph for most of it except the Stencil Buffer and some tags that you may add later to the generated code that I will also show. As a note, I greatly recommend using Amplify Shader Editor over Shader Graph as it is immensely faster, more complete and just a joy to work with.</p><p>You can find a package with the finished version at the end of the post.</p><h3>Creating a 3D interior with the Stencil Buffer</h3><p>The most evident effect in this card shader is the 3D interior that can only be seen looking through the card. This effect is achieved using the Stencil Buffer.</p><p>The Stencil Buffer is an 8-bit mask you can use to tell shaders whether they should render a pixel or not. A shader can write to the Stencil Buffer and another shader can check that information and choose what to do or render based on that. There is some fancy stuff you can do with the Stencil Buffer but for this effect, we only need to write to and check a single layer.</p><p>First, let’s set up a Unity Scene with a Quad and some sample geometry behind it, in my case two cubes. This Quad will act as a window, everything outside it will not be rendered and everything behind it will.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/554/1*7RzHc6NKwVDtmthupY7dMQ.jpeg" /></figure><p>Create a new Unlit shader and a material and assign it to the quad. In Amplify navigate to Pass -&gt; Stencil Buffer and activate the little box on the right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/264/1*nXWauGsiGPjFzZbhijAHGw.png" /></figure><p>“Reference” is the Stencil Buffer layer we are gonna use, for this project it doesn&#39;t matter what you choose, just make sure you don’t use number 0. We can also ignore Read Mask and Write Mask for the purpose of this breakdown.</p><p>“Comparison” compares the reference value to the content of the Stencil Buffer. What we want from this Shader is to write to the Stencil Buffer our reference value, doesn’t matter what the previous value was. Because of that, we use “Always” so we write to it no matter what.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/149/1*qOIiQQgKt78pJ_b4Sritqw.png" /></figure><p>“Pass Front” is the action we are gonna take for the pixels in the front face of the quad. “Replace” will write our reference value into the Stencil buffer, which is exactly what we want.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*QrWncSoCJJduWqZH3HYvHA.png" /></figure><p>If you are doing this in code, you just have to add this piece of code to the start of the Forward pass. As you see, the setting mirror the code one-to-one.</p><p>Now let’s create a new Lit Shader for the contents of our card, create a material, assign it to the cubes and navigate to the Stencil Buffer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/269/1*oGWjSe0UUDpCuPlCicsfXA.png" /></figure><p>In this case, we want to mask every pixel that is in the mask and discard the rest. First, we need to read from the appropriate layer, so we set up the reference to the same number as the other shader and set “Comparison” to “Equal” so we only act based on the information of that layer. “Pass Front” is set to Keep because we want to keep those pixels if we are inside the mask.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*ylaq5UlWXhW4Z3F9xCF5Iw.png" /></figure><p>Once you save, it will seem as if it stopped working, but that is not the case! It is in fact discarding every pixel outside the quad and rendering only those behind it, but because the engine knows the quad is in front, it will not render what is behind it.</p><p>This is achieved with the Depth Buffer, every opaque object writes to the Depth Buffer and Unity uses that to know whether an object is in front of another, but we can tweak the behavior of a specific shader.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*NEJZ46B6Y4zelpD-yHcIZA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*BqdhcpgJjTSG716z5QEwww.png" /></figure><p>Setting ZWrite to Off will make Unity render that object behind everything else, even if it is in front of the scene view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*tkVIuMsX01-wkSlHiAkiJg.png" /></figure><p>We’ve done it!</p><p>Let’s now add the rest of the card. Add a new quad with a new Lit Shader and navigate to the Stencil Buffer Options.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*AfffW4h0HqRKIo640eTdxg.png" /></figure><p>In this case, we want it to render only where the stencil buffer mask is not present, so we set “Comparison” to “Not Equal”.</p><p>If you orbit around the scene you may notice the effect doesn’t work at certain angles.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*flvqe_NXwxv6vLXdnIxmMw.png" /></figure><p>The Stencil and Depth Buffers are working, but we need the window shader to write to the Stencil Buffer BEFORE everything else renders, for that, we need to adjust the Render Queue.</p><p>In the Foil Shader navigate to SubShader -&gt; Tags -&gt; Queue and increase the index by one so it always renders after the window. Likewise, increase the queue index of the objects inside the card, in my case they are transparent, which by default is rendered after the opaque geometry.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/261/1*z_x1gTkU3oP2sCBPa-CyEA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/1*8mXifQFO0xk2gqeXZKTSVg.png" /></figure><p>Now that we have our scene set up and everything working, we can dive into the shaders.</p><h3>Sparkles</h3><p>Most effects in this card change depending on the view angle, whether it is to fake depth or just to shift colors or parameters.</p><p>Let’s start with the sparkly glitter that only shows up at certain angles. First, we create a vertical band that moves from left to right depending on the view direction to fake reflection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GNof0GOw6gs5esMRTVc-jg.png" /></figure><p>I learned this effect from Cyan (@Cyanilux on Twitter), in which we just offset our UV coordinates by the View Direction. I’ve also added some more parameters to control precisely the location and potency of the effect.</p><p>Because we want a vertical band, we can use the U channel from the UVs, which is a linear gradient in the horizontal coordinate, and feed it to a triangle wave node which will create a nice faded vertical band. Saturate the output to clamp it between 0 and 1 and connect it to a power node to control size and intensity. The saturate node is extremely important because the black part in the triangle wave preview can contain negative values that will play badly later on. I connected the result of this graph to the emission node so it acts as unlit color.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*-21tZoWlY3lYonL98yxdQA.gif" /></figure><p>Now we want to color this band. For a normal foil shader, you would choose to reflect different colors of the rainbow depending on the angle, I recommend you to check Alan Zucconi’s post about rainbow representation if you choose to do so (<a href="https://www.alanzucconi.com/2017/07/15/improving-the-rainbow/">https://www.alanzucconi.com/2017/07/15/improving-the-rainbow/</a>). In my case, I settled on coloring the band based on a two-color gradient that moves along with the band.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CYg1iid4RFb90KFAZ0cOAg.png" /></figure><p>As you can see, I use the same structure to move the UVs around and feed the U channel to the Time input of a Gradient Sample Node. You may be confused on why it says time but that is just indicating the usual purpose of the node. In reality, lower values, in our case darker colors, will be mapped to the left side of the gradient and lighter colors to the right side. We then multiply this graph with the vertical band and we have our colored band.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*3M2t8WM-LKB_ixlwi9-_Gw.gif" /></figure><p>To make it look like glitter we will then multiply it by another graph.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IQLyGsBf4oV7GcXTTZk10Q.png" /></figure><p>To make perfectly rounded specks we use a Voronoi noise and step through it to generate a dotted mask. In addition to that, I also used a simplex noise to add some more specks with different form factors. We then multiply it by our previous result and…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*mm8lPo9aZ5hGyXeeHXtqTw.gif" /></figure><h3>Surface Pattern</h3><p>Let’s disconnect our result from the master and focus now on the surface pattern.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rngi_u_dIRkVTH0RIkWo6w.png" /></figure><p>Just as before, we start with offsetting the UV coordinates by the View Direction, but this time around I multiply it by a Gradient Noise, this will offset the UVs locally, deforming the UVs and creating interesting patterns. By multiplying it by the view direction we make the distortion dependent on it.</p><p>By using the pattern to lerp between two colors we achieve the exact same behavior as sampling it with a two-color gradient like before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*-jlyq8OSxJ1f39YXyFcI6A.gif" /></figure><h3>Glare</h3><p>Just as before, disconnect the previous graph from the master node, and let’s dive into the next part.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cAdgVDgzAYC-emwFJbIRXw.png" /></figure><p>I refer to glare to the periodical diagonal shine I added because there is never too much shiny stuff.</p><p>Because I want to make it periodical, I use a sawtooth wave connected to the time node, that way we have a linear gradient that periodically resets. We then offset the UVs by this value and rotate them to make them diagonal. Feed the UVs to a rectangle node with a very high height (or width) value and we are done.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*yJK_yNW5WpTVnJro32E7HA.gif" /></figure><h3>Borders and pentagons</h3><p>The graphs we created are then modulated by some procedural borders. They all follow the same structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FAQOJa4PcikZXm1nbjN_BA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SWQk-3yglF_sAZafEJZ4KQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QRhfo1ymtWlweL4FjOGQtg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K9DwP5247kZqUDcNhGQpqg.png" /></figure><p>Just keep in mind that if you subtract a rectangle from another you may create negative values, so be sure to saturate if needed if you see unwanted effects.</p><h3>Let’s mix everything</h3><h4>Albedo</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lLsIhEF0BprlfpSznwZY7g.png" /></figure><p>These operations are self-explanatory. The albedo part of the card is very faint, as most of the work is done by emission and smoothness/metallic.</p><h4>Emission</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zEsCNKlnvnqyJ5RKo01Srw.png" /></figure><p>Starting from the left, we lerp the glitter out of the text area, in this case, I settled for very faint glitter, but we could have just multiplied the glitter by the mask to completely get rid of the stars in that area. We multiply the combined colored glitter by an emission float so we can use the excess brightness for post-processing effects like bloom. We mask the stars out of the outer edges and add the glare.</p><p>The surface pattern is also decreased in the text area thanks to a lerp, which we add to the previous result.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/820/1*je7ixZEmN2eMbXhcUpB_QA.png" /></figure><p>Finally, we increase the emission of the combined effect in the border areas, which are the sum of the outer edge, window border, pentagons, and text area border.</p><h4>Metallic and Smoothness</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SjiqsbIjcb7gOBbVcs37gQ.png" /></figure><p>Thanks to two lerps, we can adjust smoothness and metallic values over the text area, the pattern, and the borders.</p><h3>End Result</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BSG-qDzjm4za4Tey4sIqPg.png" /></figure><p>We made it! If you’ve been following, the resulting graph will look somewhat like this.</p><p>To achieve the final result, I added a pulsing glow in a third quad behind the card, and a fourth quad behind the cubes, as well as a white directional light and a very bright yellow point light. The text is just Text Mesh Pro with some HDR glow. To top it off, add some post-processing bloom and you will get something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/565/1*_jZWuPa4_nUIwwCIZCv4qA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*DV9_pKYScGBniaSzbM1k4w.gif" /></figure><p>You can grab the finished version <a href="http://valeriomarty.games/CardFoil.unitypackage">here</a> (Dependencies: Amplify Shader Editor, URP, TextMeshPro, the rotating script uses DoTween too)</p><h3>Conclusion</h3><p>If you want more shader and game dev content be sure to follow me on Twitter: <a href="https://twitter.com/ValerioMarty">@ValerioMarty</a></p><p>You can also check my itch.io page for finished projects.</p><p><a href="https://valeriomarty.itch.io/">https://valeriomarty.itch.io/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3324ca8ffdc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>