<?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:media="http://search.yahoo.com/mrss/"><channel><title><![CDATA[coty.tips]]></title><description><![CDATA[programming stuff]]></description><link>https://coty.tips/</link><image><url>https://coty.tips/favicon.png</url><title>coty.tips</title><link>https://coty.tips/</link></image><generator>Ghost 3.42</generator><lastBuildDate>Fri, 20 Nov 2026 22:33:45 GMT</lastBuildDate><atom:link href="https://coty.tips/rss/" rel="self" type="application/rss+xml"/><ttl>60</ttl><item><title><![CDATA[A Custom Level Editor For An Open World Game]]></title><description><![CDATA[<p>In 2023, I started prototyping a game for <a href="https://www.funktroniclabs.com/">Funktronic Labs</a>, at the time titled Scramble Knights Royale (which later became <a href="https://www.scrambleknights.com/">Scramble Knights Online</a>).</p><figure class="kg-card kg-image-card"><img src="https://coty.tips/content/images/2026/11/image-35.png" class="kg-image" alt></figure><p>This was an ambitious title. One of the level-design goals were to have a large-scale open world map, potentially several miles in diameter. Much of the original</p>]]></description><link>https://coty.tips/a-custom-level-editor-for-an-open-world-game/</link><guid isPermaLink="false">6b0084656b7faa02a5f213e5</guid><dc:creator><![CDATA[Coty Getzelman]]></dc:creator><pubDate>Fri, 20 Nov 2026 19:10:48 GMT</pubDate><content:encoded><![CDATA[<p>In 2023, I started prototyping a game for <a href="https://www.funktroniclabs.com/">Funktronic Labs</a>, at the time titled Scramble Knights Royale (which later became <a href="https://www.scrambleknights.com/">Scramble Knights Online</a>).</p><figure class="kg-card kg-image-card"><img src="https://coty.tips/content/images/2026/11/image-35.png" class="kg-image" alt></figure><p>This was an ambitious title. One of the level-design goals were to have a large-scale open world map, potentially several miles in diameter. Much of the original design was inspired by popular battle royales of the time, such as <a href="https://store.steampowered.com/app/578080/PUBG_BATTLEGROUNDS/">PUBG </a>and <a href="https://www.fortnite.com/">Fortnite</a>. </p><hr><p>In order to support development of this goal, I first talked it over with the studio's art director (<a href="https://www.linkedin.com/in/pat-vince-9997631b/">Pat Vince</a>) and later with the level designer (<a href="https://www.linkedin.com/in/eddie-peters-70372649/">Eddie Peters</a>), to ensure what I was about to make would cover any use cases they might need. </p><p>Here's a short list of the wants:</p><ul><li>The ability to work in a tile-based fashion. </li><li>Automatic tile selection by default, with override abilities. </li><li>Keep everything as "Unity-friendly" as possible - do not break support for basic prefab / component modifications. </li><li>Runtime level streaming, do not wait on the whole level to load before jumping into a match. </li><li>Some in-Unity way of quickly placing props too, not just tiles.</li><li>Always be able to immediately test changes.</li></ul><p>The trickiest ask here was the tile based world editing. I sat down to think about it, and sketched out a few ideas. </p><p>In the past, I've worked on a lot of voxel-based systems (for example, as far back as 2021 I was <a href="https://x.com/cotycrg/status/1370275541698277376">tinkering with Marching Cubes</a>, and then in 2022 <a href="https://x.com/cotycrg/status/1607061221496467456">I released a voxel plugin</a> on the unity asset store). I thought in-depth about how Marching Cubes worked, in particular, and how it could potentially be applied here. </p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://coty.tips/content/images/2026/11/brave_H93YgQReH5.gif" class="kg-image" alt><figcaption>Marching Cubes terrain with FallingSand-style physics.</figcaption></figure><hr><h2 id="marching-cubes">Marching Cubes</h2><p>Because I had spent so much time in the past thinking about Marching Cubes, my initial gut reaction about how to handle level-development of this "clay aesthetic zelda-inspired" artstyle was a voxel terrain. However, I knew that the level design wishlist did not really contain realtime modification of levels or anything fancy like that, so I did not really want to go overboard and dive straight into another voxel project. Instead, I was pondering on if there were any learnings I could take from my experience here and if they could be applied to an entirely new system. </p><p>There are <a href="https://fab.cba.mit.edu/classes/S62.12/docs/Lorensen_marching_cubes.pdf">tons </a>of <a href="https://www.cs.carleton.edu/cs_comps/0405/shape/marching_cubes.html">writeups</a> <a href="https://dl.acm.org/doi/10.1145/37402.37422">about</a> <a href="https://en.wikipedia.org/wiki/Marching_cubes">marching cubes</a>, which are likely going to do a far better job at explaining the algorithm in-depth than I would here. But, I'll give a brief overview: </p><p>Given some surface defined by a density function (or data), you can generate topology around that surface by using simple rules defined by a lookup table. When you dig into it, there's just a few distinct rules, which can be rotated / flipped into a full <a href="https://gist.github.com/dwilliamson/c041e3454a713e58baf6e4f8e5fffecd">lookup table</a>.</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://coty.tips/content/images/2026/11/image-36.png" class="kg-image" alt srcset="https://coty.tips/content/images/size/w600/2026/11/image-36.png 600w, https://coty.tips/content/images/size/w1000/2026/11/image-36.png 1000w, https://coty.tips/content/images/size/w1600/2026/11/image-36.png 1600w, https://coty.tips/content/images/2026/11/image-36.png 1920w" sizes="(min-width: 720px) 720px"><figcaption>(image from <a href="https://en.wikipedia.org/wiki/Marching_cubes#/media/File:MarchingCubesEdit.svg">wikipedia</a>)</figcaption></figure><p>If you think about it, these rules are just iterating over each 'voxel' and seeing "I'm blocked above? I'm blocked below? I'm blocked to the side?" over and over. Through all these rules, you can generate pretty much any surface's topology (<em>there's some ambiguity in some edge cases - but I'm glossing over them </em>here). </p><p>Marching Cubes packs these rules into a single lookup table, which is indexed into via some bitmasking of the 'rules', and it just works. It's fast, it's easy, and it looks pretty good for something so simple. However, in this case we don't really need to be fast or easy, and I want it to look VERY good. </p><h2 id="rules">Rules</h2><p>What I came up with was to take this 'rules' idea from Marching Cubes and expand on it. Skip all the optimization of bitmasking and lookup tables for now, and get soemthing going. The plan:</p><ul><li>Write a <code>Tile Ruleset</code> scriptable object, with a custom inspector for all the rules.</li><li>Write a <code>Tile Group</code> component, which could be placed in the scene.</li><li>Write a custom level editor that allows placing <code>Tile Group</code>s (among other things), keeping it unity-friendly and fully in the <code>SceneView</code>. </li></ul><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://coty.tips/content/images/2026/11/image-37.png" class="kg-image" alt><figcaption>At the heart of it were 'state' checks.</figcaption></figure><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://coty.tips/content/images/2026/11/image-40.png" class="kg-image" alt><figcaption>Each 'rule' would have a state check, with some meta data.</figcaption></figure><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://coty.tips/content/images/2026/11/7c701a72-c95a-4cae-9255-fb50761f8629.png" class="kg-image" alt><figcaption>A list of rules were defined per TileGroupData (think: biome, themes).</figcaption></figure><p>The editor for rules was made to look like a 3d grid of state checks. 3x3x3, so any case could be handled (similar to marching cubes). I kept a strict restriction of "neighbor only" checks, at least at first, to keep thinks simple to implement in code and to hopefully keep things fast in the editor moving forward. </p><figure class="kg-card kg-image-card"><img src="https://coty.tips/content/images/2026/11/Unity_WFQGjZd4kS.png" class="kg-image" alt srcset="https://coty.tips/content/images/size/w600/2026/11/Unity_WFQGjZd4kS.png 600w, https://coty.tips/content/images/size/w1000/2026/11/Unity_WFQGjZd4kS.png 1000w, https://coty.tips/content/images/size/w1600/2026/11/Unity_WFQGjZd4kS.png 1600w, https://coty.tips/content/images/2026/11/Unity_WFQGjZd4kS.png 1902w" sizes="(min-width: 720px) 720px"></figure><figure class="kg-card kg-image-card"><img src="https://coty.tips/content/images/2026/11/Unity_3TMBGgC2Jf.png" class="kg-image" alt srcset="https://coty.tips/content/images/size/w600/2026/11/Unity_3TMBGgC2Jf.png 600w, https://coty.tips/content/images/size/w1000/2026/11/Unity_3TMBGgC2Jf.png 1000w, https://coty.tips/content/images/size/w1600/2026/11/Unity_3TMBGgC2Jf.png 1600w, https://coty.tips/content/images/2026/11/Unity_3TMBGgC2Jf.png 1858w" sizes="(min-width: 720px) 720px"></figure><p>The rule-editor looked like this. A preview of the prefab on the left, with the rules defined on the right. Below (y=-1), self (y=0), above (y=+1) 3x3 grids, where clicking these buttons would allow selecting a particular 'state' for the rule to check. In this image, you can see there are many more states than in the enum I described above, as these states were eventually added later in development. </p><p>In theory, these rules could be setup to mimic the base rules from marching cubes, and have code handle rotation/flips as a level designer or artist would prefer on a rule by rule basis. </p><p>I explained this thought process to the artist (<a href="https://www.linkedin.com/in/pat-vince-9997631b/">Pat Vince</a>) in charge of actually concepting/modeling the tiles themselves. I offered a sytem for automating those rules, but he opted for doing them by hand, suggesting that not every tile group would need the full ruleset. In hindsight, I did regret not simply baking in the default marching cube rules as a 'default' as later in development we did continuously run into bad rules/tiles that needed to be hand adjusted. Regardless, we pressed forward! </p><p>After getting the initial tile group art made, the level designer was able to go for a test drive. </p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://coty.tips/content/images/2026/11/Unity_Y1oM3OB3aZ.gif" class="kg-image" alt><figcaption>Resizing and moving groups.</figcaption></figure><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://coty.tips/content/images/2026/11/Unity_GGPYIXHUv1.gif" class="kg-image" alt><figcaption>Placing and removing tiles.</figcaption></figure><p>While not perfect (you can see issues in meshing even in this gif above), this workflow quickly proved to be a huge success. The level designer was able to quickly block out large chunks of the overworld and unique dungeons. </p><p>The level designer did have a few more requests, though.</p><h2 id="making-things-interactive">Making Things Interactive</h2><p>Now that the overworld development was underway, the level designer asked for sytems to allow him to make the world interactive. </p><p>Unity, unfortunately, does not have any sort of built in node-behavior-editor. Nothing blueprint-like. I was tempted to start development of a Unity plugin for something similar, although there are many on the asset store already. But, given the time constraints of the project, I opted for something a lot simpler: an in-level-editor signal system. This was mostly inspired by the "Signal System" in <a href="https://steamcommunity.com/app/761010/workshop/">Wave Break's level editor</a> (a previous thing I had developed), which itself was heavily inpsired by <a href="https://minecraft.wiki/w/Redstone">Minecraft's redstone system</a>. </p><p>The signal system was pretty straightforward:</p><ul><li>Define a <code>DeviceTrigger</code> that sends out a 'signal' when triggered.</li><li>Define a <code>DeviceMechanism</code> that listens for 'signals' and does <em>something</em>.</li><li>Define a <code>DeviceGate</code> that sits between triggers and mechanisms, for complex logic. </li><li>Define a <code>DeviceWire</code> which connects triggers to gates and mechanisms. </li></ul><figure class="kg-card kg-image-card"><img src="https://coty.tips/content/images/2026/11/Unity_HEJQ11sAl2.gif" class="kg-image" alt></figure><p>These pieces were all just basic Unity prefabs and components, nothing fancy going on really. The level editor was made to handle custom rendering of wires and states, to make it easy to debug issues. </p><p>The signal system included goodies such as:</p><ul><li>Push blocks, Damage blocks, Pick-up blocks</li><li>Buttons, Levers, Pully triggers</li><li>Doors, Gates</li><li>Activators, Spawners, Despawners</li><li>Logic gates: AND, NAND, OR, NOR, XOR, NOT, DELAY, and more.</li></ul><p>With all of these in place, sophisticated dungeons became very easy to make. </p><h2 id="okay-but-maybe-we-do-want-realtime-editing">Okay, but maybe we do want realtime editing?</h2><p>While this was not an initial goal of the system, I did try to keep the level editing experience as snappy as possible. Clicking and waiting is horrible, so any time that performance became an issue I hopped back on the editor to profile and fix whatever the issue was. </p><p>The <code>TileGroup</code> resolve pass ended up being a burst-compiled job, and it was <em>pretty fast</em>. Fast enough that it typically did not even register on the profiler on it's own (the <code>UnityEngine.Object</code> <code>Instantiation</code> of those tiles was another story..)</p><figure class="kg-card kg-image-card"><img src="https://coty.tips/content/images/2026/11/image-41.png" class="kg-image" alt srcset="https://coty.tips/content/images/size/w600/2026/11/image-41.png 600w, https://coty.tips/content/images/2026/11/image-41.png 918w" sizes="(min-width: 720px) 720px"></figure><p>Because of this, the idea kept coming up in the office "can we get runtime modifiable groups?" Honestly, I really wanted to avoid this, because I had planned on static-baking various parts of this system. So instead, I provided a toggle for certain <code>TileGroup</code>s to opt into realtime modification support. The build system would skip over these when doing built-time optimizations, and these groups were allowed to be modified at runtime. </p><p>The first real use-case of this was tall grass tiles. </p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://coty.tips/content/images/2026/11/Unity_jr2ZrODtKy.gif" class="kg-image" alt><figcaption>Choppable grass is just another TileGroup, but with Dynamic Mode enabled.</figcaption></figure><p>There were quite a few use-cases for this that ended up popping up throughout the project (breakable tiles, unstable floors, things of that nature). Looking back, I'm glad the system stayed flexible enough to allow this to work! </p><hr><h2 id="what-about-runtime">What about runtime? </h2><p>At this point, I was pretty happy with the state of the level editor, at least on the Unity editor side of things. Unfortunately, the first build of the game with a large chunk of the world actually created was not doing too hot. </p><p>The first implementation of this system simply spawned in the whole overworld when loading a level, which of course was not sustainable long term. However, I had already been thinking of a way to deal with this and was working on a plan. </p><p>Inspired again by previous voxel work, my plan was:</p><ul><li>At game-build-time, gather all of the level assets and group them into spatial chunks (16x16x16?). </li><li>For each chunk, generate a Unity prefab and serialize it to disk. </li><li>At runtime, take the player's positions and spawn chunks within view of the camera, while despawning chunks far outside of view. </li></ul><p>The first pass of this was pretty successful. Things streamed in and out, all was well. However, runtime performance was generally still very poor. On my Steam Deck, I was only getting ~30 fps. My goal was to hit 60 fps with plenty of overhead on that little Steam Deck. </p><p>After some profiling, I found that Unity was simply spending way too much time on submitting draw calls from the CPU to the GPU. The CPU was spending nearly 20ms on <em>just</em> issueing these commands. For a top-down game that seemingly wasn't rendeirng that much, I really thought this was a bug, at first. </p><p>This was only my second project using the Universal Render Pipeline (URP) in Unity, so I did a bit of research to see if we were missing something vital. We were already using the <code>SRP Batcher</code> appropriately, which had given us big gains in the past. I did discover that URP at that time had just released it's <code>GPU Resident Drawer</code> support (in a version right above where we were). I spent some time upgrading our Unity project and give this a whirl. </p><p>The <code>GPU Resident Drawer</code> has some.. somewhat annoying requirements. I had to make sure all of our shaders supported the new <code>Forward+</code> renderer, and our lighting code was all custom. However, I did get this working after some fiddling, and got to profile the game using the resident drawer. It did increase performance (roughly 2x improvement, was only 10ms spent issuing commands). But, I did not find this acceptable at the time. Surely it could be much faster, there really isn't much going on! </p><h3 id="static-all-the-things">Static all the things?</h3><p>Because of the nature of spawning in-out meshes, I had not ticked on <code>isStatic</code> on our generated prefabs, but tried out using Unity's built-in <a href="https://docs.unity.com/en-us/engine/6000.6/script-reference/unityengine/staticbatchingutility"><code>StaticBatchingUtility</code> </a>API at runtime, running it over the whole chunk. A world chunk would spawn, we'd statically batch it. </p><p>This actually increased runtime performance significantly, only spending ~5ms per frame on submitting these draw commands. However, the huge tradeoff was that the static batch pass was pretty slow. So, maybe we could do it at build time? Unfortunately this did not seem to be a built-in option, so I wrote a tool that would iterate over the built level chunk prefabs and mesh combine them manually. </p><p>Doing this manually had a few extra benefits:</p><ul><li>No runtime cost at generating these meshes. They were just there, ready to go. </li><li>Precision of the meshes thesmelves could be lowered, saving GPU memory and disk space. </li></ul><p>One thing that did suck about this baked mesh approach was that the filesize of the built player exploded. The world was large, so the disk space for the game install went from ~2 GB to ~10 GB immediately. However, the runtime CPU savings were well worth it: down from the initial ~20ms to ~4ms. </p><h3 id="what-else-can-be-saved">What else can be saved?</h3><p>Because this approach worked so well for rendering savings on the CPU, I had to wonder: are there other things that can be trimmed down in a similar way? </p><ul><li>There's a huge runtime cost to instantiating prefabs with deep dependenies (prefabs nested in prefabs nested in prefabs). </li><li>The physics pass was actually pretty slow when a lot of the world was loaded (literally over 1 million static box colliders at times). </li></ul><p>These two big things were not too bad to deal with. The build system simply stripped out unmodified prefabs (no component overrides) from the built-level-chunks and stored them in a list, to have Unity later run an Async multi instantiation pass on. This had big frame hitch savings as players ran through the world, with the tradeoff being slight pop-in sometimes being visible. The physics pass was a bit tricker, but I managed to run a sort of 'greedy meshing'-like approach on box colliders throughout the built-level-chunks, which drastically reduced the typical number of loaded box colliders (down from 1 million to ~50,000 as the new peak). </p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://coty.tips/content/images/2026/11/euNldSmxZi.png" class="kg-image" alt srcset="https://coty.tips/content/images/size/w600/2026/11/euNldSmxZi.png 600w, https://coty.tips/content/images/size/w1000/2026/11/euNldSmxZi.png 1000w, https://coty.tips/content/images/2026/11/euNldSmxZi.png 1374w" sizes="(min-width: 720px) 720px"><figcaption>Static box collider merge pass. It definitely wasn't perfect, but did a pretty good job at mass combining box colliders.</figcaption></figure><p>After all of these changes, the game ran at 60 fps on my Steam Deck (maintaining a smooth 144 fps on my desktop PC). </p><hr><h2 id="the-pivot">The Pivot</h2><p>Scramble Knights later pivoted from "Battle Royale" into "MMO-lite" (a very Monster Hunter inspired take on the genre). With this change, the level editor mostly stayed the same, but there were some new requests for the runtime support of the systems. </p><p>One big ask was to have "instanced dungeons" exist, akin to something like going into <a href="https://www.wowhead.com/classic/zone=1581/the-deadmines">Deadmines </a>in <a href="https://worldofwarcraft.blizzard.com/en-us/">World of Warcraft</a>. </p><p>Because of how the level editor already structured existing dungeons as scriptable objects, it really was just a matter of changing how they were spawned in the world. Instead of spawning them somewhere underground, instanced scenes instead would use Unity's additive scene loading and physics world support. This worked pretty seamlessly, and had the added benefit of splitting up the physics simulation workload into smaller bite-sized chunks, which improved performance as the level and number of dungeons grew in size. </p><p></p>]]></content:encoded></item><item><title><![CDATA[Custom Netcode for a Battle Royale]]></title><description><![CDATA[<p>In 2026, I was working at <a href="https://www.funktroniclabs.com/">Funktronic Labs</a> when they released the game <a href="https://store.steampowered.com/app/2379350/Scramble_Knights_Online/">Scramble Knights Online</a> (as an Early Access title). We started working on this game as early as February of 2022. </p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://coty.tips/content/images/2026/11/image-14.png" class="kg-image" alt><figcaption>Scramble Knights Royale eventually became Scramble Knights Online.</figcaption></figure><p>In those early days, we were prototyping various game</p>]]></description><link>https://coty.tips/custom-netcode-for-a-battle-royale/</link><guid isPermaLink="false">6afd0fc96b7faa02a5f2120b</guid><dc:creator><![CDATA[Coty Getzelman]]></dc:creator><pubDate>Mon, 26 Oct 2026 17:00:00 GMT</pubDate><content:encoded><![CDATA[<p>In 2026, I was working at <a href="https://www.funktroniclabs.com/">Funktronic Labs</a> when they released the game <a href="https://store.steampowered.com/app/2379350/Scramble_Knights_Online/">Scramble Knights Online</a> (as an Early Access title). We started working on this game as early as February of 2022. </p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://coty.tips/content/images/2026/11/image-14.png" class="kg-image" alt><figcaption>Scramble Knights Royale eventually became Scramble Knights Online.</figcaption></figure><p>In those early days, we were prototyping various game modes. After a lot of iteration, the team decided on making a Battle Royale. The goals of this game were ambitious: </p><ul><li>64 player matches, potentially everyone vs everyone.</li><li>Physics based gameplay, using hitbox style melee fighting. </li><li>Proximity based voice chat, for maximum chaos. </li><li>Dedicated game servers, transiently scaling in and out as player counts ebbed and flowed. </li><li>Allow self-hosting custom matches (maybe modded?)</li></ul><p>I spent some time researching various networking solutions for Unity, but felt dissatisfied by many of them. Being as crazy as we were back then, I opted for writing a totally custom networking solution for Unity from scratch. </p><p><em>I'll spoil a bit: The game did not launch as a Battle Royale, but rather it was pivoted into an MMO-lite (sort of a Monster Hunter-like) right before hitting Early Access. Thankfully, all of the networking stuff carried over and even further evolved to meet the new goals. </em></p><figure class="kg-card kg-image-card"><img src="https://coty.tips/content/images/2026/11/ea276eccaf4b66d093c35ac129912827.gif" class="kg-image" alt></figure><hr><h2 id="where-to-start">Where to start? </h2><p>For big tasks like this, I like to split up stuff into chunks and work out each chunk at a time. Knowing that we wanted dedicated servers (including player-hosted), it was a classic server/client setup. </p><ul><li>Server would be always-on, listening for players to connect. </li><li>Clients would somehow know the IP:Port to connect to, and request to do so. </li><li>Server would respond to these clients with some simple handshake, exchanging information about the map and game settings. This would include all of the information clients would need about <em>each other</em> as well. </li><li>Clients would reply with information about their player, such as number of splitscreen participants, customization loadouts, that sort of thing. </li><li>Server would spawn the new clients players, and relay that information to everyone else already connected. </li></ul><figure class="kg-card kg-image-card"><img src="https://coty.tips/content/images/2026/11/image-15.png" class="kg-image" alt></figure><p>There were certain properties about the networking that became obvious, given the overall mechanical intentions of the game too:</p><ul><li>Things were bound to be fast paced, physics-oriented. This meant we very much needed to handle unreliable (UDP) streams of data. </li><li>Players had big blocks of data they would need to send, so of course we also needed to handle large in-order streams of reliable (TCP) data.</li><li>We wanted players to be able to communicate with voice via proximity chat. This could be handled unreliable or reliably, but either way needed a dedicated stream that is okay to fail on it's own, without blocking actual gameplay (TCP or UDP). </li></ul><p> These various streams of data meant that clients and the server each need to allocate various buffers of memory. How much exactly is somewhat arbitrary and so I'll gloss over details like that, but let me break down how things were laid out. </p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://coty.tips/content/images/2026/11/image-16.png" class="kg-image" alt srcset="https://coty.tips/content/images/size/w600/2026/11/image-16.png 600w, https://coty.tips/content/images/size/w1000/2026/11/image-16.png 1000w, https://coty.tips/content/images/2026/11/image-16.png 1028w" sizes="(min-width: 720px) 720px"><figcaption>From the perspective of a game server, every client each had their own set of streams (Reliable in, Reliable out, Unreliable in, Unreliable out, Voice in, Voice Out) plus some sort of scratch buffer for staging into and out of raw sockets.&nbsp;</figcaption></figure><p>Seeing that this data was essentially the same for the client and server, I wrapped this up in structure that looked similar to this: </p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://coty.tips/content/images/2026/11/image-17.png" class="kg-image" alt><figcaption>Each 'player' (note: the server is considered a 'player' from the perspective of a client). NetworkPlayers contain all of the buffers allocated for any other player, both their inputs and outputs.&nbsp;</figcaption></figure><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://coty.tips/content/images/2026/11/image-18.png" class="kg-image" alt><figcaption>NetworkBuffers contain their raw byte array, but also read/write indices, so they can be written to and read from in various stages of the networking pipeline.&nbsp;</figcaption></figure><p>The reason for splitting the buffers into all these inputs and outputs, with read/write cursors, is so we can think about things asynchronously as much as possible. Consider the following example CPU threads:</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://coty.tips/content/images/2026/11/image-19.png" class="kg-image" alt srcset="https://coty.tips/content/images/size/w600/2026/11/image-19.png 600w, https://coty.tips/content/images/size/w1000/2026/11/image-19.png 1000w, https://coty.tips/content/images/2026/11/image-19.png 1277w" sizes="(min-width: 720px) 720px"><figcaption>In theory, it's most optimal to read in network data before the GameUpdate, and then write out any outgoing data after GameUpdate, such that we never stall the main thread with networking work.</figcaption></figure><p>In practice of course, the server will have various network threads (a simple static thread pool is fine for 64 players, where the main thread sets a flag 'gooo!!!' and the worker threads grab the work that needs to be done and then idle until more work is available. That looks something like this: </p><figure class="kg-card kg-image-card"><img src="https://coty.tips/content/images/2026/11/image-20.png" class="kg-image" alt srcset="https://coty.tips/content/images/size/w600/2026/11/image-20.png 600w, https://coty.tips/content/images/size/w1000/2026/11/image-20.png 1000w, https://coty.tips/content/images/2026/11/image-20.png 1020w" sizes="(min-width: 720px) 720px"></figure><p><br>With this architecture in mind, I believed it would be easiest to have network messages simply flow in and out of the "networking layer" as raw bytes, while the "game layer" only sent in and got back out user-friendly structured messages. </p><p>Keeping these worlds entirely distinct in this way would allow me to focus on optimizing each piece on it's own, and keep most of the complicated networking bits hidden away from the other developers. Hopefully, this would lead to less bugs as the game was developed further. So, I started working out the game side of it first: a <code>NetworkMessage</code>. </p><p>Network messages would need to somehow be serialized, then those serialized bytes would be sent to other players and back. When receiving those bytes, they'd get deserialized back into network messages. </p><p>The hope was that the game would not necessarily need to care about <em>where</em> most messages came from and would allow each message to do whatever it needed on the event one came in. </p><h2 id="network-messages">Network Messages</h2><p>I wanted network messages to be extremely easy to write, to minimize the amount of bugs generated by other developers and myself. We're only human, and we're very prone to making mistakes. </p><p>So, I started with a simple <code>Interface</code>.</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://coty.tips/content/images/2026/11/image-21.png" class="kg-image" alt srcset="https://coty.tips/content/images/size/w600/2026/11/image-21.png 600w, https://coty.tips/content/images/2026/11/image-21.png 619w"><figcaption>This interface was kept as simple as possible. Tag a struct as a network message and give it some callbacks for the client and server separately. This allowed either to handle each message on a case by case basis.&nbsp;</figcaption></figure><p>Using this interface, the very first NetworkMessage was a simple ping. </p><figure class="kg-card kg-image-card"><img src="https://coty.tips/content/images/2026/11/image-23.png" class="kg-image" alt srcset="https://coty.tips/content/images/size/w600/2026/11/image-23.png 600w, https://coty.tips/content/images/2026/11/image-23.png 823w" sizes="(min-width: 720px) 720px"></figure><p>You might notice, there's a <code>[GameNetworkMessage]</code> attribute in there, too! As I was writing this first network message, it dawned on me that I absolutely did not want to hand write serialization/deserialization for every single network message by hand. The whole point of this system was to keep things easy to write for other developers. </p><p>So, my solution was to tag network messages with an attribute, then generate code at build time for automatically serializing and deserializing the public fields in any particular network message. </p><p>To start the prototype off simple, I simply hooked this step up into a button in the tools menu of Unity. You'd hit "Game -&gt; Refresh Networking" and all network messages would automatically generate <code>InternalNetworkMessage</code> structure variants with serialization/deserialization written out for you. </p><p>The auto-generated code would result in something like this:</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://coty.tips/content/images/2026/11/Code_IumeTEVTTe.png" class="kg-image" alt srcset="https://coty.tips/content/images/size/w600/2026/11/Code_IumeTEVTTe.png 600w, https://coty.tips/content/images/size/w1000/2026/11/Code_IumeTEVTTe.png 1000w, https://coty.tips/content/images/2026/11/Code_IumeTEVTTe.png 1227w" sizes="(min-width: 720px) 720px"><figcaption>Note: I did not expect other developers to be conciously aware of this internal-network-message layer, but it was visible and ready for easy debugging if necessary.</figcaption></figure><p>The code that generates code is fairly straightforward, it simply looks over structs that have the <code>[NetworkMethod]</code> attribute and fills out the text in a giant <code>InternalNetworkMessages.cs</code> file. </p><p>Then, using a network messages becomes as simple as: </p><figure class="kg-card kg-image-card"><img src="https://coty.tips/content/images/2026/11/image-25.png" class="kg-image" alt srcset="https://coty.tips/content/images/size/w600/2026/11/image-25.png 600w, https://coty.tips/content/images/2026/11/image-25.png 624w"></figure><p>At the time, this felt like a good solution to me. Write a simple network message, construct it, send it, that's it. Unfortunately I later came to realize that this was simply too many steps for most developers (even myself) as often things would go wrong somewhere in this process. <em>(I'll get back to this, later.)</em></p><hr><h2 id="the-bridge-between-networkmessages-and-bytes">The bridge between NetworkMessages and bytes</h2><p>At this moment in development, I was pretty happy with the game-side of things, the way network messages were kind of abstracted away from the actual networking that needed to be done. But now, I needed to actually start generating bytes and shuffling them around the internet. </p><p>Just a moment ago, I teased this method: <code>NetManager.SendMessage()</code>. Inside of here is where the transition from a structure into raw bytes happens. In a nutshell, there is a conversion from <code>NetworkMessage</code> to <code>InternalNetworkMessage</code>, and the <code>Internal*</code> variants contain the <code>Read</code>/<code>Write</code> buffer methods. But what would be to serialize things? There are plenty of libraries that do this, especially in c#. However, I do like to try and minimize dependencies where reasonable. So, I decided on writing serialization methods, and wanted to ensure that it would be easy to slot in more in the future. </p><p>To write a serialization/deserialization pair as simply as possible, I used attributes. I made <code>NetworkSerializeWriterAttribute</code> and <code>NetworkSerializeReaderAttribute</code>, which could be tacked onto any static method to designate it as a reader or writer for any struct or class. </p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://coty.tips/content/images/2026/11/image-26.png" class="kg-image" alt srcset="https://coty.tips/content/images/size/w600/2026/11/image-26.png 600w, https://coty.tips/content/images/2026/11/image-26.png 662w"><figcaption>This worked for basically any type. When "refreshing" the network code, it would automatically generate calls to these methods based on the types inside of a NetworkMessage.</figcaption></figure><p>I wrote out the read/write for all the base types in c# ( <code>int</code>, <code>string</code>, etc), as well as most of the Unity types (<code>Vector3</code>, <code>Quaternion</code>, etc).</p><hr><h2 id="a-problem">A Problem</h2><p>I loved this solution, on some sort of primal personal level. I like writing code, and I like knowing exactly where bytes are coming from and where they are going. However, not everyone is wired like this. When other engineers on the projected wanted to contribute to anything networking related, they often stumbled on this step in particular. Writing serialization, writing network messages, refreshing, remember which API to use. It was too much! </p><p>So I went back to the drawing board on this. I asked the other engineers what they actually wanted to do, most of the time. What they really wanted was pretty simple: "I want to call a method for all players." Almost always, that's all they wanted. Admittedly, thinking about it in hindsight, this should have been obvious. With this in mind, I thought about how I could change the workflow in order to allow them to do this more easily. </p><p>The solution I ended up with, I am very happy about even today: tag a method with a <code>[NetworkMethod]</code> attribute, and then everything is somehow magically handled for you. You can call that method, and it "just works" for all players in a match. </p><p>This was possible because of two things:</p><ul><li>There was already a 'refresh netcode' button, which was free to generate any necessary code. </li><li>The game is made in Unity, which uses C#, which has modifiable object code after compilation. </li></ul><p>I set it up such that code that looks like this: </p><figure class="kg-card kg-image-card"><img src="https://coty.tips/content/images/2026/11/image-27.png" class="kg-image" alt></figure><p>..would "just work". The steps to get there:</p><ol><li>Write out a method with an attached <code>[NetworkMethod]</code> attribute.</li><li>Hit the refresh netcode button in unity (whenever finished). </li><li>a <code>NetworkMessage</code> would automatially be built for you, somewhere hidden away. </li><li>An <code>InternalNetworkMessage</code> would automatically be generated from that, with serialization of parameters handled for you automatically too, using the methods above.</li><li>The compiled assembly ( <code>dll</code> ) would be 'weaved' automatically, replacing all instances of that method being called with the previously auto-generated <code>NetworkMessage</code>, feeding it through the appropriate API to send the message. </li></ol><p>This made the code a bit of a lie. However, this sped up development of anything netcode-related dramatically. The best part is that there really was not any overhead to the runtime for this, it really was doing the same work as manually writing all the code anyways. Much less bug prone, as a cherry on top. </p><hr><h2 id="bringing-it-all-together-">Bringing it all together.</h2><p>At this point, we have a bunch of parts:</p><ul><li>A work scheduler, for the server to communicate with various clients at once without stalling the main thread. </li><li>A system for writing <code>NetworkMessage</code>s manually</li><li>A system for writing <code>NetworkMethod</code>s manually, which auto generates <code>NetworkMessage</code>s.</li><li>A system for adding serialization/deserialization for any custom types. </li></ul><p>These bits were all the foundation of the networking plugin, and both individually and together everything seemed to work great. That is, until we started getting a lot of players in one area. </p><figure class="kg-card kg-image-card"><img src="https://coty.tips/content/images/2026/11/image-28.png" class="kg-image" alt srcset="https://coty.tips/content/images/size/w600/2026/11/image-28.png 600w, https://coty.tips/content/images/2026/11/image-28.png 660w"></figure><p>Even if these systems are great and fast at a fundamental level, the way code is written still matters a great deal. Most aspects of the initial prototype were very 'naive' in the sense that they did things at the most basic level. For example, players position updates would send their updates to every other player. And at a scale of 64 players, that's the server sending 64 * 64 = 4096 rigidbody updates every server tick (1/30), so 122,880/s * 76 bytes = ~9,000,000 bytes/s, or 9 MB/s. Not impossible, but a pretty insane number for JUST player updates. </p><p>Getting this number down to a more reasonable level could be achieved in a few ways. The first, most obvious one, is to simply crunch down the precision of the types being used in updates like this. </p><figure class="kg-card kg-image-card"><img src="https://coty.tips/content/images/2026/11/image-29.png" class="kg-image" alt></figure><p>Rotations don't need to be full quaternions for basically anything, in this game in particular, so just send the axis Y rotation. Velocities really do not need to be full precision in basically any scenario, so crunch them down. Unfortunately, positions really do need to be higher precision or you start losing visual quality pretty drastically, so those were left alone. These little changes got us from 72 bytes to 50 bytes, not bad! That takes us from about 9MB/s to 5MB/s, which is still way too high. Something needed to change at a fundamental-systems level. </p><h2 id="taking-everything-apart-">Taking everything apart. </h2><p>Running through the project's <code>NetworkMessage</code>s and crunching compressions was definitely worth doing, but it was not going to be enough as a long term solution to keeping bandwidth low. I needed to find a way to be able to determine if any particular message was actually worth sending to any other particular player. At 64 players it may not seem unreasonable to simply do a basic distance check "is this player too far from me? skip sending the message", but ~4,000 distance checks for a single message, and the fact there's hundreds of messages being send per frame, means we may potentially be performing millions of (redundant) distance checks over and over. </p><p>One early idea I had was to simply cache them, but even performing 4,000 distance checks per frame seemed a bit wasteful to me, and in practive it still turned out to be pretty slow (because it turned out it wasn't just distance checks for rigidbody updates, but you really need arbitrary checks from any position to any player, as you do not know what will generate network messages ahead of time). </p><p>Because of some past experience with voxel tech, I tend to think about everything in terms of 'chunks' or 'buckets,' so when I thought about this problem an interesting solution came to me: Split the world into distinct chunks, then do a distance check for every player to every chunk, once per server tick. Then, if a network message is generated, only send it to players within range of the chunk it originated from! </p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://coty.tips/content/images/2026/11/image-30.png" class="kg-image" alt srcset="https://coty.tips/content/images/size/w600/2026/11/image-30.png 600w, https://coty.tips/content/images/2026/11/image-30.png 691w"><figcaption>If player A is very far from player B, they'll be in far away 'chunks' in the world. In this case, any NetworkMessageRigidbodyUpdate that would be generated by A, would never reach B.</figcaption></figure><p>My first implementation of this system was successful, although it was a bit slow. Luckily, this kind of problem was perfect for the Unity Job System, and so I rewrote it as a multi-step job. </p><ul><li>Gather a list of game client's player positions.</li><li>Put them into 'buckets' or 'chunks', by taking their position (<code>float3</code>) and dividing it by some arbitrary value (<code>chunk_size</code>). Clamp it into an <code>int3</code> and use that a key into a <code>Dictionary&lt;int3, Chunk&gt;</code></li><li>For every player, maintain a list of <code>visible_chunks</code> (a <code>List&lt;int3&gt;</code>). The list would simply contain their current chunk, and all touching neighbor chunks (the 3x3 grid, essentially). </li><li>When any <code>NetworkMessage</code> tries to <code>SendAll()</code>, when iterating over players it will check if the <code>NetworkMessage</code>'s origin position's chunk is in the list of <code>visible_chunks</code> for each player. If not, the player is skipped. </li></ul><p>Because of how the game was structured, this was a huge huge win. Typical network usage dropped from the 10s of MB down to KB per second, when idle. </p><h2 id="going-even-further-beyond">Going even further beyond</h2><p>At this point, I was very happy with the results. But, KB/s was still really not good enough. I kept thinking to myself "surely that's too many bytes." "What is actually being sent?" was another thought that often popped into my head. So, at some point I finally started logging the NetworkMessages and seeing what was really eating up all that bandwidth. </p><p>I expected the number 1 thing to be rigidbody updates, since they are so frequent and there are a lot of synced rigidbodies. But, to my surprise, it was actually 'visibility updates'. These were a result of the chunked system I described above: when a player crossed a chunk boundary, the server kept track of what objects were in which chunks, and so it would send a batched "destroy these objects" and "create these objects" to that player. This kept the object count low for players, ensuring they were not wasting time with offscreen objects. But, players run around the world a lot. And these messages added up fast, mostly because they contained string <code>GUID</code>s of prefab references into the asset bundle system. "spawn tree" "destroy crate" etc. </p><p>Seeing this, I felt like it could be resolved if the strings themselves could easily be compressed. After all, they're just <code>GUID</code>s right? They shouldn't eat up that much space. I think this would have been a valid pursuit, but I actually ended up doing something a bit more generalized: I compressed the entire network stream. </p><p>My first attempt at compressing the stream was very basic: run length encode (RLE) the stream, byte by byte. This did work, but I did not see much of a gain out of it. Bytes were just too random! So I printed out a chunk of the network stream as bytes and stared at it for awhile.  </p><figure class="kg-card kg-image-card"><img src="https://coty.tips/content/images/2026/11/image-31.png" class="kg-image" alt></figure><p>After looking at the raw byte stream for awhile, I was thinking about what is actually in the bytes most of the time. The raw stream always contained this, just over and over: </p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://coty.tips/content/images/2026/11/image-32.png" class="kg-image" alt srcset="https://coty.tips/content/images/size/w600/2026/11/image-32.png 600w, https://coty.tips/content/images/size/w1000/2026/11/image-32.png 1000w, https://coty.tips/content/images/2026/11/image-32.png 1257w" sizes="(min-width: 720px) 720px"><figcaption>The size is 2 bytes, ID is 2 bytes, contents are variable.</figcaption></figure><p>And the contents themselves contained data that often looked like this:</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://coty.tips/content/images/2026/11/image-33.png" class="kg-image" alt srcset="https://coty.tips/content/images/size/w600/2026/11/image-33.png 600w, https://coty.tips/content/images/size/w1000/2026/11/image-33.png 1000w, https://coty.tips/content/images/2026/11/image-33.png 1413w" sizes="(min-width: 720px) 720px"><figcaption>strings were an <code>int</code> (4 bytes) size, then <code>int</code> (4 bytes) char, char, char.</figcaption></figure><p>If you squint, you may notice that almost everything here is either 4 bytes or 2 bytes. Nothing of consequence is JUST one byte. So I had an idea, why not run RLE but over 4 bytes at a time? </p><p>This actually worked very well! I started to see ~50% less network bandwidth being used across the board. Often, idling was as small as ~500 bytes per second. </p><p>This was pretty good, I thought. But, if I was able to do this by just thinking about it, I'm pretty sure someone smarter had a much more elegant solution. I did a little research about how Unity handles compression in general and came across LZ4. </p><p>I won't get into the details of LZ4 compression, because, franky, I have absolutely no clue. It's basically a magic black box written by some genius, from my perspective. I found a single file c implementation of it, then ported it into c# and made that code compatible with Unity's Burst compiler so it could be run as a basic static method within my network jobs. </p><p>My first test of this was an even biggest success than my silly 4-byte RLE test, I saw 80%-90% reductions in bandwidth across the board. 👏Great, I was very satisfied with this. LZ4 was even pretty good at compressing seemingly random data, such as rigidbody updates and voice packets. </p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://coty.tips/content/images/2026/11/image-34.png" class="kg-image" alt><figcaption>Running around the overworld with many other players, uploading ~300bytes/s downloading ~4.6kb/s</figcaption></figure><hr><p>With these two methods combined (chunking the world for visibility culling and network stream compression), bandwidth was in a shippable spot. </p><p>After this, I spent some time on abstracting out the "Transport Layer" of the plugin, so the game could support using Epic Online Services as a transport backend for p2p connections and also support raw c# sockets for typical dedicated servers. This was pretty straightforward, more or less what you'd expect, so I won't ramble about it here. </p><hr><p>At this point, I felt the "networking plugin" aspect was more or less complete. Everything that came after was moreso about how to effectively engineer the game itself, without having to think too hard about netcode awhile doing so. </p>]]></content:encoded></item><item><title><![CDATA[Hitting 90z on the Quest 2]]></title><description><![CDATA[A short bio on the development of The Light Brigade. ]]></description><link>https://coty.tips/hitting-90z-on-the-quest-2/</link><guid isPermaLink="false">6afb7f256b7faa02a5f20ff2</guid><dc:creator><![CDATA[Coty Getzelman]]></dc:creator><pubDate>Wed, 22 Feb 2023 18:00:00 GMT</pubDate><content:encoded><![CDATA[<p></p><p>In 2023, I worked at <a href="https://www.funktroniclabs.com/">Funktronic Labs</a> and we released <a href="https://store.steampowered.com/app/1579880/The_Light_Brigade_Definitive_Edition/">The Light Brigade</a>. This was a VR shooter, which needed to run at 90hz on a Quest 2 (and also released on Steam for PC headsets). </p><p>From the store page:<em> "An award-winning roguelike VR shooter with realistic gunplay &amp; immersive light magic."</em></p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://coty.tips/content/images/2026/11/image.png" class="kg-image" alt><figcaption>The Light Brigade (Steam Store Capsule)</figcaption></figure><p>This game needed to be able to run at 90hz on a Quest 2. As usual, development began on the Steam version (PC) and the team grinded away and getting things working, before making them fast. </p><p>The development of the game set out with some clear goals, from pretty early on: </p><ul><li>It needed to be fun. </li><li>It needed to feel larger than life (scale in VR can be huge!)</li><li><strong>Levels needed to be procedural</strong>.</li><li>The gunplay had to feel incredible. </li></ul><figure class="kg-card kg-image-card"><img src="https://coty.tips/content/images/2026/11/0f81c2454b3b9fced88f6481ad8ef452.gif" class="kg-image" alt></figure><p>We knew that the levels needed to be procedural, in order to ship a title like this from the small team at Funktronic. The prototyping of different procedural generation methods was handled by the company cofounder, <a href="https://www.linkedin.com/in/eddietree/">Eddie Lee</a>. After a few different methods, he found that Wave Function Collapse (WFC) was the best option for The Light Brigade. </p><p>A brief overview of how WFC works:</p><ul><li>Define a lot of 'tiles' (in this case, small chunks of the world).</li><li>Setup connection rules for how any particular tile is allowed or not allowed to connect to every other tile. </li><li>Slot in a START and END tile (start of level, end of level).</li><li>Based on a seed, randomly select neighbor tiles around the start until you flood fill the level until the end, accepting only valid connections. </li></ul><p>The end result is that you can get a pretty reasonable looking level, with some simple rules. Funktronic hired a level designer (<a href="https://www.linkedin.com/in/eddie-peters-70372649/">Eddie Peters</a>) to hand tweak values over and over until the levels started to look almost hand crafted. </p><figure class="kg-card kg-image-card"><img src="https://coty.tips/content/images/2026/11/90f77f1b-1a35-4437-9bd2-73b96e3e2829.gif" class="kg-image" alt></figure><hr><h2 id="the-problem-s-">The Problem(s)</h2><p>The levels looked great. Design goals were met: scale was incredible, levels felt immersive, and a player could easily get lost in huge levels. Unfortunately, the levels and general content was <em>too much</em> for the Quest 2 to handle. When we first tried to get this game running on the Quest 2, we were met with frequent Out-of-Memory crashes, single-digit framerates, and WFC-generation times in the tens of minutes. It was rough! </p><p>But, all was not lost. I took a deep hard look at what was going on, and came up with a game plan at tackling it. My goal: get this game running at full framerate with NO frame drops, without sacrificing the core values of the game itself, and to keep the game 100% the same mechanically across platforms. I wanted things so similar between versions, you could copy/paste your save file from Quest ot PC and just keep playing (spoiler: this works!). </p><figure class="kg-card kg-image-card"><img src="https://coty.tips/content/images/2026/11/levels.gif" class="kg-image" alt></figure><p>So, what was actually wrong? When I started profiling, it seemed almost hopeless. Everything was slow! Rendering (GPU at 100%, CPU at 100%, RAM near 100%). Opening the Unity profiler, I was met with a timeline that looked like it stretched into eternity. So, where to start? </p><p>For issues like this, I try to tackle the most glaring issues first. Looking at the Unity profiler timeline, the lowest hanging fruit was the time the CPU spent issuing commands to the GPU. The main thread spent well over 50 ms simply issuing commands, stalling everything else in the process. The next largest issue was clearly the time the GPU spent on grinding through those commands. The rest of the timeline was pretty large too, but I figured once we resolved whatever this was, we might be able to take on the rest after. </p><p><em>( The Light Brigade shipped with Unity 2021.3 using a custom fork of URP, for reference.  )</em></p><hr><h2 id="break-downs">Break Downs</h2><p>With rendering being such a huge part of the CPU profiler timeline, I knew two things must be true:</p><ol><li>We're doing too much.</li><li>We're doing something wrong. </li></ol><p>When performance is this bad right out of the gate, it's tempting to start cutting things. However, I found that there were quite a few low hanging fruit all over the project. I'll spare you the boring details, but to cut a long story short there were many instances of double-renderers, LODs were not setup anywhere properly, everything was casting shadows. Grinding through all of this basic stuff, I managed to get performance down to a more reasonable level. We went from a ballpark of ~50 ms on the CPU down to ~20 ms. </p><p>To take this a step further, I needed to come up with a way to really reduce the amount of work Unity was doing every frame. Unity does have a magical function: <a href="https://docs.unity3d.com/2023.1/Documentation/ScriptReference/StaticBatchingUtility.html"><code>StaticBatchingUtility</code></a><code>.Combine()</code> - this method will attempt to combine meshes into a format that allows the engine to draw things more efficiently. In theory, Unity can combine many meshes into a single buffer, then use faster <code>DrawMesh()</code> methods with index offsets into that giant buffer. Unfortunately, using this method actually resulted in <em>slower</em> rendering in the Light Brigade. So, I wrote a custom static batch utility. My reasoning for why Unity's must be slow: <a href="https://discussions.unity.com/t/unitys-static-batching-why-does-it-shoot-itself-in-the-foot/827372">they don't take spatial contiguity into consideration</a>, and WFC-nature of this game would heavily benefit from that. </p><h3 id="my-static-mesh-baker">My Static Mesh Baker</h3><p>Because I was writing one just for this project, I aimed to keep it simple. The idea:</p><ul><li>Slap a <code>BakeStaticMeshGroup</code> component above a group of static objects, in the transform hierarchy.</li><li>Bake these meshes (either manually via a button on the component, or during Build time). </li><li>Don't have to think about it. </li></ul><p>There are definitely other ways of going about this, such as baking at runtime on-device, after a WFC level has been built. But, this needed to run on Quest and I did not want to do anything that would negatively impact load times, at this point. So, with this in mind the <code>BakeStaticMeshGroup</code> was created. How it worked:</p><ol><li>Gather all meshes under the node.</li><li>Do some bookkeeping to track which meshes could be merged with which others, based on Materials. </li><li>Combine the meshes, serialize to disk. Copy materials (so modifications don't carry over). Modify materials if necessary. </li><li>Automatically merge LODs, too. </li><li>Disable Shadows on LOD0, duplicate renderer so LOD0 shadows were actually LOD1. </li><li>Disable the original assets in the scene (so the process could be reverted). </li><li>At build time, delete the original assets in the scene (so they don't clutter the game at runtime). </li></ol><p>Some extra goodies that ended up coming out of this system: I found that we did not need full precision of meshes. Everything was pretty tightly contained in small chunks, and the batcher could take advantage of that and aggressively lower precision (<code>vert</code>:  <code>float16</code>, <code>normals</code>: <code>float16</code>, <code>tangent</code>: <code>unorm8</code>, <code>color</code>: <code>unorm8</code>, <code>uvs</code>: <code>float16</code>). This resulted in a small bump in GPU performance, and pretty drastic memory reductions. </p><h3 id="what-else-could-be-merged">What else could be merged?</h3><p>This static mesh baker was a good start, but we also had a problem of drawing too much when it came to enemies. Enemies were mostly humanoid, and they used a system similar to what you'd find in a game with a flexible character creator. They had a whole 'equipment' system similar to what you'd typically see for players, and would have outfits procedurally generated at runtime. For some aspects of this game, this would affect things mechanically. For some aspects, this was purely cosmetic. Either way, it resulted in a LOT of SKINNED mesh renderers. At the time, Unity's animator was not friendly at dealing with this. GPU skinning was not yet batched, so all of these individual skinned computations were being done one draw at a time. </p><p>So, I wrote a <code>SkinnedMeshCombiner</code> script, to try and merge things as much as possible. The idea:</p><ul><li>Spawn things as normal, procedurally building an enemy's outfit. </li><li>When it's finished, gather all the meshes and materials, determine what is combinable. </li><li>Then, combine aggressively (and, compress!)</li></ul><p>This ended up working great, as well. Enemies went from ~10-15 unique renderers per enemy down to ~1-3 per enemy. As a bonus, the same mesh compression trick from the static batcher worked on the skinned mesh combiner. Unfortunately, I had to keep positions at a higher precision (<code>float32</code>), but everything else could be crunched all the same. </p><p>One issue I ran into with combining skinned meshes: the bone list from one mesh to the next was often different. Unity seemed to only import the bones necessary for animation per mesh (or maybe they were exported that way, I'm not 100% sure). Either way, I needed to handle this. I ended up writing a <code>BoneRemapper</code> helper, which was a jobified system to simply iterate over the known bones and re-map them as necessary, before and after a skinned mesh combine pass. </p><h2 id="what-else-could-be-done">What else could be done? </h2><p>With both static and dynamic renderers being aggressively merged across the project, and LODs setup properly, double renderers fixed, shadows being LOD biased up by one, performance was <em>still</em> pretty rough, often over ~10ms on the CPU side of things. </p><p>Looking at the profiler, I knew something was wrong with how graphics were being drawn on the Quest. The main thread was doing a lot of work, and tons of job threads were sitting empty. This seemed wrong, as we had Graphics Jobs and Multithreaded rendering both enabled in the Project Settings. </p><figure class="kg-card kg-image-card"><img src="https://coty.tips/content/images/2026/11/Unity_JMTTScrvxE.png" class="kg-image" alt srcset="https://coty.tips/content/images/size/w600/2026/11/Unity_JMTTScrvxE.png 600w, https://coty.tips/content/images/size/w1000/2026/11/Unity_JMTTScrvxE.png 1000w, https://coty.tips/content/images/2026/11/Unity_JMTTScrvxE.png 1238w" sizes="(min-width: 720px) 720px"></figure><p>Through some trial and error, I found that disabling graphics jobs and enabling multithreaded rendering drastically decreased the work being done on the CPU. I was so shocked by this, I actually <a href="https://discussions.unity.com/t/vulkan-bug-quest-2-urp-graphics-jobs-no-multithreaded-rendering-slow/864629">asked about it</a> on the Unity forums, assuming it was a bug. </p><p>Unfortunately, the answer I was given was a bit disappointing: </p><figure class="kg-card kg-image-card"><img src="https://coty.tips/content/images/2026/11/image-1.png" class="kg-image" alt srcset="https://coty.tips/content/images/size/w600/2026/11/image-1.png 600w, https://coty.tips/content/images/size/w1000/2026/11/image-1.png 1000w, https://coty.tips/content/images/2026/11/image-1.png 1280w" sizes="(min-width: 720px) 720px"></figure><p>Enabling Graphics Jobs would actually implicitly disable LZR/HSR?!?! This was unfortunate, but it was nice to get a confirmation about it. But, you might be wondering, what is he talking about?</p><h3 id="early-z-rejection">Early Z Rejection</h3><p>The Quest 2 uses a Qualcomm Snapdragon XR2, a mobile chip which handles graphics with a deferred pipeline. Not deferred in the typical graphics-pipeline sense (deferring lights to a separate pass), but deferred in that you submit all your triangles and the hardware will actually try to early-z reject as many of them as possible, to save on fragment shading costs. </p><p>The main takeaways with this are:</p><ul><li>Developers should lean into early-z-rejection as much as possible. </li><li>When it's working, the GPUs fragment time should be quite low. </li><li><a href="https://web.archive.org/web/20211011233004/https://developer.qualcomm.com/sites/default/files/docs/adreno-gpu/developer-guide/gpu/faq.html#what-causes-lrz-to-be-disabled">A lot of stuff can break it</a>, AVOID BREAKING IT.</li><li>Verify things are working via RenderDoc as often as possible. </li></ul><p>We knew about this feature early on in development and made a constant conscious effort to avoid breaking it. The number 1 rule was NO TRANSPARENCY (with a few exceptions). If you take a deep look at The Light Brigade, even on the PC version, you'll notice there is very little transparency at all. Everything is mesh particles, lights, or custom fog. The artists (<a href="https://www.linkedin.com/in/pat-vince-9997631b/">Pat</a>, <a href="https://www.linkedin.com/in/katrinatankit/">Kat</a>, <a href="https://www.linkedin.com/in/digitalarob/">Alex</a>) were all extremely good at utilizing various techniques at faking transparency. My personal favorite thing they often did: flip the cull mode on a round object to make it seem like you were looking through it (the fire used this, for layering materials). </p><p>Knowing that the hardware pipeline is going to handle rejecting triangles for us, I had a thought: why bother sorting? I disabled Unity's sorting of opaque objects via <code>Camera.opaqueSortMode = OpaqueSortMode.NoDistanceSort</code> - this essentially tells Unity to skip sorting entirely and push straight to the GPU. After doing this, I verified that the CPU time went slightly down, and the GPU time stayed immeasurably the same. </p><h3 id="instanced-stereo-rendering-multiview">Instanced Stereo Rendering / Multiview </h3><p>The Quest 2 has two lenses that peer into a single display. However, this display needs to be rendered to twice, one for the left eye and one for the right. By default, in the version of Unity we were using at the time, Unity would simply render everything twice. This is called "Multi-Pass Rendering". It's the easiest to do because it has no extra setup required and 'just works' for basically every game. The obvious tradeoff is: everything takes twice as long to do. You submit everything on the CPU twice, you draw everything on the GPU twice. There's a lot of wasted effort going on.</p><p>Now a days, if you are using URP / ShaderGraph, this is typically handled for you. But during the development of The Light Brigade, we had an entirely custom shader library. Thankfully, this wasn't actually too much of a hassle to handle. Unity has a few built in macros that you slap around your shaders, and everything mostly just works. </p><p>Implementing Multiview resulted in a near halving of our CPU side costs and a small reduction of in the GPU costs. </p><p>Verifying this was working required attaching the Unity Frame Debugger and checking that Unity was rendering into a texture array, instead of a typical texture. </p><h3 id="shader-complexity">Shader Complexity</h3><p>Register pressure ended up being a constant headache on Quest 2 version of The Light Brigade. This was mostly a consequence of very complex shaders, in every conceivable metric. They were long, had lots of branches, sampled from many many textures, and were tricky to debug. </p><p>One of the first things I did when joining the project was to try and "unify then simplify" the entire shading pipeline. I wrapped everything up in macros, unified as much code as possible, and implemented custom fog and lighting through those <code>#include</code>s and macros. </p><p>When it was all said and done, every shader flowed through the same lighting and fog passes, which were configurable at both global and material levels. I minimized the number of keywords as much as reasonably possible given the timeframe, and removed almost every branch. Not all branches are evil, of course, but many really needed to go. </p><p>After going through these low hanging fruit, I tried to find what else could be optimized away. Through profiling, trial-and-error, and good old reasoning, I found that the biggest gains I could achieve would be by hoisting as much as possible OUT of the fragment passes and IN to the vertex passes. This turned out to be relatively easy, but I did eventually run into more performance issues by shoving too much into the vertex interpolators. Profiling with RenderDoc, I found that register pressure was the biggest bottleneck, so converting as many <code>float</code>s into <code>half</code>s as possible actually gave extremely significant gains across the board, on the GPU. </p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://coty.tips/content/images/2026/11/image-12.png" class="kg-image" alt srcset="https://coty.tips/content/images/size/w600/2026/11/image-12.png 600w, https://coty.tips/content/images/2026/11/image-12.png 950w" sizes="(min-width: 720px) 720px"><figcaption>The end result was very close to this, where most of the vertex structure was lower precision and many things that could be calculated in the fragment (especially related to lighting) were moved into the vertex pass, then passed along in the interpolator.&nbsp;</figcaption></figure><p>I also found that doing as much on the CPU and passing it along to the GPU as possible was essentially free gains, anywhere it could feasibly be done. </p><p>To a lesser degree, I occasionally found it useful to use Unity's <em><strong>Compile and Show Code button</strong></em>, in order to really dig deep and figure out if something was being compiled in a silly way, due to the design of the shader or various other factors. Sometimes, simply shuffling things around or re-writing things in another way (re-framing the problem) would result in more code being vectorized, which almost always resulted in some minor gains. </p><figure class="kg-card kg-image-card"><img src="https://coty.tips/content/images/2026/11/image-13.png" class="kg-image" alt srcset="https://coty.tips/content/images/size/w600/2026/11/image-13.png 600w, https://coty.tips/content/images/2026/11/image-13.png 689w"></figure><figure class="kg-card kg-image-card"><img src="https://coty.tips/content/images/2026/11/devenv_QYmg4Rw7Qk.png" class="kg-image" alt srcset="https://coty.tips/content/images/size/w600/2026/11/devenv_QYmg4Rw7Qk.png 600w, https://coty.tips/content/images/size/w1000/2026/11/devenv_QYmg4Rw7Qk.png 1000w, https://coty.tips/content/images/2026/11/devenv_QYmg4Rw7Qk.png 1042w" sizes="(min-width: 720px) 720px"></figure><p>In older versions of Unity, with simpler shaders on your plate, this method could be quite useful for debugging the behavior of things with shaders. However now a days it's not quite as useful, as Unity needs to compile ALL variants to get you this file. Another option available to you is actually RenderDoc's shader resource view, especially if you're using Vulkan and are comfortable reading vulkan's assembly language. The main thing I've found useful to watch for is vectorization.  </p><h3 id="sampler-counts">Sampler Counts</h3><p>One of the major issues with mobile GPUs is their lack of VRAM and small cache sizes. Texture/sampler caches are tiny, so developers need to keep that in mind. Cutting this down in The Light Brigade was done in a few ways:</p><ul><li>Aggressively combine textures, to reduce sample counts. </li><li>Drastically reduce texture sizes, for less texture cache misses. </li><li>Sample extremely small textures in vertex shaders, not just in fragment shaders. Interpolate. </li></ul><p>If noise was ever needed, we used a multi-channel noise texture, with very unique settings on each channel. Needed a lot of noise samples? Just read from the R, G, B, and A channels independently. Essentially any use of "texture A is used as an input to sample from texture B" was banned on the Quest port (ruined texture cache hits, constantly stalled fragment shaders). This was done via shader compiler defines (<code>#ifdef</code> / <code>#endif</code>). </p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://coty.tips/content/images/2026/11/image-4.png" class="kg-image" alt><figcaption>Two unique noise textures, with totally different settings.</figcaption></figure><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://coty.tips/content/images/2026/11/image-5.png" class="kg-image" alt><figcaption>The same noise textures, but only using a single channel (R, then G).</figcaption></figure><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://coty.tips/content/images/2026/11/image-6.png" class="kg-image" alt><figcaption>Both noise textures combined into a single texture (RG), only one sample required to access data from both textures.</figcaption></figure><p>The Light Brigade used a typical toon-ramp texture setup, but on the Quest 2 version of the game I moved the ramp texture into the vertex pass rather than the fragment pass. In fact, most of the lighting was handled in the vertex shader on the Quest version. You can see this 'mode' on steam if you lower the shader quality settings to the minimum. </p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://coty.tips/content/images/2026/11/image-7.png" class="kg-image" alt><figcaption>A simplified toon ramp texture.</figcaption></figure><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://coty.tips/content/images/2026/11/image-8.png" class="kg-image" alt><figcaption>Of course, only using one channel (R). Possible to combine channels for different light settings, if necessary.&nbsp;</figcaption></figure><h3 id="application-space-warp">Application Space-Warp</h3><p>After all of this was done, we were able to <em>mostly</em> hit 72 fps (base target on Quest 2). BUT! What if we could go further? 72 was OK, but if the game could run at 90 fps it would really feel good. I did spend some more time optimizing shaders but felt that I had essentially hit a wall. Any further gains would have to be large structural changes to how things were developed, and we did not have time for that. </p><p>In comes: Application Space-Warp (ASW). The idea:</p><ul><li>Render a motion vector texture. Feed it into the Quest 2's pipeline.</li><li>Quest 2 will generate in-between frames via interpolation. </li><li>You get 1 frame of latency added, but render twice as many frames. </li></ul><p>In theory, we could render at 45 fps (!!!) and get a smooth 90 hz output. This sounded too good to be true, and honestly I was extremely skeptical about it. Surely the extra latency would give motion sickness, or I would notice weird artifacting? Well, I tried their demos and was very impressed. </p><p>So I thought to myself, why not? I'll spend a day or two on this and see where it goes. At that time in development, you had to download a custom fork of URP in order to generate the motion vectors required for ASW to process. This turned out to be a whole thing, because our render/shading was so customized. I had to go through all of the shaders and use their special macros for generating motion vectors (custom pass), and be very careful about what exactly was being rendered. I also ran into some issues with general motion in the game resulting in full-screen incorrect vectors, but after some fiddling with the URP source I did eventually get this all sorted. </p><p>The end result really shocked me: everything basically looked the same, but ran much smoother. What a dream come true? We were optimizing for 72 fps, and suddenly now we only had to hit 45 fps?!?! I don't have much more to say here, Meta really knocked the ball out of the park on this feature, it was incredible to have. It bridged the gap from 72 fps to 90 fps!  </p><p>That being said, there were many nuances to take into consideration. What to do with (the few) semitransparent objects? What about quickly rotating renderers? What about very fast projectiles? What about teleporting? </p><p>For semitransparent things (such as UI cards) I ended up just placing an 'invisible' (motion-vector-only) renderer behind them, which more or less resolved most artifacts around them. I also modified our motion vector macro to clamp rotation and velocity values, to avoid huge artifacts from sudden movements or unnatural rotations. When teleporting, I had the whole system actually disable and then re-enable a frame later. I was worried this would be a noticeable frame drop, but surprisingly turned out to be seamless. </p><h3 id="shader-stutters">Shader Stutters</h3><p>Towards the end of development, we had the game relatively stable at 45 fps (90 hz), but would very often get frame drops. After some investigating, these turned out to be typical shader stutters you see in many modern games. </p><p>The solution was pretty straightforward: after WFC generation, gather a list of materials and pre-render everything once. I also included a small list of 'spawnables' to pre-spawn and pre-render. The code looked something like the following: </p><figure class="kg-card kg-image-card"><img src="https://coty.tips/content/images/2026/11/image-10.png" class="kg-image" alt></figure><p>The idea was to grab all the unique pairs of "material data" and "mesh data" that existed in the scene, and render them once (we did some per-frame batching, a little more complicated than this - but simplified for this example). A unique pair meant that the vertex attributes + shader + shader keywords + some material settings matched, not necessarily unique materials or unique meshes. Since we were using Vulkan, almost every setting mattered when it comes to compiling every shader variant, so often there would be a couple hundred draws at the start of each level. </p><p>This effectively reduced <em>almost</em> all frame drops to zero. The remaining ones tended to come from synchronous loads happening from object instantiations; those were solved by going through and making them asynchronous instantiations where possible. </p><hr><h2 id="conclusion">Conclusion</h2><p>The Light Brigade was about a 3 year project, with lots of effort from every developer involved. We managed to get it running very smoothly on the Quest 2, and later added extra graphical options when doing the Quest 3 port. I was very pleased with many of the tools available to us from Unity and from Meta, and especially grateful for RenderDoc. It was a tough journey, but I think everyone involved was greatly satisfied with the result. </p><p>If you haven't played the game, please check it out on <a href="https://store.steampowered.com/app/1579880/The_Light_Brigade_Definitive_Edition/">Steam</a>. It's compatible with most headsets as of the time of writing. </p>]]></content:encoded></item><item><title><![CDATA[Raytracing in Unity's built-in render pipeline]]></title><description><![CDATA[Getting started with Raytracing in Unity, using the Raytracing API directly.
]]></description><link>https://coty.tips/raytracing-in-unity/</link><guid isPermaLink="false">5fb215f4882de638e3645857</guid><category><![CDATA[raytracing]]></category><category><![CDATA[rtx]]></category><dc:creator><![CDATA[Coty Getzelman]]></dc:creator><pubDate>Thu, 03 Dec 2020 17:22:17 GMT</pubDate><media:content url="https://coty.tips/content/images/2020/11/Unity_GKqZOSxtwj-1.png" medium="image"/><content:encoded><![CDATA[<img src="https://coty.tips/content/images/2020/11/Unity_GKqZOSxtwj-1.png" alt="Raytracing in Unity's built-in render pipeline"><p></p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://coty.tips/content/images/2020/11/Unity_GKqZOSxtwj.png" class="kg-image" alt="Raytracing in Unity's built-in render pipeline" width="1578" height="850" srcset="https://coty.tips/content/images/size/w600/2020/11/Unity_GKqZOSxtwj.png 600w, https://coty.tips/content/images/size/w1000/2020/11/Unity_GKqZOSxtwj.png 1000w, https://coty.tips/content/images/2020/11/Unity_GKqZOSxtwj.png 1578w" sizes="(min-width: 720px) 720px"><figcaption>Raytraced Reflections and Shadows</figcaption></figure><hr><p>Unity 2019 added an API for DX12's RTX stuff. Nice, finally!</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://coty.tips/content/images/2020/11/brave_AjqZilvHsd.png" class="kg-image" alt="Raytracing in Unity's built-in render pipeline" width="530" height="74"><figcaption>Oh wait.. guess I'll come back to this later.</figcaption></figure><!--kg-card-begin: html--><center><img src="https://uploads.coty.tips/7TaK4G8TA.gif" width="200" height="200" alt="Raytracing in Unity's built-in render pipeline"> </center><!--kg-card-end: html--><p></p><p>It's later! Unity 2020.1 now has skinned mesh renderer support! Time to play around a bit.</p><hr><h2 id="what-s-new">What's New?</h2><p>There's a few new juicy additions to Unity's scripting API.</p><ul><li><a href="https://docs.unity3d.com/2020.2/Documentation/ScriptReference/Experimental.Rendering.RayTracingShader.html">RayTracingShader</a> - a new special type of shader which is used to generate rays, for querying geometry intersections. </li><li><a href="https://docs.unity3d.com/2020.2/Documentation/ScriptReference/Experimental.Rendering.RayTracingAccelerationStructure.html">RayTracingAccelerationStructure</a> - a GPU memory representation of the geometry to ray trace against. </li></ul><h2 id="getting-started">Getting Started</h2><p>If you are starting from scratch, the very first thing you need to do is to generate a <a href="https://docs.unity3d.com/2020.2/Documentation/ScriptReference/Experimental.Rendering.RayTracingAccelerationStructure.html">RayTracingAccelerationStructure</a>. Here's a simple example to get started.</p><figure class="kg-card kg-code-card"><pre><code class="language-c#">var settings = new RayTracingAccelerationStructure.RASSettings();
settings.layerMask = UpdateLayers;
settings.managementMode = RayTracingAccelerationStructure.ManagementMode.Automatic;
settings.rayTracingModeMask = RayTracingAccelerationStructure.RayTracingModeMask.Everything;

