<?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 Porrith Suong on Medium]]></title>
        <description><![CDATA[Stories by Porrith Suong on Medium]]></description>
        <link>https://medium.com/@psuong95?source=rss-7434879a1a19------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*wEDz5JPkbtZNegWxB_qHeg.jpeg</url>
            <title>Stories by Porrith Suong on Medium</title>
            <link>https://medium.com/@psuong95?source=rss-7434879a1a19------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 19:41:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@psuong95/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[Physics Collision and Spatial Mapping]]></title>
            <link>https://medium.com/initialprefabs/physics-collision-and-spatial-mapping-5397610c9d63?source=rss-7434879a1a19------2</link>
            <guid isPermaLink="false">https://medium.com/p/5397610c9d63</guid>
            <category><![CDATA[physics-engine]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[unity]]></category>
            <dc:creator><![CDATA[Porrith Suong]]></dc:creator>
            <pubDate>Thu, 13 Aug 2020 18:45:31 GMT</pubDate>
            <atom:updated>2020-08-14T11:57:03.465Z</atom:updated>
            <content:encoded><![CDATA[<p>Physics engines are wildly known and solved spaces as there are plenty of tutorials and frameworks out there to help you write your own version too. To name a few tutorials:</p><ul><li><a href="https://www.sciencedirect.com/book/9780123694713/game-physics-engine-development">Game Engine Physics Development</a> by <a href="https://github.com/idmillington/cyclone-physics/">Ian Millington</a></li><li><a href="https://gamedevelopment.tutsplus.com/series/how-to-create-a-custom-physics-engine--gamedev-12715">How to Create a Custom Physics Engine</a> by Randy Gaul</li></ul><p>And some frameworks:</p><ul><li><a href="https://github.com/erincatto/box2d">Box2D</a></li><li><a href="https://github.com/projectchrono/chrono">Project Chrono</a></li></ul><p>But something that has typically interested me with physics engine is how to potentially detect collisions. Now this is primarily a data structure problem, as we would have to reason about how we would want to structure all of our physics bodies based on their positions. Ultimately, the end goal of this structure is to provide a fast way to check potential collisions without having to brute force and compare every single physics body with each other (this becomes an n² check!).</p><h3>Spatial Hashmaps</h3><p>One way to store physics bodies is to divide your play area into a group of cells as a grid. We can then store a bunch of physics bodies into a cell and determine which cells that each physics body is in. By design spatial hash maps are hash maps with chained linked lists as their values. Therefore, potential physics bodies in the same cell will be registered into the same hash.</p><pre>Key Values<br>---------<br>1 -&gt; [A] [B]<br>2 -&gt; [D]<br>3 -&gt; [E] [F] [Z]</pre><pre>An example with the left column being the key and the right column being multiple values with the same key.</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/277/1*BUBJsoQ3qHvwRpJUlyapSA.png" /><figcaption>By design we want our green dots to potentially be registered into the same red cell</figcaption></figure><h4>The Hash Function</h4><p>Each physics body is typically defined with a position represented as Cartesian coordinates (float3) . Ultimately, the hash function will take each axis value and combine the values into a key which we would use to register into the hash map.</p><p>A good hash function balances balances the number of potential collision we have per cell. If we have a very accurate hash function, then we may generate new hash map entries for physics bodies which are close together. If we have an inaccurate hash function, then we potentially may add in all physics body positions into a few cells, which may lead us closer to polynomial time to detect collisions.</p><p>By dividing the physics body position x and y values by the grid size and adding the components together, we get a decent hash that can contain multiple physics bodies. Here’s the pseudo code of the description above.</p><pre>int Key(int size, float3 v)<br>{<br>  return ((int)(floor(v.x / size) + floor(v.y / size)) * size);<br>}</pre><pre>Examples for: (1, 1, 0), (2, 1, 0), and (20, 11, 0) this hash function will produce:</pre><pre>Point: (1, 1, 0)<br>-------<br>(floor(1 / 10) + floor(1 / 10)) * 10 = hash_value<br>(0 + 0) * 10 = hash_value<br>0 = hash_value</pre><pre>Point: (2, 1, 0)<br>-------<br>(floor(2 / 10) + floor (1 / 10)) * 10 = hash_value<br>(0 + 0) * 10 = hash_value<br>0 = hash_value</pre><pre>Point: (20, 11, 0)<br>-------<br>(floor(20 / 10) + floor (11 / 10)) * 10 = hash_value<br>(2 + 1) * 10 = hash_value<br>30 = hash_value</pre><h3>Physics Shapes</h3><p>Physics bodies are typically defined with a physics shape. For my needs in Carté Diem, most physics bodies currently are defined as a box. Complex shapes will eventually be included later down the line. For example, our player Ellen can occupy multiple cells:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/209/1*MQtJwYrEckp9LTPSVdfLOw.png" /><figcaption>Ellen occupying multiple cells of size 10.</figcaption></figure><p>Now the simplest way to ensure that Ellen occupies multiple cells is likely to brute force and sample some points along each edge of the box. This is obviously not a very nice solution because we can potentially register the same physics body multiple times to the same hash. We can, of course, do a final check to ensure we uniquely add physics bodies to a hash, but we possibly would not know how many times we have to perform this uniqueness check.</p><p>But even with brute force, a question like this popped up during development:</p><ul><li>Can we accurately get all the cells that the box physics shape occupy?</li></ul><p>Well this problem was similar to an old Graphics problem I learned about which was determining which pixel a line potentially occupied. This is known as <a href="https://en.wikipedia.org/wiki/Bresenham%27s_line_algorithm">Bresenham’s Line Algorithm</a>.</p><p>The idea behind the algorithm is to calculate the slope of a line segment and to sample intervals to check which cell the sampled line segment belongs to. Here’s the pseudocode implemented in my physics engine below.</p><pre>Line(float2 from, float2 to, int cellSize) <br>{<br>  value = floor(from);<br>  diff = to - from;<br>  step = sign(diff);<br>  offset = float2(<br>   to.x &gt; from.x ? <br>     ceil(from.x) - from.x : <br>     from.x - floor(from.x),<br>   to.y &gt; from.y ? <br>     ceil(from.y) - from.y : <br>     from.y - floor(from.y));<br>  angle = atan2(-diff.y, diff.x);<br>  angles = float2(cos(angle), sin(angle));<br>  tMax   = offset / angles;<br>  tDelta = cellSize / angles;<br>  dist = abs(floor(to.x) - floor(from.x)) + <br>    abs(floor(to.y) - floor(from.y));</pre><pre>  // v will be associated cell&#39;s position. We can add<br>  // this to a collection or process this immediately<br>  v = FloorToNth(value, cellSize);<br>  <br>  for (int i = cellSize; i &lt; dist; i+=cellSize) <br>  {<br>    if (abs(tMax.x) &lt; abs(tMax.y)) <br>    {<br>       tMax.x += tDelta.x;<br>       value.x += step.x * cellSize;<br>    }<br>    else <br>    {<br>       tMax.y += tDelta.y;<br>       value.y += step.y * cellSize;<br>    }<br>    // Recalcule v again to find a new cell<br>    v = FloorToNth(value, cellSize);<br>  }<br>}</pre><p>What makes Brehansem’s line algorithm incredibly useful is visualization. If we collect all cells associated with the line we can provide the cell’s position and draw a heat map which will visualize the density of potential colliders.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/771/1*N2DF805FoVWK-pyTNR8PMg.gif" /><figcaption>Visualizing potential collisions using Brehansem’s Line Algorithm and drawing voxels to see potential collisions per cell. It’s worth noting that this is built in Unity 2020.1.x using an Entity Component System workflow.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5397610c9d63" width="1" height="1" alt=""><hr><p><a href="https://medium.com/initialprefabs/physics-collision-and-spatial-mapping-5397610c9d63">Physics Collision and Spatial Mapping</a> was originally published in <a href="https://medium.com/initialprefabs">initialPrefabs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Scaffolding in Development]]></title>
            <link>https://medium.com/@psuong95/scaffolding-in-development-8edf20fccebe?source=rss-7434879a1a19------2</link>
            <guid isPermaLink="false">https://medium.com/p/8edf20fccebe</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[ramble]]></category>
            <dc:creator><![CDATA[Porrith Suong]]></dc:creator>
            <pubDate>Sat, 13 Apr 2019 00:00:00 GMT</pubDate>
            <atom:updated>2019-08-21T15:11:02.269Z</atom:updated>
            <content:encoded><![CDATA[<p>So I preferably enjoy working with low level APIs instead of high level APIs. The main reason behind that is the amount of control I have as a developer, especially on creating the functionality I need. So if there is an alternative API which provides a lower level solution than a high level API which does exactly what I need…</p><p>I would still go for the lower level solution, even if I have to recreate the same functionality as the high level API.</p><p>Now truthfully, that sounds like I’m just redoing the same work for the same functionality I need. But let’s step back a little bit and think about some of the benefits of a lower level API.</p><h3>Scaffolding</h3><p>A low level API which allows you to chain functions together to create the desired outcome you need provides a scaffold.</p><p>Scaffolds in construction are temporary structures to aid in the construction or repair of a building or structure. But as a bystander you can clearly see how construction workers are constructing the building and their methodology. Take a look at the image of a bamboo scaffold used in Hong Kong below, you can clearly see how workers are going about the billboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eUeGmK_4BLSrTxu4.jpg" /><figcaption><em>Image credit goes to Wikipedia, with photo taken by Greg Hume</em></figcaption></figure><p>So relating back to development, scaffolds can not only give you the guidelines to create a high level API, but also the logical reasoning and the <em>specific data</em> you’ll need to solve the problem you have! An API/framework that provides this is invaluable to you as a developer!</p><h3>A Common Scenario throughout Development</h3><p>Imagine as your developing a feature using spme API. Now this API gives you an out of the box solution which works and solves the problem you’re trying to solve with a single function! Now that’s a whole lot of time saved and you can now move onto the next feature.</p><p>But…some time down the line you need to tweak a functionality within the API to allow you do to do something a bit more grand. You look through StackOverflow, a forum, or Github issues to get some kind of idea on how to tweak the API’s pipeline, but then you realize that currently there is no way to solve your particular solution and the developer(s) of said API wouldn’t support said feature until X months later.</p><p>It’s a terrible situation to be in and you’ll likely plan accordingly to compensate for the situation.</p><h3>Conclusion</h3><p>Now if you’re an API designer, you should not only think about the high level functionalities your developers will likely use. You should still support low level operations such that developers can really extend your API and make something unique you’ve never even thought of supporting!</p><p>Visibility in the framework encourages that developers care about what they’re using!</p><p>Thus, a good API is one that can be used multiple times in various similar situations to solve problems many developers face.</p><p><em>Originally published at </em><a href="https://psuong.github.io/blog/low-level-apis/"><em>https://psuong.github.io</em></a><em> on April 13, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8edf20fccebe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Going About Testing in Unity ECS]]></title>
            <link>https://medium.com/initialprefabs/going-about-testing-in-unity-ecs-53887477c163?source=rss-7434879a1a19------2</link>
            <guid isPermaLink="false">https://medium.com/p/53887477c163</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[test-driven-development]]></category>
            <category><![CDATA[game-development]]></category>
            <dc:creator><![CDATA[Porrith Suong]]></dc:creator>
            <pubDate>Tue, 26 Feb 2019 19:37:52 GMT</pubDate>
            <atom:updated>2019-04-01T17:01:26.582Z</atom:updated>
            <content:encoded><![CDATA[<p>With the Conversion workflow which has been recommended by Unity the method I suggested of instantiating a prefab will <strong><em>likely </em></strong>be deprecated. Archived items will still be available for reference’s sake.</p><p>Questions or comments I hear quite often when I mention I write unit tests for games are:</p><blockquote>Why do you need to write tests when games are visual and change over time?</blockquote><blockquote>Can’t you just ask someone to help you test your game so you can catch bugs?</blockquote><p>Those questions are quite true to a degree and there are certainly times when I think about not writing tests and just being able to move on to the next feature instead. But, more often than not, some of the pain points I had with scaling a game are:</p><ul><li>it’s easy to spot bugs with your eyes but it’s difficult to pin point/debug where the issue is</li><li>with a small team and when we’re under crunch time, not everyone has the time to regressively play test features to ensure they work</li></ul><p>You won’t completely solve those issues with unit testing but you can certainly alleviate the pain of those common scenarios by writing <strong><em>smart</em></strong> unit tests.</p><h3>Game Background</h3><p>So before I get into how my team and I go about unit testing, it’s worth explaining what our game, Project Arena (name pending), is basically about.</p><p>Project Arena is a 2D arena local multiplayer game where players choose cards between each round to defeat their opponent in battle. The game is played with a common local server, like your laptop, and smart phones as client controllers and secondary screens for each player.</p><p>I’ll certainly post more about this during the upcoming weeks/months.</p><p>Because we’re dealing with network code, we actually have to write tests to reason about our logic to ensure that we expect things to happen correctly despite the network connection. But in this blog, I’ll actually walk you through one of our test which tests our character’s visual effect and gameplay mechanic.</p><p><strong>Note</strong>: From here on out, I’ll refer to visual effect as VFX.</p><p>We build our game using <strong>Hybrid Entity Component System</strong> (ECS), which is an architecture that allows us to separate data away from logic providing us ease of scale and performance benefits.</p><p>For a brief overview<strong>, Arturo Nereu</strong> of Unity has a nice comic strip which explains ECS in a digestible manner.</p><p><a href="https://github.com/ArturoNereu/ECS_101/blob/master/ECS_Infographic/ECS_Infographic_EN.jpg">ArturoNereu/ECS_101</a></p><p>So much thanks and credits to him!</p><h3>The Game Mechanic</h3><p>The playable character is very similar to the mechanics of Megaman/X/Zero. The player can move, jump, shoot projectiles and use cards. Unlike Megaman, our player actually charges automatically since holding down a button on a phone is very uncomfortable while moving and performing other simultaneous actions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/418/1*wn6sJsuaf5OBm6guWghnyQ.gif" /><figcaption>Our stand-in character from the 2DGameKit, Ellen automatically charging!</figcaption></figure><h3>Understanding the Data Behind Charging a Shot</h3><p>Even though we use the Entity Component System, we still have dependencies on MonoBehaviour such as the Particle System.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*iNMB31r5NAZXAD0rCAVXhg.png" /><figcaption>Structurally, our Particle Systems are set up with the large circle in the center as the parent ChargeEffect Particle System, while the smaller circles moving towards the center is child SubCharge Particle System.</figcaption></figure><p>In our case, we treat MonoBehaviours as simply objects with properties, with limited functionalities. Below is a table which shows the minimum amount of data we need to get the effect shown in the gif:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/684/1*LdrKQLaVGLI1UtjUvYrHFg.png" /></figure><h3>Implementing the Charge Shot Logic</h3><p>So the Charge Shot behaviour is pretty simply, when the ChargeShotTimer’s Current time is <strong><em>greater than or equal </em></strong>to the max Wait time, the larger particle in the center (the parent) will play, otherwise it disappears. The child particle will always play when the Current time is greater than epsilon.</p><blockquote>Epsilon denotes the smallest value, in our case we treat epsilon as effectively 0.</blockquote><p>When shooting, the Current time is effectively 0, thus both particle systems will <strong><em>stop</em></strong> playing<strong><em>.</em></strong> This ensures that <strong><em>visually</em></strong>, our player does not look like they are getting a more powerful shot when shooting.</p><p>Below is the logic for our ChargeFXIndicatorSystem, which handles what was stated above.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93e5057951308d626d79db2a1141e1e0/href">https://medium.com/media/93e5057951308d626d79db2a1141e1e0/href</a></iframe><p>Since we don’t actually set up our VFX to be a child of Ellen, we internally map each Particle System by its player’s ID. This keeps our character prefab light with only the data we need and keeps our VFX as a separate entity.</p><h3>But, what tests are we actually writing for the VFX?</h3><p>The tests are quite simple with function names that are quite verbose:</p><ul><li>ChargingAttackShowsChildIndicator — if we charge a shot, we show our VFX’s child Particle System</li><li>FullyChargedAttackShowsBothIndicators — when we fully charge a shot, we show our VFX’s parent and child Particle System</li><li>ReleasedChargedAttackShowsNoIndicator — when we shoot, we show neither the parent VFX or child VFX</li></ul><h3>[ARCHIVED] Prepping Up Our Tests</h3><p>One of the benefits of testing in Unity is that we can test with real prefabs we use in our game.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*9VOfAeE77TULWpZCv6PKTQ.png" /><figcaption>Above is our player entity with the ChargeShotTimer boxed in light blue. Similarly, our ParticleSystemPair and ID proxies are highlighted in our VFX entity.</figcaption></figure><p>To use these assets in our tests, we built a utility function to grab a copy of the assets from the project. This is the code version of dragging a prefab into the scene!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/99a4f6ad652a472a407ba88bb07d7b00/href">https://medium.com/media/99a4f6ad652a472a407ba88bb07d7b00/href</a></iframe><h4>Test Fixture Set Up</h4><p>Now that we have the assets, we need to set up a clean environment to perform our tests. To do this, we create a text fixture, which has the bare minimum implementation of setting up and tearing down a clean environment for each test to run in.</p><p>This helps isolate our logic from the rest of the game/systems so we ensure that the logic works correctly on its own. Below is our minimal implementation of our test fixture.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c3f439c64b762aa935b0f76f724fdca/href">https://medium.com/media/2c3f439c64b762aa935b0f76f724fdca/href</a></iframe><p>All we do in our SetUp function is we create a new test world and cache the previous, one so we can restore it in our Teardown function after a test finishes.</p><p>To quickly recap we want to test the following scenarios:</p><ul><li>if we charge a shot, we show our VFX’s child Particle System</li><li>when we fully charge a shot, we show our VFX’s parent and child Particle System</li><li>when we shoot, we show neither the parent VFX or child VFX</li></ul><p>Here’s our ChargeFXIndicatorSystemTests:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/187dee6a140ea770573d6fedc3fd7153/href">https://medium.com/media/187dee6a140ea770573d6fedc3fd7153/href</a></iframe><p>For each test we just have to set our ChargeShotTimer and ensure that the <strong>Current</strong> time is either greater than, equal to, or less than our <strong>Wait </strong>time.</p><ul><li>ChargingAttackShowsChildIndicator — we can reason that the Current time has to be larger than 0 but less than our Wait time, so we just set the Current time to be 1 second.</li><li>We only expect there to be 1 entity available after the ChargeFXIndicatorSystem updates, otherwise our system is doing something odd and creating more entities than we need!</li><li>As for our VFX, we should expect that only the child VFX plays and not the parent, otherwise our system’s logic does not operate on our data correctly.</li></ul><p>The rests of the tests follow the same structure but just test other values of the Current time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*7YXzvxn3MUw9T8ENh_k2Tw.gif" /><figcaption>After running all the tests you can enjoy the satisfying feeling of all the green check marks flying through the Unity Test Runner.</figcaption></figure><h3>Some Closing Notes</h3><p>So that is the general gist of how my team and I go about testing. We usually plan our systems and tend to ask questions regarding the game design and the data we need first. This enables to really understand our direction before we start writing any code.</p><p>We also don’t go about<strong><em> writing tests for every single case possible</em></strong>. We’re a small team, so we write tests for our primary essential features. This helps us iterate quickly on our infrastructure and be able to call out poor infrastructure choices we’ve made while we’re developing our game.</p><p>Unit testing certainly takes time and patience to do and by no means replaces manual QA testing. You’ll certainly need design feedback on your game, which unit tests can’t provide.</p><p>Some additional resources I read about unit testing that I found useful are:</p><ul><li><a href="https://blogs.unity3d.com/2018/11/02/testing-test-driven-development-with-the-unity-test-runner/">https://blogs.unity3d.com/2018/11/02/testing-test-driven-development-with-the-unity-test-runner/</a></li><li><a href="https://github.com/sophiaaar/tdd-pong">https://github.com/sophiaaar/tdd-pong</a></li><li><a href="https://docs.unity3d.com/Manual/testing-editortestsrunner.html">https://docs.unity3d.com/Manual/testing-editortestsrunner.html</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53887477c163" width="1" height="1" alt=""><hr><p><a href="https://medium.com/initialprefabs/going-about-testing-in-unity-ecs-53887477c163">Going About Testing in Unity ECS</a> was originally published in <a href="https://medium.com/initialprefabs">initialPrefabs</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Eccentric ECS — Part 1]]></title>
            <link>https://medium.com/@psuong95/eccentric-ecs-part-1-bf8e32a063a4?source=rss-7434879a1a19------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf8e32a063a4</guid>
            <category><![CDATA[cplusplus]]></category>
            <category><![CDATA[entity-component-system]]></category>
            <category><![CDATA[game-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Porrith Suong]]></dc:creator>
            <pubDate>Sun, 20 Jan 2019 20:02:58 GMT</pubDate>
            <atom:updated>2019-01-20T20:11:56.509Z</atom:updated>
            <content:encoded><![CDATA[<h3>Eccentric ECS — Part 1</h3><p>After using Unity for quite a long time (since v3x) and appreciating its features and complexities, I’ve decided to try and build my own game engine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9u2-3O1m8ibWuCmbbc2kUA.png" /><figcaption>Figure 1. A couple of tests for the start of my own game engine in an ECS architecture.</figcaption></figure><blockquote>Why?</blockquote><p>Well, if you were really to ask me that question, I would jokingly say “Well, why not?” But in all seriousness, I’ve grown <strong><em>fascinated</em></strong> with an engine’s complexities and capabilities and it is something I want to be able to reason about, attempt to create, and understand. Now, I’m not expecting to create a full fledged engine on the same quality as Godot, Unity, Unreal, so here are some of the guidelines/goals I’m laying for myself:</p><p>A. Data Oriented Design — I was first introduced to data oriented design back in college through Noel Llopis’ blog post,<a href="http://gamesfromwithin.com/data-oriented-design"> Data Oriented Design (Or Why You Might be Shooting Yourself in the Foot with OOP)</a>, which eventually lead me to Mike Acton’s <a href="https://www.youtube.com/watch?v=rX0ItVEVjHc">CPPCon Keynote</a> speech. I’ve been working in a primarily functional and data oriented fashion since then, so it makes a lot of sense to me and I’d like to push the boundaries of my knowledge.</p><p>B. Keeping it Simple — Again, to reiterate this is a sandbox for me to explore complex engine architecture and be able to reason about it. I won’t create some crazy over the top game but something small and simple, most likely a bullet hell game so I can take advantage of data oriented design.</p><p>C. Low level languages — Most of my work is done in C# and Python and it’s been almost about a year since I really touched C++ or another low level language, so this is great practice for me. (C++17)</p><p>D. Multithreading — multiple cores on a CPU is useful, how can I utilize them effectively?</p><p>E. Unit/Integration tests for sanity’s sake! I’ll be using Catch2 because it’s a pretty expressive testing framework and easy to setup.</p><p>So without further ado, let’s get started on what <strong>Eccentric ECS</strong> is all about in this multi-part blog post series.</p><h3>Part 1. What is an Entity Component System?</h3><p>Entity Component Systems or ECS is an architectural system pattern which focuses on composition of data and operations of data more than modeling data and behaviours to model the real world.</p><p>Similarly, data oriented design and of course the entity component system can be thought of a giant spreadsheet, where each column represents a component of data and each row represents an associated set of data that makes up an entity. Our systems can be functions that operate on columns and rows of data.</p><h3>Part 2: Representing Entities</h3><p>Building on my spreadsheet example, an entity is just a unique ID similar to a row’s numerical value (e.g. row 1, 2, 3, 4, etc). In Eccentric ECS, an entity is represented like so:</p><pre><strong>struct </strong>entity {<br>    <strong>unsigned int id</strong>;<br><br>    entity() { <strong>id </strong>= 0; };<br>    entity(<strong>unsigned int </strong>id) : entity() { <strong>this</strong>-&gt;<strong>id </strong>= id; };<br><br>    <strong>const bool operator</strong>==(<strong>const </strong>entity other) <strong>const </strong>{<br>        <strong>return id </strong>== other.<strong>id</strong>;<br>    }<br><br>    <strong>const bool operator </strong>!=(<strong>const </strong>entity other) <strong>const </strong>{<br>        <strong>return id </strong>!= other.<strong>id</strong>;<br>    }<br>};</pre><p>All it stores in my case is an unsigned integer as all I really care about is assigning a unique ID to the entity.</p><p>Typically, all entities are managed through an EntityManager which is responsible for:</p><ol><li>Creation/destruction of entities</li><li>Determining existence of an entity</li></ol><p>As such, we can represent an EntityManager like so:</p><pre><strong>class </strong>entity_manager {<br><br><strong>public</strong>:<em><br>    </em>entity create_entity();<br><em><br>    </em><strong>void </strong>create_entities(size_t size, entity entities[]);<br><em>    </em><strong>void </strong>destroy_entities(entity[] entities);<em><br>    </em><strong>bool </strong>exists(entity e);<br><br><em>    </em>entity_manager();<br>    ~entity_manager();<br><strong>private</strong>:<br>    std::vector&lt;entity&gt; <strong>current_entities</strong>;<br>    <strong>unsigned int last_entity</strong>;<br>};</pre><p>Creating an entity is simple, we keep track of the last_entity and increment it whenever we want to create a new entity. This allows support up to <strong><em>2³² entities</em></strong>. Now if I were to create 2³² + 1 entities, I would get an overflow error. Considering <strong><em>scale</em></strong>, I would probably want to reuse certain entities that were disposed of whose IDs are now free or look into using a 64 bit integer instead of a 32 bit integer.</p><p>In my current header, I express the usage of an array of elements instead of a single parameter for creation and destruction. Preferably, I would want to operate on batches of data instead of single elements alone. Now this is subject to change depending on profiling the performance of these operations (with and without multithreading).</p><h3>Some Afterthoughts</h3><p>In my current entity_manager, I use an STL vector, which for now <em>solves </em>the problem of managing entities. I’ve been looking into creating my own custom allocators so I can allocate a <em>chunk</em> of memory and slot entities in these chunks. The benefits of this allows me to free memory in groups rather than <em>individually</em> and limit the number of malloc calls. Malloc being general purpose memory allocator has to work for any size (1 KB, 1GB, etc), which can be <a href="https://en.wikipedia.org/wiki/C_dynamic_memory_allocation">inefficient</a>.</p><p>I’ll revisit this topic later in another blog post!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf8e32a063a4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Derby Case Study : Unity ECS For Small Things]]></title>
            <link>https://medium.com/@psuong95/derby-case-study-unity-ecs-for-small-things-a94f3b25b274?source=rss-7434879a1a19------2</link>
            <guid isPermaLink="false">https://medium.com/p/a94f3b25b274</guid>
            <category><![CDATA[ec]]></category>
            <category><![CDATA[unity3d]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Porrith Suong]]></dc:creator>
            <pubDate>Fri, 19 Oct 2018 18:37:47 GMT</pubDate>
            <atom:updated>2018-10-20T03:11:42.989Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Derby Case Study : Unity ECS For Small Things</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*cj84T5rYd0A7n84skv3Jaw.png" /><figcaption>A really horrible thumbnail image that I created for a case study icon.</figcaption></figure><h3>Background</h3><p>I’ve been building a small racing game, Derby, to explore the use cases of Unity’s Entity Component System. While Unity’s ECS is much more advanced than the current C++ ECS framework that I’m used to, <a href="https://github.com/Gronis/OpenEcs">OpenECS</a>, the style and thinking remains relatively the same.</p><ul><li>What is the minimum amount of data you need?</li><li>Where do you read this data from?</li><li>Where do you write this data to?</li><li>What do you do with this data?</li></ul><p>A lot of the use cases I’ve seen on Twitter, Unity Connect, and the forums relate to somewhat massive projects, but a lot of the comments I hear in person from developers who are familiar to Unity relate to:</p><ul><li>My game isn’t massive, so why would I need to switch from MonoBehaviours to ECS?</li></ul><h3>Derby’s Use Case</h3><p>While I think Unity has marketed ECS as a good solution for massive games, it has it’s uses in <a href="https://www.youtube.com/watch?v=EWVU6cFdmr0">small games</a>. Derby is by no means a massive game right now, in fact it’s still in the early phases of development; building the infrastructure. But, over the past few weeks I’ve been able to dish out a few features of the game using ECS:</p><ol><li>VehicleSystem(s)</li><li>A CatmullRomSplineSamplingSystem to determine relative position of the vehicle on a track</li></ol><p>When I think about a racing game that uses physics, I typically think of using rigidbodies and an input system to read controller data. Now, this is can easily be done using a RigidBody component and a few MonoBehaviour scripts, but I would lose the scale, efficiency, and flexibility to:</p><ul><li>estimate accurately</li><li>filter and manipulate data associated to vehicles (e.g. status debuffs specific to some vehicles, area affects like oil spills, etc)</li></ul><h3>Estimating Accurately: The Problem</h3><p>When we watch a race, the easiest way to determine visually who is in nth place of the race is, whomever is ahead. The first person to cross the finish line is in 1st place, the 2nd is in second place, and so forth. The very same concept can be applied in a digital racing game.</p><p>We can add a collider or a raycast for each checkpoint and just let the component attempt to hit a car that passes the checkpoint. Whoever finishes x laps wins the race and is first. But, what if I wanted to tell in realtime which place a player is in? In long stretches of laps where there is no checkpoint, any single player can be in nth place. If car A is ahead of car B between checkpoints 1 and 2, then car A is first. So the problem became,</p><blockquote><em>How can I tell who is in whatever place in real time in Derby?</em></blockquote><p>A solution I saw online from various people on Unity Answers was to make more “invisible” colliders along the path and just see whoever hits whatever collider first. But, that seems <strong><em>more of an over engineered solution</em></strong>, as I’m encouraging myself to create more data to solve what is actually, a small problem. By thinking of the implications of the already available data, the solution isn’t so difficult.</p><ol><li>We have checkpoints, therefore we can assume there is some kind of path.</li><li>We have the position of the vehicle. Cool, that’s all we need!</li></ol><p>The reality is that, if the track is wide, <strong><em>no person</em></strong> racing <strong><em>will seriously stick to a single path</em></strong>. So, we need to flatten a wide range of potential vehicle positions along a single path and determine their relative positions.</p><p>Thus, estimating accurately is one of <strong><em>most</em></strong> important functionalities in solving this problem and this is where ECS is extremely helpful.</p><h3>Estimating Accurately: The Solution</h3><p>So my tracks are usually built using a <a href="https://www.mvps.org/directx/articles/catmull/">Catmull Rom Spline</a>. A position along the spline is defined by a parametric value <strong><em>t</em></strong> (if you’re unfamiliar with this, just think of it like the Mathf.Lerp function you find in Unity). <strong><em>t</em></strong> is typically a value between 0 and 1 and by determining the vehicle’s relative position, we can associate the value <strong><em>t </em></strong>to the vehicle and just sort from greatest to smallest value to have an accurate representation of placement order.</p><p>Now where is accuracy in all of this?</p><p>Well, to determine<strong><em> t </em></strong>along a spline, I need a set of points. If there are four checkpoints, then that’s enough to determine the general shape of the spline. But of course, I need to sample between each point, so each segment is broken up into smaller segments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/268/0*8aT2mljR-r4IbL7k.png" /></figure><p>Each green dot is a potential checkpoint. The red dotted lines represent the general spline, and the blue lines represent the binormal. The binormal is the line perpendicular to the tangent’s normal.</p><p>I get the position of the vehicle, the direction between the vehicle and a point on the spline, and I calculate the angle between binormal of the spline. The angle closest to 0 represents the possible position along the spline. Now with 10 line segments, between each checkpoint, it’s not very accurate to determine t. With two vehicles relatively close to each other, an angle of approximately 4° and 5° would probably fall to the same value of t. Not ideal, so we sample more points along the spline for a degree of higher accuracy.</p><p>Now imagine if we did this in an OOD and in Unity, on a single thread. If we have a sample size of 400, and 2 cars and we implement this algorithm naively, we potentially iterate through 400 elements for each car; that’s 800 elements! Add in AI and we then sample <strong><em>x number of cars * m sample points</em></strong> (where m and x are both positive integers).</p><p>Of course, we can write checks to try and narrow down our search results by finding the lower and upper bound of the most likely value of t. But if you’re going for the naive approach, so you can move onto other tasks, then you’ll need to scale down and solve the issue.</p><p>Note: Of course it’s not to say that even when using MonoBehaviours you can’t thread, you can most certainly thread some things that are thread safe in the UnityEngine namespace or at the very least, thread your own functions.</p><h3>Using Unity ECS</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgfycat.com%2Fifr%2FOddEvilIriomotecat&amp;url=https%3A%2F%2Fgfycat.com%2Foddeviliriomotecat&amp;image=https%3A%2F%2Fthumbs.gfycat.com%2FOddEvilIriomotecat-size_restricted.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=gfycat" width="546" height="440" frameborder="0" scrolling="no"><a href="https://medium.com/media/688cd38e98a6934bf8b57b77d801023b/href">https://medium.com/media/688cd38e98a6934bf8b57b77d801023b/href</a></iframe><blockquote>Ultimately, we want our solution to do this along a sample size of 400 points.</blockquote><p>Doing this in ECS is actually quite simple. We need to store control points and cache a table of sampled points, so we can compute the angles. Now 800 points of iteration isn’t extremely large but it might as soon as vehicles tend to get more complex. In Unity’s ECS we can certainly iterate through this much more easily.</p><p>Majority of your data must be using value based data. Take a look at the MSDN’s documentation on <a href="https://docs.microsoft.com/en-us/dotnet/framework/interop/blittable-and-non-blittable-types">blittable types</a>, but in a nutshell, they’re mainly primitives with the exception of a few, like bools and chars. We can collect and iterate through each sample on separate threads through the job system.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/0*ve2iZwnuR2Ri-Kal.png" /></figure><p>By sending the Job to another thread and using Unity’s Burst Compiler, the job took ~0.030 ms. This is a huge performance gain just to determine the min angle.</p><p>But here’s some actual code to see how this kind of potential is achieved. The job below implements a naive algorithm of finding the min, we can always improve it later to look for a upper and lower bound and narrow down the search results.</p><p>Note: The code below is not the complete script as this wasn’t meant to be a full fledged programming tutorial.</p><pre>struct PotentialAngleCollectionJob : IJobProcessComponentData&lt;Position, PlayerId&gt; {<br>    [ReadOnly]  public float constraint;<br>    [ReadOnly]  public NativeArray&lt;float3&gt; splinePoints;<br>    [ReadOnly]  public NativeArray&lt;float3&gt; binormals;<br>    [WriteOnly] public NativeArray&lt;ValueTuple&lt;int, float&gt;&gt; table;<br>#if UNITY_EDITOR<br>    [WriteOnly] public NativeArray&lt;float3&gt; direction;<br>#endif<br>    public void Execute(ref Position position, ref PlayerId id) {<br>        var prevAngle = float.MaxValue;<br>        for (int i = 0; i &lt; splinePoints.Length; i++) {<br>            var binormal = binormals[i];<br>            var dir = position.Value - splinePoints[i];<br>            // This is a custom function I built which compute the angles given two vectors<br>            // using Unity&#39;s new Math lib.<br>            var angleLHS = VectorUtils.Angle(binormal, dir);</pre><pre>            if (angleLHS &lt; constraint &amp;&amp; angleLHS &lt; prevAngle) {<br>                var t = ((float)i) / splinePoints.Length;<br>                table[id.value] = Tuple.Create(id.value, (float)angleLHS);<br>#if UNITY_EDITOR<br>                direction[id.value] = dir;<br>#endif<br>                prevAngle = (float)angleLHS;<br>            }<br>        }<br>    }<br>}</pre><pre>// In JobHandle OnUpdate(JobHandle deps) function, we can simply schedule this job and let it run.<br>// The sampled points (splinePoints and binormals) can simply be retrieved from other <br>// components/chunks.<br>protected override JobHandle OnUpdate(JobHandle inputDeps) {<br>    var table = new NativeArray&lt;ValueTuple&lt;int, float&gt;&gt;(playerLength, Allocator.TempJob);<br>    inputDeps = new PotentialAngleCollectionJob {<br>        constraint = constrain,<br>        splienPoints = splinePoints,<br>        binormals = binormals,<br>        table = table;<br>    }.Schedule(this, inputDeps);<br>    inputDeps.Complete();<br>    <br>    // ... Dispose all of the native containers<br>    return inputDeps;<br>}</pre><p>With that said, a lot of this understanding and potential came from simply changing the way you think about data. Objects are convenient and simple, but if we imagined a look up table (like a spreadsheet), we can understand how memory should be laid out and how we can access it.</p><p>New versions of ECS allow chunk iteration, dynamic buffers, LODs and much more that potentially solve some of the problems that, we as game developers and designers run into. We’re limited by the hardware we build upon, but understanding a much lower level approach allows us to leverage the hardware we have and take advantage of it. With that said, it’s worth gradually delving into Unity’s ECS even for small projects and smaller problems.</p><p>You can grab the spline tool here: <a href="https://github.com/psuong/SplineTools">https://github.com/psuong/SplineTools</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a94f3b25b274" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Post PlayNYC]]></title>
            <link>https://medium.com/@psuong95/post-playnyc-be8ce7c62da4?source=rss-7434879a1a19------2</link>
            <guid isPermaLink="false">https://medium.com/p/be8ce7c62da4</guid>
            <category><![CDATA[games]]></category>
            <category><![CDATA[unity]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Porrith Suong]]></dc:creator>
            <pubDate>Sat, 18 Aug 2018 20:41:06 GMT</pubDate>
            <atom:updated>2018-08-18T20:41:06.344Z</atom:updated>
            <content:encoded><![CDATA[<p>Last weekend at PlayNYC, I had the opportunity to showcase my first prototype of Derby, an arcade racing/demolition derby game with a twist of the vehicle driving on ice! The prototype was approximately four months into development so the game is still in its pre-alpha stage.</p><p>Derby was met with a lot of positive feedback and constructive criticism for its:</p><ul><li>Controls</li><li>Gameplay</li><li>Camera</li><li>UI</li></ul><p>The controls were easy to pick up for most players, since the control scheme followed a standard layout amongst racing games, But, the controls were sensitive, meaning that a slight nudge to the joystick can turn the vehicle wildly, thus causing a steep learning curve. Additionally, vehicles moved really fast relative to the size of the map which definitely surprised players.</p><p>The gameplay was simple, complete 4 laps with your vehicle of choice. Due to the sensitivity of the controls and how the vehicles’ drag worked on the road, for many play testers, it was like they were driving on ice. Whoever figured out how to control the vehicles’ controls first typically won.</p><p>The camera needs a lot of improvement. It was nauseating for many players because the camera always tries to face the direction of vehicle’s velocity. If you moved forward, the camera was behind the vehicle and faced forward, if you moved backwards, the camera was in front of the vehicle and faced the vehicle. Any kind of collision made the camera wildly jump between the front and back of the vehicle.</p><p>The UI was lackluster at best since I didn’t get as much time to work on it as I hoped. As you entered the race, there effectively was no UI to tell players they’ve passed through a checkpoint or completed a lap. Although, this did make it interesting for me to be an announcer of the race as there was a little log I printed which told me exactly how many laps were left.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9myI0LFisnYPvYC4" /></figure><p>An example of a terrible UI and camera angle for the start of the game. There was no indication of laps, speed or even a minimap. The camera angle fooled people into thinking that the race was a top down view initially.</p><p>You can view the initial gameplay prototype on <a href="https://www.youtube.com/watch?v=A__2IxdHf2E">Youtube</a>.</p><h3>Where to go from here?</h3><p>Over the coming months, I’ll be feature-locking the game and improving on the following:</p><p><strong>Vehicle Controls</strong></p><p>The controls can be a bit easier for players such that the learning curve isn’t as steep.</p><p><strong>Camera</strong></p><p>This needs to be reworked entirely to reduce nauseating effects and provide a good field of view so people can see what’s head easier (e.g obstacles, checkpoints, sharp corners, etc).</p><p><strong>UI</strong></p><p>A much more informative UI which displays the lap number, place, and a mini-map of checkpoints to pass is required.</p><p><strong>Scene/Level Loading</strong></p><p>Ultimately, Derby wasn’t built as a standalone game. In fact it was running via Unity’s editor due to a bug when loading the levels.</p><p><strong>Level Design</strong></p><p>A level design that encourages and makes passing through gates obvious is necessary for an intuitive racing game.</p><p>Once those systems have been refactored adding in new features would be as easy as writing in a new system to accommodate!</p><p>Overall, the experience at PlayNYC was phenomenal and I was pleased with the feedback I received for a four month prototype of me experimenting with a new game and system design in Unity 2018.2.0f on Ubuntu 18.04.</p><p>Cheers,</p><p>Porrith — An exploratory game developer</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=be8ce7c62da4" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>