BorrowedTorch.Nature 0.11.2

Prefix Reserved
dotnet add package BorrowedTorch.Nature --version 0.11.2
                    
NuGet\Install-Package BorrowedTorch.Nature -Version 0.11.2
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="BorrowedTorch.Nature" Version="0.11.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="BorrowedTorch.Nature" Version="0.11.2" />
                    
Directory.Packages.props
<PackageReference Include="BorrowedTorch.Nature" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add BorrowedTorch.Nature --version 0.11.2
                    
#r "nuget: BorrowedTorch.Nature, 0.11.2"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package BorrowedTorch.Nature@0.11.2
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=BorrowedTorch.Nature&version=0.11.2
                    
Install as a Cake Addin
#tool nuget:?package=BorrowedTorch.Nature&version=0.11.2
                    
Install as a Cake Tool

BorrowedTorch.Nature

Nature for MonoGame (compute fork), generated and drawn on the GPU. Planned: grass, sky, fog, clouds, rain, snow, water. This release has grass - and with it wheat and flowers, anything that grows as blades from the ground - and a procedural sky, seen through air worked out from wherever the viewer is - on the ground, high up, in orbit - with volumetric clouds in it, seen from below, inside and above them; and the wind the grass sways in, for anything else to move in too.

Grass:

  • Plants are scattered over a heightmap terrain by a painted RGBA mask, each channel a layer's density, shaped by noise into clumps and clearings.
  • Generated once in compute; culled to the view and switched between LODs every frame in compute; drawn with indirect draws - the CPU never learns how many are visible.
  • Swaying in the wind, twisting to face it; blades pushed aside by tramplers - spheres, or capsules for a body, a log, a crate.
  • Translucency against the sun, root-to-tip occlusion, per-patch dryness and colour variance.

Sky:

  • The sun, the moon and the stars where they stand at a time of day, a day of the year and a latitude - the moon slipping east among the stars through the day, half a degree an hour, its phase going on with it.
  • The sun's disc, limb-darkened; the moon's, in its phase, with its seas - both at their true size or larger; the stars, twinkling as much as you ask, the more the lower they are, and turning about the pole through the night with a galaxy's band and a few nebulae - all of them dimmed and reddened by the air in front of them.
  • The polar lights in the dark, over as much of the sky as you ask - a glow low towards the pole, curtains up the sky, overhead, down to the far horizon - and as bright: folded curtains a hundred kilometres and more up, oxygen's green bright along a sharp foot, streaked by rays, teal over them, as photographs show them. Never the same twice: their curtains fold, drift along and brighten and fade, their rays flicker, at a pace you set. Overhead their rays meet in a crown. Behind the clouds; some 0.7 ms while they cover the whole sky.
  • The sunlight where the viewer is - its direction, and its colour through the air, white above it - for the host's directional light, the moon's once the sun is down; and a cube of the sky's light from there to light a scene by.
  • God rays: beams of the sun's glow fanning out through the gaps between the clouds and whatever stands before the sun, and lanes of shade behind them - as games show them, bright enough to see; stronger the hazier the air.

Air:

  • An Earth-like atmosphere over a planet of Earth's size (Hillaire 2020): Rayleigh and Mie scattering, ozone, light scattered more than once - the blue of the day, the glow about the sun, sunsets and twilight, a hazier sky on demand.
  • Seen from where the viewer actually is, every frame: the sky darkening and the horizon dropping as it climbs, the planet's limb glowing blue from orbit, the ground below lit through the air.
  • Aerial perspective: whatever is drawn dimmed and veiled by the air between it and the viewer, by its distance.

