A one day challenge for a racing game!


title: “Agent Based Life Simulation” —

A agent based simulation allowing exploration of different variables!— title: “Wolf Rabbit Simulation” —

An agent study where wolfs are hunting rabbits. What populations win? How do they get to a stable point?

Live demo— title: “Voxelizer” —

A voxelization study. Supports placing, removing and streaming.

Live demo— title: “Switching between a VR and Desktop configuration with a ScriptableObject” published: true tags: unity —

We wanted to build a single project experience that included first class support for VR and at the same time worked well in a desktop environment.

Builds

We decided on having dedicated builds for desktop and VR. We wanted the ability to turn off VR. To do this we needed a couple of things.

  1. Some way of configuring the project to be in VR or Desktop mode.
  2. A way for the project to know what mode it was in and spawn correct player prefab
  3. Unload VR related loaders.

Configuration

Configuration is handled by a ScriptableObject that looks something like the following:

[CreateAssetMenu]
public class GlobalConfiguration : ScriptableObject
{
    [HideInInspector]
    public bool useVR;

    public void TurnVROn()
    {
        // ...
    }

    public void TurnVROff()
    {
        // ...
    }
}

A custom inspector is used to introduce a button that will trigger the TurnVROn and TurnVROff functions.

Configuring VR Loaders

The following chunk of code will assign a loader.

XRGeneralSettingsPerBuildTarget buildTargetSettings = null;
EditorBuildSettings.TryGetConfigObject(XRGeneralSettings.k_SettingsKey, out buildTargetSettings);
XRGeneralSettings settings = buildTargetSettings.SettingsForBuildTarget(BuildTargetGroup.Standalone);      
XRPackageMetadataStore.AssignLoader(settings.Manager, typeof(Unity.XR.OpenVR.OpenVRLoader).FullName, BuildTargetGroup.Standalone);

Lets break down each of the lines.

  1. XRGeneralSettingsPerBuildTarget buildTargetSettings = null;

    We are creating a variable to store our XRGeneralSettingsPerBuildTarget in.

  2. EditorBuildSettings.TryGetConfigObject(XRGeneralSettings.k_SettingsKey, out buildTargetSettings);

    Retrieve the build target settings and store them into buildTargetSettings.

  3. XRGeneralSettings settings = buildTargetSettings.SettingsForBuildTarget(BuildTargetGroup.Standalone);

    Get the XR settings for the Standalone (BuildTargetGroup.Standalone) build.

  4. XRPackageMetadataStore.AssignLoader(settings.Manager, typeof(Unity.XR.OpenVR.OpenVRLoader).FullName, BuildTargetGroup.Standalone);

    Turn the OpenVRLoader on.

If we focus on line 4, we could also do XRPackageMetadataStore.RemoveLoader(...) to remove a loader.

Other types of loaders can be removed / added by changing the loader type from OpenVR to whatever loader is being used.

See also:

Prefab Management

Prefab management is fairly straightforward. Simply have a PlayerSpawner that will look at the globalconfiguration.useVR value and spawn either a VR prefab or a Desktop prefab depending on the scenario. When the prefab is spawned a game event is triggered to let the scene know so it can self-configure from there.


title: “A map generator in Godot” published: false tags: godot —

A procedural map is a fun topic to explore. Today I am going to look at implementing a 2D procedural map in Godot using the TileMap class as a starting point.

Software

TileMap

TileMap is a built-in class tiling map class that Godot offers.

We are going to look closely at the “Single Tile” feature of tile sets to provide tiles to the room generator.

In order to dynamically generate the rooms we will need the ability to set a tile. In the TileMap class they are referred to as cells.

The functions set_cell and set_cellv will allow us to do this.

A room

The anatomy of a room that we are going to use for generating will consist of eight edge tiles with one center tile. We can duplicate the center tiles in-order to get rooms of different dimensions. See 9 Slice Scaling for an example. We will be repeating the stretched tiles instead of scaling them.

In-order to create configurable rooms so that we can easily reconfigure how the room looks with a new room I will be using a mapping to map a location to a tile.

::TODO:: insert code for mapping tile coordinate to edge coordinate.

title: “Mineral Processing Plant - A Case Study” published: false —

Mining VR

