<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://www.sheehanahmed.com/feed.xml" rel="self" type="application/atom+xml" /><link href="https://www.sheehanahmed.com/" rel="alternate" type="text/html" /><updated>2026-11-04T16:06:57-08:00</updated><id>https://www.sheehanahmed.com/feed.xml</id><title type="html">Sheehan Ahmed</title><subtitle>Sheehan Ahmed — technical artist building shaders, real-time visual effects, and tools for game development.</subtitle><author><name>Sheehan Ahmed</name></author><entry><title type="html">Dijkstra’s Algorithm Pixel Shader for Tactics Movement</title><link href="https://www.sheehanahmed.com/dijkstra-algorithm-pixel-shader-for-tactics-movement/" rel="alternate" type="text/html" title="Dijkstra’s Algorithm Pixel Shader for Tactics Movement" /><published>2024-02-05T19:00:00-08:00</published><updated>2024-02-05T19:00:00-08:00</updated><id>https://www.sheehanahmed.com/dijkstra-algorithm-pixel-shader-for-tactics-movement</id><content type="html" xml:base="https://www.sheehanahmed.com/dijkstra-algorithm-pixel-shader-for-tactics-movement/"><![CDATA[<p>I’ve been playing Intelligent Systems’ <em>Fire Emblem</em> games recently. It’s hard not to appreciate how the tactical movement gives depth and immersion to a Game Map that’s visually just a handful of pixels compared to modern game landscapes like <em>Red Dead Redemption 2</em> or <em>Breath of the Wild</em>. Considering units’ positioning down to choices between adjacent grid cells gets a player intimately engaging with the game environment.</p>

<video class="gif align-center" width="440" height="286" muted="" loop="" playsinline="" preload="none" data-autoplay="" poster="/assets/video/04_blazing-blade.jpg" aria-label="Fire Emblem Gameplay"><source src="/assets/video/04_blazing-blade.mp4" type="video/mp4" /></video>

<p>Notice that when the player selects a unit to move them, it displays a grid. This grid depicts grid cells the player can move to in blue, and grid cells they can attack in red. This display is integral to the strategy of <em>Fire Emblem</em>, as it gives the player a clear yet informative summary of their tactical options.</p>

<p>I wanted to recreate the effect myself, with an added optimization challenge; have the whole algorithm run on the GPU with a pixel shader.</p>

<blockquote>
  <p><strong>Why the GPU?</strong></p>

  <p>Speed is a concern, since moving units is a common command. The game freezing up every time you click on a unit to move is unacceptable. This also can’t be solved with multithreading instead, because the game needs to show where a unit can travel immediately upon clicking on it. In conclusion, our solution must run fast on the main thread using a pixel shader.</p>
</blockquote>

<h3 id="expected-behavior">Expected Behavior</h3>
<p>Firstly, let’s review the needs and expected behavior of the system:</p>
<ul>
  <li>The world is organized into grid cells. Each grid cell has an integer Movement Cost (1, 2, 4, or 8), or is a wall that cannot be moved upon or through.</li>
  <li>There are Units that live in individual grid cells, and can move to other grid cells. Units can only move up, down, left or right. “Diagonal” movements are counted as moving two grid cells.</li>
  <li>Each Unit has an integer Movement Range. This means that they may travel as far as the sum of the travelled grid cells’ Movement Costs is less than or equal to their Movement Range.</li>
  <li>A Unit will be able to move at least one grid cell away from their starting one, even if their Movement Range is less than the cost of that cell’s Movement Cost.</li>
  <li>Units additionally may Attack up to an integer Attack Range grid cells away from their ending position. Attack Range ignores Movement Cost and walls.</li>
</ul>

<h3 id="dijkstras-algorithm">Dijkstra’s Algorithm</h3>
<p>The needs and expected behavior denote two specific problems:</p>
<ul>
  <li>How can we find every accessible point given a starting cell and movement range?</li>
  <li>How can we trace this point back to the starting point?</li>
</ul>

<p>This is best done with Dijkstra’s Algorithm because it’s essentially built to solve this problem.</p>

<p><img src="https://upload.wikimedia.org/wikipedia/commons/2/23/Dijkstras_progress_animation.gif" alt="" class="align-center" /></p>

<p>Here is a brief paraphrased refresher on Dijkstra’s as it applies to our problem. This is for newcomers… or if your memory of sophomore-year algorithms class is getting hazy.</p>
<ol>
  <li>Start with every cell marked open, other than a start point cell, which is closed. We will “close” nodes as we visit them to keep track of where we’ve been.</li>
  <li>Assign to every cell a Travel Cost value. This defaults to infinity for every cell other than the starting cell, which is zero. This value represents the shortest possible path to reach this cell from the starting cell.</li>
  <li>For a current node, consider all open neighbors. If an open neighbor could be given a Travel Cost less than the one it currently has by virtue of travelling there from the current node, assign it the newer Travel Cost. Close the current node.</li>
  <li>Repeat step 4 for every open neighbor of the current cell in a breadth-first search. Stop when cells whose Travel Cost exceeds the Movement Range are reached.</li>
  <li>After this process, every “closed” cell can be travelled to, and each contains a Travel Cost defining how much of the Movement Range is expended to reach it.
(This is loosely paraphrased from the <a href="https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm">Wikipedia article</a> on Dijkstra’s algorithm)</li>
</ol>

<h3 id="running-an-algorithm-on-a-pixel-shader">Running an algorithm on a Pixel Shader</h3>

<p>Dijkstra’s algorithm is cool and all but… how do we run that on a pixel shader? The algorithm asks for maintaining a set of closed cells, and shaders can’t really keep consistent state like that. It also involves a Breadth-first search, which would be best done in a loop. As it’s currently defined, a pixel shader is incapable of adapting Dijkstra’s algorithm.</p>

<p>So, we’ll have to think outside the box… and flip the script.</p>

<p><img src="https://64.media.tumblr.com/e1135919ffae84a9a05a33d6aecbcb5b/b04f7415d0823b3d-86/s540x810/da6b1bdda1fba1e0479e38494b41409be72e18f5.gif" alt="" class="align-center" /></p>

<details open="">
  <summary> Bottoms-up Dijkstra's Algorithm </summary>

  <p>This is bottoms-up because open cells who notice a closed neighbor drive themselves, instead of closed cells finding open neighbors. This works great for a pixel shader where we need to run an identical instruction on every cell and can’t rely on holding list states.</p>

  <p>Pseudocode:</p>

  <div class="language-c# highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span><span class="p">(</span><span class="n">current</span> <span class="k">is</span> <span class="n">Wall</span> <span class="n">or</span> <span class="n">current</span> <span class="k">is</span> <span class="n">Closed</span> <span class="n">or</span> <span class="n">all</span> <span class="n">neighbors</span> <span class="n">are</span> <span class="n">Open</span><span class="p">)</span>
	<span class="k">return</span>