Clouds:

  • A layer of them around the planet, curving with it, at a height and depth of your choosing: how much of the sky they cover, from a few scattered puffs to overcast, and their kind, from flat sheets to heaped towers - shaped by Perlin-Worley noise, their edges worn by a finer one, spread by a weather map into patches and whole weather systems.
  • Marched through per view, from wherever the viewer is - below the layer, in it, above it - and seen as a plain layer from orbit; lit by the sun or the moon through the air above them and through themselves, light scattered on and on inside them, onwards most of all - silver linings, golden sunsets, dark undersides - and by the sky above and the ground below; the air in front of them hazing them with distance.
  • At half the view's size each way, every pixel's steps offset by blue noise and the noise averaged away over a few frames - a couple of milliseconds at 1080p - and cut off by the horizon at the view's own; in the cube a scene is lit by, too.
  • Their shadow over the ground about the viewer, 32 km across - each cloud's own, the gaps between, at a low sun too: on the air below them, lit and shaded with them; on the ground the sky shows; and, through a matrix and a map, on the host's own scene's sunlight. Up to a millisecond or so, drawn again only as the light or the clouds change, or the viewer goes a few kilometres on.
  • Drifting on the wind up there, all of a piece - shapes, edges and weather - on the host's clock: the frames before laid over where their clouds have gone, and the shadow carried along with them, drawn again no more often for it.
  • Cirrus high over them, at a height of your choosing: thin wisps of ice drawn out into fibres and bent into hooks, in patches drawn out along them - from a few long streaks to a veil over most of the sky. A sheet worked out a pixel at a time at the view's own size - some 0.2 ms - behind the clouds from below them, over them from above; lit by the sun through the air at their height, white and glaring about the sun by day, red after it has set on the ground below; the air in front of them reddening them towards the horizon, colour by colour. Drifting half as fast again as the clouds; in the cube too.
  • A rainbow in the rain opposite the sun, as much as you ask for: each colour's bow at its own angle as water bends it - the primary at 41-42 degrees, red outside, the sky inside it brighter; the secondary at 50-53, fainter, its colours turned about; the band between them darker. As bright as the way through the rain is long - brightest at its feet, gone below the horizon from the ground, a whole circle from above the rain - and lit by the sun as it reaches the viewer, red at sunset. In front of the clouds from under them, shaded by them from over them, and in front of whatever is drawn beyond the nearest rain; some 0.15 ms.

Wind:

  • One wind for whatever moves in it - the grass now, and anything a shader of yours makes move: air blowing one way, in metres a second, slower near the ground as its roughness slows it, and swinging about its mean in gusts that travel downwind and change shape as they go, a finer flutter over them - and eddies a metre or so across in it, so each patch of a field, each part of a sheet, is pushed its own way. Its velocity at any place, height and time is WindVelocity(xz, height) in Wind/Wind.fxh, and WindAirAt(position, height, time) with its eddies; what each thing does in it is its own - a blade leans against its stiffness.
  • Wind zones on top of it, up to eight: a fan blowing along its axis, a downdraft pouring down and spreading out over the ground, a blast blowing out from its middle - steadily, or in pulses.

Requires Windows and DirectX 11, through BorrowedTorch's MonoGame compute fork (BorrowedTorch.MonoGame.Framework.Compute.WindowsDX 3.8.6.101, which comes with it; 0.9.97 and earlier came with the old fork, MonoGame.Framework.Compute.WindowsDX.NoMemoryLeak): compute shaders, structured buffers and indirect draws. It loads effects of that fork's format (MGFX 100) only, so compile the shaders with that fork's content builder - BorrowedTorch.MonoGame.Content.Builder.Task.Compute with the tool BorrowedTorch.MonoGame.Content.Builder.Compute, as the demo does - or its effect compiler: the old fork's builder (dotnet-mgcb-compute 3.8.3) writes effects it refuses. Its shaders' hashes and noise are BorrowedTorch.Randomness's, which comes with it.

The two halves

C# (BorrowedTorch.Nature.Vegetation):

Type What it is
VegetationSettings One layer: how many candidates, which mask channel, sizes, colours, wind stiffness, textures, LODs.
VegetationTemplates Blade meshes for the LODs: Strip(n), Profile(...) shrink-wrapped to a cutout, WithHead, HeadOnly.
VegetationLayer A layer on the GPU: generates its plants, culls them, draws them - with Grass.fx, or an effect of yours.
TextureUtils.BuildCoverageMips Mipmaps for an alpha-cutout texture that keep its coverage with distance (BorrowedTorch.Nature.Utils).
TextureUtils.MakeFlowerHead A flower's head for a layer's head texture: petals about a yellow middle, its mips keeping their coverage.

C# (BorrowedTorch.Nature.Sky):

Type What it is
ProceduralSkySettings Time, date, latitude; haze, moon phase, stars; how large the sun and the moon are drawn; clouds, cirrus.
ProceduralSky A view's sky - its air, clouds, sun, moon and stars - a cube of its light to light by; the sunlight.
SkyView What one view keeps of the sky: its air, its clouds, and their shadow about its viewer.
SkyEffects The three effects the sky draws with, the host's to compile and hand in.
LightShafts God rays over a view's light: beams through the gaps in clouds and things, lanes of shade behind them.
SkyClock Where the sun, the moon and the stars stand, in the sky's frame: +Y up, -Z north, +X east.

C# (BorrowedTorch.Nature.Air):

Type What it is
AirTables The air's own tables - what gets through it, light scattered again, the sky's light by height - on haze.
AirView The air as one view sees it, each frame: its light in every direction, the aerial perspective over its scene.
AirLights What lights the air: the sun's and the moon's direction and irradiance.
Atmosphere On the CPU: where a position is over the planet, and how much of a light from a direction gets through to it.

C# (BorrowedTorch.Nature.Clouds):

Type What it is
CloudLayer The layer's noises - shapes, edges, weather, cirrus, blue noise - baked once, when clouds are first wanted.
CloudView The clouds as one view sees them: marched at half size, laid over the last frames', over the scene.
CloudShadows Their shadow over the ground about a view's viewer: for the air below them, and the host's scene's sunlight.
CloudDrift How far the clouds have drifted on their wind, in double: the difference of two, how far they went between.

C# (BorrowedTorch.Nature.Wind):

Type What it is
WindSettings Air: which way, how fast 10 m up, slowed by the ground below; how far gusts swing it, their shape.
WindZone Air of its own somewhere on top of the wind: a fan, a downdraft or a blast, its speed, reach and falloff.
WindField Hands the wind, at a time, and its zones to any effect that includes Wind/Wind.fxh - every frame.

HLSL, as source: Grass.fx and the headers it includes - Vegetation/Blades.fxh, the blades but their light, for a host to light them its own way (below), with Terrain.fxh and Wind/Wind.fxh; and Light.fxh, Grass.fx's own light; Sky/ProceduralSky.fx and Sky/LightShafts.fx; Air/Air.fx with its Air/Air.fxh - the air's model and its tables' lookups; Clouds/Clouds.fx with its Clouds/Clouds.fxh - the layer and its march, which the sky's cube includes too; and Wind/Wind.fxh - the wind, for any shader of yours to include as well. They arrive in your output at Content/Effects/Nature/, together - beside BorrowedTorch.Randomness's at Content/Effects/Randomness/, whose Random.fxh and Noise.fxh they include from there, so the two folders have to stay side by side. Compile Grass.fx, Sky/ProceduralSky.fx, Sky/LightShafts.fx, Air/Air.fx and Clouds/Clouds.fx yourself - with your content pipeline, or at runtime. The demo builds the grass with its Content.mgcb, from a copy of the repository's Shaders/ its StageEffects target lays out beside Randomness's first.

Using it

All layers share one Effect (Grass.fx) and one indirect-arguments buffer, each layer owning its stretch of it. The demo (Demo/Game1.cs) does all of the following and is the reference.

Once:

  1. Load the effect, and set what the world is - see World below.

  2. Make a 1x1 white texture: a layer without a blade or head texture is drawn with it.

  3. Create the layers, each at the byte offset where the previous ones end:

    var offset = 0;
    
    foreach (var settings in new[] { grass, wheat, flowers })
    {
        var layer = new VegetationLayer(GraphicsDevice, grassEffect, settings, offset, white);
        layers.Add(layer);
        offset += layer.ArgsSize; // bytes
    }
    
    args = new uint[offset / 4];
    drawArgs = new IndirectDrawBuffer(GraphicsDevice, BufferUsage.None, ShaderAccess.ReadWrite, args.Length);
    
    foreach (var layer in layers) layer.Generate(); // again whenever placement changes - or some cells (below)
    