Unity · HTC Vive + Desktop · 3 Years · Lead + 7 Interns

A VR learning environment for mining engineering students, built around an immersive guided tour and summative exercise experience inside a copper pyrite mineral processing plant. The project ran identically across HTC Vive and desktop platforms, was sustained across three intern cohorts over three years, and had to meet real-time performance targets inside large open indoor environments.


The Challenge

A mineral processing plant is not a forgiving environment to render in real-time VR. The spaces are large, open, and industrial. Standard occlusion culling provides almost no relief because everything is visible at once, and the 90fps target required by the HTC Vive leaves almost no headroom for complexity. Baked lighting kept visual fidelity high but added draw call pressure. Semi-transparent flooring across wide areas created overdraw that threatened framerate stability throughout the experience. On top of that, simulation content like fluid dynamics and rock physics had to feel physically plausible without carrying real-time simulation cost on the GPU.

The operational side had its own pressures. The project ran for three years with rotating intern cohorts, seven people total, none of whom stayed for the full duration. Every technical and delegation decision had to account for the fact that the project would outlast everyone on it except me. The codebase, the processes, and the onboarding all had to be built to survive that turnover without losing momentum or quality.


Technical Decisions

Fluid Simulation Pipeline

The plant needed a convincing fluid simulation, but real-time fluid dynamics inside a VR environment wasn’t viable within the performance budget. I set up a Blender-to-Unity pipeline using the Alembic (.abc) interchange format, which is an industry-standard VFX container for baked simulation data. The fluid sim was authored and baked in Blender, exported as an Alembic cache, then brought into Unity where I wrote custom playback and loop logic to handle runtime behaviour the native importer doesn’t cover. The end result was a physically plausible fluid simulation with no real-time simulation cost.

Performance Architecture

Open indoor environments create a specific VR performance problem. Occlusion culling, Unity’s primary tool for managing render cost, works by skipping objects that are blocked from the camera’s view. In a wide open industrial space, almost nothing is blocked. Everything renders, all the time.

The main culprits here were draw calls from baked lighting and fill rate pressure from semi-transparent flooring. Transparent surfaces break batching and force the GPU to resolve the same pixels multiple times. Spread across an open plant floor, that compounds fast.

The fix wasn’t a single change. I reduced geometric complexity on the transparent floor surfaces at source, brought in baked effects to restore the sense of depth and dimensionality without adding polygon cost, and applied LODs to the flooring so geometry near the player stayed high fidelity while distant surfaces simplified. Together those three changes got draw calls and fill rate back within budget without a visible quality drop.

Dual Platform Architecture

The project had to run identically on both HTC Vive and desktop. Same environments, same simulations, same content. The approach was to keep the abstraction in the controller layer only. I built custom VR and desktop controllers separately, each handling input and locomotion natively for their platform, while everything underneath, the world, the content, the simulations, stayed completely untouched. Students on either platform got the same experience.


Leadership Decisions

Building for Turnover

With three cohorts rotating through over three years, the project couldn’t rely on knowledge sitting in any one person’s head. I made architectural decisions with a future unfamiliar reader in mind, and kept critical systems bounded enough that a new contributor could understand what they were working with without needing to understand the whole codebase. That shaped a lot of choices that wouldn’t have come up on a shorter project with a stable team.

Onboarding as Calibration

Each new cohort started with a one-week bootcamp covering tools, conventions, and how the project was structured. After that they moved straight into a small, scoped contribution task. The task was chosen to be completable quickly, easy to observe, and representative enough to show me what each person could actually do. Whatever came out of that first task determined what they got assigned next.

Adaptive Delegation

From there, I increased task complexity in response to output rather than on any fixed schedule. I’d push the difficulty up until someone started to visibly struggle, then assess what support was available and factor that into what came next. The goal was keeping each person working near the edge of their current capability without putting the project at risk. I ran this approach across all three cohorts and got more deliberate with it each time.


Reflection

What I’d do differently

The desktop platform was a real requirement but turned out to be underused relative to the work it took to support it. If I were starting over, I’d push back on it earlier, not to drop it outright, but to interrogate the usage assumptions behind it and see if the investment was actually proportionate. The dual platform architecture itself was fine. The bigger lesson was about asking harder questions before committing to a requirement.