<span class="k">if</span><span class="p">(</span><span class="n">up_neighbor</span> <span class="k">is</span> <span class="n">closed</span> <span class="p">&amp;&amp;</span> <span class="n">up_neighbor</span><span class="p">.</span><span class="n">travelCost</span> <span class="k">is</span> <span class="n">least</span><span class="p">)</span>
	<span class="n">current</span><span class="p">.</span><span class="n">nearestNeighbor</span> <span class="p">=</span> <span class="n">up</span>
	<span class="n">current</span><span class="p">.</span><span class="n">travelScore</span> <span class="p">=</span> <span class="n">up_neighbor</span><span class="p">.</span><span class="n">travelScore</span> <span class="p">+</span> <span class="n">up_neighbor</span><span class="p">.</span><span class="n">cost</span>

<span class="cm">/* repeat the above if statement for down, left, right */</span>

<span class="k">if</span><span class="p">(</span><span class="n">current</span><span class="p">.</span><span class="n">travelScore</span> <span class="p">&lt;=</span> <span class="n">movementRange</span><span class="p">)</span>
	<span class="nf">close</span><span class="p">(</span><span class="n">current</span><span class="p">)</span>
</code></pre></div>  </div>

</details>

<h3 id="holding-dijkstra-state-in-an-8-bit-rgba-texture">Holding Dijkstra State in an 8-bit RGBA Texture</h3>

<p>We can’t rely on holding state externally to the texture. Instead, we will find clever ways to use all 4 channels in the 8-bit texture in order to store state.</p>

<p>The only offline information we need for a Map is the Movement Cost of each cell and whether or not it’s a wall. This will be stored in the Red channel, as follows:</p>

\[MC=
\begin{cases} 
  1 &amp; 0.0 \leq R &lt; 0.2 \\
  2 &amp; 0.2 \leq R &lt; 0.4 \\
  4 &amp; 0.4 \leq R &lt; 0.6 \\
  8 &amp; 0.6 \leq R &lt; 0.8 \\
  Wall &amp; 0.8 \leq R &lt; 1.0 \\
\end{cases}\]

<p>Which can be simplified to:</p>

\[MC=\begin{cases} 
  2^{ceil(5*R)-1} &amp; 0.0 \leq R &lt; 0.8 \\
  Wall &amp; 0.8 \leq R &lt; 1.0 \\
\end{cases}\]

<p>In a real game, this Red Channel will be populated by sampling the tile map of the game world. For the purposes of this demo, I’ll draw up a sample map in Photoshop instead.</p>

<p><img src="/assets/images/posts/04_testing-maze.png" alt="" class="align-center" /></p>

<p>Here is the test map I drew, stored in the Red channel but displayed in greyscale for clarity. It’ll work well for testing purposes, although I can’t say Shouzou Kaga would be proud of the design. As you can see, the absolute black and shades of grey define grid cells that may be travelled to and their Movement Cost, whereas the absolute white defines impassable walls.</p>

<p>With the Movement Cost stored in the Red Channel, that leaves the other three channels (GBA) to hold state.</p>

<p>G: During algorithm, will be used to mark open/closed cells. After algorithm completion, acts as a mask for entire travelable area.</p>

\[Mask=\begin{cases} 
  Open / Untravelable &amp; G = 0.0 \\
  Closed / Travelable &amp; G = 1.0 \\
\end{cases}\]

<p>B: Travel Cost.</p>

\[TC=B*255\]

<p>A: Points to nearest neighbor (lowest travel cost). When the player picks a point, this will be traced to move the Unit to that location.</p>

\[NN=\begin{cases} 
  Up &amp; 0.0 \leq A &lt; 0.2 \\
  Down &amp; 0.2 \leq A &lt; 0.4 \\
  Left &amp; 0.4 \leq A &lt; 0.6 \\
  Right &amp; 0.6 \leq A &lt; 0.8 \\
  N/A &amp; 0.8 \leq A &lt; 1.0 \\
\end{cases}\]

<p>Now that we know how to use the texture, we can define our pixel shader’s behavior. Instead of travelling top-down from the starting cell, the pixel shader will apply an iterative process to the entire image. This single iteration will use a plus-shaped kernel to convolve the image.</p>

<blockquote>
  <p><strong>What is a kernel?</strong></p>

  <p>A kernel describes a certain shape for sampling around the current pixel when running a pixel shader. Usually, this is a square with specified dimensions. For example, a simple box blur uses a 3x3 kernel to sample the 9 pixels surrounding a pixel and average them to achieve a blurring effect. In our case, we use a 3x3 plus-shaped kernel because Units can only move up, down, left and right, not diagonally.</p>
</blockquote>

<p><img src="/assets/images/posts/04_plus-kernel.png" alt="" class="align-center" /></p>

<p>Now that we know our kernel, lets write the pass.</p>

<details open="">
  <summary> Helper Functions </summary>

  <p>I started by implementing some simple helper functions that keep the code demystified.</p>

  <div class="language-hlsl highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">float</span> <span class="nf">pack255</span><span class="p">(</span><span class="n">float</span> <span class="n">val</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span> <span class="n">val</span> <span class="o">/</span> <span class="mi">255</span><span class="p">.</span><span class="mi">0</span><span class="p">;</span> <span class="p">}</span>
<span class="n">float</span> <span class="nf">unpack255</span><span class="p">(</span><span class="n">float</span> <span class="n">val</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span> <span class="n">val</span> <span class="o">*</span> <span class="mi">255</span><span class="p">.</span><span class="mi">0</span><span class="p">;</span> <span class="p">}</span>
<span class="n">float</span> <span class="nf">getMoveCost</span><span class="p">(</span><span class="n">fixed4</span> <span class="n">col</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span> <span class="nb">max</span><span class="p">(</span><span class="mi">1</span><span class="p">.</span><span class="mi">0</span><span class="p">,</span> <span class="nb">pow</span><span class="p">(</span><span class="mi">2</span><span class="p">,</span><span class="nb">ceil</span><span class="p">(</span><span class="n">col</span><span class="p">.</span><span class="n">r</span> <span class="o">*</span> <span class="mi">4</span><span class="p">.</span><span class="mi">99</span><span class="p">)</span><span class="o">-</span><span class="mi">1</span><span class="p">));</span> <span class="p">}</span>
<span class="n">bool</span> <span class="nf">isWall</span><span class="p">(</span><span class="n">fixed4</span> <span class="n">col</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span> <span class="n">unpack255</span><span class="p">(</span><span class="n">col</span><span class="p">.</span><span class="n">r</span><span class="p">)</span> <span class="o">&gt;=</span> <span class="mi">200</span><span class="p">;</span> <span class="p">}</span>
<span class="n">bool</span> <span class="nf">isOpen</span><span class="p">(</span><span class="n">fixed4</span> <span class="n">col</span><span class="p">)</span> <span class="p">{</span> <span class="k">return</span> <span class="n">col</span><span class="p">.</span><span class="n">g</span> <span class="o">&lt;=</span> <span class="mi">0</span><span class="p">.</span><span class="mo">01</span><span class="p">;</span> <span class="p">}</span>
<span class="kt">void</span> <span class="nf">close</span><span class="p">(</span><span class="k">inout</span> <span class="n">fixed4</span> <span class="n">col</span><span class="p">)</span> <span class="p">{</span> <span class="n">col</span><span class="p">.</span><span class="n">g</span> <span class="o">=</span> <span class="mi">1</span><span class="p">.</span><span class="mi">0</span><span class="p">;</span> <span class="p">}</span>
</code></pre></div>  </div>

</details>

