CaveGenerator.cs
using System;
using System.Collections.Generic;

/// <summary>
/// Builds a sealed, organic cavern: a closed noise-deformed shell with its faces pointing inward,
/// a bumpy walkable floor, and matching collision. Because the shell is one closed surface there
/// is no way out. Runs in the editor too, and rebuilds whenever a property changes.
/// </summary>
[Title( "Cave Generator" ), Category( "World" ), Icon( "landscape" )]
public sealed class CaveGenerator : Component, Component.ExecuteInEditor
{
	[RequireComponent] public ModelRenderer Renderer { get; set; }
	[RequireComponent] public ModelCollider Collider { get; set; }

	[Property] public Material Material { get; set; }

	/// <summary>Half-extents of the cavern before noise, in inches.</summary>
	[Property] public Vector3 Size { get; set; } = new( 1600, 1200, 400 );

	[Property] public int Seed { get; set; } = 1337;

	/// <summary>Subdivision level of the shell. 5 is about 20k triangles.</summary>
	[Property, Range( 3, 6 )] public int Detail { get; set; } = 5;

	/// <summary>How far the walls and ceiling bulge in and out, as a fraction of Size.</summary>
	[Property, Range( 0f, 0.6f )] public float WallNoise { get; set; } = 0.3f;

	[Property] public float NoiseFrequency { get; set; } = 1.8f;

	/// <summary>Where the floor cuts the shell, from -1 (very bottom) to 0 (halfway up).</summary>
	[Property, Range( -0.9f, 0f )] public float FloorLevel { get; set; } = -0.55f;

	/// <summary>Height of the rolling bumps on the floor, in inches.</summary>
	[Property] public float FloorBumpHeight { get; set; } = 28f;

	/// <summary>Small-scale crags on the walls and ceiling, as a fraction of Size.</summary>
	[Property, Range( 0f, 0.2f )] public float WallDetail { get; set; } = 0.06f;

	/// <summary>World units covered by one repeat of the texture.</summary>
	[Property] public float TextureScale { get; set; } = 256f;

	[Property, Group( "Formations" )] public int Stalactites { get; set; } = 45;
	[Property, Group( "Formations" )] public int Stalagmites { get; set; } = 25;
	[Property, Group( "Formations" )] public int Boulders { get; set; } = 20;

	/// <summary>Floor radius around the player spawn (local 0,0) kept free of stalagmites and boulders.</summary>
	[Property, Group( "Formations" )] public float SpawnClearRadius { get; set; } = 300f;

	/// <summary>
	/// Directions (from the cave's centre, local space) where a small hole is punched through the
	/// shell. Holes let light in but keep their collision, so nothing can leave through them.
	/// </summary>
	[Property, Group( "Holes" )] public List<Vector3> HoleDirections { get; set; } = new();
	[Property, Group( "Holes" )] public float HoleRadius { get; set; } = 75f;

	// Hold on to the generated mesh and models: if the managed Mesh is garbage collected its GPU
	// buffers go with it and the cave silently stops drawing.
	Mesh _mesh;
	Model _renderModel;
	Model _collisionModel;

	int _builtSettings;

	// Live geometry, kept so the cave can be reshaped while playing.
	List<Vector3> _pos;
	List<int> _tris;
	Vector3[] _normals;
	bool _deformed;
	bool _collisionStale;
	RealTimeSince _sinceCollision;

	// Reused between rebuilds so digging doesn't allocate big lists every time.
	readonly List<Vertex> _verts = new();
	readonly List<int> _renderTris = new();
	int _shellTris;

	// Holes are anchored to a shell vertex, so they move with the rock when it is dug.
	readonly List<(int Vertex, float Radius)> _holes = new();

	/// <summary>World positions of the centres of all holes currently in the shell.</summary>
	public IEnumerable<Vector3> HolePositions
	{
		get
		{
			if ( _pos is null ) yield break;
			foreach ( var hole in _holes ) yield return WorldTransform.PointToWorld( _pos[hole.Vertex] );
		}
	}