The dialog system is the other one. It shipped with a data-driven architecture, so content could be updated without touching code, which was the right call structurally. But the tooling for actually working with it stayed pretty rough throughout the project. People editing dialog were doing more manual work than they should have been. If I built it again I’d treat the authoring experience as part of the deliverable, not a nice-to-have after the runtime was working.

What this project changed

Three years on a single project is long enough that you stop thinking about individual features and start thinking about what holds up over time. Every decision eventually gets touched by someone who wasn’t there when it was made, and that changes what good architecture actually means. That’s the thing Mining VR made concrete for me, and it’s carried into everything I’ve worked on since.— title: “Read Only Prefabs in Unity” published: true —

The readonly prefab utility prevents accidental prefab changes. It does a few key things: Stops accidental changes to existing items Makes items not selectable to prevent accidental movements and other selection based issues Reverts changes automatically with a reported error Provides functionality to enable changes Additionally allows editing in the open prefab mode

Once this system is in place you can have reasonable confidence that the prefabs are not being altered, the settings are remaining in place. This allows for people to alter the prefabs without having to consider issues like setting overrides or scene based links breaking. This ends up being a more robust prefab because you have enhanced guarantees that it is not being modified in many different ways. To enable prefab overrides a top level script can be used to act on the prefab at runtime.

ReadOnly Prefab

Here is an animation of the read only behaviour being triggered:

And here is the flow for altering a prefab:


title: “Optimizing a Quest 3 experience” published: false —

Debugging Meta Quest 3 Performance: From 30fps to 72fps

I’ve been building a Meta Quest 3 experience and hit the kind of performance problem that makes you question everything: stuck at 30fps on device, perfectly fine through Link, Air Link, and the PC simulator. Classic.

Since the PC builds looked fine, I started profiling from there. The frame time was splitting roughly three ways: about 6.4ms for the internal rendering pipeline, 6.3ms for XRBeginFrame, and 7.3ms for Update.ScriptRunBehaviourUpdate. Nothing obviously catastrophic, but the rendering numbers looked heavy enough to start there.

Profiler 1

Profiler 2

Drilling into each category didn’t turn up much. My first two suspects were occlusion culling and an additively loaded scene. Baking occlusion culling helped a little. Pulling the extra scene made no difference.


Narrowing it down

To rule out the hardware or the build process itself, I tried a near-empty project. 80fps, no problem. The app has a detailed power plant model, so naturally I assumed the geometry was to blame and ran a build without it.

40fps. Not the smoking gun I expected.

No Power Plant

With that assumption gone, I started toggling individual objects between the empty build and the no-plant build:

Test What changed FPS
1 Turntable moved further away 45
2 Turntable removed entirely 45
3 Top-level “Plant” object disabled 45
4 Table mover and buttons removed 60
5 Everything re-enabled except table mover and buttons 35

The table mover and buttons were clearly doing something, but the numbers still didn’t fully add up relative to the empty build baseline.


Quest Runtime Optimizer

The Quest Runtime Optimizer’s bottleneck analyzer gave a clearer picture: GPU-bound at 51ms versus CPU at 21ms. That pointed the investigation in a more useful direction.

Bottleneck Analysis

With GPU as the likely culprit, I ran through a series of tests:

Decimating the high-vertex cooling tower and switch yard geometry — no difference. Capping all textures to size 32 to probe texture bandwidth — still 30fps. Disabling occlusion culling and dynamic lights — 30fps. Disabling the plant, water, and pipes together — 30fps. Switching from a debug build to release — 30fps. Swapping “Install and Run” for a manual install — 30fps. Manually setting the frame rate target — 30fps.

The one result that stood out: empty scene hit 80fps, but adding the scene loader alone dropped it to 50fps. The additive scene setup was doing more work than it should.


Cleaning up the scene loading

I rolled everything back and looked more carefully at the scene structure. Two scenes were loaded and rendering at the same time. The plan had been to rely on occlusion culling to handle this since the scenes get teleported in and out of view — but that was optimistic. I switched to explicitly disabling renderers when scenes weren’t in use instead.


The ASW trap