_AccelerationStructure = new RayTracingAccelerationStructure(settings);</code></pre><figcaption>maybe somewhere in a manager's OnEnable(), for example</figcaption></figure><figure class="kg-card kg-code-card"><pre><code class="language-c#">_AccelerationStructure.Update();
_AccelerationStructure.Build(); </code></pre><figcaption>in some manager's Update(), for example</figcaption></figure><p>Once this has been setup, you're ready to generate rays! </p><h3 id="generating-rays">Generating Rays</h3><p>RTX rays are generated from a ray generation shader. If you've used <a href="https://docs.unity3d.com/Manual/class-ComputeShader.html">Compute Shaders</a> in Unity, things will look pretty familiar to you. </p><pre><code class="language-hlsl">#include "HLSLSupport.cginc"
#include "UnityRaytracingMeshUtils.cginc"
#include "UnityShaderVariables.cginc"

RaytracingAccelerationStructure _RaytracingAccelerationStructure : register(t0);

float4x4 _CameraToWorld;
float4x4 _InverseProjection;

[shader("raygeneration")]
void MyRayGenerationShader()
{
    uint3 dispatchId = DispatchRaysIndex();
    uint3 dispatchDim = DispatchRaysDimensions();

    // somehow get the world space position of the pixel we care about
    // somehow generate a ray from that pixel in a meaningful Direction
    // color the pixel we care about, with the information that ray gathered
}</code></pre><p>For the sake of example, we should create something meaningful. Let's dispatch rays from every pixel on the screen, which we will eventually get intersecting with geometry in the acceleration structure that we defined earlier. </p><p>Also, note that the <a href="https://docs.microsoft.com/en-us/windows/win32/direct3d12/raytracingaccelerationstructure">RaytracingAccelerationStructure </a>needs to be defined somewhere, too. t0 is the register that Unity uses for this structure. </p><figure class="kg-card kg-code-card"><pre><code class="language-hlsl">float2 texcoord = (dispatchId.xy + float2(0.5, 0.5)) / float2(dispatchDim.x, dispatchDim.y);
</code></pre><figcaption>assuming we dispatch our generation shader such that this kernel is ran for every pixel on the screen, we'll want to do some math to convert that to a 0 to 1 range.</figcaption></figure><figure class="kg-card kg-code-card"><pre><code class="language-hlsl">float3 viewPosition = float3(texcoord * 2.0 - float2(1.0, 1.0), 0.0);</code></pre><figcaption>after that, we can convert it to be in clip space</figcaption></figure><figure class="kg-card kg-code-card"><pre><code class="language-hlsl">float4 clip = float4(viewPosition.xyz, 1.0);
float4 viewPos = mul(_InverseProjection, clip);</code></pre><figcaption>next is converting from our clip space, to camera space</figcaption></figure><figure class="kg-card kg-code-card"><pre><code class="language-hlsl">viewPos.xyz /= viewPos.w;</code></pre><figcaption>don't forget that perspective divide 🔪</figcaption></figure><figure class="kg-card kg-code-card"><pre><code class="language-hlsl">float3 worldPos = mul(_CameraToWorld, viewPos);
float3 worldDirection = worldPos - _WorldSpaceCameraPos;</code></pre><figcaption>and finally, we can get our world position (and world direction)!</figcaption></figure><p>Now that we know from where and to where we want to cast rays, let's start building a ray and it's payload. In the raytracing API provided to us, we need to build both a <a href="https://docs.microsoft.com/en-us/windows/win32/direct3d12/raydesc">RayDesc </a>and a custom payload struct, which are passed into a TraceRay() call. </p><figure class="kg-card kg-code-card"><pre><code class="language-hlsl">RayDesc ray;
ray.Origin = _WorldSpaceCameraPos; 
ray.Direction = worldDirection; 
ray.TMin = 0;
ray.TMax = 10000;</code></pre><figcaption>RayDesc is an intrinsic structure to the RTX API</figcaption></figure><p>You can use any payload that you wish. Keep in mind that you may run into issues with high memory footprint payloads, so try to keep them as small as possible. In this example, we'll just use color. </p><figure class="kg-card kg-code-card"><pre><code class="language-hlsl">struct MyPayload
{
	float4 color;
};</code></pre><figcaption>define this somewhere</figcaption></figure><pre><code class="language-hlsl">MyPayload payload;
payload.color = float4(0, 0, 0, 0);</code></pre><pre><code class="language-hlsl">TraceRay(_RaytracingAccelerationStructure, 0, 0xFFFFFFF, 0, 1, 0, ray, payload);</code></pre><p><a href="https://docs.microsoft.com/en-us/windows/win32/direct3d12/traceray-function">TraceRay</a>() is another magic call we can do with the raytracing API. I highly recommend clicking on the previous link, to read up on some of the finer details. At the least, you'll need an acceleration structure to pass in, some flags for intersection rules, a 32 bit <a href="https://docs.unity3d.com/ScriptReference/LayerMask.html">LayerMask </a>flag, the RayDesc, and the custom payload.</p><p>After you've traced a ray, you need to do something with the payload result. </p><figure class="kg-card kg-code-card"><pre><code class="language-hlsl">RWTexture2D&lt;float4&gt; RenderTarget;</code></pre><figcaption>define a RenderTexture to write to, outside of this kernel</figcaption></figure><figure class="kg-card kg-code-card"><pre><code class="language-hlsl">RenderTarget[dispatchId.xy] = payload.color;</code></pre><figcaption>write the color into the render texture. assumming that you have dispatched an array of rays equal to the width and height of your input render texture, you can just use the dispatchId as the position in your texture to write into.</figcaption></figure><p>This traced ray may or may not intersect with geometry. If it does not, you'll probably want to provide a "miss" kernel. </p><figure class="kg-card kg-code-card"><pre><code class="language-hlsl">[shader("miss")]
void MyMissShader(inout MyPayload payload : SV_RayPayload)
{
    payload.color = 0;
}</code></pre><figcaption>a miss shader could look something like this</figcaption></figure><p>This miss kernel would be called if the ray does not hit anything, as the name implies.</p><p><em>Keep note of that <strong><a href="https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-function-parameters">inout </a></strong>keyword. For our purposes, you can assume it works similarly to the <strong>ref </strong>keyword in c# (although its a bit different. inout actually does a copy in and a copy out, its not a reference being passed around). </em></p><p>On the c# side, you'll need some component which can reference the ray generation shader, and then execute it. </p><figure class="kg-card kg-code-card"><pre><code class="language-c#"> // define a RT, to see whats going on 
 // note, if its public, 
 //   you can double click it in the inspector to preview it,
 //   when the game view is focused 
 public RenderTexture _RenderTexture;
 
 </code></pre><figcaption>need to define a render texture to write to</figcaption></figure><figure class="kg-card kg-code-card"><pre><code class="language-c#">public RayTracingShader MyRayGenerationShader;</code></pre><figcaption>need to reference the raytracing shader somehow</figcaption></figure><p>I recommend using a <a href="https://docs.unity3d.com/ScriptReference/Rendering.CommandBuffer.html">CommandBuffer </a>to dispatch the ray generation shader, but you can also just do it from the shader itself. </p><figure class="kg-card kg-code-card"><pre><code class="language-c#">command.SetRayTracingTextureParam(MyRayGenerationShader, "RenderTarget", _RenderTexture); </code></pre><figcaption>don't forget to assign the render texture you want to write to</figcaption></figure><figure class="kg-card kg-code-card"><pre><code class="language-c#">command.SetRayTracingShaderPass(MyRayGenerationShader, "MyRaytracingPass");