	/// <summary>
	/// Opens a new see-through hole in the shell at the point nearest to a world position, and
	/// returns the hole's centre. Collision is kept.
	/// </summary>
	public Vector3 OpenHole( Vector3 worldPoint, float radius )
	{
		if ( _pos is null ) return worldPoint;
		int vertex = NearestShellVertex( WorldTransform.PointToLocal( worldPoint ) );
		_holes.Add( (vertex, radius) );
		_deformed = true;
		return WorldTransform.PointToWorld( _pos[vertex] );
	}

	/// <summary>
	/// Makes sure a world point is inside the cavern. A point counts as outside once it is within
	/// <paramref name="margin"/> of passing through the shell (keep that well below the distance
	/// things normally rest from the rock); it is then put back <paramref name="pullback"/> inside.
	/// Works from the shell's own triangles, not physics, so it holds even while collision is out
	/// of date or something has tunnelled through it. Returns true if the point was moved.
	/// </summary>
	public bool Contain( ref Vector3 worldPoint, float margin, float pullback )
	{
		if ( _pos is null || _tris is null ) return false;

		// Count how many times the line from the cave's centre to the point crosses the shell.
		// An odd count means the point is outside.
		var p = WorldTransform.PointToLocal( worldPoint );
		float dist = p.Length;
		if ( dist < 1f ) return false;
		var dir = p / dist;

		_crossings.Clear();
		for ( int i = 0; i < _shellTris; i += 3 )
		{
			if ( !RayTriangle( dir, _pos[_tris[i]], _pos[_tris[i + 1]], _pos[_tris[i + 2]], out float t ) ) continue;
			if ( t <= dist + margin ) _crossings.Add( t );
		}

		// A line through a shared edge or vertex hits several triangles at the same distance;
		// those are one crossing, not many.
		_crossings.Sort();
		int crossings = 0;
		float exit = 0f;
		foreach ( float t in _crossings )
		{
			if ( crossings > 0 && t - exit < 0.05f ) continue;
			crossings++;
			exit = t;
		}
		if ( crossings % 2 == 0 ) return false;

		worldPoint = WorldTransform.PointToWorld( dir * MathF.Max( exit - pullback, 0f ) );
		return true;
	}

	readonly List<float> _crossings = new();

	/// <summary>Distance along a ray from the local origin to a triangle, if it hits (either side).</summary>
	static bool RayTriangle( Vector3 dir, Vector3 a, Vector3 b, Vector3 c, out float t )
	{
		t = 0f;
		var e1 = b - a;
		var e2 = c - a;
		var h = Vector3.Cross( dir, e2 );
		float det = Vector3.Dot( e1, h );
		if ( det > -1e-6f && det < 1e-6f ) return false;
		float inv = 1f / det;
		var s = -a;
		float u = Vector3.Dot( s, h ) * inv;
		if ( u < 0f || u > 1f ) return false;
		var q = Vector3.Cross( s, e1 );
		float v = Vector3.Dot( dir, q ) * inv;
		if ( v < 0f || u + v > 1f ) return false;
		t = Vector3.Dot( e2, q ) * inv;
		return t > 0f;
	}

	int NearestShellVertex( Vector3 local )
	{
		int best = 0; float bestDist = float.MaxValue;
		for ( int i = 0; i < _shellVerts; i++ )
		{
			float d = (_pos[i] - local).LengthSquared;
			if ( d < bestDist ) { bestDist = d; best = i; }
		}
		return best;
	}

	int _shellVerts;
	RealTimeSince _sinceRebuild;

	/// <summary>
	/// Pushes the rock near a world point in or out. Negative amounts dig into the rock, positive
	/// amounts raise it into the cavern. The surface stays one closed shell, so it stays sealed.
	/// </summary>
	public void Deform( Vector3 worldPoint, float radius, float amount )
	{
		if ( _pos is null || _normals is null ) return;
		var p = WorldTransform.PointToLocal( worldPoint );
		float r2 = radius * radius;
		for ( int i = 0; i < _pos.Count; i++ )
		{
			float d2 = (_pos[i] - p).LengthSquared;
			if ( d2 >= r2 ) continue;
			float falloff = 1f - d2 / r2;
			_pos[i] += _normals[i] * (amount * falloff * falloff);
		}
		_deformed = true;
	}

