Wilden

Plant pollination and hot/cold states

By Robin Dowling · 1 years ago

Problem: simulating plants or other sessile organisms pollinating and mating with others of the same species over distance.

A straightforward approach was to check for same-species organisms at adjacent positions. This mirrors pollen spreading by wind and was convenient because I already had the functionality for adjacent position searches. The drawback was that it put more pressure on an already tight loop with little FPS headroom.

After weighing alternative designs and their complexity against possible efficiency gains, I kept the adjacent-position search but added two under-the-hood improvements. I wanted to cache adjacent data per position and species, but that required a stable state to cache. Since my state changed constantly by design, a cache would go stale immediately.

Solutions

  1. Double buffer read/write state
    Previously, I used a single “hot” state for both reads and writes, meaning the state changed constantly during iteration. This worked because I ensured each organism was processed only once per iteration, but it made caching impractical.

    The fix was to implement a double-buffered state manager with two parallel states. One state is read-only for the duration of the iteration. All updates are written to the second state, which is rebuilt in the background. At the end of the iteration, the states swap, so the next iteration reads from the previously written state while a new one is built from scratch.

  2. Cache
    With a static read-only state, I could implement a simple key-value cache for lookups, such as adjacent positions. This allowed plants to locate nearby same-species plants and attempt mating efficiently.

Evolution of Server-Client Communication

By Robin Dowling · 1 years ago

Building an efficient server-client communication system for my evolution simulation has been a fascinating journey. Each iteration brought new challenges and insights as I balanced performance, bandwidth usage, and user experience. Here's a look at my progression:

1. Always Full State

My first implementation was straightforward: send the entire world state to every client on each update. I created a data structure that contained all entity information, metadata about the world state, and statistics. This provided a reliable baseline but quickly revealed scalability issues as my simulation grew.

This approach worked well for testing but wasn't sustainable with hundreds of organisms and multiple clients.

2. Custom Serialization

To reduce payload size, I implemented custom serialization. Instead of sending verbose JSON with property names, I used a simple array where keys and values are packed together, removing the need for many control chars.

This significantly reduced my payload size, with some entities shrinking from ~200 bytes to just ~50 bytes.

3. Minimized IDs

Entity IDs were initially small 4 char base62 IDs. I implemented a more compact ID system using incremental base62 IDs for session-scoped references, reducing size even more.

4. Change Deltas

Instead of sending complete entities on each update, I began tracking client state and sending only what changed. I implemented a function that compares two states of an entity and returns only the properties that differ between them. This delta approach meant that if only an entity's position changed, I would send just the position rather than the entire entity definition.

This reduced typical payloads by 70-90% in stable world states, as most entities only change position or a few properties between frames.

5. Notify Server of Missing States

Delta-based approaches created a new problem: what if clients miss an update? I implemented a feedback mechanism allowing clients to notify the server when they're missing entity data. When a client sends a feedback message indicating it has missing entities, the server clears its assumptions about what the client knows and sends a full update on the next iteration.

6. Skip Out-of-Order State Iterations

Network delays sometimes resulted in iterations arriving out of sequence. I added a simple mechanism to track the last applied iteration and ignore older ones. In the client code, I check if the received state's iteration number is less than the already applied iteration, and if so, discard it.

This prevented visual glitches where the world would temporarily "jump backward."

7. Client-Side State Buffering

To further address the occasional out-of-order delivery, I implemented a buffering system in the client. The system stores incoming states in a map keyed by iteration number. When processing states, it first looks for the exact next iteration needed. If that iteration is available, it's applied and removed from the buffer. If too many states accumulate in the buffer, it falls back to using the oldest one to prevent memory issues.

This buffer allowed the client to store states that arrived early and apply them in the correct sequence, creating smoother animations.

8. Aggregate Similar Organisms

As my simulations grew more complex, areas with high organism density created bandwidth spikes. A solution was to aggregate similar organisms in congested positions. When detecting multiple organisms of the same species in the same position, I add a special "aggregate" metadata property to the first organism's state, indicating how many similar organisms are at that location.

The client then expands these aggregates into individual entities. It checks for the aggregate property, and if present, creates that many individual entities with slightly modified IDs to distinguish them.

9. MessagePack Binary Serialization

Even with custom text-based serialization, every payload was still transmitted as a UTF-8 string over WebSocket text frames. Numeric values like coordinates and counts were encoded as decimal character sequences, and the framing overhead of string-based transport added up.