Every frame:

  1. Set the frame's parameters - camera, LOD, wind, light, occlusion, tramplers (below).

  2. Cull, before drawing anything, so the GPU finishes its compute work first:

    foreach (var layer in layers) layer.WriteArgs(args); // resets each LOD's instance count
    drawArgs.SetData(args);
    
    grassEffect.Parameters["DrawArgsRW"].SetValue(drawArgs);
    grassEffect.Parameters["FrustumPlanes"].SetValue(frustumPlanes); // 6, world space, normalized, pointing in
    
    foreach (var layer in layers) layer.Cull();
    
  3. Draw your scene, then foreach (var layer in layers) layer.Draw(drawArgs);.

By cell

VegetationSettings.Cells splits a field into a grid across and down its uv - (1, 1), the whole field one cell, unless you say otherwise. Each cell has its share of the candidates (PerCell: Candidates shared out, rounded up) and keeps its plants together, so a cell can be grown and culled on its own:

  • layer.Generate(cells, count) grows the first count cells of cells again and leaves the rest as they are - the same plants any grow of them gave before, over the ground and the mask as they are now. A brush stroke grows again only the cells under it.
  • layer.Cull(cells, count) culls only the cells listed - those in the view, found by their boxes on the CPU - and never looks at the rest. A layer's draw buffer is sized to the cells a view lists, not to the whole field: grown when a view lists more, never shrunk.

A cell is x + y * Cells.X; Generate() and Cull() with no cells mean all of them. Nothing is read back: how many plants grew is the GPU's, and LiveCount reads it only if asked - waiting for the GPU, once after each Generate. With Cells (1, 1), a field's plants grow where 0.5 grew them.

The effect's parameters

What each layer's settings hold, VegetationLayer sets. The rest is the host's:

Group Parameters When
World FieldOrigin, FieldU, FieldV (the field, world XZ: its corner, and its edges - square to the axes or turned), HeightMap (over the field: R = height 0..1, A = 0 where there is no ground - read at the nearest texel, and blended only across texels on the same ground, so a step in it is a step and no plant grows off an edge), TerrainHeight (world units for 1), HeightTexel (1 / heightmap size), MaskMap (over the field: a layer's density per channel) once, and on change
Camera CameraPos, ViewProjection, PixelScale = 2 tan(fovY / 2) / viewport height, MsaaSamples (of the target - cutouts turn alpha into coverage); for an orthographic camera, whose pixel is as large at every distance, also PixelScaleAtEye = its view height / viewport height and LodDistanceAtEye, the distance every blade then counts as for its level of detail (0 both for a perspective camera) every frame
LOD LodStart (full density up to here), MaxDistance, FadeBand, MaxWiden, MinPixels as needed
Wind WindField.Bind(effect, wind, seconds) - the air, metres a second, and its zones where given; and the grass's own: TwistAmount, EdgeResponse, MaxBendAngle, UseBezier (0 arc, 1 Bézier) every frame
Light LightDir (towards the light), LightColor, AmbientColor, Roundness as needed
Occlusion RootFade, GroundBlend, AOMin, AOPower, AODirect as needed
Trampling Tramplers (up to 8: xyz one end - a sphere's centre - w radius), TramplersB (xyz the other end, w 1 for a capsule; left unset, w 0, a sphere about the first), TramplerCount, MaxTrampleTilt every frame
Colour PatchScale, PatchLo, PatchHi, DryAmount, TipDryness, BrightJitter - baked at generation before Generate
Cull DrawArgsRW, FrustumPlanes every frame

Shaders/Vegetation/Blades.fxh says what each one does, beside its declaration.

Lighting them your own way

Grass.fx lights the blades by one light and a flat ambient. A renderer with lights, shadows or a G-buffer of its own writes an effect of its own instead, on Vegetation/Blades.fxh: it has the Generate and Cull kernels (CS, CSCull) to make techniques of those names from, and for its vertex shader BladeVertex(tmpl, SV_InstanceID) - a template vertex of the drawn LOD's blade, posed: where it is in the world, its normal and rounding, the ground's normal, how far along the blade, its dryness and brightness, its uv - and for its pixel shader what the blade is there: BladeTextureAt, BladeNormal, BladeAlbedo, BladeOcclusion, BladeGroundWeight, BladeTransmission (the colour and strength of the light getting through it). layer.Draw(drawArgs, "YourTechnique") draws a layer with it - pick a cutout layer's (AlphaCutout) technique yourself.

Define BLADES_MOTION before including it, and BladeVertex gives where each vertex was the frame before as well (PreviousWorld), for motion vectors: the cull poses each blade a second time in the wind at WindTimePrevious - bind it with WindField.Bind(effect, wind, seconds, previousSeconds) - and among PreviousTramplers and PreviousTramplersB.

A trampler is a capsule - the points within its radius of the segment from one end to the other - and a sphere where its two ends are one, or where TramplersB is never set: so a host that hands over spheres alone, as before 0.11, goes on as it was. Each blade, taken as a segment of its own from its root up to its tip, is pushed as a sphere about the point of the capsule's axis nearest it would push it: out from a log lying across the field, round its ends, and out from a body standing in it.

Define BLADES_OCCLUSION, and before including it a function

bool BladeOccluded(float3 centre, float radius)

and the cull asks it of every plant the frustum keeps - its bounding sphere, world space as the blades are, its height and its head's size about it: true, and the plant is not drawn. How you know it is hidden is yours - a depth pyramid of what you drew first, say, read where the sphere's box on the screen spans a texel or two; Nature knows nothing of your depth or your matrices.

The sky

One ProceduralSky, one SkyView a view, and the compiled ProceduralSky.fx, Air.fx and Clouds.fx, handed in together as SkyEffects. The sky is light, linear and unbounded, on the scale of SunIrradiance - what the sun gives a surface facing it above the air: a floating-point target and an exposure after.

Positions are in the sky's frame, in metres. The world's ground at y = 0 lies on a planet of Earth's size, its centre straight below the world's origin: a camera at y = 2 stands on it, one at y = 400 000 is in orbit, and one far off across the world is over a part of the planet curving away below it.

var sky = new ProceduralSky(GraphicsDevice);
var view = new SkyView(GraphicsDevice);
var effects = new SkyEffects(skyEffect, airEffect, cloudsEffect);
var cube = new RenderTargetCube(GraphicsDevice, 256, true, SurfaceFormat.HalfVector4, DepthFormat.None);
var settings = new ProceduralSkySettings
{
    TimeOfDay = 18.5f, DayOfYear = 172, Latitude = 45.0f,
    CloudCover = 0.4f, CloudType = 0.6f, CloudBase = 1500.0f, CloudThickness = 3000.0f,
    CirrusCover = 0.3f, CirrusHeight = 9000.0f
};

CloudCover 0, the default, leaves the clouds out altogether - nothing of them marched or paid for - and CirrusCover 0, its default too, the cirrus; both 0, nothing of either is baked. The cirrus are kept some 500 m over the clouds' top while there are clouds under them, whatever CirrusHeight says.

A day that goes by on its own: run the settings on by the hours gone, on a clock you keep - past midnight into the next day, the date and the moon's phase on with it, so nothing jumps:

settings = settings.Later(seconds * 24.0f / dayLengthSeconds);

Every frame, first - it does nothing unless the settings changed, when it draws the air's tables again (the haze) and the galaxy and the nebulae, turned with the stars; and, the first time clouds are asked for, bakes their noises, some tens of milliseconds:

sky.Update(effects, settings);

Then the clouds carried on by the wind up there, settings.CloudWind - metres a second across the ground in the sky's frame, x east and y south, some twice the wind on the ground - for the seconds gone by since the last frame, on a clock you keep: 0 while it is paused, and they stand still. A view's clouds are laid over where the last frames' have gone, and their shadow goes along with them, drawn again only once the viewer is a few kilometres from its middle, as without a wind. The cube's clouds stay where they were when it was rendered: render it again once they have gone some way - sky.Clouds.Drift, minus the drift it was rendered at, says how far:

sky.Advance(gameTime.ElapsedGameTime.TotalSeconds);

When the settings change, and as the camera travels far - up through the air, or round the planet - a cube of the sky's light from where it is, clouds and all, to light the scene by if you light by the sky; a millisecond or two:

sky.RenderCube(effects, cube, cameraPosition, view); // the air, the ground and the clouds - not the sun's and moon's discs

var light = ProceduralSky.LightOf(settings, cameraPosition); // towards the sun (or the moon), and its irradiance there

Give your directional light light.Irradiance, shining along -light.Direction. The sun, the moon and the stars are not in the cube: a scene lit from the cube and by a light for the sun as well would have the sun counted twice. view, optional, is the view the cube lights: its clouds' shadow about the camera shades the air in the cube.

Every frame, for each view - its air from where its camera is, then its sky over the whole of its target, before the scene:

sky.PrepareView(effects, view, cameraPosition, skyFromView, projectionScale); // the view's tables: leaves no target bound
sky.Draw(effects, view, brightness, seconds);

skyFromView turns a view-space direction into the sky's frame (the inverse view, and the sky's own turn undone); projectionScale is 1 / the projection's M11 and M22. An orthographic camera looks down one way at every pixel, so a sky through its own projection would be one colour: draw the sky behind it through a perspective lens of your choosing instead - projectionScale that lens's - and pass the scene's own as PrepareView's last argument, sceneProjectionScale, (0, 0) for an orthographic scene. What lies over the scene - its air, the clouds and the bow in front of it - is then as far off as the scene really is, and its air looked through along the scene's own lines of sight (null, the default, for a scene seen through the sky's lens). For an orthographic scene, pass also sceneOriginScale, 1 / its projection's M11 and M22 - half its view's width and height: the clouds and the cirrus in front of it are marched along each pixel's own line, from beside the camera down the view, so a view down over the clouds from above them shows them where they lie over the ground; and its air is read down its one way, which the sky's screen need not hold. projectionOffset shifts the sky's lens off the view's middle - its M31 / M11 and M32 / M22, an off-centre projection's - sliding the sky up or down the screen as a flat picture, the view looking the way it does: a backdrop that follows an orthographic camera up and down a level, its horizon dropping as the camera climbs - give LightShafts.Draw the same, its last argument. seconds a clock you keep running, from any start, which the stars twinkle by, the polar lights change shape by, at settings.AuroraSpeed, and the lightning flashes by: some settings.Lightning flashes a minute within LightningDistance of the camera, where the clouds are thick enough to hold a storm, each flickering a few times - inside the clouds, lighting them from within, or, LightningStrikes of them, a bolt down from their base to the ground - their light LightningBrightness times LightningColor, white a little blue unless you say otherwise. The same moment always shows the same flashes: a clock held still holds them, one run back shows them again. They light the ground below the horizon the sky draws, and after Draw, view.LightningLight is their light where the camera is, for your scene: what a surface facing a normal gets of it, in the sky's frame - the clouds they light, from about where each is, and the brightest bolt from its own way - is view.LightningLight.IrradianceOn(normal), unshadowed, on the scale of the rest of the sky's light; the editor adds it to the sky's light on every surface, through the occlusion (Lib/SkyLight.fxh's SkyFlash).

PrepareView draws the clouds' shadow about the camera first, when it has to (view.Shadows): a 512 x 512 map, mipmapped, of how much of the light gets down through them to each point of the ground 32 km about it - in red; in green, how much of the rest gets down scattered, the grey light under an overcast, less the thicker it is. Shade your scene's sunlight with it, as the editor's Lib/CloudShadow.fxh does: a position, relative to the camera in the sky's frame, goes through view.Shadows.MapFrom(cameraPosition) to the map's uv in x and y - where the light reaching it came down through the clouds - and its height above the map's ground in z; read view.Shadows.Map there - past its edge, its last mip, the average - and fade it out up through view.Shadows.Layer, the clouds' base and top. The light it is for is view.Shadows.Light, the one LightOf gives where the camera is; nothing to read while view.Shadows.IsDrawn is false, as without clouds.

Once the scene is drawn, what is in front of it - the air, by the distance of whatever is drawn, then the clouds over the sky and over whatever is beyond them, lit from inside by the lightning, and the bolts striking the ground and the rainbow while settings.Rainbow asks for one - over the clouds from under them, under them from over them:

sky.DrawOverScene(effects, view, depth, sceneTarget, brightness);

depth is the view's linear view-space depth, red 0 wherever nothing was drawn and the sky shows, which holds the air already. The clouds are laid over the last few frames' to smooth their noise away: after a cut, call view.Clouds.Invalidate() so the next frame starts afresh. Anything else drawn through the same air or clouds can use their tables and noises too: sky.Air.Bind(effect), view.Air.Bind(effect) and sky.Clouds.Bind(...) hand them to an effect that includes Air/Air.fxh or Clouds/Clouds.fxh, where SkyViewAt, AerialPerspectiveAt and MarchClouds read them.

God rays, every frame, once the scene is drawn over the sky - one LightShafts a view, compiled LightShafts.fx:

var shafts = new LightShafts(GraphicsDevice);

shafts.Draw(shaftsEffect, settings, depth, sceneTarget, skyFromView, projectionScale, sky.HasClouds ? view.Clouds.Result : null);

depth is the view's depth, red 0 wherever nothing was drawn and the sky shows - an R32F view-space distance, say; sceneTarget the view's light, left bound. Along the lines to the sun more open than those beside them - through the gaps between what is drawn and the clouds the view drew this frame - the light of the open sky about the sun is added over the sky and the clouds: the beams. Along the ones less open, the sky is dimmed: the lanes of shade. A sky open all round the sun, or shut all round it, is left as it is. Stronger than the haze's own light would make them, so that they show - as Haze is thick, times SunRays - and worked out on the screen, so the sun has to be in view, or near it. About half a millisecond at 2125 x 1352.

The wind

One WindSettings for the world, handed to every effect that moves in it - the grass's, and any of yours that includes Wind/Wind.fxh - every frame, on a clock you keep running:

var wind = new WindSettings { Direction = new Vector2(1.0f, 0.3f), Speed = 7.5f, Roughness = 0.03f, Gustiness = 0.5f };

WindField.Bind(grassEffect, wind, gameTime.TotalGameTime.TotalSeconds);

It is air, in metres a second:

  • Speed is its mean at ReferenceHeight above the ground - 10 m, as weather stations and the Beaufort scale measure it - and what its gusts travel downwind at.
  • Nearer the ground it is slower, by the log law over the ground's roughness length, Roughness: 0.0002 m open water, 0.03 open grass, 0.1 crops, 0.5 to 1 woods and towns. Over open grass it blows at some half of its 10 m speed half a metre up, and at nothing at the roughness length and below; it grows on up to 500 m, above which the ground no longer slows it.
  • Gustiness is how far its gusts swing the speed about the mean, either way: 0.5 from half of it in a lull to half again in a full gust; 1 from calm to twice it.
  • Scale, Evolve and Flutter shape the gusts: how large, how fast they change as they travel, how much finer flutter there is over them.
  • Turbulence is how strong its eddies are - the air's turbulence near the ground, which the gusts, tens of metres across and smooth below that, leave out: a share of the log law's own over the ground's roughness, 1 what the air near the ground has - along the wind a quarter of its speed at head height over grass, a tenth over water, three quarters of that across it and half up and down. 0, the default, has none, as before 0.8. EddySize is how large they are, 1.2 m across; they ride the wind past and turn over as they go.

In a shader, with heights in metres above the ground, which only you know:

  • WindVelocity(xz, height) is the air's velocity there now, level, the way it blows; WindVelocityAt and WindSpeedAt take a time as well.
  • WindAirAt(position, height, time) is the air's velocity at a point in the world, its eddies in it: up and down and across the wind as well. The eddies ride past at the wind's mean WindEddyHeight above the ground - 2 m unless your effect sets its own, the height of what it moves; WindField leaves it alone - the same everywhere, so their pattern does not shear apart with height. WindEddiesAt(position, mean, height, carry, time) is the eddies alone, in air of your own: a draught of yours on top of the wind takes its own mean and carry.
  • WindProfile(height) is the mean's growth with height, and WindGust(xz) the gusts alone, 0 the deepest lull to 1 a full gust.
  • WindSettings.SpeedAt(height) is the mean on the CPU.

Wind zones

Air of its own here and there, on top of the wind - or in still air - handed over with it, up to WindField.MaxZones (8), the same then as now:

var fan = new WindZone { Kind = WindZoneKind.Fan, Position = fanPosition, Direction = fanForward, Speed = 8.0f, Radius = 1.5f, Length = 8.0f };

WindField.Bind(grassEffect, wind, seconds, previousSeconds, [fan]);
  • A Fan blows along its Direction from where it stands, a column Radius across and Length long - nothing behind it.
  • A Downdraft pours straight down from where it stands, a column Radius across and Length deep. Where it meets the ground - each point's height above it, which the caller passes, the ground taken as level about it - its air turns out over it within a radius of the ground, fastest at the column's edge, slowing as it spreads, gone three radii out, as strong as the column is where it lands.
  • A Blast blows out from where it stands every way, to its Radius: steadily, or with a Period once a period on the wind's clock, from 0 - its front going out to the radius in a quarter of the period, the air behind it dying away over the rest.

Each blows at its Speed, metres a second, inside its reach, easing to nothing over the outer Falloff share of it: 0 a hard edge, 1 all the way from the middle. WindAirAt adds them to the wind's mean, so the grass leans in them and the eddies ride in them too; WindZonesAt(position, height, time) is the zones alone, for air of your own - a cloth solver's. WindField.Bind without zones hands over none.

What each thing does in it is its own: a cloth's drag, a tree's sway. The grass is pushed as the square of the air's speed two thirds of the way up each blade, against its layer's LeanSpeed: the air there, m/s, that leans it all the way over - a breeze half as fast leans it a quarter as far - and the way the air blows there, its eddies turning it. The same settings and clock give the same air in every effect.

The demo

Demo/ is a field of grass, wheat and flowers over a heightmap, with a trampler hopping through it:

dotnet run --project Demo

WASD to move, Q/E down and up, Shift to go faster, right mouse button to look. B switches the blades' lean between an arc and a Bézier curve; F freezes the culling where the camera is, to see it from outside.

The demo still builds its effects with the old fork's content builder, whose effects the fork it now runs on refuses: until a content builder from BorrowedTorch's fork takes its place, it stops at loading them.

License

MIT

Product Compatible and additional computed target framework versions.
.NET net8.0-windows7.0 is compatible.  net9.0-windows was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on BorrowedTorch.Nature:

Package Downloads
BorrowedTorch.Engine

Kindling, Borrowed Torch's game engine: what a game's own code builds against - its features registering components, systems, keys and UI handlers - for the Kindling editor and player to run

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.11.2 103 11/18/2026
0.11.1 82 11/18/2026
0.11.0 88 11/17/2026
0.10.0 110 11/16/2026
0.9.99 100 11/14/2026
0.9.98 96 11/14/2026
0.9.97 103 11/13/2026
0.9.96 104 11/13/2026
0.9.95 92 11/12/2026
0.9.94 88 11/12/2026
0.9.93 99 11/12/2026
0.9.92 97 11/12/2026
0.9.91 94 11/12/2026
0.9.8 92 11/11/2026
0.9.7 94 11/11/2026
0.9.6 108 11/9/2026
0.9.5 87 11/9/2026
0.9.4 97 11/9/2026
0.9.3 98 11/9/2026
0.9.2 83 11/9/2026
Loading failed