	// A render mesh created inside OnEnabled/OnValidate in the editor never draws, while one
	// created during a frame update does. So collision is built immediately on enable (nothing can
	// fall through on the first frame), and OnUpdate rebuilds whenever the settings differ from the
	// last update build. That also catches changes that don't fire OnValidate, such as properties
	// set through the editor's MCP tools.
	protected override void OnEnabled() { Build(); _builtSettings = 0; }

	protected override void OnUpdate()
	{
		// Rebuild when a setting changes, or when something else has replaced our generated models.
		int settings = SettingsHash();
		if ( settings != _builtSettings || Renderer?.Model != _renderModel || Collider?.Model != _collisionModel )
		{
			_builtSettings = settings;
			Build();
			return;
		}

		// After digging: redraw at most about 20 times a second, and rebuild the (much more
		// expensive) collision at most about 5 times a second. Contain() keeps things inside
		// the shell in the meantime.
		if ( _deformed && _sinceRebuild > 0.05f )
		{
			_deformed = false;
			_collisionStale = true;
			Rebuild( false );
		}
		if ( _collisionStale && _sinceCollision > 0.2f ) RebuildCollision();
	}

	int SettingsHash() => HashCode.Combine(
		HashCode.Combine( Material, Size, Seed, Detail, WallNoise, NoiseFrequency, FloorLevel, FloorBumpHeight ),
		HashCode.Combine( WallDetail, TextureScale, Stalactites, Stalagmites, Boulders, SpawnClearRadius, HoleRadius, HoleHash() ) );

	int HoleHash()
	{
		int hash = HoleDirections?.Count ?? 0;
		if ( HoleDirections is not null )
			foreach ( var d in HoleDirections ) hash = HashCode.Combine( hash, d );
		return hash;
	}

	void Build()
	{
		if ( Renderer is null || Collider is null ) return;

		var dirs = new List<Vector3>();
		var tris = new List<int>();
		BuildIcosphere( Math.Clamp( Detail, 1, 7 ), dirs, tris );

		// Shape: an ellipsoid pushed in and out by noise, with everything below the floor
		// surface flattened onto it.
		var pos = new List<Vector3>( dirs.Count );
		float floorZ = FloorLevel * Size.z;
		foreach ( var d in dirs )
		{
			float bulge = 1f + WallNoise * Fbm( d * NoiseFrequency, 5, Seed )
				+ WallDetail * Fbm( d * NoiseFrequency * 4.5f, 3, Seed + 57 );
			var p = new Vector3( d.x * Size.x, d.y * Size.y, d.z * Size.z ) * bulge;

			// Rolling floor: broad rises and dips plus smaller lumps.
			var fp = new Vector3( p.x, p.y, 0 );
			float floor = floorZ
				+ FloorBumpHeight * Fbm( fp / 900f, 3, Seed + 101 )
				+ FloorBumpHeight * 0.3f * Fbm( fp / 180f, 2, Seed + 202 );
			if ( p.z < floor ) p.z = floor;

			pos.Add( p );
		}

		// Make every triangle face the inside: a closed mesh wound inward has negative volume.
		float volume = 0;
		for ( int i = 0; i < tris.Count; i += 3 )
			volume += Vector3.Dot( pos[tris[i]], Vector3.Cross( pos[tris[i + 1]], pos[tris[i + 2]] ) );
		if ( volume > 0 )
		{
			for ( int i = 0; i < tris.Count; i += 3 )
				(tris[i + 1], tris[i + 2]) = (tris[i + 2], tris[i + 1]);
		}

		_shellVerts = pos.Count;
		_shellTris = tris.Count;
		AddFormations( pos, tris );

		// Configured holes: the shell vertex furthest along each direction.
		_holes.Clear();
		foreach ( var dir in HoleDirections ?? new() )
		{
			if ( dir.Length < 0.001f ) continue;
			var d = dir.Normal;
			int best = 0; float bestDot = float.MinValue;
			for ( int i = 0; i < _shellVerts; i++ )
			{
				float dot = Vector3.Dot( pos[i].Normal, d );
				if ( dot > bestDot ) { bestDot = dot; best = i; }
			}
			_holes.Add( (best, HoleRadius) );
		}

		_pos = pos;
		_tris = tris;
		Rebuild();
	}

