Skip to main content

ForestGenerator

A class in Root.Township, Alta.Forests.

Generates the procedural forest from a seed: a path graph inside an outline, reshaped and painted terrain, rivers, and per-chunk content. Most results are cached on disk by seed. A scene component on both sides; All lists them.

Constructors​

MemberWhat it is
ForestGenerator()Unity makes components itself; use AddComponent or spawn a prefab instead of new.

Fields​

63 private and internal fields
MemberWhat it is
private static HashSet<ForestGenerator> allBacking field for All.
private Action<string> bootupStatusProgress callback used while Bootup runs. Null otherwise.
private bool btnNavmeshEditor button that runs RegenerateNavmesh.
private string cacheBacking field for Cache. Part of every cache file name for this forest.
private float currentMaximumMost distance two points can be apart and still get an edge, for the current pass.
private float currentMinimumLeast spacing between points, for the current pass.
private float edgeBufferDistance points and edges must keep from the outline. 20 by default.
private float edgeHeightPullFalloffNot read in this class.
private float edgeHeightPullFalloffPowerNot read in this class.
private float edgeHeightPullStrengthNot read in this class.
private List<Node> entranceNodesBacking field for Entrances. Not assigned in this class.
private float entranceRadiusRadius given to entrance nodes. 5 by default.
private Transform[] entrancesTransforms marking where paths enter the forest. They become the first nodes.
private IForestGeneration[] forestGenerationThe IForestGeneration steps under the generator (trees, rocks and more) that make global, static and dynamic content.
private Task<ForestGeneration> generationThe generation task, started once by GetGenerationAsync.
private int groupSizeXNot used. Group sizes come from the heightmap size instead.
private int groupSizeZNot used. Group sizes come from the heightmap size instead.
private int hardLimitMost points the graph can have. 2000 by default.
private int heightInterationsNumber of ModifyHeights smoothing passes. 10 by default.
private float heightRandomPowerPower applied to the random height nudge, so most nudges are small. 2 by default.
private int initialCountHow many starting points were added after the entrances. Used by gizmos.
private float initialHeightHeight new nodes start at. 10 by default.
private float initialMaximumNearbyDistanceEdge distance limit while connecting the entrances. 20 by default.
private float initialMinimumPointDistancePoint spacing while connecting the entrances. 10 by default.
private int initialPathIncrementPoints added per pass until every entrance is connected. 1 by default.
private float initialPointExtraRadiusMaximumMost extra radius for the starting points. 12 by default.
private float initialPointExtraRadiusMinimumLeast extra radius for the starting points. 5 by default.
private int initialRandomPointCountRandom points tried at the start. 100 by default.
private Dictionary<LocationChunk, InstructionSet> instructionsStatic instruction set run for each loaded chunk, undone on ReleaseStatic.
private bool isDrawingGizmosEditor: draws the generated graph in play mode.
private float lastIterationWeightMultiplierHow strong the random nudge is on the last height pass, compared to the first. 0.1 by default.
private static Logger loggerNLog logger for this class.
private float maximumHeightPerIterationLargest random height change per pass. 5 by default.
private float maximumNearbyDistanceEdge distance limit after the entrances are connected. 20 by default.
private float maximumRadiusLargest base node radius, picked by noise. 10 by default.
private float minimumPointDistancePoint spacing after the entrances are connected. 10 by default.
private float minimumRadiusSmallest base node radius, picked by noise. 2 by default.
private ConcurrentBag<ForestGenerator.NearestInfo> nearestInfosPool of nearest-edge buffers reused across height worker threads.
private NodeMapModifier[] nodeMapModifiersModifiers under the generator that change the finished node map. Those that are also terrain modifiers change heights.
private float openingMinimumDistancePoint spacing for the very first points. 20 by default.
private Transform[] outlineTransforms tracing the forest's border.
private static readonly NNConstraint overworldOnlyAstarA* constraint limited to the first graph, used for navmesh updates.
private float radiusNoiseScaleScale of the noise that picks node radii. 10000 by default.
private int randomPointCountTarget node count for the second, filling pass. 1000 by default.
private List<Vector3> randomPointRadiusWorking list of points as x, z and radius. The first ones are the entrances.
private float randomWeightingChance (0 to 1) that carving restarts from a random used node instead of the newest.
private int seedThe forest seed. -1 until set; the server picks a random one. Saved and synced to clients.
private float selfHeightWeightingHow much a node's own height counts against its neighbours when smoothing. 2 by default.
private int sizeXHeightmap resolution on X, from SetupConstants.
private int sizeZHeightmap resolution on Z, from SetupConstants.
private Texture2D splatMapNot read in this class.
private int splatMapResolutionMultiplierNot read in this class.
private ISplatPainter[] splatPaintersSplat painters under the generator, found when painting starts.
private MethodSync syncSeedMethod sync that sends the seed to joining players.
private TerrainInfo terrainThe terrain the forest reshapes and paints.
private float terrainEdgeBlurPowerNot read in this class.
private float terrainEdgeBlurStrengthNot read in this class.
private float terrainFadeDistanceDistance inside the border over which generated heights blend into the existing terrain. 10 by default.
private List<ITerrainModifier> terrainModifiersNode map modifiers that also change terrain heights.
private ForestGenerator.TerrainNoise[] terrainNoiseNoise layers added to terrain heights, each with scale, magnitude and a fade near paths.
private Vector3 unitHeightmap scale: world size of one heightmap cell and the height range.
private List<Node> usedNodesNodes reached by carved paths, used to pick where carving continues.
private TaskCompletionSource<bool> wipeLockSet while Wipe runs, so generation and a second wipe wait for it.