I migrated the entire WebSocket pipeline — both the state and stats channels — to MessagePack over binary WebSocket frames. On the server side, the serialized string payloads are encoded into MessagePack using msgpackr, then optionally compressed with zlib. The client receives ArrayBuffer messages, decompresses if needed, and decodes the MessagePack bytes back into the compact string format that the existing deserializer already understands.

The switch to binary framing eliminated UTF-8 encoding overhead and allowed the transport layer to handle raw bytes end-to-end. Combined with the existing delta and aggregation optimizations, this reduced typical per-update payload sizes by a further ~20-30% compared to the previous text-based approach.

Results

The iterative improvements paid off:

  • Average payload size: reduced from ~1.5MB to ~1.5KB per update
  • Peak bandwidth usage: reduced from ~10MB/s to ~15KB/s

Each optimization built upon the previous one, creating a data transfer system that's efficient, resilient, and scalable.

Minimal serialization

By Robin Dowling · 1 years ago

When sending frequent updates in a real-time system, JSON wastes a surprising amount of bandwidth. Every key is wrapped in quotes, separated by colons, and repeated on every update. For small payloads, that overhead can be bigger than the actual data.

For example, a JSON delta update like:

{ "a": "Alice", "b": "30" }
      

is 23 bytes on the wire. By removing quotes, braces, and colons, and by making the first character of each segment the key, the same data becomes:

aAlice,b30
      

— just 14 bytes.

This compact format works best when keys are short and fixed, and values are simple strings. It’s trivial to encode and decode, and in high-frequency updates the savings add up quickly.

To go a step further, the system wraps this compact string format inside MessagePack binary frames. The serialization logic stays the same, but the transport layer encodes the result into MessagePack bytes and sends them over binary WebSocket frames, eliminating UTF-8 framing overhead and shaving off another ~20-30% on the wire.

Minimizing ids

By Robin Dowling · 1 years ago

In order to minimize data size in memory and over the wire, I wanted to reduce all unnecessary bloat. Entity ids was one area that could be optimized. minimizing data size saves latency, memory and cost of data egress, which adds up over time for many clients.

I used to have a four char base62 id for entities, which is already very small. But it could be smaller, using base62 incremental ids.

The new id scheme is incrementing values in a base62 address space, starting with ”a” up to ”9”, then continues from ”aa” up to ”a9”, increasing the size of the id slowly, always ensuring the smallest possible set of unique ids.

These ids are purely internal, and the typical number of entities in an evolution is below 1 million.

An eternal cycle of energy

By Robin Dowling · 1 years ago

Sessile organisms feed off of elements in the soil, while motile organisms feed off of each other, and off of sessile organisms. When an organism dies, part of its internal elements are returned to the soil as elements for sessile organisms to feed on.

This creates an eternal cycle of energy in the simulated world.

Finding an equilibrium

By Robin Dowling · 1 years ago

Balancing the weight variables that drive the evolution simulation is very tricky. Each factor pushes and pulls on the others, and even the smallest tweak can set off a chain reaction. Sometimes two values directly oppose each other, forcing me to decide which way the scales should tip. At the moment, there are about 15–20 core variables, all intertwined — a web of influence that's roughly 15² connections deep. It's like tuning an ecosystem’s DNA: the goal is to find an equilibrium where life can flourish without overrunning itself, resilient enough to weather big shocks, but fluid enough to evolve in new directions. History is full of surprises — who would have bet on a world without dinosaurs after the Cretaceous?

Watching the environment adapt is really fascinating. Sometimes it recovers, sometimes it collapses spectacularly. Either way, I'm still turning the dials, chasing that perfect balance.

Client payload sizes

By Rosedo Devs · 1 years ago

Transferring state from backend to client has been very greedy so far, passing payloads of over 1MB per evolutionary update, ~60 frames per second. Fine for development, but slow and costly to put into production, where egress costs accumulate and data has to travel over the wire across long physical distances to each client.

Typically you want a single payload to be no more than 1kb, and ideally less than 10kb per second.

A simulation of evolutions

By Robin Dowling · 1 years ago

I'm building an evolution simulation where observers can watch as species evolve, thrive, and establish themselves in different regions of their world, only to eventually be displaced by other emerging species.

Species

The simulation models the process of evolution through emergent behavior and randomness. There are no predefined organisms, species, or events. Instead, all life forms are generated based on randomly assigned genetics, and evolution unfolds through the cumulative effects of interaction and adaptation.