	bool InHole( Vector3 point )
	{
		foreach ( var hole in _holes )
			if ( (point - _pos[hole.Vertex]).LengthSquared < hole.Radius * hole.Radius ) return true;
		return false;
	}

	/// <summary>Turns the current vertex positions into the render mesh and collision.</summary>
	void Rebuild( bool collision = true )
	{
		if ( _pos is null || Renderer is null || Collider is null ) return;
		var pos = _pos;
		var tris = _tris;
		_sinceRebuild = 0;

		// Smooth normals, pointing into the cavern (and out of each formation).
		var normals = _normals is not null && _normals.Length == pos.Count ? _normals : new Vector3[pos.Count];
		Array.Clear( normals );
		for ( int i = 0; i < tris.Count; i += 3 )
		{
			int a = tris[i], b = tris[i + 1], c = tris[i + 2];
			var n = Vector3.Cross( pos[b] - pos[a], pos[c] - pos[a] );
			normals[a] += n; normals[b] += n; normals[c] += n;
		}
		for ( int i = 0; i < normals.Length; i++ ) normals[i] = normals[i].Normal;
		_normals = normals;

		// Render vertices are unshared so each triangle can use one projection throughout (blending
		// projections inside a triangle is what streaked the steep walls). Lighting still uses the
		// smooth shared normals.
		//  - Faces that look up or down (floors, ceilings) are textured from above.
		//  - The shell's walls are wrapped round the cave like a label round a jar: distance round
		//    the cave by height. That is continuous from one wall triangle to the next, where
		//    picking a flat side projection per triangle left a patchwork.
		//  - Formations (spikes, boulders) are small and keep the per-triangle side projection.
		var verts = _verts;
		verts.Clear();
		float wrapRadius = MathF.Max( (Size.x + Size.y) * 0.5f, 1f );
		for ( int i = 0; i < tris.Count; i += 3 )
		{
			if ( i < _shellTris && InHole( (pos[tris[i]] + pos[tris[i + 1]] + pos[tris[i + 2]]) / 3f ) ) continue;

			var fn = Vector3.Cross( pos[tris[i + 1]] - pos[tris[i]], pos[tris[i + 2]] - pos[tris[i]] );
			var an = new Vector3( MathF.Abs( fn.x ), MathF.Abs( fn.y ), MathF.Abs( fn.z ) );
			bool flat = an.z >= an.x && an.z >= an.y;
			bool wrap = !flat && i < _shellTris;
			int axis = flat ? 2 : an.x >= an.y ? 0 : 1;

			// Angle round the cave of the triangle's first corner; the others are kept within
			// half a turn of it so a triangle never straddles the join.
			float firstAngle = MathF.Atan2( pos[tris[i]].y, pos[tris[i]].x );

			for ( int k = 0; k < 3; k++ )
			{
				var p = pos[tris[i + k]];
				var n = normals[tris[i + k]];

				Vector2 uv; Vector3 uAxis;
				if ( wrap )
				{
					float angle = MathF.Atan2( p.y, p.x );
					if ( angle - firstAngle > MathF.PI ) angle -= MathF.PI * 2f;
					else if ( firstAngle - angle > MathF.PI ) angle += MathF.PI * 2f;
					uv = new Vector2( angle * wrapRadius, -p.z );
					uAxis = new Vector3( -p.y, p.x, 0 ).Normal; // direction round the cave
				}
				else if ( axis == 2 ) { uv = new Vector2( p.x, p.y ); uAxis = Vector3.Forward; }
				else if ( axis == 0 ) { uv = new Vector2( p.y, -p.z ); uAxis = Vector3.Left; }
				else { uv = new Vector2( p.x, -p.z ); uAxis = Vector3.Forward; }
				uv /= TextureScale;

				var tangent = (uAxis - n * Vector3.Dot( uAxis, n )).Normal;
				verts.Add( new Vertex( p, n, tangent, new Vector4( uv.x, uv.y, 0, 0 ) ) );
			}
		}

		// Draw both windings so the shell is visible from either side (double-sided).
		var renderTris = _renderTris;
		if ( renderTris.Count != verts.Count * 2 )
		{
			renderTris.Clear();
			for ( int i = 0; i < verts.Count; i += 3 )
			{
				renderTris.Add( i ); renderTris.Add( i + 1 ); renderTris.Add( i + 2 );
				renderTris.Add( i ); renderTris.Add( i + 2 ); renderTris.Add( i + 1 );
			}
		}

		var mesh = new Mesh( Material );
		mesh.CreateVertexBuffer( verts.Count, verts );
		mesh.CreateIndexBuffer( renderTris.Count, renderTris );
		mesh.Bounds = BBox.FromPoints( pos );

		// Separate models for drawing and for collision.
		_mesh = mesh;
		_renderModel = Model.Builder.AddMesh( mesh ).Create();
		Renderer.Model = _renderModel;

		if ( collision ) RebuildCollision();
	}