Properties​

MemberWhat it is
static IEnumerable<ForestGenerator> All { get; }Every forest generator in the scene.
string Cache { get; }The forest's name in cache file names, such as "The Forest".
ICollection<Node> Entrances { get; }The entrance nodes of the path graph.
int GizmosVersion { get; private set; }Counter bumped when debug gizmo data changes.
bool IsDuringCalculate { get; }True while generation is running.
RiverGenerator RiverGenerator { get; private set; }The river, lake and waterfall generator under this forest.

Events​

MemberWhat it is
event Action<LocationChunk> GeneratedDynamicRaised when a chunk has had its dynamic content (creatures, items) generated.

Methods​

MemberWhat it is
static async Task<ForestGenerator> Get(Vector2 position)Finds the forest whose outline contains an x/z point. Waits for generation.
async Task<IEnumerable<ForestGCoreInstruction>> GetAllGCores(ForestGeneration generating)Collects the generation core instructions of every chunk in a layout.
ForestGeneration GetGenerated(bool isThrowingError = true)The layout if generation has finished, else null (logging an error unless told not to).
Task<ForestGeneration> GetGenerationAsync()The generated layout. Starts generation the first time and returns the same task after.
override void Initialize()Sets up the message that syncs the seed.
override void InitializeAsServer(SpawnData spawnData)Server: picks a random seed if none is saved.
override void OnConnected(Player player)Server: sends the seed to a joining player.
async void RegenerateNavmesh()Rebuilds the A* navmesh inside the forest outline.
async void Reheight()Editor tool: recomputes terrain heights inside the forest.
void ReleaseDynamic(LocationChunk chunk)Clears a chunk's dynamic content from every generation step.
void ReleaseStatic(LocationChunk chunk)Clears a chunk's static content and undoes its instructions.
async Task RequestDynamic(LocationChunk chunk)Generates a chunk's dynamic content and raises GeneratedDynamic.
async Task RequestStatic(LocationChunk chunk, bool isRequiringTerrain, CancellationToken cancellationToken)Runs a chunk's static instructions (trees, rocks). On the server it can also update the navmesh for the chunk.
async void Resplat()Editor tool: repaints terrain textures inside the forest.
async Task Wipe(int newSeed = -1)Server: clears the forest's caches and chunk saves, moves players out and regenerates. A seed passed in is ignored; negative picks a random one. TavernLib replaces it with a reset that takes effect at the next restart.
void ZeroHeights()Editor tool: flattens the terrain inside the outline to 0.
28 private and internal methods
MemberWhat it is
private void AddRandomInTriangle(ForestGeneration result, Random random, int startIndex, float additionalRadius)Picks a random point in one outline triangle and keeps it if it is far enough from the border and other points.
private void AddRandomPoint(ForestGeneration result, Random random, float additionalRadius)Tries to add one random point, picking an outline triangle weighted by area.
private float AreaStartingAt(ForestGeneration result, int index)Area of the outline triangle starting at an index, on the x/z plane.
private void Awake()Finds the river generator, node map modifiers and generation steps under it, and adds itself to All.
private async Task Bootup(Action<string> progressNotification)Generates the forest while reporting progress. No callers in this build.
private Node Carve(ForestGeneration result, Random random, Node current)Extends a path from a node to a random unused neighbour, marking the edge as a normal path. Returns the new node or null.
private async Task Connection(Connection connection, Action<string> progressNotification)Makes sure a connecting client has the node and terrain caches for this seed. No callers in this build.
private void CreateRandomPoints(ForestGeneration result, Random random, int count, bool isClearing, float additionalRadiusMinimum = 0, float additionalRadiusMaximum = -1)Adds up to count random points (each may fail), optionally clearing first and re-adding the entrances.
private async Task EvaluateHeights(ForestGeneration result, Random random, float[,] heights, TerrainAccess access, int minX, int minY, int maxX, int maxY)Worker for a block of heightmap rows: sets heights inside the outline from nearby paths and noise, fading into the existing terrain at the border.
private async Task EvaluateSplatData(ForestGeneration result, Random random, SplatData[,] data, TerrainAccess access, int minX, int minY, int maxX, int maxY)Worker for a block of splat rows: runs every splat painter on cells inside the outline.
private float EvaluateTargetHeight(ForestGeneration generation, ForestGenerator.NearestInfo info, Vector2 position, out float distanceToPath)Works out a terrain height from the nearest path edges' node heights, then applies the terrain modifiers.
private async Task<ForestGeneration> GenerateAsync()Waits for a wipe and a seed, then loads the forest layout from cache or generates nodes, terrain and chunk instructions.
private async Task<bool> GenerateInternalAsync(ForestGeneration result)Builds the path graph on a worker thread: random points, Delaunay edges, carved paths, heights, spaces and node modifiers.
private async Task GenerateTerrain(ForestGeneration forest)Gets the forest's heights and splat (from cache or by generating, with rivers), applies them and spawns river visuals and global content.
private Task<InstructionSet> GetChunkInstructionsAsync(LocationChunk chunk, ForestGeneration forest)Gets a chunk's static instruction set from cache, or builds it by running every generation step's GenerateStatic.
private Node GetNext(Random random)Picks the next node to carve from: usually the newest used node, or a random one by randomWeighting.
private void ModifyHeights(ForestGeneration result, Random random, float weight)One smoothing pass over node heights: blends each with its path neighbours and adds a random nudge. Entrances keep their height.
private void OnDestroy()Removes itself from All.
private async void OnDrawGizmos()Editor: draws the outline, or after generation (if isDrawingGizmos) the biome spheres, outline, paths and spaces.
private void OutlineGizmo(ForestGeneration result)Editor: draws the outline triangles.
private void PathGizmos(ForestGeneration result)Editor: draws the starting points, node radii and edges coloured by type.
private void Reproduce(ForestGeneration result, Dictionary<Node, List<Node>> toReproduce)Rebuilds paths from the last pass by pathfinding between previously linked nodes in the new graph.
private void SetupConstants()Reads heightmap size and scale from the terrain data.
private void SpaceGizmos(ForestGeneration result)Editor: draws a sphere at each space's centre, coloured by space type.
private void SyncSeed(IPlayer player, Stream stream)Method sync handler that sends or reads the seed.
private void Traverse(ForestGeneration result, Random random)Carves paths from used nodes until none can grow further.
private void WeightToEdge(ForestGeneration result, float fade)Pulls each node's height towards the height of the nearest outline edge. A fade of 0 sets it fully.
private async Task WipeChunk(LocationChunk chunk)Unloads a chunk, saves and clears its save, and deletes its static instruction cache. Used by Wipe.

Used in​

Members of other types that take, return or hold a ForestGenerator: