Kindlewild

Plant pollination and hot/cold states

By Robin Dowling · 4 months 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.