Hex Map 5.8
This Unity tutorial follows Hex Map 5.7 and converts river creation into a Burst Job.
Random Values in Burst Jobs
We're going to convert CreateRiversJob into a Burst job this time. The primary obstacle in this case is its reliance on UnityEngine.Random. We cannot perfectly replicate its number generation in Burst because we don't have access to its exact code, so we're not even going to bother with an approximation, no matter how close it could get. Thus this is the moment that we let go of trying to exactly reproduce the same maps as the original map generator.
From now on we'll rely on Unity.Mathematics.Random instead. It is a lightweight random number generator that works in Burst jobs that is sufficient for our needs. To avoid type name clashes we stop using the UnityEngine namespace.
//using UnityEngine;
using Unity.Mathematics;
We also switch to math.round() for rounding the river budget in Execute().
int riverBudget = (int)math.round(
landCells * settings.riverPercentage * 0.01f);
The job now has to keep track of its own random state. We initialize it using the seed. Instead of using the seed directly we pass it to Random.CreateFromIndex(). By adding an offset to the seed while doing this we can give each job its own random sequence. We'll use 4 as the offset, which is the job's index in the whole generation process, though any unique number would suffice.
Random random;
public static void Execute(…)
{
List<HexDirection> directions = ListPool<HexDirection>.Get();
new CreateRiversJob()
{
…
landCells = landCells,
random = Random.CreateFromIndex((uint)settings.seed + 4)
}.Execute();
ListPool<HexDirection>.Add(directions);
}
We used Random.Range() in Execute() to grab a random river origin. We have to replace it with random.NextInt(), passing it an exclusive maximum value. We can omit the inclusive minimum because it is zero.
int index = random.NextInt(riverOrigins.Count);
We also have to make this change in CreateRiver() when determining a flow direction.
direction = flowDirections[random.NextInt(flowDirections.Count)];
Besides that we need a random value when checking for an extra lake. We used Random.value for that, which we replace with random.NextFloat().
if (minNeighborElevation >= cell.Elevation &&
random.NextFloat() < settings.extraLakeProbability)
We now get different rivers, which can also change the terrain types, because the climate partially depends on rivers and also also because SetTerrainTypeJob could pick a different noise channel.
Native Collections
With the big hurdle out of the way the next step is to no longer rely on the System.Collections.Generic namespace, replacing it with Unity.Collections.
//using System.Collections.Generic;
using Unity.Collections;
Turn the climate field into a native array and remove the list for flow directions.
NativeArray<CreateClimateJob.ClimateData> climate;
//List<HexDirection> flowDirections;
public static void Execute(
HexGrid grid,
MapGeneratorSettings settings,
NativeArray<CreateClimateJob.ClimateData> climate,
int cellCount,
int landCells)
{
//List<HexDirection> directions = ListPool<HexDirection>.Get();
new CreateRiversJob()
{
grid = grid,
settings = settings,
climate = climate,
//flowDirections = directions,
cellCount = cellCount,
landCells = landCells,
random = Random.CreateFromIndex((uint)settings.seed + 4)
}.Execute();
//ListPool<HexDirection>.Add(directions);
}
We're creating a temporary list of river origins in GetRiverOrigins(). Replace it with a NativeList. Let's use the cell count for a reasonable default capacity.
NativeList<int> GetRiverOrigins()
{
NativeList<int> riverOrigins = new(cellCount, Allocator.Temp);
Adapt Execute() to work with the native river origins list and also let it create a temporary native list for the flow directions, passing it to CreateRiver(). The theoretical maximum is 30 flow direction entries, so we use that for its capacity. We also can no longer log the warning in the job, but not using up the river budget isn't a problem, so we just remove it.
void Execute()
{
NativeList<int> riverOrigins = GetRiverOrigins();
NativeList<HexDirection> flowDirections = new(30, Allocator.Temp);
int riverBudget = (int)math.round(
landCells * settings.riverPercentage * 0.01f);
…
riverBudget -= CreateRiver(originIndex, flowDirections);
…
//if (riverBudget > 0)
//{
//Debug.LogWarning("Failed to use up river budget.");
//}
//ListPool<int>.Add(riverOrigins);
}
What's left is to make CreateRiver() work with the native flow directions list.
int CreateRiver(int originIndex, NativeList<HexDirection> flowDirections)
{
…
if (flowDirections.Length == 0)
…
direction = flowDirections[random.NextInt(flowDirections.Length)];
…
}
We can now pass the native climate data directly to CreateRiversJob in ExperimentalMapGenerator. The generic climate list is no longer needed at all, so it can be removed.
CreateClimateJob.Schedule(
cellData,
info,
settings,
default,
out NativeArray<CreateClimateJob.ClimateData> climate).Complete();
//List<CreateClimateJob.ClimateData> climate =
//ListPool<CreateClimateJob.ClimateData>.Get();
//climate.AddRange(climateNA);
CreateRiversJob.Execute(…);
SetTerrainTypeJob.Schedule(
cellData,
info,
grid.CellPositions,
settings,
climate,
default,
out NativeArray<float> noiseSamples).Complete();
…
//ListPool<CreateClimateJob.ClimateData>.Add(climate);
Cell Data and Map Info
Like we did for the other Burst jobs we make CreateRiversJob work with native HexCellData and HexMapInfo fields instead of HexGrid. We also again get rid of the separate cell count.
//HexGrid grid;
NativeArray<HexCellData> cellData;
HexMapInfo info;
…
//int cellCount, landCells;
int landCells;
Random random;
public static void Execute(
//HexGrid grid,
NativeArray<HexCellData> cellData,
HexMapInfo info,
MapGeneratorSettings settings,
NativeArray<CreateClimateJob.ClimateData> climate,
//int cellCount,
int landCells
)
{
new CreateRiversJob()
{
//grid = grid,
cellData = cellData,
info = info,
settings = settings,
climate = climate,
//cellCount = cellCount,
landCells = landCells,
random = Random.CreateFromIndex((uint)settings.seed + 4)
}.Execute();
}
Adapt Execute() to work with the new data.
HexCellData origin = cellData[originIndex];
…
if (info.TryGetNeighborCellIndex(
origin.coordinates, d, out int neighborIndex) &&
(cellData[neighborIndex].HasRiver ||
cellData[neighborIndex].IsUnderwater))
{ … }
Do the same for GetRiverOrigins().
NativeList<int> riverOrigins = new(cellData.Length, Allocator.Temp);
for (int i = 0; i < cellData.Length; i++)
{
HexCellData cell = cellData[i];
…
}
And CreateRiver().
HexCellData cell = cellData[cellIndex];
HexDirection direction = HexDirection.NE;
while (!cell.IsUnderwater)
{
int minNeighborElevation = int.MaxValue;
flowDirections.Clear();
for (HexDirection d = HexDirection.NE; d <= HexDirection.NW; d++)
{
if (!info.TryGetNeighborCellIndex(
cell.coordinates, d, out int neighborIndex))
{
continue;
}
HexCellData neighbor = cellData[neighborIndex];
…
if (neighbor.HasOutgoingRiver)
{
cell.flags = cell.flags.WithRiverOut(d);
cellData[cellIndex] = cell;
neighbor.flags = neighbor.flags.WithRiverIn(d.Opposite());
cellData[neighborIndex] = neighbor;
return length;
}
…
}
if (flowDirections.Length == 0)
{
…
if (minNeighborElevation >= cell.Elevation)
{
…
//grid.CellData[cellIndex].values = cell.values;
cellData[cellIndex] = cell;
}
break;
}
direction = flowDirections[random.NextInt(flowDirections.Length)];
cell.flags = cell.flags.WithRiverOut(direction);
info.TryGetNeighborCellIndex(
cell.coordinates, direction, out int outIndex);
HexCellData outCell = cellData[outIndex];
outCell.flags = outCell.flags.WithRiverIn(direction.Opposite());
cellData[outIndex] = outCell;
…
cellData[cellIndex] = cell;
cellIndex = outIndex;
//cell = grid.CellData[cellIndex];
cell = outCell;
}
Pass the correct data to CreateRiversJob.Execute() in ExperimentalMapGenerator.GenerateMap(). Also remove the copy from the native cell data back to the grid directly afterwards.
CreateClimateJob.Schedule(…).Complete();
CreateRiversJob.Execute(
//grid,
cellData,
info,
settings,
climate,
//cellCount,
landCells);
//cellData.CopyFrom(grid.CellData);
SetTerrainTypeJob.Schedule(…).Complete();
Burst Job and Settings
We also again have to replace the reference to MapGeneratorSettings with individual settings fields in CreateRiversJob. We convert it to a Burst IJob at the same time.
using Unity.Burst;
using Unity.Collections;
using Unity.Jobs;
using Unity.Mathematics;
[BurstCompile]
public struct CreateRiversJob : IJob
{
NativeArray<HexCellData> cellData;
HexMapInfo info;
//MapGeneratorSettings settings;
NativeArray<CreateClimateJob.ClimateData> climate;
float extraLakeProbability, riverPercentage;
int elevationMaximum, waterLevel;
int landCells;
Random random;
public static JobHandle Schedule(
…
int landCells,
JobHandle dependency
)
{
return new CreateRiversJob()
{
cellData = cellData,
info = info,
//settings = settings,
climate = climate,
extraLakeProbability = settings.extraLakeProbability,
riverPercentage = settings.riverPercentage,
elevationMaximum = settings.elevationMaximum,
waterLevel = settings.waterLevel,
landCells = landCells,
random = Random.CreateFromIndex((uint)settings.seed + 4)
}.Schedule(dependency);
}
public void Execute() { … }
Get rid of the settings. prefix of all settings usage in the rest of the job.
Scedule and complete the job in ExperimentalMapGenerator.GenerateMap().
CreateRiversJob.Schedule(
cellData,
info,
settings,
climate,
landCells,
default).Complete();
Job Dependency Chain
We now have three burst jobs the run in sequence without any extra steps in between. So we can use their job handles to chain them together, invoking Complete() on the last one only, instead of completing them one at a time.
JobHandle handle = CreateClimateJob.Schedule(
cellData,
info,
settings,
default,
out NativeArray<CreateClimateJob.ClimateData> climate); //.Complete();
handle = CreateRiversJob.Schedule(
cellData,
info,
settings,
climate,
landCells,
handle); //.Complete();
SetTerrainTypeJob.Schedule(
cellData,
info,
grid.CellPositions,
settings,
climate,
handle,
out NativeArray<float> noiseSamples).Complete();
We will convert the remaining mock jobs in the future.