command.SetRayTracingAccelerationStructure(MyRayGenerationShader, "_RaytracingAccelerationStructure", _AccelerationStructure);</code></pre><figcaption>take note of "MyRaytracingPass", going to talk about it soon</figcaption></figure><figure class="kg-card kg-code-card"><pre><code class="language-c#">var projection = GL.GetGPUProjectionMatrix(camera.projectionMatrix, false);
var inverseProjection = projection.inverse;

command.SetRayTracingMatrixParam(MyRayGenerationShader, "_InverseProjection", inverseProjection);
command.SetRayTracingMatrixParam(MyRayGenerationShader, "_CameraToWorld", camera.cameraToWorldMatrix);
command.SetRayTracingVectorParam(MyRayGenerationShader, "_WorldSpaceCameraPos", camera.transform.position);</code></pre><figcaption>you'll need to setup those variables for the ray generation shader to actually calculate the stuff it needs</figcaption></figure><figure class="kg-card kg-code-card"><pre><code class="language-c#">command.DispatchRays(MyRayGenerationShader, "MyRayGenerationShader", (uint)_texture.width, (uint)_texture.height, 1u, camera);</code></pre><figcaption>the string passed in matches the raygeneration kernel name, in the RaytracingShader</figcaption></figure><p>Once this dispatch is called, you'll be generating rays! However, they won't do anything when they hit anything, yet. </p><h3 id="hit-">Hit!</h3><p>To do anything interesting, you'll need to provide a hit kernel. In Unity, you can do this in the .shader file of any shader by adding a <a href="https://docs.unity3d.com/Manual/SL-Pass.html">Pass{} block.</a> When you dispatch rays, you can use <a href="https://docs.unity3d.com/ScriptReference/Rendering.CommandBuffer.SetRayTracingShaderPass.html">SetRayTracingShaderPass </a>to specify a name, and when a ray intersects an object, Unity will check for any <a href="https://docs.unity3d.com/Manual/SL-Pass.html">Passes </a>that match that name. </p><p>As an example, let's create a new shader. </p><figure class="kg-card kg-image-card"><img src="https://coty.tips/content/images/2020/11/p8xUWwtBDU.png" class="kg-image" alt="Raytracing in Unity's built-in render pipeline" width="768" height="210" srcset="https://coty.tips/content/images/size/w600/2020/11/p8xUWwtBDU.png 600w, https://coty.tips/content/images/2020/11/p8xUWwtBDU.png 768w" sizes="(min-width: 720px) 720px"></figure><p>Open it up, and add in something like this, after the <a href="https://docs.unity3d.com/Manual/SL-SubShaderTags.html">SubShader</a> block.</p><figure class="kg-card kg-code-card"><pre><code class="language-hlsl">SubShader
{
    Pass
    {
        Name "MyRaytraceShaderPass"

        HLSLPROGRAM

        #pragma raytracing MyHitShader

        struct MyPayload
        {
            float4 color; 
        };
        
        struct AttributeData
        {
            float2 barycentrics; 
        };

        [shader("closesthit")]
        void MyHitShader(inout MyPayload payload : SV_RayPayload,
          AttributeData attributes : SV_IntersectionAttributes)
        {
            payload.color = 1;
        }

        ENDHLSL
    }
}</code></pre><figcaption>a very simple hit shader</figcaption></figure><p>HLSL has some a new attribute: [shader("")]. You can define what type of raytracing shader this function is meant for. The most useful for us is "<a href="https://docs.microsoft.com/en-us/windows/win32/direct3d12/closest-hit-shader">closesthit</a>" - which is ran when the ray intersection nearest to the ray's origin is found. </p><p>Here is a list of available DXR shader types, with their appropriate method signatures.</p><figure class="kg-card kg-code-card"><pre><code class="language-hlsl">[shader("raygeneration)]
void RayGeneration() {} 

[shader("intersection")]
void Intersection() {}

[shader("miss")]
void Miss(inout MyPayload payload : SV_RayPayload) {}

[shader("closesthit")]
void ClosestHit(inout MyPayload payload : SV_RayPayload, MyAttributes attributes : SV_IntersectionAttributes) {}

[shader("anyhit")]
void AnyHit(inout MyPayload payload : SV_RayPayload, MyAttributes attributes : SV_IntersectionAttributes) {}
</code></pre><figcaption>SV_RayPayload and SV_IntersectionAttributes are both user defined structs.&nbsp;</figcaption></figure><p>What will happen now, is our ray generation shader will generate black for any pixels that are not overlapping geometry, and white for any pixels that are generating geometry. We're raytracing!</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://coty.tips/content/images/2020/11/image-1.png" class="kg-image" alt="Raytracing in Unity's built-in render pipeline" width="672" height="611" srcset="https://coty.tips/content/images/size/w600/2020/11/image-1.png 600w, https://coty.tips/content/images/2020/11/image-1.png 672w"><figcaption>VERY advanced raytracing going on here</figcaption></figure><hr><h2 id="what-can-we-do-with-this">What can we do with this? </h2><p>The raytracing API that DX12 is providing us unlocks some great stuff. </p><p>Here's a screenshot of some raytraced reflections I've thrown together.</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://coty.tips/content/images/2020/11/Unity_NvJa5yCt2I.png" class="kg-image" alt="Raytracing in Unity's built-in render pipeline" width="808" height="519" srcset="https://coty.tips/content/images/size/w600/2020/11/Unity_NvJa5yCt2I.png 600w, https://coty.tips/content/images/2020/11/Unity_NvJa5yCt2I.png 808w" sizes="(min-width: 720px) 720px"><figcaption>the "closesthit" kernel is using TraceRay() to keep searching for more intersections, to keep adding on layers of reflections. rays are jiggled around to simulate roughness of materials.&nbsp;</figcaption></figure><p>This can be taken a step further, too. Why not have shadows in our reflections? </p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://coty.tips/content/images/2020/11/Unity_czoqNZYi64.png" class="kg-image" alt="Raytracing in Unity's built-in render pipeline" width="856" height="519" srcset="https://coty.tips/content/images/size/w600/2020/11/Unity_czoqNZYi64.png 600w, https://coty.tips/content/images/2020/11/Unity_czoqNZYi64.png 856w" sizes="(min-width: 720px) 720px"><figcaption>I've added an additional ray which sets a flag in the payload to identify as a shadow ray check, to darken areas where rays do not run the miss kernel</figcaption></figure><p>And if our reflections can have raytraced shadows.. why not replace unity's shadows completely with raytraced shadows?</p><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://coty.tips/content/images/2020/11/Unity_9QEULsWqWE.png" class="kg-image" alt="Raytracing in Unity's built-in render pipeline" width="683" height="481" srcset="https://coty.tips/content/images/size/w600/2020/11/Unity_9QEULsWqWE.png 600w, https://coty.tips/content/images/2020/11/Unity_9QEULsWqWE.png 683w"><figcaption>rays are cast from the world position of the object the pixel is drawing, towards the light. if the ray misses, its white, if it hits, its black. casting multiple rays in semi-random directions can be used to increase the quality of this effect. this is generating a shadow map, which I'm using to replace unity's shadowmap</figcaption></figure><figure class="kg-card kg-embed-card kg-card-hascaption"><blockquote class="twitter-tweet" data-width="550"><p lang="en" dir="ltr">its about time voxelgame got some <a href="https://twitter.com/hashtag/rtx?src=hash&amp;ref_src=twsrc%5Etfw">#rtx</a> support<a href="https://twitter.com/hashtag/gamedev?src=hash&amp;ref_src=twsrc%5Etfw">#gamedev</a> <a href="https://twitter.com/hashtag/madewithunity?src=hash&amp;ref_src=twsrc%5Etfw">#madewithunity</a> <a href="https://t.co/w2KuLFFcf0">pic.twitter.com/w2KuLFFcf0</a></p>&mdash; Coty Getzelman (@cotycrg) <a href="https://twitter.com/cotycrg/status/1332761311466442757?ref_src=twsrc%5Etfw">November 28, 2020</a></blockquote>
<script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
<figcaption>Here's one more example, it's a bit more real-world. I've been working on implementing raytraced effects into my side project.</figcaption></figure><hr><h3 id="getting-useful-data-from-intersections">Getting Useful Data From Intersections</h3><pre><code class="language-hlsl">struct AttributeData
{
    float2 barycentrics; 
};</code></pre><p>Using a user defined struct, you can request some data from intersections. It's possible to use these barycentric coordinates provided to get useful interpolated data from the vertices. For example, you could use this to get the albedo of the triangle with proper uv mapping, or you could even shade the triangle like normal.</p><figure class="kg-card kg-code-card"><pre><code class="language-hlsl">#include "UnityRaytracingMeshUtils"</code></pre><figcaption>Unity has recently added some helper functions to their built-in shaders, which makes this pretty trivial to do. Be sure to include it!</figcaption></figure><figure class="kg-card kg-code-card"><pre><code class="language-hlsl">struct Vertex
{
    float2 texcoord;
};</code></pre><figcaption>Let's make a new struct, for getting some vertex data.</figcaption></figure><figure class="kg-card kg-code-card"><pre><code class="language-hlsl">uint primitiveIndex = PrimitiveIndex();</code></pre><figcaption>this is a new intrinsic function for hlsl, to fetch a ray's intersected primitive data</figcaption></figure><figure class="kg-card kg-code-card"><pre><code class="language-hlsl">uint3 triangleIndicies = UnityRayTracingFetchTriangleIndices(primitiveIndex);</code></pre><figcaption>UnityRayTracingFetchTriangleIndices is a new unity built-in function, borrowed from that include earlier</figcaption></figure><figure class="kg-card kg-code-card"><pre><code class="language-hlsl">Vertex v0, v1, v2;</code></pre><figcaption>to get interpolated data, we're going to need the three vertices that make up the triangle our ray intersected</figcaption></figure><figure class="kg-card kg-code-card"><pre><code class="language-hlsl">v0.texcoord = UnityRayTracingFetchVertexAttribute2(triangleIndicies.x, kVertexAttributeTexCoord0);

v1.texcoord = UnityRayTracingFetchVertexAttribute2(triangleIndicies.y, kVertexAttributeTexCoord0);

v2.texcoord = UnityRayTracingFetchVertexAttribute2(triangleIndicies.z, kVertexAttributeTexCoord0);</code></pre><figcaption>UnityRayTracingFetchVertexAttribute[0..4] are helper functions from unity, which we can use to get vertex attribute data given the data from earlier</figcaption></figure><figure class="kg-card kg-code-card"><pre><code class="language-hlsl">float3 barycentrics = float3(1.0 - attributeData.barycentrics.x - attributeData.barycentrics.y, attributeData.barycentrics.x, attributeData.barycentrics.y);</code></pre><figcaption>its time to use those barycentric coordinates!</figcaption></figure><pre><code class="language-hlsl">Vertex vInterpolated;

vInterpolated.texcoord = v0.texcoord * barycentrics.x + v1.texcoord * barycentrics.y + v2.texcoord * barycentrics.z;</code></pre><p>From here, you can sample from textures in the normal way. </p><figure class="kg-card kg-code-card"><pre><code class="language-hlsl">Texture2D&lt;float4&gt; _MainTex;
SamplerState sampler_MainTex;

[shader("closesthit")]
void MyHitShader(inout ExamplePayload payload : SV_RayPayload, AttributeData attributes : SV_IntersectionAttributes)
{
    // get texcoord somehow
    // then use below 
    
    payload.color = _MainTex.SampleLevel(sampler_MainTex, texcoord, 0);
}</code></pre><figcaption>using the texture coordinates</figcaption></figure><figure class="kg-card kg-image-card kg-card-hascaption"><img src="https://coty.tips/content/images/2020/12/image.png" class="kg-image" alt="Raytracing in Unity's built-in render pipeline" width="495" height="492"><figcaption>rays returning albedos</figcaption></figure><p>Some useful data! You can expand this further by using TraceRay() inside of the closesthit shader passes. Keep in mind that you need to increase <em>#pragma max_recursion_depth 1</em>, when using TraceRay() inside of a hit function. You'll also need to manage your recursion manually. Keep this in mind, or you may crash!</p><hr><h2 id="self-promo">Self Promo</h2><p>If you just want to download some source code, I'm providing it all in the form of a Unity Asset Store package. The raytraced reflections and raytraced shadows are both packaged with it, of course. I've also included a lot of helpful macros, for quickly making your own raytracing shaders. </p><figure class="kg-card kg-bookmark-card kg-card-hascaption"><a class="kg-bookmark-container" href="https://assetstore.unity.com/packages/slug/184088"><div class="kg-bookmark-content"><div class="kg-bookmark-title">Corgi Raytracing - Built-in Render Pipeline (Forward and Deferred!) | VFX Shaders | Unity Asset Store</div><div class="kg-bookmark-description">Add depth to your next project with Corgi Raytracing - Built-in Render Pipeline (Forward and Deferred!) from Wandering Corgi. Find this &amp; more VFX Shaders on the Unity Asset Store.</div><div class="kg-bookmark-metadata"><img class="kg-bookmark-icon" src="https://unity-assetstorev2-prd.storage.googleapis.com/cdn-origin/images/favicons/apple-touch-icon.png?v=1" alt="Raytracing in Unity's built-in render pipeline"><span class="kg-bookmark-publisher">Unity Asset Store</span></div></div><div class="kg-bookmark-thumbnail"><img src="https://assetstorev1-prd-cdn.unity3d.com/key-image/a6836fab-7699-4309-ac31-774f28c90eaa.png" alt="Raytracing in Unity's built-in render pipeline"></div></a><figcaption>my asset includes all of it's source code, so it is easily modifiable</figcaption></figure><hr><h2 id="further-reading">Further Reading</h2><p>I highly recommend the following for further reading.</p><ul><li><a href="https://on-demand.gputechconf.com/siggraph/2019/pdf/sig940-getting-started-with-directx-ray-tracing-in-unity.pdf">https://on-demand.gputechconf.com/siggraph/2019/pdf/sig940-getting-started-with-directx-ray-tracing-in-unity.pdf</a></li><li><a href="http://intro-to-dxr.cwyman.org/presentations/IntroDXR_RaytracingShaders.pdf">http://intro-to-dxr.cwyman.org/presentations/IntroDXR_RaytracingShaders.pdf</a></li><li><a href="https://microsoft.github.io/DirectX-Specs/d3d/Raytracing.html">https://microsoft.github.io/DirectX-Specs/d3d/Raytracing.html</a></li></ul>]]></content:encoded></item><item><title><![CDATA[Wave Break’s Waves]]></title><description><![CDATA[<p><code>Technical Breakdown</code></p><hr><figure class="kg-card kg-image-card"><img src="https://lh6.googleusercontent.com/yD36ZzEb2Le47_Iw_hNsbpqRGh7F0S6upzUR5LbLbIfBu4XkwaTczTJ2ovF1AQ0-nNmITw88qCfaXQI13TgqEPL8BUa-qf81khZO-8qmAjDjP3tBdkO-gusYrtDidWoPwivrbfFV" class="kg-image" alt></figure><p>Hey, I’m Coty Getzelman, the lead engineer on <em>Wave Break</em>, the world’s first skateboating game, made in Unity! <em>Wave Break</em> is inspired by classic arcade skateboarding games, with a splash of boating, explosions, and cold-blooded murder.</p><hr><figure class="kg-card kg-image-card"><img src="https://lh6.googleusercontent.com/lgoSMsW_DVm6Kk3u1hXJT0GNnPJdENIB4A2WegbJ37h9XJuGYHG7Pth_wJmyPEOQv4PcSnK4vudAUlxmkZkllBdBbbutFCJEDGLgGo3iqzy2W-_0b0srXv6GTn7M0KIXqzfhEwV2" class="kg-image" alt></figure><p>Inspired by the water physics from <em>Wave Race 64</em>, I</p>]]></description><link>https://coty.tips/wave-breaks-waves/</link><guid isPermaLink="false">5ef233540a535243807ee465</guid><dc:creator><![CDATA[Coty Getzelman]]></dc:creator><pubDate>Tue, 23 Jun 2020 16:53:05 GMT</pubDate><content:encoded><![CDATA[<p><code>Technical Breakdown</code></p><hr><figure class="kg-card kg-image-card"><img src="https://lh6.googleusercontent.com/yD36ZzEb2Le47_Iw_hNsbpqRGh7F0S6upzUR5LbLbIfBu4XkwaTczTJ2ovF1AQ0-nNmITw88qCfaXQI13TgqEPL8BUa-qf81khZO-8qmAjDjP3tBdkO-gusYrtDidWoPwivrbfFV" class="kg-image" alt></figure><p>Hey, I’m Coty Getzelman, the lead engineer on <em>Wave Break</em>, the world’s first skateboating game, made in Unity! <em>Wave Break</em> is inspired by classic arcade skateboarding games, with a splash of boating, explosions, and cold-blooded murder.</p><hr><figure class="kg-card kg-image-card"><img src="https://lh6.googleusercontent.com/lgoSMsW_DVm6Kk3u1hXJT0GNnPJdENIB4A2WegbJ37h9XJuGYHG7Pth_wJmyPEOQv4PcSnK4vudAUlxmkZkllBdBbbutFCJEDGLgGo3iqzy2W-_0b0srXv6GTn7M0KIXqzfhEwV2" class="kg-image" alt></figure><p>Inspired by the water physics from <em>Wave Race 64</em>, I started reading a bunch of fluid sim physics papers and tried out many methods. However, the simplicity of <em>Wave Race’s</em> design still holds up to this day. Let’s talk about how we could scale this idea up for modern hardware.</p><p>I wanted the resolution of the wave sim to be such that a single “wave” could be smaller than a player, so that the wakes created by their driving would be in high detail. Getting this level of detail would require a lot of memory, and even now in 2020 this is way too much data to process on a CPU. Instead, We can take advantage of the massively parallel nature of a modern GPU. Unity has Compute Shaders, which will allow us to read and write to arbitrary buffers for this effect.</p><figure class="kg-card kg-image-card"><img src="https://lh3.googleusercontent.com/FtYkPNzE43q_MdHBys6yRYIx2AM3ke77TGP7CJ1NClW_-k3YbCYuzqANBJAKijCEt8sUBFfLwGs9g-gcEoZu0v9k9rfSZIe48QklhyNbrudWbqH0-7mkmDBVasuuXz6paNhGSMwM" class="kg-image" alt></figure><p>The core idea is to treat a water plane as a set of interconnected springs. For <em>Wave Break</em>, I set up a 2D RenderTexture, in which each pixel represents a spring state. With some simple math, you can get some spring-like behavior by passing the texture through a Compute Shader. In this example gif, the Compute Shader has each pixel sample it’s neighbor pixels and spring accordingly; this alone is enough to generate these nice ripple patterns.</p><figure class="kg-card kg-image-card"><img src="https://lh6.googleusercontent.com/IFUbYhWk-9UrI-yi_MD4wYiGjuIuJixfVBS0p-LctS6GbwvnMSj9ztksWQI7vkiB0RurPs4MIHoqXPRjWvq4G9RHgZZrUIH79hXdK9xkbutEIjbfh04wXAUvnWwh7gTyB2RGgBVk" class="kg-image" alt></figure><p>Take that texture and blur it to get nice, smooth ripples. Spring + Blur starts looking like some convincing shallow waves!</p><hr><figure class="kg-card kg-image-card"><img src="https://lh5.googleusercontent.com/UtrS3UlhtDIFfix7MEDV3FPSN2e7OvJ9cY1YZJ6zduyV8bge2UmsCFqNPbc_b0UhRRY9Nr2LZ4630iAC0x2lelxyDWBJcWpcJFfTKrfXG12iFwAdKmvrNuTik1nxrRqDeut3Az5b" class="kg-image" alt></figure><p>The very first pass of this looked like this! All that’s done here is combining that RenderTexture with a simple custom transparent shader, which samples the texture for offsetting vertices and using the length (current - previous) spring states of the pixel for detecting “foam”.</p><p>Obvious issue: the water is too still for ocean/lakes. We need to do a wind pass. We’ll need the world position of the vertex we want to apply wind to. For this world position, we can do the following. Take the current pixel’s (x,y) position, divided by the width and height of the wave texture to normalize into a 0-1 range, then shift over to (-1, 1) range to pretend it’s in the water plane’s transform’s local space, then use localToWorld matrix of the transform to convert it to world space. This allows shifting, rotating, and scaling while still getting the correct world position of a pixel in the RenderTexture. We can then pass the world position into a noise function. However, calling that noise function on every fragment would be pretty slow. Instead, it’s a better idea to create a noise texture!</p><hr><p>Ripples are great for making wakes, but to make a really convincing ocean, you need wind, both by the shoreline and out to sea. So I made this simple unity editor tool for generating noise textures.</p><figure class="kg-card kg-image-card"><img src="https://lh4.googleusercontent.com/QRRshxgjoBfwDZDVNXlqcO5bodCuD4G1vuYikC7wl6VsWHWrY-KQMKUb3m40qV8WzHA_43tqy7llLlBB3V30TAnlqb1TMyd93fnt-OZWYHhgQYk081iCx1oqIecqHUM5XbJ6PKYP" class="kg-image" alt></figure><figure class="kg-card kg-image-card"><img src="https://lh3.googleusercontent.com/xmG3Yny_IKXIEZImurOAcRZ1Nevf4WhvhK4C1lqb9JbO91XPvvTo0jsxt9fAEi4I6aS_SoD0FQsZzQduCtJJ9zh5gwlx_5oJ_Lt31ibyQ9SPcbOYnaPt1iJdstMIHIzAKW811el2" class="kg-image" alt></figure><p>Combining the noise texture into the ripple texture results in this texture. Starting to look good!</p><p>With blurred ripples with wind, it looks like waves. Once we start rendering it, it is obvious that the foam is missing. I tried doing it dynamically in a fragment shader, but I wanted the foam to stick around, and it is kind of wasteful doing it for a lot of fragments at a higher resolution (4k?). Instead: allocate a dedicated foam RenderTexture. Also, we’ll need to create two Compute Shader kernels: one for generating foam from wave delta, one for fading foam over time.</p><figure class="kg-card kg-image-card"><img src="https://lh4.googleusercontent.com/8omBwxE7kB7T7hX6QlicW-P71Ez3neYg89VA4LWWKEyPDERepj2H4OcVqMOdnLqBz8US01cGdDdWNQ0Q4Zzk9xZWgLdICRD22cTLNFEURXHbFBgy7glJwsv6rhLf0d3lTyiBhPA4" class="kg-image" alt></figure><figure class="kg-card kg-image-card"><img src="https://lh4.googleusercontent.com/bHOFFQKu1RK-dF4t7QPyxmMRgGmeBVya4cxfDKVsPTR4_dKGdKF2ibbgrII2-fSlbUIcDeSD01dzwVvbsJ5lzICa-e4fX5c2lXQEtYx6msZL6jfABn5j-X2LROfhoAVzsoDXlEtv" class="kg-image" alt></figure><p>On top of those two Compute Shaders passively generating foam based on the waves, we should also stamp to the foam texture when we write to the wave texture. For each wave sim step, I’m diffusing the foam while the ripple is happening. Afterwards, I combine these two textures, using the R channel for the waves and G channel for the foam.</p><p>Water planes are placed in a grid, using blurred data for rendering. Unfortunately, this has very visible seams. Our blur is sampling neighbor pixels, but edge pixels were sampling themselves, because there is no info on their neighbor textures!</p><hr><figure class="kg-card kg-image-card"><img src="https://lh6.googleusercontent.com/WItRfeOgNPuXVYijWgTIrz1NciWA_zp899hz9Jd8w4BpZGb9-5lz4vgTXhy4V9VpPrJW31axu52muuYwZvdyFcObZUVY_ANvl2z7BUXKhgImU-NbFgiGBci17RJgYwRMKuD3Qf_S" class="kg-image" alt></figure><p>The next challenge is to get these textures in-game without seams. The blur effect is tricky, because if you only sample just one texture, you will generate seams around the edges which looks ugly in-game. Each fetch could check if it needs to use the neighbor textures, but that’s just way too slow. One solution is just splitting 1 blur kernel into 5, one for inside block and 4 for the outside edges. Fixed!</p><p>A similar problem occurs when rendering as well, as the fragment shader is billinearly interpolating the blur texture, because there is no info on neighboring textures. So, the shader will need to use a manual bilinear filter, but.. that’s also slow! To avoid shading in this way for most of the screen, I split up the water plane mesh into two meshes: an inside chunk and an outside strip of triangles. The two meshes have the same shader and material, but the outside edge has a material setting to toggle the shader keyword so it uses a shader variant to use a manual bilinear filter which combines neighboring textures. Whew!</p><figure class="kg-card kg-image-card"><img src="https://lh6.googleusercontent.com/4aR5-WQzge1xeoOwEMzUMT6gR1Y9NrbthpQvDNDVgp837_qn48lV5Wut3d_tRQBP6bbyT_8S9ubQbQAyA-uZbSPenOLDMVC4bzbBv23Cueb4sPQ82I9JkszfM5rCgelbkenYmSZn" class="kg-image" alt></figure><p>Now that we have fixes, we can start rendering. I’m just doing a normal vert/frag shader, where the vertex pass moves verts based on blurred wave texture. But.. verts moved means the normals will be broken! To deal with this, I’m sampling the neighboring wave heights to calculate the new vertex normal, which gets passed to the fragment shader.</p><p>Lighting is typical N dot L diffuse, with some normals scaling and specular adjustments for that stylised feel. The fragment’s normals are shifted a bit by a “micro normals” texture, for added detail. Artists can adjust these micro normals to create the sparkles you see in the gif. The foam RenderTexture is sampled to use as a mask for an artist, who made a repeating foam texture.</p><figure class="kg-card kg-image-card"><img src="https://lh4.googleusercontent.com/hscNF0ULZZPverL6wiYne_k4r94C3CtnkS3KE4T_Pkqk2VaWBzl-TiGqP7FFNX4hzSIuhG8yrT3JXiuKlrzf0zCSttLkCRFwJS649XErF3qRs1aIptpI3jMXJMkOb5GEU8OL_53u" class="kg-image" alt></figure><figure class="kg-card kg-image-card"><img src="https://lh4.googleusercontent.com/99iKbnZFRxTrnDJW7wnO7mg2eF5C4Au4ncq9zx0qIqlbqsKVDyStMtohUQ-2uPJOlpEiOtMkBgFUAvJaGk9HNV48dm3V-pekPOzkgJV2AkGlKZXuxohbroNGwWmhgUAYr5-PXAmm" class="kg-image" alt></figure><hr><figure class="kg-card kg-image-card"><img src="https://lh3.googleusercontent.com/cyDJxbiZqWWuTARYcKiE_3nD1R6-cErmn72rEXLjMqxyuyXSaVk_dwzGW_-JHwl8Dm4AvoCh00J-ct51l_VJ6B5aA-5-xH9H8LN70f1N9ZmiSi6X0ibY3pvjBAOXA-Wpu-5XeTqC" class="kg-image" alt></figure><figure class="kg-card kg-image-card"><img src="https://lh4.googleusercontent.com/7fdgWGgtrDs-emy-GcPU_ufcXf4XCQ9S6r-HFVy1K2VXcq6ioxIHketUEKAf8esfM8o5olNyoDqt1s6aNlKnRrMAkSHTiUw4or4qlS7k4fsu7Ap9NPhuS_eXsvRTc92QtNC1duES" class="kg-image" alt></figure><p>Here are some stylised examples of what is possible with this shader.</p><p>Wireframe is a typical wireframe shader, fragments know their distance from the edge of the triangle. The wire is lit up based on foam mask RT. Light is used to light entire triangles at once.</p><hr><figure class="kg-card kg-image-card"><img src="https://lh3.googleusercontent.com/1kg27CYHI58oJP-WPtOEqkZ7ksWNkq6j4a_RsmtCpVvhlPR1en3QQTADgIsWwq3qEeHjlzL9qFWwhXsSqeaUCJTqBVpNdeiA8vSEETlPkssPPTlfpRdVww1gBfZS09u2BXIeC8ub" class="kg-image" alt></figure><p>For gameplay, this water is only really useful if there’s two way coupling. This means, I want unity’s Rigidbodies to affect the water, and I want the water to affect the Rigidbodies!</p><p>To ramp off waves, I need to be able to get the wave height from the wave texture. The problem is, it’s not just some array to sample, it’s memory on the GPU. Latency from GPU -&gt; CPU is no joke, so we need to be clever.</p><p>The water plane objects have a trigger to collect a list of touched “floatable” objects that need to query wave height. A List will be used to build a buffer of texture coordinates (made from taking world position -&gt; local position -&gt; uv position) to pass to a Compute Shader, which iterates over the texture and fills an output buffer with wave heights and calculated wave normals.</p><p>Using this method of passing a buffer of positions to a Compute Shader which does the handful of texture samples on the GPU, which are then returned to the CPU, allowing us to get the data we need to calculate buoyancy for hundreds of objects, if necessary, without a significant performance impact of waiting on a whole texture to come back to the CPU.</p><p>However, processing buoyancy math for hundreds of objects would still be slow; C# is bad at math. This is a good use of Unity’s Job System with the Burst Compiler. Buoyancy for multiple objects can be calculated in parallel, since they do not directly affect one another. The slowest part now is iterating over the results of the job, and calling the Rigidbody.AddForce functions.</p><figure class="kg-card kg-image-card"><img src="https://lh3.googleusercontent.com/DQUVn25Ir1hm4_hTms7JOtnAUVTkL23qWhoXMP27P_jfm8Pf9uQtcC0XvgroykarRPOahZsQPMKZ52sFPK8GhE4_221cLpQVSq02BSVTEejlp4p1-uiF_C1gv-zc6viJFbIvpWCO" class="kg-image" alt></figure><hr><figure class="kg-card kg-image-card"><img src="https://lh6.googleusercontent.com/1nSbDu6cByXAhPPFJ0mDyzihpMH29_-fcpsuq_7lbGVK6GQpMGoKbbkSvJk4i7m-XYUH3gMcvk5Is89ise1P4ZRoZ3J6hOMslIcmbU5yRKf3ESbnwaQQQ0IF4Ksmk1NM-IBVcoOP" class="kg-image" alt></figure><figure class="kg-card kg-image-card"><img src="https://lh3.googleusercontent.com/BpbopjIOTM3PvJiC_lYNkitVeiibb69eL0TUpxEYrfykzydG57bwuEcpqaYQ-ZF6vsFgTlvedOK0jA4hLlr0X3qQY6Z07VIL-KbaMxE7SJ1WcjDWB-MZo-wg2UK81--OpdPhbXtZ" class="kg-image" alt></figure><p>The Burst job is managed by another script which checks the water plane’s distance from the nearest cameras to LOD, to use for both physics and rendering.</p><p>Notice those high detail strips of triangles between the LODs? Remember when I mentioned we would need a strip of triangles for the manual bilinear filter which samples nearby textures along the edges? That’s what that is!</p><p>The core of the wave system is complete, the rest is polish!</p><hr><figure class="kg-card kg-image-card"><img src="https://lh3.googleusercontent.com/xmG3Yny_IKXIEZImurOAcRZ1Nevf4WhvhK4C1lqb9JbO91XPvvTo0jsxt9fAEi4I6aS_SoD0FQsZzQduCtJJ9zh5gwlx_5oJ_Lt31ibyQ9SPcbOYnaPt1iJdstMIHIzAKW811el2" class="kg-image" alt></figure><figure class="kg-card kg-image-card"><img src="https://lh3.googleusercontent.com/xmG3Yny_IKXIEZImurOAcRZ1Nevf4WhvhK4C1lqb9JbO91XPvvTo0jsxt9fAEi4I6aS_SoD0FQsZzQduCtJJ9zh5gwlx_5oJ_Lt31ibyQ9SPcbOYnaPt1iJdstMIHIzAKW811el2" class="kg-image" alt></figure><figure class="kg-card kg-image-card"><img src="https://lh3.googleusercontent.com/CkfGW0xGRV1qiQR7oRjjTzJqxp2p6MBgM24OwaUADRcHm0dD8wf_OnJ9kzOfKAWhM-SKm2w8TCgNdpNxHYWxGIiyB8sPahc9OsOn2M0nWNKpwRSAm1qXHfP2r6Sx4VkzkbPpQ3cq" class="kg-image" alt></figure><figure class="kg-card kg-image-card"><img src="https://lh6.googleusercontent.com/r1zKajamvVUnB8zRBz28q-9SOKeaxaFjap6ZP5k36CS3Oio-ACEXEXBZTH_ZyAyTCJILYbXmPKPZxAhBZWBDPigQXnqoMPjZ1FzBrwDgTNYNSEVL-GDzum8xkApp1LgzteqtIWtV" class="kg-image" alt></figure><p>Here’s a question. At what time step do we want to run the physics sim? Every frame would make water move super fast, but a fixed timestep makes it look like a slideshow.</p><p>Solution: time travel?!</p><p>I keep the previous wave texture around, and linearly interpolate between the last physics tick’s texture and current, based on how much time has passed since the last physics step. Because our method is so resolution dependent, we can adjust our timescale based on quality settings in-game. Half the resolution wave sim in quality settings? Then we can also halve the time-step! Huge performance savings for lower quality settings!</p><p>Bonus: This lets us have slow motion waves by just changing the timescale variable in unity!</p><figure class="kg-card kg-image-card"><img src="https://lh4.googleusercontent.com/aYd-pvSsA2Zb4P08AZauQKbpwDrXeyTvrZ2j1UzXC7orjPbEsBroHQGsIjc2CYjCW_tas78fY8QzXk0cP7RB2OCKfMmKr8QVLF__mj8aQYyGf5cMf6M6GmcxLsxrwQ1DEZvXRl3g" class="kg-image" alt></figure><figure class="kg-card kg-image-card"><img src="https://lh4.googleusercontent.com/xhkkamLtDqU19oafZzF0fQDnRxz1GNOvGlzTxy_PSk2EVnLXkWzHl6qK3SpiY1fNuib0AUPS89hEb5JAzM9D_K4EkNx67TranC4u4R90tIQv3lDEjEC8vz_sEnVPaW3yQTuIHKHH" class="kg-image" alt></figure><p>Post process, for most games, is just comparing screen position converted to world position to the water plane’s position/normal. More complex water in most games only calculates the world position of water by using the same wave function the vertex pass of the water is using. Ours isn’t so simple; we need to go from screen space to world space to local space to texture space, get value, back to world space for comparison. We just generate one matrix by multiplying all these matrices together on the CPU, and pass to the post process shader so it’s only one multiple away from the correct position.</p><hr><figure class="kg-card kg-image-card"><img src="https://lh5.googleusercontent.com/Wi2DIXAjFO7kC5i0ioLIjkjxngAsHTOdvZSi9VhdbHjhcqSP_qejUPs-zMk2fV6g80LAg7TDUdG3kfemC1iB8bPW_CHceNpO4tL0OGoSCyYU3oLRFJo1MEibVEeTPQSZZ1WEYRYW" class="kg-image" alt></figure><p>That’s it! Any questions? You can hit me up.</p><ul><li>Email: <a href="mailto:coty@funktroniclabs.com">coty@funktroniclabs.com</a></li><li>Twitter: <a href="https://www.google.com/url?q=https://twitter.com/cotycrg&amp;sa=D&amp;ust=1592934377139000">@cotycrg</a></li></ul><p>And be sure to check out our game!</p><ul><li>Website: <a href="https://www.google.com/url?q=http://wavebreakgame.com/&amp;sa=D&amp;ust=1592934377139000">wavebreakgame.com</a></li><li>Twitter: <a href="https://www.google.com/url?q=https://twitter.com/WaveBreakGame&amp;sa=D&amp;ust=1592934377139000">@WaveBreakGame</a></li><li>Discord: <a href="https://www.google.com/url?q=https://discordapp.com/invite/funktroniclabs&amp;sa=D&amp;ust=1592934377140000">discord.gg/funktroniclabs</a></li></ul><figure class="kg-card kg-image-card"><img src="https://lh4.googleusercontent.com/u29IyXxbtPsr_JIse1ZjoD0nT7SrjgObwg38BeCB8MY8wMbhi4Je8IJeAevYHvLPElpMFPt_nZIH0XruQj4ZFWI3q0LcpwKoqMzuxRiSJkKjz-g4dMsdAFe52p4ttJ6UEz9LADpi" class="kg-image" alt></figure><p>Thanks for reading!</p>]]></content:encoded></item></channel></rss>