	void RebuildCollision()
	{
		if ( _pos is null || Collider is null ) return;
		_collisionStale = false;
		_sinceCollision = 0;
		_collisionModel = Model.Builder.AddCollisionMesh( _pos, _tris ).Create();
		Collider.Static = true;
		Collider.Model = _collisionModel;
	}

	/// <summary>
	/// Adds stalactites, stalagmites and boulders as separate closed shapes. Positions come from
	/// vertical rays against the shell, so each one sits on the floor or hangs from the ceiling.
	/// </summary>
	void AddFormations( List<Vector3> pos, List<int> tris )
	{
		int shellTris = tris.Count;
		var rng = new Random( Seed );
		float R( float a, float b ) => a + (float)rng.NextDouble() * (b - a);

		bool FloorAndCeiling( float x, float y, out float floor, out float ceiling )
		{
			floor = float.MaxValue; ceiling = float.MaxValue;
			var hits = new List<float>();
			for ( int i = 0; i < shellTris; i += 3 )
				if ( VerticalHit( pos[tris[i]], pos[tris[i + 1]], pos[tris[i + 2]], x, y, out var z ) ) hits.Add( z );
			if ( hits.Count < 2 ) return false;
			hits.Sort();
			floor = hits[0];
			ceiling = hits[1];
			return true;
		}

		Vector2 RandomSpot() => new( R( -0.85f, 0.85f ) * Size.x, R( -0.85f, 0.85f ) * Size.y );
		bool NearSpawn( Vector2 p ) => p.Length < SpawnClearRadius;

		for ( int n = 0, tries = 0; n < Stalactites && tries < Stalactites * 6; tries++ )
		{
			var s = RandomSpot();
			if ( !FloorAndCeiling( s.x, s.y, out var f, out var c ) ) continue;
			float length = R( 50f, 220f );
			if ( c - f < length + 140f ) continue; // keep head room under the tip
			AddSpike( pos, tris, new Vector3( s.x, s.y, c ), -1f, R( 18f, 55f ), length, rng );
			n++;
		}

		for ( int n = 0, tries = 0; n < Stalagmites && tries < Stalagmites * 6; tries++ )
		{
			var s = RandomSpot();
			if ( NearSpawn( s ) || !FloorAndCeiling( s.x, s.y, out var f, out var c ) ) continue;
			float length = R( 40f, 170f );
			if ( c - f < length + 60f ) continue;
			AddSpike( pos, tris, new Vector3( s.x, s.y, f ), 1f, R( 25f, 70f ), length, rng );
			n++;
		}

		for ( int n = 0, tries = 0; n < Boulders && tries < Boulders * 6; tries++ )
		{
			var s = RandomSpot();
			if ( NearSpawn( s ) || !FloorAndCeiling( s.x, s.y, out var f, out _ ) ) continue;
			float size = R( 30f, 110f );
			AddBoulder( pos, tris, new Vector3( s.x, s.y, f + size * 0.35f ),
				new Vector3( size * R( 0.8f, 1.4f ), size * R( 0.8f, 1.4f ), size * R( 0.6f, 0.9f ) ), rng );
			n++;
		}
	}

	/// <summary>Where a vertical line at (x,y) crosses a triangle, if it does.</summary>
	static bool VerticalHit( Vector3 a, Vector3 b, Vector3 c, float x, float y, out float z )
	{
		z = 0;
		float d = (b.y - c.y) * (a.x - c.x) + (c.x - b.x) * (a.y - c.y);
		if ( MathF.Abs( d ) < 1e-6f ) return false;
		float u = ((b.y - c.y) * (x - c.x) + (c.x - b.x) * (y - c.y)) / d;
		float v = ((c.y - a.y) * (x - c.x) + (a.x - c.x) * (y - c.y)) / d;
		float w = 1 - u - v;
		if ( u < 0 || v < 0 || w < 0 ) return false;
		z = u * a.z + v * b.z + w * c.z;
		return true;
	}

	/// <summary>A lumpy cone from a base point along ±Z. Its base is sunk into the surface so no gap shows.</summary>
	static void AddSpike( List<Vector3> pos, List<int> tris, Vector3 basePoint, float dir, float radius, float length, Random rng )
	{
		const int segments = 9, rings = 6;
		int start = pos.Count;
		float phase = (float)rng.NextDouble() * 10f;
		var lean = new Vector2( (float)rng.NextDouble() - 0.5f, (float)rng.NextDouble() - 0.5f ) * radius * 0.6f;

		for ( int r = 0; r < rings; r++ )
		{
			float t = r / (float)rings;
			float z = (t * length - radius * 0.6f) * dir;
			float rad = radius * MathF.Pow( 1f - t, 1.3f );
			var offset = lean * t;
			for ( int s = 0; s < segments; s++ )
			{
				float ang = s / (float)segments * MathF.PI * 2f;
				float lump = 1f + 0.3f * ValueNoise( new Vector3( MathF.Cos( ang ) * 1.7f, MathF.Sin( ang ) * 1.7f, t * 3f + phase ), 7 );
				pos.Add( basePoint + new Vector3( MathF.Cos( ang ) * rad * lump + offset.x, MathF.Sin( ang ) * rad * lump + offset.y, z ) );
			}
		}
		int tip = pos.Count;
		pos.Add( basePoint + new Vector3( lean.x, lean.y, length * dir ) );
		int bottom = pos.Count;
		pos.Add( basePoint + new Vector3( 0, 0, -radius * 0.6f * dir ) );

		int first = tris.Count;
		for ( int r = 0; r < rings - 1; r++ )
			for ( int s = 0; s < segments; s++ )
			{
				int a = start + r * segments + s, b = start + r * segments + (s + 1) % segments;
				int c = a + segments, d = b + segments;
				tris.AddRange( new[] { a, b, d, a, d, c } );
			}
		int last = start + (rings - 1) * segments;
		for ( int s = 0; s < segments; s++ )
		{
			tris.AddRange( new[] { last + s, last + (s + 1) % segments, tip } );
			tris.AddRange( new[] { start + (s + 1) % segments, start + s, bottom } );
		}
		OrientOutward( pos, tris, first );
	}

	static void AddBoulder( List<Vector3> pos, List<int> tris, Vector3 center, Vector3 size, Random rng )
	{
		var dirs = new List<Vector3>();
		var local = new List<int>();
		BuildIcosphere( 2, dirs, local );
		int start = pos.Count, seed = rng.Next( 100000 );
		foreach ( var d in dirs )
		{
			float lump = 1f + 0.25f * Fbm( d * 1.5f, 3, seed );
			pos.Add( center + new Vector3( d.x * size.x, d.y * size.y, d.z * size.z ) * lump );
		}
		int first = tris.Count;
		foreach ( var i in local ) tris.Add( start + i );
		OrientOutward( pos, tris, first );
	}

	/// <summary>Flips the triangles from <paramref name="first"/> on so their normals point away from their centre.</summary>
	static void OrientOutward( List<Vector3> pos, List<int> tris, int first )
	{
		var centre = Vector3.Zero; int count = 0;
		for ( int i = first; i < tris.Count; i++ ) { centre += pos[tris[i]]; count++; }
		centre /= Math.Max( count, 1 );

		float volume = 0;
		for ( int i = first; i < tris.Count; i += 3 )
			volume += Vector3.Dot( pos[tris[i]] - centre, Vector3.Cross( pos[tris[i + 1]] - centre, pos[tris[i + 2]] - centre ) );
		if ( volume >= 0 ) return;
		for ( int i = first; i < tris.Count; i += 3 )
			(tris[i + 1], tris[i + 2]) = (tris[i + 2], tris[i + 1]);
	}