While digging into this, I came across something that explained the “locked at exactly 30fps” pattern. Meta’s Asynchronous Spacewarp kicks in automatically when an app can’t hold a stable 60, 72, or 90Hz. When it does, it halves the target framerate to compensate — so a 60Hz app doesn’t run at 58fps, it runs at exactly 30fps. If you’re seeing a suspiciously round number, that’s probably why.

Reference: Meta ASW documentation

A small script to disable ASW and lock the frame rate target confirmed this was a factor:

public class SetupOculusSettings : MonoBehaviour
{
    const int TARGET_FPS = 90;

    void Start()
    {
        Application.targetFrameRate = TARGET_FPS;
        QualitySettings.vSyncCount = 0;

        #if UNITY_ANDROID && !UNITY_EDITOR
            OVRManager.display.displayFrequency = TARGET_FPS;
            OVRManager.SetSpaceWarp(false);
        #endif
    }
}

The actual fix

With the Metrics HUD enabled and real-time lights disabled, performance crept up toward 80fps. Dropping denoised textures to size 32 didn’t move the needle. Then I spotted it: eye scale in the OVR settings was set above 1.0.

Bumping eye scale over 1.0 tanks an otherwise empty scene to 35fps instantly. Disabling passthrough helped too. Those two changes, plus stripping out some leftover developer features, brought the build to 72fps. A full production build confirmed it.


What actually caused it

The 30fps wasn’t one thing — it was a pile of things compounding each other. Eye scale above 1.0 was the biggest single hit, passthrough added unnecessary GPU overhead, ASW was disguising the real framerate by halving it, and the scene loader was burning time even when the scenes weren’t visible.

None of this showed up clearly in the initial profiler pass. If you’re stuck at a round number on Quest and the usual suspects — geometry, textures, draw calls — aren’t moving it, check your eye scale and passthrough settings before spending too long on optimization work that won’t help.— title: “Rock Simulation in Unity” published: false —

During one project I had the opportunity to work on a couple of different rock simulations. One about rocks falling down a hill and one where they are tumbling through a mill.


title: “XRay effect in Unity Shader Graph” tags: [unity, unity-shader-graph, node-step, node-lerp, shader] —

The effect

I am using Unity 6.4 LTS and URP for this project.

This is a simple effect that has an outline disolve. Its being used when an object is shown / hidden in a project. It would be used for things like Sci-Fi spawn / despawn, xray vision / deactivation mode, ghostly transitions, etc.

Here is a sample with a slider placed into the shader graph, this slider is driven by a variable normally.

Outline Effect

Utilizing inputs we can customize the following elements:

Overview of the graph

Shader Graph

Graph Setup

Because we are using alpha clipping the shader must have alpha clipping enabled.

Graph Settings

Step node

Step node returns 1 if in > then the edge value otherwise 0. This can be a great way of developing masks. For example:

\[\text{step} = \left\{ \begin{array}{cl} 1 & : \ \text{In} \geq \text{Edge} \\ 0 & : \ \text{In} < \text{Edge} \end{array} \right.\]

Step Node

We can develop an interesting alpha clip with this, creating a bit of a fade out effect.

Step Node

Edge Effect

Because the gradient is smooth, we can use it to also get a bit of an edge effect with the step node. This is a little subtle in the images.

Outline Effect

The smooth gradient is important, without it the outline can’t exist. We are essentially using the smoothness to determine how thick the line edge is. Because both the line edge step function and the alpha clip step function are operating on the same input, the edge step function is just cutting away a little bit more than what the alpha clip is using. This little bit more is the edge effect size.

Another way to think about it is to think we are developing a mask with the step node that defines where the base color is. The edge will be everywhere else.

Outline Effect

Different Types of Noise - Gradient Noise

Demonstration of the gradient noise

Different Types of Noise - Voronoi

Demonstration of the voronoi noise

Properties

Property Reference Type Range
Color _Color Color NA
Dissolve Edge Color _Dissolve_Edge_Color Color NA
Dissolve Progress _Dissolve_Progress Float 0..1
Dissolve Edge Depth _Dissolve_Edge_Depth Float 0..1

Links

A catalog of different normal spaces

Part of the motivation of this thinking is that in godot the NORMAL comes in view space by default:

NORMAL (vec3): Normal that comes from the vertex() function, in view space. ...

INV_VIEW_MATRIX (vec4): View space to world space transform.


Convert from view space to world space

n_world_space = INT_VIEW_MATRIX * vec4(NORMAL, 0.0)

Convert from world space to local space

mat4 inv_model_matrix = inverse(MODEL_MATRIX);

vec3 n_local = (inv_model_matrix * vec4(n_world_space, 0.0)).xyz;

Working with vec3 and vec4

When working with some of these values we have to use a vec. There is a handy shortform:

vec4(vec3, value) which converts this to vec4(vec3.x, vec3.y, vec3.z, value);

To retrieve values, or convert down we have vec4().xyz which will return a vec3.

View/Camera Space

View space (or camera space) shifts the center of the universe to the camera lens. While it is natural to assume the camera looks straight forward down the Z-axis, Godot’s right-handed coordinate system flips this logic. The positive Z-axis actually points backward out of the screen toward you, meaning the camera is technically staring down the negative Z-axis into your 3D world.

World Space

Think of world space as the master grid of your entire game level. It is the global, shared coordinate system where the origin (0, 0, 0) acts as the exact center of the universe. All transformations are calculated relative to this grid. If you place a cube at (5, 0, 3), you are defining its absolute location within the world, regardless of how the object itself is rotated or where the camera is looking.

Model/Local space

Think of model space as an object’s personal, internal blueprint. The origin (0, 0, 0) is simply the pivot point of the mesh itself. Whenever you scale or rotate an object locally, you are manipulating it inside this specific space. A 3D cube might be placed a thousand miles away in the game world, but inside its own model space, its vertices still sit perfectly around its own center, ranging predictably from (-1, -1, -1) to (1, 1, 1).

Tangent Space

Normals point in the direction of the z-axis away from the face. Tangent space originates at the point on the polygon that it is being calculated at. The z-axis is point straight away from the mesh and the x,y are pointing perfectly flat along the polygon.

Snow Effect

The snow shader adds a top snow dusted appearance:

Outline Effect

Demonstration of the Different Attributes

Overview of the graph

Parameters

It supports a couple of parameters to drive how much snow will be on the model.

Snow Start: A value from 0..1 of where the snow will start lerping / appearing.

Snow End: A value from 0..1 of where the snow will finish lerping.

Everything else is different textures for the base / snow effect.

Params

Graph Setup

Full Graph

Creating the top mask

Using a normal vector configured to world with a dot product and Vector3.up works well to get the top mask.

The only issue is that this will of course return [-1, 1] since that is the range of the dot product.

The remap node is a handy node in this case, remapping the output from [-1, 1] to [0, 1]

Right now we don’t have any control over where the snow actually goes. You can see from the remap node that it is a smooth gradient from 0 to 1 from bottom to top. To turn it to a point where we have black where we don’t want snow and white where we do, the smoothstep node is great.

It takes a minimum value and returns 0 for anything under it, and 1 for everything above a max value. It does an interpolation between min and max otherwise.

Smooth Node

Dot Product

Since we are doing a dot product with the global Vector3.up. The dot product of 2 vectors will be 1 if they are facing the same direction, -1 if they are facing opposite, and 0 if they are 90 degrees from each other.

Note the geometric definition of a dot product is:

\[A \cdot B = \lVert A \rVert \lVert B \rVert \cos(\theta)\]

Since we are dealing with normalized vectors, $\lVert A \rVert$ and $\lVert B \rVert$ will both be 1.

\[A \cdot B = \cos(\theta)\]

This site has a nice visualization: https://maththebeautiful.com/dot-product/

Mixing a second material

Since the snow will be mixed with two materials, a base and a snow a little bit of effort has to be put into the mixing. Here is the base, roughness and normal mixing.

Base Color

Roughness Blending

Both color and roughness are the same node setup. I think there is not much to say about them other then the “T” value comes from the smoothstep discussed above.

Normal Blending

A little bit of care has to be taken when lerping normals. The normals have to be normalized after the lerp.

Vertex movement

This graph uses a little bit of vertex movement to get the snow pushing out ontop effect. Each of the vertexs will be moved along its normal to sort of poof out the snowy parts of the object. There is a requirement to have enough vertex density for the effect to make sense!

Vertex Movement