Organisms in the simulation are not technically categorized as plants or animals internally. Their genetics determine their role: some remain stationary, effectively resembling plants, while others move and interact with others, resembling animals. Regardless of their behavior, all organisms share the same core objectives: to survive and reproduce.

Species are not static or predefined, but instead form dynamically. Organisms with similar genetics are grouped into species through a process that reduces and transforms genetic data into clusters. Over time, mutations and genetic drift ensure that species composition evolves continually.

Energy

Energy is central to survival. Organisms lose energy over time and must replenish it by consuming other organisms or environmental elements.

Reproducion

Organisms reproduce with suitable mates, and after pregnancy completes, the genetic material of the two mating organisms are combined into an average of both, with mutations introducing variation in their offspring. The success of reproduction depends on both environmental conditions and the ability of organisms to survive long enough to reproduce.

Conflict

Conflict naturally arises as organisms compete for limited resources, access to suitable habitats, and opportunities to reproduce. These conflicts may result in threats, or direct confrontations, sometimes leading to the death of one or more organisms.

Diseases

Diseases add an additional layer of complexity. Like organisms, diseases have genetic profiles and spread based on compatibility with host genetics. Transmission occurs through proximity or specific interactions, and the severity of their effects depends on the genetic match between the disease and the host as well as the character of the specific disease.

Knowledge

Organisms are capable of learning from their experiences. They learn whether a particular energy source, location, or interaction was beneficial or harmful, and they adapt their behavior accordingly. This knowledge can be shared with others, and survive across generations, enabling the spread of adaptive strategies within populations.

Simple and complex

The simulation is built around a few core elements: Energy, Organisms, Elements, and Diseases. These components interact in a complex system, where survival and evolution emerge from the interplay of randomness, competition, and adaptation.

Endless evolutions

Observers will see different species moving about, sometimes scattered and sometimes in groups. When all life is extinguished, a new evolution begins, with yet another set of randomly created organisms and species.

The energy cycle

By Wilden · 1 years ago

In the simulation, energy is never created or destroyed, but constantly changes form and location as it moves through the ecosystem. The way organisms interact with their environment and each other is fundamentally shaped by this cycle.

Sessile and motile feeding

Sessile organisms—those that remain fixed in place—draw their energy from elements in the soil. These elements are distributed throughout the world and act as the primary food source for sessile life. Motile organisms, on the other hand, are more opportunistic. They feed on other organisms, including both sessile and other motile types. This predation and consumption is the main way energy moves up the food chain.

Death and recycling

When any organism dies, its internal composition is not simply lost. Instead, a portion of its elemental makeup is returned to the environment. These elements are released back into the soil, becoming available once again for sessile organisms to absorb. This recycling is not total—only a fraction of the organism’s elements are returned, which means energy is always in flux, but never static.

The cycle

This system creates a closed loop: elements in the soil feed sessile organisms, which in turn become food for motile organisms. When motile organisms die, their elements are recycled back into the soil. The same is true for sessile organisms. Over time, energy and matter circulate endlessly through the world, passing from soil to plant to animal and back again.

Code and configuration

The rates at which energy is consumed, transferred, and recycled are all configurable. The amount of energy sessile and motile organisms consume, and the rate at which elements regenerate in the environment, are also controlled by parameters. This design ensures that the world never runs out of energy entirely, but also that energy is never so abundant that populations can grow without limit. The balance between consumption and recycling is what allows the simulation to sustain itself over many generations, with populations rising and falling as energy flows through the system.

At least that is the goal. Balance is very tricky.

Everything depends on everything

By Robin Dowling · 1 years ago

Complexity in setting the weight variables for everything affects the evolution massively. All weights influence each other, and changing one value ever so slightly can have enormous effects. Sometimes you need to weigh two or more values against each other, since they can have clashing effects.

Currently, with about 15–20 values, and each value able to vary independently across a wide range, the number of possible combinations is incredibly large — effectively limitless. The space of evolutionary paths grows exponentially with each added value. Add to that all the genetic compositions, each individually affected by the weights.

One problem with this is finding an equilibrium — a stable environment where life can be sustained continuously, but not overflow. It needs to be resilient to big changes, but also fluent enough to follow them into unexpected new evolutionary directions. Like, whoever thought that dinosaurs wouldn't be a thing after the Cretaceous period?

It's fun to see the environment adapt — and often collapse, unfortunately. I'm still tweaking those weights.