<details open="">
  <summary> Defining the Kernel </summary>

  <p>Then, in the fragment shader, I define the kernel by sampling the four points necessary: up, down, left and right.</p>

  <div class="language-hlsl highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">const</span> <span class="kt">float2</span> <span class="n">cell_size</span> <span class="o">=</span> <span class="n">_MainTex_TexelSize</span><span class="p">.</span><span class="n">xy</span><span class="p">;</span>  
<span class="n">fixed4</span> <span class="n">col</span> <span class="o">=</span> <span class="nb">tex2D</span><span class="p">(</span><span class="n">_MainTex</span><span class="p">,</span> <span class="n">i</span><span class="p">.</span><span class="n">uv</span><span class="p">);</span>  
<span class="k">const</span> <span class="n">fixed4</span> <span class="n">col_u</span> <span class="o">=</span> <span class="nb">tex2D</span><span class="p">(</span><span class="n">_MainTex</span><span class="p">,</span> <span class="n">i</span><span class="p">.</span><span class="n">uv</span> <span class="o">+</span> <span class="n">cell_size</span> <span class="o">*</span> <span class="nf">float2</span><span class="p">(</span><span class="mi">0</span><span class="p">.</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">.</span><span class="mi">0</span><span class="p">));</span>  
<span class="k">const</span> <span class="n">fixed4</span> <span class="n">col_d</span> <span class="o">=</span> <span class="nb">tex2D</span><span class="p">(</span><span class="n">_MainTex</span><span class="p">,</span> <span class="n">i</span><span class="p">.</span><span class="n">uv</span> <span class="o">+</span> <span class="n">cell_size</span> <span class="o">*</span> <span class="nf">float2</span><span class="p">(</span><span class="mi">0</span><span class="p">.</span><span class="mi">0</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">.</span><span class="mi">0</span><span class="p">));</span>  
<span class="k">const</span> <span class="n">fixed4</span> <span class="n">col_l</span> <span class="o">=</span> <span class="nb">tex2D</span><span class="p">(</span><span class="n">_MainTex</span><span class="p">,</span> <span class="n">i</span><span class="p">.</span><span class="n">uv</span> <span class="o">+</span> <span class="n">cell_size</span> <span class="o">*</span> <span class="nf">float2</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">.</span><span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">.</span><span class="mi">0</span><span class="p">));</span>  
<span class="k">const</span> <span class="n">fixed4</span> <span class="n">col_r</span> <span class="o">=</span> <span class="nb">tex2D</span><span class="p">(</span><span class="n">_MainTex</span><span class="p">,</span> <span class="n">i</span><span class="p">.</span><span class="n">uv</span> <span class="o">+</span> <span class="n">cell_size</span> <span class="o">*</span> <span class="nf">float2</span><span class="p">(</span><span class="mi">1</span><span class="p">.</span><span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">.</span><span class="mi">0</span><span class="p">));</span> 
</code></pre></div>  </div>

</details>

<details open="">
  <summary> Guard Clause </summary>

  <p>We check for if the cell is closed, a wall, or if all neighbors are open.</p>

  <div class="language-hlsl highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">if</span><span class="p">(</span><span class="o">!</span><span class="n">isOpen</span><span class="p">(</span><span class="n">col</span><span class="p">)</span> <span class="o">||</span> <span class="n">isWall</span><span class="p">(</span><span class="n">col</span><span class="p">)</span> <span class="o">||</span> <span class="nb">max</span><span class="p">(</span><span class="nb">max</span><span class="p">(</span><span class="n">col_u</span><span class="p">.</span><span class="n">g</span><span class="p">,</span> <span class="n">col_d</span><span class="p">.</span><span class="n">g</span><span class="p">),</span> <span class="nb">max</span><span class="p">(</span><span class="n">col_l</span><span class="p">.</span><span class="n">g</span><span class="p">,</span> <span class="n">col_r</span><span class="p">.</span><span class="n">g</span><span class="p">))</span> <span class="o">&lt;=</span> <span class="mi">0</span><span class="p">.</span><span class="mo">01</span><span class="p">)</span>  
<span class="k">return</span> <span class="n">col</span><span class="p">;</span>
</code></pre></div>  </div>

</details>

<details open="">
  <summary> Reverse Dijkstra </summary>

  <p>Now, for the main operation: find the neighbor with the least Travel Cost, and update our own Travel Cost by adding the Movement Cost to it. Keep in mind that the B channel stores Travel Cost and the A channel stores Nearest Neighbor.</p>

  <div class="language-hlsl highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">const</span> <span class="n">float</span> <span class="n">tc_u</span> <span class="o">=</span> <span class="n">unpack255</span><span class="p">(</span><span class="n">col_u</span><span class="p">.</span><span class="n">b</span><span class="p">);</span>  
<span class="k">const</span> <span class="n">float</span> <span class="n">tc_d</span> <span class="o">=</span> <span class="n">unpack255</span><span class="p">(</span><span class="n">col_d</span><span class="p">.</span><span class="n">b</span><span class="p">);</span>  
<span class="k">const</span> <span class="n">float</span> <span class="n">tc_l</span> <span class="o">=</span> <span class="n">unpack255</span><span class="p">(</span><span class="n">col_l</span><span class="p">.</span><span class="n">b</span><span class="p">);</span>  
<span class="k">const</span> <span class="n">float</span> <span class="n">tc_r</span> <span class="o">=</span> <span class="n">unpack255</span><span class="p">(</span><span class="n">col_r</span><span class="p">.</span><span class="n">b</span><span class="p">);</span>  

<span class="n">float</span> <span class="n">min_tc</span> <span class="o">=</span> <span class="mi">9999</span><span class="p">;</span> <span class="c1">// minimum travel cost  </span>
<span class="n">float</span> <span class="n">mc</span> <span class="o">=</span> <span class="mi">0</span><span class="p">.</span><span class="mi">0</span><span class="p">;</span> <span class="c1">// movement cost</span>

<span class="c1">// If closed and travel value &lt; minValue  </span>
<span class="k">if</span><span class="p">(</span><span class="o">!</span><span class="n">isOpen</span><span class="p">(</span><span class="n">col_u</span><span class="p">)</span> <span class="o">&amp;&amp;</span> <span class="n">tc_u</span> <span class="o">&lt;</span> <span class="n">min_tc</span><span class="p">)</span>  
<span class="p">{</span>  
	<span class="n">min_tc</span> <span class="o">=</span> <span class="n">tc_u</span><span class="p">;</span>  
	<span class="n">mc</span> <span class="o">=</span> <span class="n">getMoveCost</span><span class="p">(</span><span class="n">col_u</span><span class="p">);</span>  
	<span class="n">col</span><span class="p">.</span><span class="n">a</span> <span class="o">=</span> <span class="mi">0</span><span class="p">.</span><span class="mi">1</span><span class="p">;</span>  
<span class="p">}</span>  
<span class="k">if</span><span class="p">(</span><span class="o">!</span><span class="n">isOpen</span><span class="p">(</span><span class="n">col_d</span><span class="p">)</span> <span class="o">&amp;&amp;</span> <span class="n">tc_d</span> <span class="o">&lt;</span> <span class="n">min_tc</span><span class="p">)</span>  
<span class="p">{</span>  
	<span class="n">min_tc</span> <span class="o">=</span> <span class="n">tc_d</span><span class="p">;</span>  
	<span class="n">mc</span> <span class="o">=</span> <span class="n">getMoveCost</span><span class="p">(</span><span class="n">col_d</span><span class="p">);</span>  
	<span class="n">col</span><span class="p">.</span><span class="n">a</span> <span class="o">=</span> <span class="mi">0</span><span class="p">.</span><span class="mi">3</span><span class="p">;</span>  
<span class="p">}</span>  
<span class="k">if</span><span class="p">(</span><span class="o">!</span><span class="n">isOpen</span><span class="p">(</span><span class="n">col_l</span><span class="p">)</span> <span class="o">&amp;&amp;</span> <span class="n">tc_l</span> <span class="o">&lt;</span> <span class="n">min_tc</span><span class="p">)</span>  
<span class="p">{</span>  
	<span class="n">min_tc</span> <span class="o">=</span> <span class="n">tc_l</span><span class="p">;</span>  
	<span class="n">mc</span> <span class="o">=</span> <span class="n">getMoveCost</span><span class="p">(</span><span class="n">col_l</span><span class="p">);</span>  
	<span class="n">col</span><span class="p">.</span><span class="n">a</span> <span class="o">=</span> <span class="mi">0</span><span class="p">.</span><span class="mi">5</span><span class="p">;</span>  
<span class="p">}</span>  
<span class="k">if</span><span class="p">(</span><span class="o">!</span><span class="n">isOpen</span><span class="p">(</span><span class="n">col_r</span><span class="p">)</span> <span class="o">&amp;&amp;</span> <span class="n">tc_r</span> <span class="o">&lt;</span> <span class="n">min_tc</span><span class="p">)</span>  
<span class="p">{</span>  
	<span class="n">min_tc</span> <span class="o">=</span> <span class="n">tc_r</span><span class="p">;</span>  
	<span class="n">mc</span> <span class="o">=</span> <span class="n">getMoveCost</span><span class="p">(</span><span class="n">col_r</span><span class="p">);</span>  
	<span class="n">col</span><span class="p">.</span><span class="n">a</span> <span class="o">=</span> <span class="mi">0</span><span class="p">.</span><span class="mi">7</span><span class="p">;</span>  
<span class="p">}</span>

</code></pre></div>  </div>

</details>

<details open="">
  <summary> Finalize Pass </summary>

  <p>Finalize setting our own Travel Cost. Importantly, only close the cell if the Travel Cost is less than the Movement Range; this ensures that we can’t travel beyond the Movement Range’s scope.</p>

  <div class="language-hlsl highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">const</span> <span class="n">float</span> <span class="n">tc</span> <span class="o">=</span> <span class="n">min_tc</span> <span class="o">+</span> <span class="n">mc</span><span class="p">;</span>  
<span class="n">col</span><span class="p">.</span><span class="n">b</span> <span class="o">=</span> <span class="n">pack255</span><span class="p">(</span><span class="n">tc</span><span class="p">);</span>  
<span class="k">if</span><span class="p">(</span><span class="n">tc</span> <span class="o">&lt;=</span> <span class="n">_MoveRange</span><span class="p">)</span>  
	<span class="n">close</span><span class="p">(</span><span class="n">col</span><span class="p">);</span>  
<span class="k">return</span> <span class="n">col</span><span class="p">;</span>
</code></pre></div>  </div>

</details>

<details open="">
  <summary> Iterations </summary>

  <p>This shader pass only counts for a single iteration, though. For the algorithm to work, we have to run the texture through this pass for a movement range number of iterations.</p>

  <div class="language-c# highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">for</span><span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="p">=</span> <span class="m">0</span><span class="p">;</span> <span class="n">i</span> <span class="p">&lt;</span> <span class="n">movementRange</span><span class="p">;</span> <span class="n">i</span><span class="p">++)</span>  
<span class="p">{</span>  
	<span class="n">Graphics</span><span class="p">.</span><span class="nf">Blit</span><span class="p">(</span><span class="n">mRenderTexture</span><span class="p">,</span> <span class="n">tempRT</span><span class="p">,</span> <span class="n">mAlgorithmMaterial</span><span class="p">);</span>  
	<span class="n">Graphics</span><span class="p">.</span><span class="nf">Blit</span><span class="p">(</span><span class="n">tempRT</span><span class="p">,</span> <span class="n">mRenderTexture</span><span class="p">);</span>  
<span class="p">}</span>
</code></pre></div>  </div>

</details>

<hr />

<p>And… the result:</p>

<video class="gif align-center" width="600" height="464" muted="" loop="" playsinline="" preload="none" data-autoplay="" poster="/assets/video/04_movement-vis.jpg"><source src="/assets/video/04_movement-vis.mp4" type="video/mp4" /></video>

<p>Although the above gif is slowed down for clarity, the actual algorithm runs lightning fast. For expected use-cases of Movement Ranges under 32, I consistently get &lt;0.2ms of total runtime.</p>

<h3 id="attack-ranges">Attack Ranges</h3>

<p>We’re over the hard part, but still need the attack ranges. These are the little red squares that show how far a Unit can attack if they move to the very edge of their Movement Range.</p>

<video class="gif align-center" width="440" height="286" muted="" loop="" playsinline="" preload="none" data-autoplay="" poster="/assets/video/04_blazing-blade.jpg" aria-label="Fire Emblem Gameplay"><source src="/assets/video/04_blazing-blade.mp4" type="video/mp4" /></video>

<p>Luckily, this is quite simple. Since the Attack Range ignores Movement Cost and walls, we don’t need to do any pathfinding of any sort. Instead, we will convolve the G channel of the Reverse Dijkstra result with an expansion formula, using the same plus-shaped kernel.</p>

<details open="">
  <summary> Expansion </summary>

  <div class="language-hlsl highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">fixed4</span> <span class="n">col</span> <span class="o">=</span> <span class="nb">tex2D</span><span class="p">(</span><span class="n">_MainTex</span><span class="p">,</span> <span class="n">i</span><span class="p">.</span><span class="n">uv</span><span class="p">);</span>  
<span class="k">const</span> <span class="kt">float2</span> <span class="n">cell_size</span> <span class="o">=</span> <span class="n">_MainTex_TexelSize</span><span class="p">.</span><span class="n">xy</span><span class="p">;</span>  
<span class="k">const</span> <span class="n">float</span> <span class="n">down</span> <span class="o">=</span> <span class="nb">tex2D</span><span class="p">(</span><span class="n">_MainTex</span><span class="p">,</span> <span class="n">i</span><span class="p">.</span><span class="n">uv</span> <span class="o">+</span> <span class="n">cell_size</span> <span class="o">*</span> <span class="kt">float2</span><span class="p">(</span><span class="mi">0</span><span class="p">.</span><span class="mi">0</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">.</span><span class="mi">0</span><span class="p">)).</span><span class="n">g</span><span class="p">;</span>  
<span class="k">const</span> <span class="n">float</span> <span class="n">left</span> <span class="o">=</span> <span class="nb">tex2D</span><span class="p">(</span><span class="n">_MainTex</span><span class="p">,</span> <span class="n">i</span><span class="p">.</span><span class="n">uv</span> <span class="o">+</span> <span class="n">cell_size</span> <span class="o">*</span> <span class="kt">float2</span><span class="p">(</span><span class="o">-</span><span class="mi">1</span><span class="p">.</span><span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">.</span><span class="mi">0</span><span class="p">)).</span><span class="n">g</span><span class="p">;</span>  
<span class="k">const</span> <span class="n">float</span> <span class="n">right</span> <span class="o">=</span> <span class="nb">tex2D</span><span class="p">(</span><span class="n">_MainTex</span><span class="p">,</span> <span class="n">i</span><span class="p">.</span><span class="n">uv</span> <span class="o">+</span> <span class="n">cell_size</span> <span class="o">*</span> <span class="kt">float2</span><span class="p">(</span><span class="mi">1</span><span class="p">.</span><span class="mi">0</span><span class="p">,</span> <span class="mi">0</span><span class="p">.</span><span class="mi">0</span><span class="p">)).</span><span class="n">g</span><span class="p">;</span>  
<span class="k">const</span> <span class="n">float</span> <span class="n">up</span> <span class="o">=</span> <span class="nb">tex2D</span><span class="p">(</span><span class="n">_MainTex</span><span class="p">,</span> <span class="n">i</span><span class="p">.</span><span class="n">uv</span> <span class="o">+</span> <span class="n">cell_size</span> <span class="o">*</span> <span class="kt">float2</span><span class="p">(</span><span class="mi">0</span><span class="p">.</span><span class="mi">0</span><span class="p">,</span> <span class="mi">1</span><span class="p">.</span><span class="mi">0</span><span class="p">)).</span><span class="n">g</span><span class="p">;</span>  
<span class="k">const</span> <span class="n">float</span> <span class="n">maximum</span> <span class="o">=</span> <span class="nb">max</span><span class="p">(</span><span class="nb">max</span><span class="p">(</span><span class="n">down</span><span class="p">,</span> <span class="n">left</span><span class="p">),</span> <span class="nb">max</span><span class="p">(</span><span class="n">up</span><span class="p">,</span> <span class="n">right</span><span class="p">));</span>  
<span class="n">col</span><span class="p">.</span><span class="n">g</span> <span class="o">=</span> <span class="nb">max</span><span class="p">(</span><span class="n">col</span><span class="p">.</span><span class="n">g</span><span class="p">,</span> <span class="nb">min</span><span class="p">(</span><span class="mi">0</span><span class="p">.</span><span class="mi">5</span><span class="p">,</span> <span class="n">maximum</span><span class="p">));</span>  
<span class="k">return</span> <span class="n">col</span><span class="p">;</span>
</code></pre></div>  </div>

  <p>This will simply take any pixel with a value greater than 0.5 and set the neighboring pixels to 0.5. The effect will look like an expansion.</p>

</details>

<video class="gif align-center" width="600" height="382" muted="" loop="" playsinline="" preload="none" data-autoplay="" poster="/assets/video/04_expansion.jpg" aria-label="Expansion"><source src="/assets/video/04_expansion.mp4" type="video/mp4" /></video>

<p>Perfect! Now the effect is complete.</p>

<h3 id="conclusion">Conclusion</h3>

<video class="gif align-center" width="800" height="418" muted="" loop="" playsinline="" preload="none" data-autoplay="" poster="/assets/video/04_final.jpg" aria-label="Expansion"><source src="/assets/video/04_final.mp4" type="video/mp4" /></video>

<p>Here is the demonstration of the final effect.</p>

<p>In the future for my tactics side-project, I’ll add:</p>
<ul>
  <li>Red Channel auto-generation from world map contents</li>
  <li>Pretty in-game shader to display this grid to the player</li>
  <li>Arrow tracing player start to destination</li>
</ul>

<p>Thank you for reading my blog. If you were impressed and are an employer, consider hiring me as a Technical Artist (<a href="https://www.linkedin.com/in/sheehan-ahmed-94136b192/">My LinkedIn</a>).</p>

<hr />]]></content><author><name>Sheehan Ahmed</name></author><category term="HLSL" /><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://www.sheehanahmed.com/assets/images/og-default.jpg" /><media:content medium="image" url="https://www.sheehanahmed.com/assets/images/og-default.jpg" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Realtime Rain VFX Breakdown</title><link href="https://www.sheehanahmed.com/realtime-rain-vfx-breakdown/" rel="alternate" type="text/html" title="Realtime Rain VFX Breakdown" /><published>2023-07-09T19:35:00-07:00</published><updated>2023-07-09T19:35:00-07:00</updated><id>https://www.sheehanahmed.com/realtime-rain-vfx-breakdown</id><content type="html" xml:base="https://www.sheehanahmed.com/realtime-rain-vfx-breakdown/"><![CDATA[<div class="embed"><iframe src="https://www.youtube-nocookie.com/embed/S7RwDOuJ_ds" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" loading="lazy" title="YouTube video"></iframe></div>

<hr />

<p><em>Made with Unity, Blender, HLSL, ShaderGraph, VFX Graph</em></p>

<p>My friends in LA look at me like I’m crazy when I mention how much I love rainy overcast days. I can’t help it! I’m from the best place on Earth: the Pacific Northwest.</p>

<h3 id="gathering-reference">Gathering Reference</h3>

<p>Now usually if I wanted to take a close look at rain, I would just take a stroll outside, but Portland is having an unfortunately dry summer. I checked out some YouTube videos instead, like this one:</p>

<div class="embed"><iframe src="https://www.youtube-nocookie.com/embed/0en2q82Zaok" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" loading="lazy" title="YouTube video"></iframe></div>

<hr />

<p>There were some phenomena in the reference video that I chose to leave out, namely the bubbles and the base waves on the surface of the water. I wanted to shoot for a shallower puddle that still had the vibrancy of rain hitting a deep body of water. It’s not completely realistic, but then again, no great visual effect ever is!</p>

<p>My effect was made in Unity by layering several steps/passes:</p>

<ul>
  <li>Droplets (ortho camera depth pass -&gt; VFX graph spawn)</li>
  <li>Splashes (ortho camera depth pass -&gt; VFX graph spawn)</li>
  <li>Puddles (vertex color + height blend)</li>
  <li>Ripples (UV manipulation shader)</li>
  <li>Wash cascades (transparent mesh with scrolling shader)</li>
  <li>Mist (depth effect)</li>
</ul>

<h3 id="the-base-environment">The Base Environment</h3>

<p>The base environment is a simple blocky mesh that has areas of cover, elevated ground, and varied shapes (sphere and angled block). These represent the main environment problems I expected my rain to solve for. I wanted the splashes to follow the form of the environment and rain to ignore areas that should be covered and safe from rainfall.</p>

<p><img src="/assets/images/posts/02_base-environment.png" alt="BaseEnvironment" width="100%" /></p>

<h3 id="the-ortho-camera">The Ortho Camera</h3>

<p>Inspired by my friend Sichen Liu’s <a href="https://80.lv/articles/recreating-death-stranding-odradek-terrain-scanner-in-unity/">Odradek Scanner effect</a>, I created an orthographic camera facing down on the scene. I render out this camera’s depth and normals to a RenderTexture. These will come in handy later.</p>

<p><img src="/assets/images/posts/02_normal-depth.png" alt="NormalDepth" width="100%" /></p>

<h3 id="droplets">Droplets</h3>

<p>The droplets are as simple as can be: a LineRenderer in the VFX Graph that scales the lifetime of each line according to the depth of the ortho camera. This ensures that rain droplets don’t intersect the level and appear underneath cover.</p>

<p><img src="/assets/images/posts/02_raindrop-depth-sample-node.png" alt="Nodes" width="50%" /></p>

<video class="gif" width="1080" height="608" muted="" loop="" playsinline="" preload="none" data-autoplay="" poster="/assets/video/02_raindrop-depth-sample-result.jpg" style="width:50%" aria-label="NormalDepth"><source src="/assets/video/02_raindrop-depth-sample-result.mp4" type="video/mp4" /></video>

<h3 id="splashes">Splashes</h3>

<p>Splashes are a spritesheet particle spawned along the ground with the particle-up facing the normal and the particle-forward facing the camera plane. During my process, I ran into issues with ledges. Splashes were spawning half-on a ledge and along the wall, which were immersion-breaking and ugly. To solve this, I run the orthographic camera’s depth through a Sobel filter, which essentially creates outlines around areas of depth contrast. Because the camera is facing downward, these areas of high contrast are my walls and ledges.</p>

<p><img src="/assets/images/posts/02_sobel.png" alt="Sobel" width="50%" /></p>

<p>By passing this mask into my VFX graph, I can make my splashes ignore walls. The outline has the added benefit of culling away a bit from the ledges, which solves the half-on-ledge problem as well.</p>

<video class="gif" width="1004" height="830" muted="" loop="" playsinline="" preload="none" data-autoplay="" poster="/assets/video/02_splashes.jpg" aria-label="Splashes"><source src="/assets/video/02_splashes.mp4" type="video/mp4" /></video>

<h3 id="puddles">Puddles</h3>

<p>The puddles and general wetness in the scene was painted on through vertex color and adjusted by sharpness and fill. This is also influenced by the heightmap of the underlying texture.</p>

<video class="gif" width="972" height="706" muted="" loop="" playsinline="" preload="none" data-autoplay="" poster="/assets/video/02_wetness.jpg" aria-label="Wetness"><source src="/assets/video/02_wetness.mp4" type="video/mp4" /></video>

<h3 id="ripples">Ripples</h3>

<p>The typical approach for ripples on deep water is a voronoi-style pattern that creates overlapping circles. I wanted to make the ripples feel like they had more local impact, so I instead used a normal texture for the ripple.</p>

<p><img src="/assets/images/posts/02_ripple-texture.png" alt="Wetness" width="50%" /></p>

<p>In my shader, I sampled this texture with two layers of ripples. Having two layers on separate start times helps kill the grid-like look. I then simulate a ripple animation by scaling the UV of the ripples and fading the normal strength in and out with an ease curve based on the following function:</p>

<p><code class="language-plaintext highlighter-rouge">1.0 - pow(2.0 * input - 1.0, 2)</code></p>

<p>This function gives a nice ease to the ripple transparency that looks natural.</p>

<p><img src="/assets/images/posts/02_ripples-shader.png" alt="Ripple" /></p>

<p>I also use a population slider that basically compares a <code class="language-plaintext highlighter-rouge">floor(rand(uv))</code> sample against a threshold value to kill a certain percentage of ripples. A full set of ripples looks strangely uniform anyway, and this gives me control over how torrential I want the rainfall to look.</p>

<video class="gif" width="1080" height="432" muted="" loop="" playsinline="" preload="none" data-autoplay="" poster="/assets/video/02_ripple-population.jpg" aria-label="RipplePopulation"><source src="/assets/video/02_ripple-population.mp4" type="video/mp4" /></video>

<h3 id="wash-cascades">Wash Cascades</h3>

<p>I saw this effect on a pillar in Overwatch 2, and it felt like a nice, slightly stylized way to evoke water travelling down a lateral surface.</p>

<video class="gif" width="1080" height="672" muted="" loop="" playsinline="" preload="none" data-autoplay="" poster="/assets/video/02_water-cascades-overwatch.jpg" aria-label="OW2Cascades"><source src="/assets/video/02_water-cascades-overwatch.mp4" type="video/mp4" /></video>

<p>I recreated it in a relatively simple way: generating a mesh at the side of every ledge that water would be washing down on and scrolling a voronoi + clouds texture along the Y of the UV.
Here is the effect with exaggurated visibility.</p>

<video class="gif" width="1080" height="752" muted="" loop="" playsinline="" preload="none" data-autoplay="" poster="/assets/video/02_water-cascades.jpg" aria-label="OW2Cascades"><source src="/assets/video/02_water-cascades.mp4" type="video/mp4" /></video>

<h3 id="mist">Mist</h3>

<p>Finally, the mist is scrolling noise with a depth mask in order to keep it closely hugging the ground.
Here is the effect with exaggurated visibility.</p>

<video class="gif" width="1080" height="714" muted="" loop="" playsinline="" preload="none" data-autoplay="" poster="/assets/video/02_mist.jpg" aria-label="Mist"><source src="/assets/video/02_mist.mp4" type="video/mp4" /></video>

<h3 id="conclusion">Conclusion</h3>

<p>Thank you for reading my breakdown! This was a fun project that challenged me to use the information I had at hand in interesting ways. Making a tribute to my home state felt satisfying, and I feel well-equipped to use ortho-camera depth sampling techniques for various other effects.</p>

<video class="gif" width="800" height="450" muted="" loop="" playsinline="" preload="none" data-autoplay="" poster="/assets/video/swallow-falls-rain.jpg" aria-label="FinalGif"><source src="/assets/video/swallow-falls-rain.mp4" type="video/mp4" /></video>]]></content><author><name>Sheehan Ahmed</name></author><category term="C#" /><category term="HLSL" /><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://www.sheehanahmed.com/assets/images/og-default.jpg" /><media:content medium="image" url="https://www.sheehanahmed.com/assets/images/og-default.jpg" xmlns:media="http://search.yahoo.com/mrss/" /></entry><entry><title type="html">Starting out with Flecs ECS in Monogame</title><link href="https://www.sheehanahmed.com/starting-out-flecs-monogame/" rel="alternate" type="text/html" title="Starting out with Flecs ECS in Monogame" /><published>2022-08-16T19:35:00-07:00</published><updated>2022-08-16T19:35:00-07:00</updated><id>https://www.sheehanahmed.com/starting-out-flecs-monogame</id><content type="html" xml:base="https://www.sheehanahmed.com/starting-out-flecs-monogame/"><![CDATA[<h2 id="leaving-the-unity-birdnest">Leaving the Unity birdnest</h2>
<p>I started game development when I was around ten using Clickteam Fusion to make simple platformers. After learning to code, I started using Unity, and have been a pretty loyal Unity dev ever since. All I’ve ever really known is coding within Unity’s paradigm of GameObjects and C# and whatnot. I figured it was time to try something new.</p>

<h3 id="what-to-pick">What to pick?</h3>
<p>To maximize the learning opportunity I wanted to use a lower-key framework, something that leaves most of the game loop to me.</p>

<p>I ended up settling with Monogame, as coming from Unity I’m most used to C# anyway. Monogame (prev. XNA) is very battle-tested: several high-profile indie games use it, like <a href="http://www.celestegame.com/"><em>Celeste</em></a> by <a href="https://exok.com/games.html">Extremely Ok Games</a>, <a href="https://terraria.org/"><em>Terraria</em></a> by <a href="https://re-logic.com/">Re-Logic</a> and <a href="https://www.stardewvalley.net/"><em>Stardew Valley</em></a> by <a href="https://twitter.com/ConcernedApe">Eric Barone</a>.</p>

<p><em>Other choices I researched and did not go with, but you might!</em></p>
<ul>
  <li><strong>Godot</strong>: Although I appreciate how much more it stays “out of your way” than other engines, it still feels too much for my current wants.</li>
  <li><strong>Bevy</strong>: Young but I am keeping an eye on this one!</li>
  <li><strong>SDL2/C++</strong>: I use C++ all the time at school anyway so wanted to do something else when I’m coding for fun.</li>
</ul>

<h3 id="first-date-with-monogame-a-little-nervous">First date with Monogame, a little nervous</h3>
<p>It seems like a pattern I have for any new engine/framework is… <strong>try to make Cave Story with it</strong>. It was the first thing I tried to do with Clickteam Fusion, Unity, and now Monogame.</p>

<p><img src="/assets/images/posts/01_my-first-mono-screenshot.png" alt="MyFirstMonoScreenshot" width="100%" /></p>

<p>Getting Quote on the screen with relatively basic platformer controls is at this point my personal <em>Hello World</em>. I have to admit, I was intimidated at first by having no software to go off other than good old VSCode, but after this point most of my anxieties disappeared. I love the freedom of having the framework give me just the bare essentials: an entry point, a <code class="language-plaintext highlighter-rouge">Tick()</code>, and a <code class="language-plaintext highlighter-rouge">Draw()</code>.</p>

<p>I was about to type out a familiar Actor.cs class… when the freedom really went to my head. After all, I’ve been doing the traditional pattern my whole life. While everyone else was going out and partying and hating OOP last year, I had to stay inside with my GameObjects and MonoBehaviours. It’s not a phase, Mom!</p>

<p><img src="/assets/images/posts/01_friendship-ended-with-actor.png" alt="FriendshipEnded" width="100%" /></p>

<p>Which brings us to…</p>

<h2 id="in-my-ecs-era">In my ECS Era</h2>

<p>I watched <a href="https://youtu.be/zrIY0eIyqmI">that one Overwatch GDC Talk about ECS</a> and was immediately sold. One of my absolute favorite aspects of game design is <strong>consistent systems.</strong> I love when every actor in a game, from the player to enemies to even random little objects, have to obey the same rules of the universe.</p>

<p>These personal core values of game design is basically a match made in heaven with ECS, a programming paradigm based on “declarations (there shall be this)” instead of “imperative statements (do this)” (<a href="https://ajmmertens.medium.com/why-vanilla-ecs-is-not-enough-d7ed4e3bebe5">Martens</a>). To use an example from <em>Breath of the Wild</em>: I want to tell my game that fire catches on wood, <strong>no matter the circumstance of fire catching wood</strong>, whether I am lighting an arrowhead on a bonfire or hurling magic fireballs at an enemy Bokoblin’s wooden shield.</p>

<h3 id="what-is-ecs-anyway">What is ECS, anyway?</h3>

<p>There are a lot of in-depth explanations for ECS online – one of the best ones is an Overwatch GDC talk linked above – so I’ll try to distill the essence of it briefly in three main points.</p>

<ul>
  <li>1: Your game consists of a list of <strong>Entities</strong>. These have no individual data/functionality but contain a list of <strong>Components</strong>.</li>
  <li>2: These <strong>Components</strong> are SIMPLY data-objects with zero functionality. Nothing more.</li>
</ul>

<p>So far, this may sound familiar to Unity or Unreal users, but the <em>zero functionality</em> is a key difference. No mutations, no logic, nothing. Imagine if MonoBehaviours or ActorComponents were only allowed to have public variables. All of your functional code is instead delegated over to…</p>

<ul>
  <li>3: Sets of <strong>Systems</strong> iterate over components that they care about and read/write accordingly.</li>
</ul>

<p>This is the crux of ECS software design: complete separation between data and logic. Entities only care about what components they have and components only care about what data they hold. It’s all up to systems to determine the flow of change in your software, and an ordered set of systems is massively easier to keep in check when compared to the typical OOP slew of side-effects. The “I want to damage my enemy, but sometimes they can block it, but sometimes I have armor-piercing”-type situations we’ve all been in suddenly feel a lot more manageable.</p>

<p>For my project I decided to go with <a href="https://github.com/flecs-hub/flecs-cs">a C# wrapper for Flecs</a>.</p>

<blockquote>
  <p>NOTE: Original Flecs is written in C/C++. The wrapper adapts C source code to be usable by C# projects.</p>
</blockquote>

<h3 id="paradigm-shift">Paradigm shift</h3>

<p>ECS sounds very cool at first, but once you start trying to create components and systems it can be a bit daunting of how to proceed appropriately. Researching the Flecs user manual helped me understand a lot of the unique aspects and challenges of ECS. I decided on a new Hello World: Have at least 5 digits of entities carrying this image of Pochita from <em>CHAINSAW MAN</em> bounce around in an enclosed square.</p>

<p><img src="/assets/images/posts/01_pochita.png" alt="Pochita" width="50%" /></p>

<p>The best way to start planning an ECS project is to boil down entities to as granular components as possible. My first hunch was that I would need a Transform component, but this is actually incorrect as per a <a href="https://flecs.docsforge.com/master/designing-with-flecs/#component-size">direct example from the Flecs manual.</a> A Transform is already not granular enough, because it could be boiled down further into Position, Rotation, and Scale. This atomic way of thinking about data allows systems to <em>only</em> bother the data that they need to, instead of having to manage potential side effects of entire OOP classes. I’m excited by the possibilities but recognize that this will take a lot of getting used to.</p>

<p>For my Pochita game, I figured I would need the aforementioned Position, Rotation, and Scale components, as well as two more components: Velocity and Sprite. The components themselves are kind of self-explanatory, especially since they literally do not contain anything other than their named value. For example, Position is just:</p>
<div class="language-cs highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">struct</span> <span class="nc">C_Position</span> <span class="p">:</span> <span class="n">IComponent</span>
<span class="p">{</span>
    <span class="k">public</span> <span class="n">Vector2</span> <span class="n">Position</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div></div>
<p>That’s literally it. It’s very freeing that in terms of data, ECS is very WYSIWYG (What you see is what you get) about things. Data is granular and gives you exactly what you expect. Nothing less, nothing more.</p>

<p>My Sprite component ended up being more verbose, but mostly due to helper functions and some data I assume will never be used outside of the context of a sprite draw. If I need to refactor it into multiple components later, it should be easy enough to do so.</p>

<blockquote>
  <p>TIP: When using Flecs, REMEMBER that every component needs to be registered at the beginning of the program.</p>
</blockquote>

<p>Systems are defined as functions that can get subscribed into the Flecs ecosystem. They take an <code class="language-plaintext highlighter-rouge">Iterator</code> as a parameter and use their <code class="language-plaintext highlighter-rouge">Field&lt;T&gt;</code> function to generate several <code class="language-plaintext highlighter-rouge">Span&lt;T&gt;</code> that allow the developer to access specified components. Here is the system that applies velocity to position.</p>

<div class="language-cs highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">public</span> <span class="k">static</span> <span class="k">void</span> <span class="nf">ApplyVelocityToPosition</span><span class="p">(</span><span class="n">Iterator</span> <span class="n">it</span><span class="p">)</span>
<span class="p">{</span>
    <span class="kt">float</span> <span class="n">deltaTime</span> <span class="p">=</span> <span class="n">it</span><span class="p">.</span><span class="nf">DeltaSystemTime</span><span class="p">();</span>     <span class="c1">// Gather deltaTime. I contributed this method! :D</span>
    
    <span class="kt">var</span> <span class="n">posIter</span> <span class="p">=</span> <span class="n">it</span><span class="p">.</span><span class="n">Field</span><span class="p">&lt;</span><span class="n">C_Position</span><span class="p">&gt;(</span><span class="m">1</span><span class="p">);</span>      <span class="c1">// Initialize span for position</span>
    <span class="kt">var</span> <span class="n">velIter</span> <span class="p">=</span> <span class="n">it</span><span class="p">.</span><span class="n">Field</span><span class="p">&lt;</span><span class="n">C_Velocity</span><span class="p">&gt;(</span><span class="m">2</span><span class="p">);</span>      <span class="c1">// Initialize span for velocity</span>

    <span class="k">for</span><span class="p">(</span><span class="kt">int</span> <span class="n">i</span> <span class="p">=</span> <span class="m">0</span><span class="p">;</span> <span class="n">i</span> <span class="p">&lt;</span> <span class="n">it</span><span class="p">.</span><span class="n">Count</span><span class="p">;</span> <span class="n">i</span><span class="p">++)</span>           <span class="c1">// Loop thru every entity in the game</span>
    <span class="p">{</span>
        <span class="k">ref</span> <span class="kt">var</span> <span class="n">pos</span> <span class="p">=</span> <span class="k">ref</span> <span class="n">posIter</span><span class="p">[</span><span class="n">i</span><span class="p">];</span>           <span class="c1">// Position component MUST be mutated so use 'ref' keyword</span>
        <span class="kt">var</span> <span class="n">vel</span> <span class="p">=</span> <span class="n">velIter</span><span class="p">[</span><span class="n">i</span><span class="p">];</span>                   <span class="c1">// Velocity component is simply being read</span>

        <span class="n">pos</span><span class="p">.</span><span class="n">Position</span> <span class="p">+=</span> <span class="n">vel</span><span class="p">.</span><span class="n">Velocity</span> <span class="p">*</span> <span class="n">deltaTime</span><span class="p">;</span> <span class="c1">//Add velocity*dt to position</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>As you can see, this loops through every entity to handle a system all at once. It’s not difficult to imagine the possibilities for how this simplifies things. You have access to every other entity that a particular system concerns, right in the business-logic code for that system!</p>

<p>Subscribing the function as a system to ECS looks like this:</p>
<div class="language-cs highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">World</span><span class="p">.</span><span class="nf">RegisterSystem</span><span class="p">(</span><span class="n">S_Physics</span><span class="p">.</span><span class="n">ApplyVelocityToPosition</span><span class="p">,</span> <span class="n">EcsOnUpdate</span><span class="p">,</span> <span class="s">$"</span><span class="p">{</span><span class="k">typeof</span><span class="p">(</span><span class="n">C_Position</span><span class="p">)}</span><span class="s">, </span><span class="p">{</span><span class="k">typeof</span><span class="p">(</span><span class="n">C_Velocity</span><span class="p">)}</span><span class="s">"</span><span class="p">);</span>
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">EcsOnUpdate</code> describes the phase this will participate in. the <code class="language-plaintext highlighter-rouge">$"{typeof(C_Position)}, {typeof(C_Velocity)}"</code> describes the query that will occur to search through entities to update. It specifies to only bother Entities with <code class="language-plaintext highlighter-rouge">C_Position</code> and <code class="language-plaintext highlighter-rouge">C_Velocity</code> components with this system.</p>

<p>This is pretty beautiful because this system will apply to any entity that has both a position and velocity without asking any other questions about them. Also, the data being structs means I have to explicitly state when variables are to be mutated or not, using the ref keyword.</p>

<p>The 4 total systems are: ApplyVelocityToPosition, BounceOffWall, RotateTowardVelocityDirection, and PendSpritesForDraw. All of them were pretty straightforward to write and do <em>exactly</em> what their name implies with zero side-effects.</p>

<p><img src="/assets/images/posts/01_thousand-pochitas.png" alt="Thousand Pochitas" /></p>

<h3 id="visualizing-ecs-data-with-dear-imgui">Visualizing ECS data with Dear IMGUI</h3>

<p>With ECS as data-driven as it is, I would like to have a way to visualize all of my entities with their components. I decided to start with a simple approach that could grow to be more complex later. For my visualization I went with the <a href="https://github.com/mellinoe/ImGui.NET">.NET Wrapper</a> for Dear IMGUI. <a href="https://flatredball.com/news/dear-imgui-integration/">This tutorial from FlatRedBall</a> was really helpful to figure out how to do this.</p>

<p><img src="/assets/images/posts/01_dear-imgui.png" alt="Dear IMGUI Integration" /></p>

<p>So far it’s just a simple setup with an entity browser that allows the user to dynamically change values at runtime. It doesn’t have any features for adding/removing components or entities as of now.</p>

<h2 id="conclusion">Conclusion</h2>

<p>The final result (for now) is 10,000 Pochitas bouncing around a virtual box. I can move the camera around or change any of their positions/velocities as I wish.</p>

<div class="embed"><iframe src="https://www.youtube-nocookie.com/embed/Jxl7S-t2Azc" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen="" loading="lazy" title="YouTube video"></iframe></div>

<h3 id="next-steps">Next steps</h3>

<p>So far all I have used Flecs ECS for is a simple physics simulation. I’m sure trying to make a character-based platformer video game like <em>Cave Story</em> will have its own set of challenges, like handling different kinds of queries, using tags, and component relationships. I’ll see how it goes and continue to publish my progress here.</p>

<p>For the IMGUI visualizer, there are a couple next steps I have in mind.</p>
<ul>
  <li><strong>Entity focuser</strong>. A toggle that targets the camera at a specific entity’s position.</li>
  <li><strong>Entity browser filter by component.</strong></li>
  <li><strong>Hierarchy based on Flecs relationships.</strong></li>
</ul>

<p>Thanks for reading! School starts in a couple days but I’ll try to continue this side project as well as I can.</p>

<p>Check out <a href="https://github.com/sahmed19/ProjectMono">this project repo on Github.</a></p>]]></content><author><name>Sheehan Ahmed</name></author><category term="Monogame" /><category term="C#" /><category term="ECS" /><media:thumbnail xmlns:media="http://search.yahoo.com/mrss/" url="https://www.sheehanahmed.com/assets/images/og-default.jpg" /><media:content medium="image" url="https://www.sheehanahmed.com/assets/images/og-default.jpg" xmlns:media="http://search.yahoo.com/mrss/" /></entry></feed>