	/// <summary>A unit sphere made by subdividing an icosahedron. Closed, with no seams.</summary>
	static void BuildIcosphere( int detail, List<Vector3> verts, List<int> tris )
	{
		float t = (1f + MathF.Sqrt( 5f )) / 2f;
		foreach ( var v in new Vector3[] {
			new( -1, t, 0 ), new( 1, t, 0 ), new( -1, -t, 0 ), new( 1, -t, 0 ),
			new( 0, -1, t ), new( 0, 1, t ), new( 0, -1, -t ), new( 0, 1, -t ),
			new( t, 0, -1 ), new( t, 0, 1 ), new( -t, 0, -1 ), new( -t, 0, 1 ) } )
			verts.Add( v.Normal );

		tris.AddRange( new[] {
			0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
			1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
			3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
			4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1 } );

		for ( int level = 0; level < detail; level++ )
		{
			var midpoints = new Dictionary<long, int>();
			int Mid( int a, int b )
			{
				long key = a < b ? ((long)a << 32) | (uint)b : ((long)b << 32) | (uint)a;
				if ( midpoints.TryGetValue( key, out var index ) ) return index;
				verts.Add( ((verts[a] + verts[b]) * 0.5f).Normal );
				midpoints[key] = verts.Count - 1;
				return verts.Count - 1;
			}

			var next = new List<int>( tris.Count * 4 );
			for ( int i = 0; i < tris.Count; i += 3 )
			{
				int a = tris[i], b = tris[i + 1], c = tris[i + 2];
				int ab = Mid( a, b ), bc = Mid( b, c ), ca = Mid( c, a );
				next.AddRange( new[] { a, ab, ca, b, bc, ab, c, ca, bc, ab, bc, ca } );
			}
			tris.Clear();
			tris.AddRange( next );
		}
	}

	/// <summary>Fractal value noise in roughly -1..1, deterministic for a given seed.</summary>
	static float Fbm( Vector3 p, int octaves, int seed )
	{
		float sum = 0, amp = 0.5f, norm = 0;
		for ( int o = 0; o < octaves; o++ )
		{
			sum += amp * ValueNoise( p, seed + o * 31 );
			norm += amp;
			p *= 2.03f;
			amp *= 0.5f;
		}
		return sum / norm;
	}

	static float ValueNoise( Vector3 p, int seed )
	{
		int x0 = (int)MathF.Floor( p.x ), y0 = (int)MathF.Floor( p.y ), z0 = (int)MathF.Floor( p.z );
		float fx = Smooth( p.x - x0 ), fy = Smooth( p.y - y0 ), fz = Smooth( p.z - z0 );

		float Lerp( float a, float b, float f ) => a + (b - a) * f;
		float Corner( int dx, int dy, int dz ) => Hash( x0 + dx, y0 + dy, z0 + dz, seed );

		return Lerp(
			Lerp( Lerp( Corner( 0, 0, 0 ), Corner( 1, 0, 0 ), fx ), Lerp( Corner( 0, 1, 0 ), Corner( 1, 1, 0 ), fx ), fy ),
			Lerp( Lerp( Corner( 0, 0, 1 ), Corner( 1, 0, 1 ), fx ), Lerp( Corner( 0, 1, 1 ), Corner( 1, 1, 1 ), fx ), fy ),
			fz );
	}

	static float Smooth( float f ) => f * f * (3f - 2f * f);

	static float Hash( int x, int y, int z, int seed )
	{
		unchecked
		{
			uint h = (uint)(x * 374761393 + y * 668265263 + z * 1440662683 + seed * 2246822519u);
			h = (h ^ (h >> 13)) * 1274126177u;
			h ^= h >> 16;
			return (h & 0xFFFFFF) / (float)0xFFFFFF * 2f - 1f;
		}
	}
}