{"TotalCount":99,"Files":[{"Ident":"redsnail.watertool2","Path":".obj/__compiler_extra.cs","FileName":"__compiler_extra.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":445731,"IsPrivate":false,"Code":"global using static Sandbox.Internal.GlobalGameNamespace;\r\nglobal using Microsoft.AspNetCore.Components;\r\nglobal using Microsoft.AspNetCore.Components.Rendering;\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022AddonTitle\u0022, \u0022Water Tool\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022AddonIdent\u0022, \u0022watertool2\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022OrgIdent\u0022, \u0022redsnail\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022Ident\u0022, \u0022redsnail.watertool2\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022EngineVersion\u0022, \u002232\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022EngineMinorVersion\u0022, \u00221\u0022 )]\r\n\r\n[assembly: System.Runtime.Versioning.TargetFramework( \u0022.NETCoreApp,Version=v9.0\u0022, FrameworkDisplayName = \u0022.NET 9.0\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022CompileTime\u0022, \u00222026-11-09T10:33:37.6526324Z\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyVersion(\u00220.0.126.0\u0022)]\r\n[assembly: global::System.Reflection.AssemblyFileVersion(\u00220.0.126.0\u0022)]"},{"Ident":"redsnail.watertool2","Path":"Building/CoastScanner.cs","FileName":"CoastScanner.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":445731,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\nusing Sandbox;\n\nnamespace RedSnail.WaterTool2;\n\n/// \u003Csummary\u003E\n/// Turns a scan of the ground into coastlines: closed loops round every piece of land the open sea reaches. The scan is\n/// a grid of heights relative to the coast\u0027s height (land where positive); the open sea is whatever below that the\n/// scan\u0027s edge connects to, so a basin inland, however low, is land and the sea never floods it.\n/// \u003C/summary\u003E\ninternal static class CoastScanner\n{\n\t/// \u003Csummary\u003E\n\t/// The coastlines in a scan: \u003Cparamref name=\u0022_Field\u0022/\u003E holds, at every grid point (row after row, \u003Cparamref\n\t/// name=\u0022_Width\u0022/\u003E to a row), how far the ground is above the coast\u0027s height. The scan\u0027s edge is taken as open sea.\n\t/// Each loop is in the world (in plan), simplified to within a quarter of a grid step; loops round less land than\n\t/// \u003Cparamref name=\u0022_MinArea\u0022/\u003E are left out. The field is changed in place.\n\t/// \u003C/summary\u003E\n\tpublic static List\u003CVector2[]\u003E Extract(float[] _Field, int _Width, int _Height, Vector2 _Origin, float _Step, float _MinArea)\n\t{\n\t\tvar loops = new List\u003CVector2[]\u003E();\n\n\t\tif (_Width \u003C 3 || _Height \u003C 3)\n\t\t\treturn loops;\n\n\t\t// The scan\u0027s edge is the open sea, whatever is there.\n\t\tfor (int i = 0; i \u003C _Width; i\u002B\u002B)\n\t\t{\n\t\t\t_Field[i] = MathF.Min(_Field[i], -1.0f);\n\t\t\t_Field[(_Height - 1) * _Width \u002B i] = MathF.Min(_Field[(_Height - 1) * _Width \u002B i], -1.0f);\n\t\t}\n\n\t\tfor (int j = 0; j \u003C _Height; j\u002B\u002B)\n\t\t{\n\t\t\t_Field[j * _Width] = MathF.Min(_Field[j * _Width], -1.0f);\n\t\t\t_Field[j * _Width \u002B _Width - 1] = MathF.Min(_Field[j * _Width \u002B _Width - 1], -1.0f);\n\t\t}\n\n\t\tFillBasins(_Field, _Width, _Height);\n\n\t\tvar next = Contour(_Field, _Width, _Height);\n\t\tvar visited = new HashSet\u003Cint\u003E();\n\n\t\tforeach (int start in next.Keys)\n\t\t{\n\t\t\tif (visited.Contains(start))\n\t\t\t\tcontinue;\n\n\t\t\tvar loop = new List\u003CVector2\u003E();\n\t\t\tint edge = start;\n\t\t\tbool closed = false;\n\n\t\t\twhile (visited.Add(edge))\n\t\t\t{\n\t\t\t\tloop.Add(Crossing(_Field, _Width, _Origin, _Step, edge));\n\n\t\t\t\tif (!next.TryGetValue(edge, out int following))\n\t\t\t\t\tbreak;\n\n\t\t\t\tedge = following;\n\t\t\t\tclosed = edge == start;\n\t\t\t}\n\n\t\t\tif (!closed || loop.Count \u003C 3)\n\t\t\t\tcontinue;\n\n\t\t\tvar simplified = SimplifyClosed(loop, _Step * 0.25f);\n\n\t\t\t// Land is on the right of the way round, so a loop round land runs clockwise; one the other way round would be\n\t\t\t// sea shut in by land, which the fill has already made land.\n\t\t\tfloat area = SignedArea(simplified);\n\n\t\t\tif (simplified.Count \u003C 3 || area \u003E 0.0f || -area \u003C _MinArea)\n\t\t\t\tcontinue;\n\n\t\t\tloops.Add(simplified.ToArray());\n\t\t}\n\n\t\treturn loops;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Everything below the coast\u0027s height that the open sea doesn\u0027t reach (through the grid, edge to edge) becomes land.\n\t/// \u003C/summary\u003E\n\tprivate static void FillBasins(float[] _Field, int _Width, int _Height)\n\t{\n\t\tvar sea = new bool[_Field.Length];\n\t\tvar queue = new Queue\u003Cint\u003E();\n\n\t\tfor (int i = 0; i \u003C _Field.Length; i\u002B\u002B)\n\t\t{\n\t\t\tint x = i % _Width;\n\t\t\tint y = i / _Width;\n\n\t\t\tif ((x == 0 || y == 0 || x == _Width - 1 || y == _Height - 1) \u0026\u0026 _Field[i] \u003C= 0.0f)\n\t\t\t{\n\t\t\t\tsea[i] = true;\n\t\t\t\tqueue.Enqueue(i);\n\t\t\t}\n\t\t}\n\n\t\twhile (queue.Count \u003E 0)\n\t\t{\n\t\t\tint i = queue.Dequeue();\n\t\t\tint x = i % _Width;\n\t\t\tint y = i / _Width;\n\n\t\t\tVisit(x - 1, y);\n\t\t\tVisit(x \u002B 1, y);\n\t\t\tVisit(x, y - 1);\n\t\t\tVisit(x, y \u002B 1);\n\t\t}\n\n\t\tfor (int i = 0; i \u003C _Field.Length; i\u002B\u002B)\n\t\t{\n\t\t\tif (!sea[i] \u0026\u0026 _Field[i] \u003C= 0.0f)\n\t\t\t\t_Field[i] = 0.01f;\n\t\t}\n\n\t\tvoid Visit(int _X, int _Y)\n\t\t{\n\t\t\tif (_X \u003C 0 || _Y \u003C 0 || _X \u003E= _Width || _Y \u003E= _Height)\n\t\t\t\treturn;\n\n\t\t\tint index = _Y * _Width \u002B _X;\n\n\t\t\tif (sea[index] || _Field[index] \u003E 0.0f)\n\t\t\t\treturn;\n\n\t\t\tsea[index] = true;\n\t\t\tqueue.Enqueue(index);\n\t\t}\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Marching squares: every grid cell the coast crosses gives a piece of it, from edge to edge, with the land on its\n\t/// right. Edges are numbered so a piece leaving one cell through an edge is the piece that enters the next cell\n\t/// through it: the result maps every crossed edge to the next one along the coast.\n\t/// \u003C/summary\u003E\n\tprivate static Dictionary\u003Cint, int\u003E Contour(float[] _Field, int _Width, int _Height)\n\t{\n\t\tvar next = new Dictionary\u003Cint, int\u003E();\n\t\tvar edges = new int[4];\n\t\tvar corners = new bool[4];\n\t\tvar crossEdges = new int[4];\n\t\tvar crossIntoLand = new bool[4];\n\n\t\tfor (int y = 0; y \u003C _Height - 1; y\u002B\u002B)\n\t\t{\n\t\t\tfor (int x = 0; x \u003C _Width - 1; x\u002B\u002B)\n\t\t\t{\n\t\t\t\tfloat f00 = _Field[y * _Width \u002B x];\n\t\t\t\tfloat f10 = _Field[y * _Width \u002B x \u002B 1];\n\t\t\t\tfloat f11 = _Field[(y \u002B 1) * _Width \u002B x \u002B 1];\n\t\t\t\tfloat f01 = _Field[(y \u002B 1) * _Width \u002B x];\n\n\t\t\t\t// Round the cell counter-clockwise: bottom, right, top, left.\n\t\t\t\tcorners[0] = f00 \u003E 0.0f;\n\t\t\t\tcorners[1] = f10 \u003E 0.0f;\n\t\t\t\tcorners[2] = f11 \u003E 0.0f;\n\t\t\t\tcorners[3] = f01 \u003E 0.0f;\n\n\t\t\t\tif (corners[0] == corners[1] \u0026\u0026 corners[1] == corners[2] \u0026\u0026 corners[2] == corners[3])\n\t\t\t\t\tcontinue;\n\n\t\t\t\tedges[0] = HorizontalEdge(x, y, _Width);\n\t\t\t\tedges[1] = VerticalEdge(x \u002B 1, y, _Width);\n\t\t\t\tedges[2] = HorizontalEdge(x, y \u002B 1, _Width);\n\t\t\t\tedges[3] = VerticalEdge(x, y, _Width);\n\n\t\t\t\tint crossings = 0;\n\n\t\t\t\tfor (int k = 0; k \u003C 4; k\u002B\u002B)\n\t\t\t\t{\n\t\t\t\t\tbool from = corners[k];\n\t\t\t\t\tbool to = corners[(k \u002B 1) % 4];\n\n\t\t\t\t\tif (from == to)\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tcrossEdges[crossings] = edges[k];\n\t\t\t\t\tcrossIntoLand[crossings] = to;\n\t\t\t\t\tcrossings\u002B\u002B;\n\t\t\t\t}\n\n\t\t\t\t// A piece runs from where the way round goes into the land to where it comes out, which keeps the land on\n\t\t\t\t// its right. A saddle has two: they cut off the land corners when the middle is sea, the sea corners when\n\t\t\t\t// it is land.\n\t\t\t\tbool middleLand = f00 \u002B f10 \u002B f11 \u002B f01 \u003E 0.0f;\n\n\t\t\t\tfor (int k = 0; k \u003C crossings; k\u002B\u002B)\n\t\t\t\t{\n\t\t\t\t\tif (!crossIntoLand[k])\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tint partner = crossings == 4 \u0026\u0026 middleLand ? (k \u002B crossings - 1) % crossings : (k \u002B 1) % crossings;\n\n\t\t\t\t\tnext[crossEdges[k]] = crossEdges[partner];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn next;\n\t}\n\n\n\n\tprivate static int HorizontalEdge(int _X, int _Y, int _Width)\n\t{\n\t\treturn (_Y * _Width \u002B _X) * 2;\n\t}\n\n\n\n\tprivate static int VerticalEdge(int _X, int _Y, int _Width)\n\t{\n\t\treturn (_Y * _Width \u002B _X) * 2 \u002B 1;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Where the coast crosses a grid edge, between its two points\u0027 heights.\n\t/// \u003C/summary\u003E\n\tprivate static Vector2 Crossing(float[] _Field, int _Width, Vector2 _Origin, float _Step, int _Edge)\n\t{\n\t\tint cell = _Edge / 2;\n\t\tint x = cell % _Width;\n\t\tint y = cell / _Width;\n\t\tbool vertical = (_Edge \u0026 1) == 1;\n\n\t\tfloat a = _Field[y * _Width \u002B x];\n\t\tfloat b = vertical ? _Field[(y \u002B 1) * _Width \u002B x] : _Field[y * _Width \u002B x \u002B 1];\n\t\tfloat t = Math.Clamp(a / (a - b), 0.01f, 0.99f);\n\n\t\treturn vertical\n\t\t\t? new Vector2(_Origin.x \u002B x * _Step, _Origin.y \u002B (y \u002B t) * _Step)\n\t\t\t: new Vector2(_Origin.x \u002B (x \u002B t) * _Step, _Origin.y \u002B y * _Step);\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Douglas-Peucker on a closed loop: split at the point furthest from the first, each half simplified on its own.\n\t/// \u003C/summary\u003E\n\tprivate static List\u003CVector2\u003E SimplifyClosed(List\u003CVector2\u003E _Loop, float _Tolerance)\n\t{\n\t\tif (_Loop.Count \u003C 8)\n\t\t\treturn _Loop;\n\n\t\tint far = 0;\n\t\tfloat farthest = -1.0f;\n\n\t\tfor (int i = 1; i \u003C _Loop.Count; i\u002B\u002B)\n\t\t{\n\t\t\tfloat distance = _Loop[i].Distance(_Loop[0]);\n\n\t\t\tif (distance \u003C= farthest)\n\t\t\t\tcontinue;\n\n\t\t\tfarthest = distance;\n\t\t\tfar = i;\n\t\t}\n\n\t\tvar keep = new bool[_Loop.Count \u002B 1];\n\t\tkeep[0] = true;\n\t\tkeep[far] = true;\n\t\tkeep[_Loop.Count] = true;\n\n\t\tSimplify(_Loop, 0, far, _Tolerance, keep);\n\t\tSimplify(_Loop, far, _Loop.Count, _Tolerance, keep);\n\n\t\tvar result = new List\u003CVector2\u003E();\n\n\t\tfor (int i = 0; i \u003C _Loop.Count; i\u002B\u002B)\n\t\t{\n\t\t\tif (keep[i])\n\t\t\t\tresult.Add(_Loop[i]);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Marks which points between two kept ones stay (index \u003Cc\u003ECount\u003C/c\u003E is the first point again), without recursion.\n\t/// \u003C/summary\u003E\n\tprivate static void Simplify(List\u003CVector2\u003E _Loop, int _From, int _To, float _Tolerance, bool[] _Keep)\n\t{\n\t\tvar stack = new Stack\u003C(int From, int To)\u003E();\n\t\tstack.Push((_From, _To));\n\n\t\twhile (stack.Count \u003E 0)\n\t\t{\n\t\t\tvar (from, to) = stack.Pop();\n\n\t\t\tif (to - from \u003C 2)\n\t\t\t\tcontinue;\n\n\t\t\tVector2 a = _Loop[from];\n\t\t\tVector2 b = _Loop[to % _Loop.Count];\n\t\t\tint worst = -1;\n\t\t\tfloat worstDistance = _Tolerance;\n\n\t\t\tfor (int i = from \u002B 1; i \u003C to; i\u002B\u002B)\n\t\t\t{\n\t\t\t\tfloat distance = DistanceToSegment(_Loop[i], a, b);\n\n\t\t\t\tif (distance \u003C= worstDistance)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tworst = i;\n\t\t\t\tworstDistance = distance;\n\t\t\t}\n\n\t\t\tif (worst \u003C 0)\n\t\t\t\tcontinue;\n\n\t\t\t_Keep[worst] = true;\n\t\t\tstack.Push((from, worst));\n\t\t\tstack.Push((worst, to));\n\t\t}\n\t}\n\n\n\n\tprivate static float DistanceToSegment(Vector2 _Point, Vector2 _A, Vector2 _B)\n\t{\n\t\tVector2 span = _B - _A;\n\t\tfloat lengthSquared = span.LengthSquared;\n\t\tfloat t = lengthSquared \u003E 0.0f ? Math.Clamp(Vector2.Dot(_Point - _A, span) / lengthSquared, 0.0f, 1.0f) : 0.0f;\n\n\t\treturn (_A \u002B span * t).Distance(_Point);\n\t}\n\n\n\n\tprivate static float SignedArea(List\u003CVector2\u003E _Loop)\n\t{\n\t\tfloat area = 0.0f;\n\n\t\tfor (int i = 0; i \u003C _Loop.Count; i\u002B\u002B)\n\t\t{\n\t\t\tVector2 a = _Loop[i];\n\t\t\tVector2 b = _Loop[(i \u002B 1) % _Loop.Count];\n\n\t\t\tarea \u002B= a.x * b.y - b.x * a.y;\n\t\t}\n\n\t\treturn area * 0.5f;\n\t}\n}\n"},{"Ident":"redsnail.watertool2","Path":"Building/LakeShore.cs","FileName":"LakeShore.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":445731,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\nusing Sandbox;\n\nnamespace RedSnail.WaterTool2;\n\n/// \u003Csummary\u003E\n/// A lake\u0027s shore as a closed polyline, walked with the water on its left seen from above (counter-clockwise round a\n/// lake, clockwise round a coast\u0027s land): its control points joined by a smooth curve (or by straight edges), sampled\n/// finely, at the lake\u0027s height. Everything about a lake\u0027s outline (where a river opens into it, which stretch of shore\n/// the opening replaces) is measured as a distance round this, the same way for a lake and for the sea.\n/// \u003C/summary\u003E\npublic sealed class LakeShore\n{\n\tpublic readonly List\u003CVector3\u003E Points = new();\n\n\t/// \u003Csummary\u003E\n\t/// The way away from the water at every point: out of a lake, or into a coast\u0027s land.\n\t/// \u003C/summary\u003E\n\tpublic readonly List\u003CVector3\u003E Outwards = new();\n\n\tpublic readonly List\u003Cfloat\u003E Distances = new();\n\n\t/// \u003Csummary\u003E\n\t/// The whole way round.\n\t/// \u003C/summary\u003E\n\tpublic float Length { get; private set; }\n\n\tpublic int Count =\u003E Points.Count;\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The shore of a lake, sampled every \u003Cparamref name=\u0022_Spacing\u0022/\u003E at most. Null for a lake with too few points.\n\t/// \u003C/summary\u003E\n\tpublic static LakeShore Build(WaterLake _Lake, float _Spacing)\n\t{\n\t\tif (_Lake is null || !_Lake.IsValid)\n\t\t\treturn null;\n\n\t\tvar shore = new LakeShore();\n\t\tfloat spacing = MathF.Max(4.0f, _Spacing);\n\n\t\t// Counter-clockwise whatever way the points were laid, so the outside is always on the right.\n\t\tvar control = new List\u003CVector3\u003E(_Lake.Points.Count);\n\t\tbool clockwise = _Lake.SignedArea() \u003C 0.0f;\n\n\t\tfor (int i = 0; i \u003C _Lake.Points.Count; i\u002B\u002B)\n\t\t\tcontrol.Add(_Lake.PointAt(clockwise ? _Lake.Points.Count - 1 - i : i));\n\n\t\tint count = control.Count;\n\n\t\tfor (int i = 0; i \u003C count; i\u002B\u002B)\n\t\t{\n\t\t\tVector3 p0 = control[(i \u002B count - 1) % count];\n\t\t\tVector3 p1 = control[i];\n\t\t\tVector3 p2 = control[(i \u002B 1) % count];\n\t\t\tVector3 p3 = control[(i \u002B 2) % count];\n\n\t\t\tfloat chord = p1.Distance(p2);\n\n\t\t\tif (chord \u003C 0.01f)\n\t\t\t\tcontinue;\n\n\t\t\t// A curve runs a little longer than its chord.\n\t\t\tint steps = Math.Max(1, (int)MathF.Ceiling(chord * (_Lake.Smooth ? 1.2f : 1.0f) / spacing));\n\n\t\t\tfor (int k = 0; k \u003C steps; k\u002B\u002B)\n\t\t\t{\n\t\t\t\tfloat t = (float)k / steps;\n\t\t\t\tVector3 point = _Lake.Smooth ? CatmullRom(p0, p1, p2, p3, t) : Vector3.Lerp(p1, p2, t);\n\n\t\t\t\tshore.Add(point.WithZ(_Lake.Height));\n\t\t\t}\n\t\t}\n\n\t\tif (shore.Count \u003C 3)\n\t\t\treturn null;\n\n\t\t// A smooth shore can loop round a point laid too close to another; whatever it does, the outside stays on the\n\t\t// right of the way round.\n\t\tif (shore.SignedArea() \u003C 0.0f)\n\t\t\tshore.Points.Reverse();\n\n\t\t// A coast\u0027s water is outside it. Walked the other way round, the water is on the left for a coast as for a lake,\n\t\t// and everything measured along the shore (openings, flares, which way a river leaves) works the same.\n\t\tif (_Lake.IsCoast)\n\t\t\tshore.Points.Reverse();\n\n\t\tshore.Finish();\n\n\t\treturn shore;\n\t}\n\n\n\n\tprivate void Add(Vector3 _Point)\n\t{\n\t\tif (Points.Count \u003E 0 \u0026\u0026 Points[^1].Distance(_Point) \u003C 0.01f)\n\t\t\treturn;\n\n\t\tPoints.Add(_Point);\n\t}\n\n\n\n\tprivate float SignedArea()\n\t{\n\t\tfloat area = 0.0f;\n\n\t\tfor (int i = 0; i \u003C Points.Count; i\u002B\u002B)\n\t\t{\n\t\t\tVector3 a = Points[i];\n\t\t\tVector3 b = Points[(i \u002B 1) % Points.Count];\n\n\t\t\tarea \u002B= a.x * b.y - b.x * a.y;\n\t\t}\n\n\t\treturn area * 0.5f;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Distances round the shore, and the way away from the water at every point.\n\t/// \u003C/summary\u003E\n\tprivate void Finish()\n\t{\n\t\tDistances.Clear();\n\t\tOutwards.Clear();\n\n\t\tfloat distance = 0.0f;\n\n\t\tfor (int i = 0; i \u003C Count; i\u002B\u002B)\n\t\t{\n\t\t\tif (i \u003E 0)\n\t\t\t\tdistance \u002B= Points[i - 1].Distance(Points[i]);\n\n\t\t\tDistances.Add(distance);\n\n\t\t\tVector3 tangent = (Points[(i \u002B 1) % Count] - Points[(i \u002B Count - 1) % Count]).WithZ(0.0f);\n\n\t\t\tOutwards.Add(WaterCurve.RightOf(tangent.IsNearZeroLength ? Vector3.Forward : tangent.Normal));\n\t\t}\n\n\t\tLength = distance \u002B Points[^1].Distance(Points[0]);\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Centripetal Catmull-Rom between p1 and p2: a smooth curve through every point that never loops or overshoots,\n\t/// however unevenly the points are spaced.\n\t/// \u003C/summary\u003E\n\tprivate static Vector3 CatmullRom(Vector3 _P0, Vector3 _P1, Vector3 _P2, Vector3 _P3, float _T)\n\t{\n\t\tfloat t0 = 0.0f;\n\t\tfloat t1 = t0 \u002B Knot(_P0, _P1);\n\t\tfloat t2 = t1 \u002B Knot(_P1, _P2);\n\t\tfloat t3 = t2 \u002B Knot(_P2, _P3);\n\t\tfloat t = MathX.Lerp(t1, t2, _T);\n\n\t\tVector3 a1 = Blend(_P0, _P1, t0, t1, t);\n\t\tVector3 a2 = Blend(_P1, _P2, t1, t2, t);\n\t\tVector3 a3 = Blend(_P2, _P3, t2, t3, t);\n\t\tVector3 b1 = Blend(a1, a2, t0, t2, t);\n\t\tVector3 b2 = Blend(a2, a3, t1, t3, t);\n\n\t\treturn Blend(b1, b2, t1, t2, t);\n\t}\n\n\n\n\tprivate static float Knot(Vector3 _A, Vector3 _B)\n\t{\n\t\treturn MathF.Max(0.001f, MathF.Sqrt(_A.Distance(_B)));\n\t}\n\n\n\n\tprivate static Vector3 Blend(Vector3 _A, Vector3 _B, float _TA, float _TB, float _T)\n\t{\n\t\tfloat span = _TB - _TA;\n\n\t\tif (span \u003C 0.000001f)\n\t\t\treturn _A;\n\n\t\treturn _A * ((_TB - _T) / span) \u002B _B * ((_T - _TA) / span);\n\t}\n\n\n\n\tpublic float Wrap(float _Distance)\n\t{\n\t\tif (Length \u003C= 0.0f)\n\t\t\treturn 0.0f;\n\n\t\tfloat distance = _Distance % Length;\n\n\t\treturn distance \u003C 0.0f ? distance \u002B Length : distance;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Where the shore is at a distance round it, which way is away from the water there, and which way the shore runs.\n\t/// \u003C/summary\u003E\n\tpublic void At(float _Distance, out Vector3 _Point, out Vector3 _Outward, out Vector3 _Direction)\n\t{\n\t\tfloat distance = Wrap(_Distance);\n\t\tint index = IndexAt(distance);\n\t\tint next = (index \u002B 1) % Count;\n\n\t\tfloat from = Distances[index];\n\t\tfloat to = index \u002B 1 \u003C Count ? Distances[next] : Length;\n\t\tfloat t = to \u003E from ? Math.Clamp((distance - from) / (to - from), 0.0f, 1.0f) : 0.0f;\n\n\t\t_Point = Vector3.Lerp(Points[index], Points[next], t);\n\t\t_Outward = Vector3.Lerp(Outwards[index], Outwards[next], t).Normal;\n\n\t\tVector3 direction = (Points[next] - Points[index]).WithZ(0.0f);\n\t\t_Direction = direction.IsNearZeroLength ? Vector3.Cross(Vector3.Up, _Outward) : direction.Normal;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The index of the shore point at or before a (wrapped) distance.\n\t/// \u003C/summary\u003E\n\tprivate int IndexAt(float _Distance)\n\t{\n\t\tint low = 0;\n\t\tint high = Count - 1;\n\n\t\tif (_Distance \u003E= Distances[high])\n\t\t\treturn high;\n\n\t\twhile (high - low \u003E 1)\n\t\t{\n\t\t\tint mid = (low \u002B high) / 2;\n\n\t\t\tif (Distances[mid] \u003C= _Distance)\n\t\t\t\tlow = mid;\n\t\t\telse\n\t\t\t\thigh = mid;\n\t\t}\n\n\t\treturn low;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The points of the shore from one distance round to another, both ends included (interpolated). A stretch that\n\t/// runs past the end of the loop carries on from its start.\n\t/// \u003C/summary\u003E\n\tpublic List\u003CVector3\u003E Between(float _From, float _To)\n\t{\n\t\tvar run = new List\u003CVector3\u003E();\n\n\t\tAt(_From, out Vector3 start, out _, out _);\n\t\trun.Add(start);\n\n\t\tfloat from = Wrap(_From);\n\t\tfloat span = Wrap(_To - _From);\n\n\t\tif (span \u003C= 0.01f)\n\t\t\tspan = Length;\n\n\t\tint first = IndexAt(from);\n\n\t\tfor (int step = 1; step \u003C= Count; step\u002B\u002B)\n\t\t{\n\t\t\tint index = (first \u002B step) % Count;\n\t\t\tfloat along = Wrap(Distances[index] - from);\n\n\t\t\tif (along \u003C= 0.01f)\n\t\t\t\tcontinue;\n\n\t\t\tif (along \u003E= span - 0.01f)\n\t\t\t\tbreak;\n\n\t\t\trun.Add(Points[index]);\n\t\t}\n\n\t\tAt(_To, out Vector3 end, out _, out _);\n\t\trun.Add(end);\n\n\t\treturn run;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// How far round the shore the point nearest another one sits, and how far from the shore that point is.\n\t/// \u003C/summary\u003E\n\tpublic float NearestDistance(Vector3 _Point, out float _Offset)\n\t{\n\t\tfloat best = float.MaxValue;\n\t\tfloat distance = 0.0f;\n\t\tvar target = new Vector2(_Point.x, _Point.y);\n\n\t\tfor (int i = 0; i \u003C Count; i\u002B\u002B)\n\t\t{\n\t\t\tint next = (i \u002B 1) % Count;\n\t\t\tvar from = new Vector2(Points[i].x, Points[i].y);\n\t\t\tvar span = new Vector2(Points[next].x, Points[next].y) - from;\n\t\t\tfloat lengthSquared = span.LengthSquared;\n\t\t\tfloat t = lengthSquared \u003E 0.0f ? Math.Clamp(Vector2.Dot(target - from, span) / lengthSquared, 0.0f, 1.0f) : 0.0f;\n\t\t\tfloat offset = (from \u002B span * t).Distance(target);\n\n\t\t\tif (offset \u003E= best)\n\t\t\t\tcontinue;\n\n\t\t\tbest = offset;\n\t\t\tdistance = Distances[i] \u002B MathF.Sqrt(lengthSquared) * t;\n\t\t}\n\n\t\t_Offset = best;\n\n\t\treturn Wrap(distance);\n\t}\n\n\n\n\tpublic float NearestDistance(Vector3 _Point)\n\t{\n\t\treturn NearestDistance(_Point, out _);\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Walking round the shore from a distance (forwards, or backwards) that lies inside a region, how far round it first\n\t/// leaves the region: that distance, unwrapped (it can run past either end of the loop). False when the walk starts\n\t/// outside, or comes all the way round without leaving.\n\t/// \u003C/summary\u003E\n\tpublic bool TryLeave(float _From, bool _Forward, Func\u003CVector3, bool\u003E _Inside, out float _Distance)\n\t{\n\t\t_Distance = _From;\n\n\t\tif (Count \u003C 3 || Length \u003C= 0.0f)\n\t\t\treturn false;\n\n\t\tfloat from = Wrap(_From);\n\t\tint index = IndexAt(from);\n\n\t\tAt(from, out Vector3 previous, out _, out _);\n\n\t\tif (!_Inside(previous))\n\t\t\treturn false;\n\n\t\tfloat previousAlong = 0.0f;\n\n\t\t// The first shore point the walk reaches, and how far along the shore it is.\n\t\tint current = _Forward ? (index \u002B 1) % Count : index;\n\t\tfloat along = _Forward ? (index \u002B 1 \u003C Count ? Distances[index \u002B 1] : Length) - from : from - Distances[index];\n\n\t\tfor (int step = 0; step \u003C= Count \u0026\u0026 along \u003C= Length; step\u002B\u002B)\n\t\t{\n\t\t\tVector3 point = Points[current];\n\n\t\t\tif (!_Inside(point))\n\t\t\t{\n\t\t\t\t// Where between the last point inside and this one the edge is crossed.\n\t\t\t\tfloat inside = 0.0f;\n\t\t\t\tfloat outside = 1.0f;\n\n\t\t\t\tfor (int k = 0; k \u003C 24; k\u002B\u002B)\n\t\t\t\t{\n\t\t\t\t\tfloat middle = (inside \u002B outside) * 0.5f;\n\n\t\t\t\t\tif (_Inside(Vector3.Lerp(previous, point, middle)))\n\t\t\t\t\t\tinside = middle;\n\t\t\t\t\telse\n\t\t\t\t\t\toutside = middle;\n\t\t\t\t}\n\n\t\t\t\tfloat walked = previousAlong \u002B (along - previousAlong) * outside;\n\n\t\t\t\t_Distance = _Forward ? _From \u002B walked : _From - walked;\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\tprevious = point;\n\t\t\tpreviousAlong = along;\n\n\t\t\tif (_Forward)\n\t\t\t{\n\t\t\t\talong \u002B= SegmentLength(current);\n\t\t\t\tcurrent = (current \u002B 1) % Count;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tcurrent = (current \u002B Count - 1) % Count;\n\t\t\t\talong \u002B= SegmentLength(current);\n\t\t\t}\n\t\t}\n\n\t\treturn false;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The length of the shore from a point to the next one round.\n\t/// \u003C/summary\u003E\n\tprivate float SegmentLength(int _Index)\n\t{\n\t\treturn _Index \u002B 1 \u003C Count ? Distances[_Index \u002B 1] - Distances[_Index] : Length - Distances[_Index];\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Whether a point (in plan) is inside the shore: in a lake\u0027s water, or on a coast\u0027s land.\n\t/// \u003C/summary\u003E\n\tpublic bool Contains(Vector3 _Point)\n\t{\n\t\tbool inside = false;\n\n\t\tfor (int i = 0, j = Count - 1; i \u003C Count; j = i\u002B\u002B)\n\t\t{\n\t\t\tVector3 a = Points[i];\n\t\t\tVector3 b = Points[j];\n\n\t\t\tif ((a.y \u003E _Point.y) != (b.y \u003E _Point.y) \u0026\u0026 _Point.x \u003C (b.x - a.x) * (_Point.y - a.y) / (b.y - a.y) \u002B a.x)\n\t\t\t\tinside = !inside;\n\t\t}\n\n\t\treturn inside;\n\t}\n}\n"},{"Ident":"redsnail.watertool2","Path":"Building/RiverBuilder.cs","FileName":"RiverBuilder.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":445731,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\nusing Sandbox;\n\nnamespace RedSnail.WaterTool2;\n\n/// \u003Csummary\u003E\n/// Builds the surface of a stretch of river: its rows, one after the other down the river, joined into a strip. Rows\n/// may differ in how many points they have (a river widening, or the row it shares with a lake), so each pair of rows\n/// is zipped together by where their points sit across the river rather than point for point.\n/// \u003C/summary\u003E\ninternal static class RiverBuilder\n{\n\t/// \u003Csummary\u003E\n\t/// How much the water slows towards the banks: 0 runs as fast at the bank as in the middle, 0.5 at half speed.\n\t/// \u003C/summary\u003E\n\tpublic static float BankFactor(float _Across, float _BankDrag)\n\t{\n\t\tfloat offset = 2.0f * _Across - 1.0f;\n\n\t\treturn 1.0f - _BankDrag * offset * offset;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// A row across a river at a distance along it: its points from bank to bank, the water\u0027s velocity at each (along\n\t/// the river, slowed towards the banks), its wave strength and its foam.\n\t/// \u003C/summary\u003E\n\tpublic static RiverRow BuildRow(WaterCurveTable _Table, in RiverWidth _Width, RiverFlow _Flow, float _Distance, float _CellSize, float _BankDrag, Func\u003Cfloat, float\u003E _FoamFor)\n\t{\n\t\t_Table.Frame(_Distance, out Vector3 centre, out Vector3 tangent);\n\n\t\tVector3 right = WaterCurve.RightOf(tangent);\n\t\tVector3 flat = tangent.WithZ(0.0f);\n\t\tVector2 direction = flat.IsNearZeroLength ? new Vector2(-right.y, right.x) : new Vector2(flat.x, flat.y).Normal;\n\n\t\tfloat half = _Width.HalfAt(_Distance);\n\t\tint count = RiverRow.ColumnCount(half * 2.0f, _CellSize);\n\n\t\tfloat speed = _Flow?.SpeedAt(_Distance) ?? 0.0f;\n\t\tfloat waves = _Flow?.WavesAt(_Distance) ?? 0.0f;\n\t\tfloat foam = _FoamFor?.Invoke(speed) ?? 0.0f;\n\n\t\tvar row = new RiverRow(count) { Distance = _Distance };\n\n\t\tfor (int i = 0; i \u003C count; i\u002B\u002B)\n\t\t{\n\t\t\tfloat across = RiverRow.Across(i, count);\n\n\t\t\trow.Points[i] = centre \u002B right * (-half \u002B 2.0f * half * across);\n\t\t\trow.Velocities[i] = direction * (speed * BankFactor(across, _BankDrag));\n\t\t\trow.Waves[i] = waves;\n\t\t\trow.Foams[i] = foam;\n\t\t}\n\n\t\treturn row;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The strip through a list of rows, in network space, moved into the world.\n\t/// \u003C/summary\u003E\n\tpublic static WaterMeshData Build(IReadOnlyList\u003CRiverRow\u003E _Rows, in Transform _Transform)\n\t{\n\t\tint total = 0;\n\n\t\tforeach (var row in _Rows)\n\t\t\ttotal \u002B= row.Count;\n\n\t\tvar mesh = new WaterMeshData(total);\n\t\tvar starts = new int[_Rows.Count];\n\t\tvar indices = new List\u003Cint\u003E(total * 6);\n\t\tint cursor = 0;\n\n\t\tfor (int r = 0; r \u003C _Rows.Count; r\u002B\u002B)\n\t\t{\n\t\t\tvar row = _Rows[r];\n\n\t\t\tstarts[r] = cursor;\n\n\t\t\tfor (int i = 0; i \u003C row.Count; i\u002B\u002B)\n\t\t\t{\n\t\t\t\tmesh.Positions[cursor] = row.Points[i];\n\t\t\t\tmesh.Velocities[cursor] = row.Velocities[i];\n\t\t\t\tmesh.Waves[cursor] = row.Waves[i];\n\t\t\t\tmesh.Foams[cursor] = row.Foams[i];\n\t\t\t\tcursor\u002B\u002B;\n\t\t\t}\n\t\t}\n\n\t\tfor (int r = 0; r \u002B 1 \u003C _Rows.Count; r\u002B\u002B)\n\t\t{\n\t\t\tZip(indices, starts[r], _Rows[r].Count, starts[r \u002B 1], _Rows[r \u002B 1].Count);\n\n\t\t\t// Where the river runs at sea level, the sea under it is cut away, one stretch between two rows at a time\n\t\t\t// (its banks are exactly the river\u0027s own edges there).\n\t\t\tvar from = _Rows[r];\n\t\t\tvar to = _Rows[r \u002B 1];\n\n\t\t\tvar quad = new[]\n\t\t\t{\n\t\t\t\tnew Vector2(from.Points[0].x, from.Points[0].y),\n\t\t\t\tnew Vector2(to.Points[0].x, to.Points[0].y),\n\t\t\t\tnew Vector2(to.Points[^1].x, to.Points[^1].y),\n\t\t\t\tnew Vector2(from.Points[^1].x, from.Points[^1].y)\n\t\t\t};\n\n\t\t\tfloat lowest = MathF.Min(MathF.Min(from.Points[0].z, from.Points[^1].z), MathF.Min(to.Points[0].z, to.Points[^1].z));\n\n\t\t\tmesh.SeaHoles.Add(SeaHole.Polygon(quad, lowest));\n\t\t}\n\n\t\tmesh.Finish(_Transform, indices);\n\n\t\treturn mesh;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Joins two neighbouring rows with triangles, walking across both at once and always stepping along whichever row\n\t/// has its next point nearer the left bank. Rows run down the river, points from the left bank to the right, so the\n\t/// triangles come out counter-clockwise seen from above.\n\t/// \u003C/summary\u003E\n\tprivate static void Zip(List\u003Cint\u003E _Indices, int _StartA, int _CountA, int _StartB, int _CountB)\n\t{\n\t\tint a = 0;\n\t\tint b = 0;\n\n\t\twhile (a \u003C _CountA - 1 || b \u003C _CountB - 1)\n\t\t{\n\t\t\tbool stepA;\n\n\t\t\tif (a \u003E= _CountA - 1)\n\t\t\t\tstepA = false;\n\t\t\telse if (b \u003E= _CountB - 1)\n\t\t\t\tstepA = true;\n\t\t\telse\n\t\t\t\tstepA = RiverRow.Across(a \u002B 1, _CountA) \u003C= RiverRow.Across(b \u002B 1, _CountB);\n\n\t\t\tif (stepA)\n\t\t\t{\n\t\t\t\t_Indices.Add(_StartA \u002B a);\n\t\t\t\t_Indices.Add(_StartA \u002B a \u002B 1);\n\t\t\t\t_Indices.Add(_StartB \u002B b);\n\t\t\t\ta\u002B\u002B;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\t_Indices.Add(_StartA \u002B a);\n\t\t\t\t_Indices.Add(_StartB \u002B b \u002B 1);\n\t\t\t\t_Indices.Add(_StartB \u002B b);\n\t\t\t\tb\u002B\u002B;\n\t\t\t}\n\t\t}\n\t}\n}\n"},{"Ident":"redsnail.watertool2","Path":"Building/RiverFlow.cs","FileName":"RiverFlow.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":445731,"IsPrivate":false,"Code":"using System;\n\nnamespace RedSnail.WaterTool2;\n\n/// \u003Csummary\u003E\n/// The state of the water along one river, worked out by the network from the whole graph: how fast it runs at every\n/// distance (it arrives with whatever flows into the river, speeds up on slopes and settles back to the river\u0027s own\n/// speed on the flat), and how its wave strength blends into whatever it meets at each end.\n/// \u003C/summary\u003E\ninternal sealed class RiverFlow\n{\n\t/// \u003Csummary\u003E\n\t/// Speeds are kept to a quarter of a unit per second. A small change upstream then dies out a little way down\n\t/// the network instead of nudging, and rebuilding, every river below it.\n\t/// \u003C/summary\u003E\n\tpublic const float SpeedQuantum = 0.25f;\n\n\tpublic float Length;\n\tpublic float Step;\n\tpublic float[] Speeds;\n\n\t/// \u003Csummary\u003E\n\t/// The range of the river that is built as river: past the confluence or the lake at each end.\n\t/// \u003C/summary\u003E\n\tpublic float TrimStart;\n\tpublic float TrimEnd;\n\n\t/// \u003Csummary\u003E\n\t/// The river\u0027s own wave strength, the strength it has to arrive at on its first and last rows, and how far from\n\t/// those rows the blend reaches.\n\t/// \u003C/summary\u003E\n\tpublic float Waves;\n\tpublic float WavesStart;\n\tpublic float WavesEnd;\n\tpublic float BlendStart;\n\tpublic float BlendEnd;\n\n\n\n\tpublic float SpeedAt(float _Distance)\n\t{\n\t\tif (Speeds is null || Speeds.Length == 0)\n\t\t\treturn 0.0f;\n\n\t\tif (Speeds.Length == 1 || Step \u003C= 0.0f)\n\t\t\treturn Speeds[0];\n\n\t\tfloat position = Math.Clamp(_Distance, 0.0f, Length) / Step;\n\t\tint index = Math.Min((int)position, Speeds.Length - 2);\n\t\tfloat fraction = Math.Clamp(position - index, 0.0f, 1.0f);\n\n\t\treturn Speeds[index] \u002B (Speeds[index \u002B 1] - Speeds[index]) * fraction;\n\t}\n\n\n\n\tpublic float WavesAt(float _Distance)\n\t{\n\t\tfloat waves = Waves;\n\n\t\tfloat fromStart = _Distance - TrimStart;\n\t\tfloat fromEnd = Length - TrimEnd - _Distance;\n\n\t\twaves \u002B= (WavesStart - Waves) * Ramp(fromStart, BlendStart);\n\t\twaves \u002B= (WavesEnd - Waves) * Ramp(fromEnd, BlendEnd);\n\n\t\treturn MathF.Max(0.0f, waves);\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// 1 on the row the blend starts from, easing to 0 at the blend\u0027s reach.\n\t/// \u003C/summary\u003E\n\tprivate static float Ramp(float _Distance, float _Reach)\n\t{\n\t\tif (_Reach \u003C= 0.001f)\n\t\t\treturn _Distance \u003C= 0.001f ? 1.0f : 0.0f;\n\n\t\tfloat t = Math.Clamp(_Distance / _Reach, 0.0f, 1.0f);\n\n\t\treturn 1.0f - t * t * (3.0f - 2.0f * t);\n\t}\n\n\n\n\tpublic static float Quantize(float _Speed)\n\t{\n\t\treturn MathF.Round(_Speed / SpeedQuantum) * SpeedQuantum;\n\t}\n\n\n\n\tpublic void AddToHash(ref StableHash _Hash, float _From, float _To)\n\t{\n\t\t_Hash.Add(Length);\n\t\t_Hash.Add(Step);\n\t\t_Hash.Add(TrimStart);\n\t\t_Hash.Add(TrimEnd);\n\t\t_Hash.Add(Waves);\n\t\t_Hash.Add(WavesStart);\n\t\t_Hash.Add(WavesEnd);\n\t\t_Hash.Add(BlendStart);\n\t\t_Hash.Add(BlendEnd);\n\n\t\tif (Speeds is null || Step \u003C= 0.0f)\n\t\t\treturn;\n\n\t\t// Only the samples that reach into the stretch: a speed change further down does not touch it.\n\t\tint first = Math.Max(0, (int)MathF.Floor(_From / Step) - 1);\n\t\tint last = Math.Min(Speeds.Length - 1, (int)MathF.Ceiling(_To / Step) \u002B 1);\n\n\t\tfor (int i = first; i \u003C= last; i\u002B\u002B)\n\t\t\t_Hash.Add(Speeds[i]);\n\t}\n}\n"},{"Ident":"redsnail.watertool2","Path":"Code/Building/RiverRow.cs","FileName":"RiverRow.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":445731,"IsPrivate":false,"Code":"using System;\nusing Sandbox;\n\nnamespace RedSnail.WaterTool2;\n\n/// \u003Csummary\u003E\n/// One cross section of a river as its mesh is built: the points across it from its left bank to its right bank\n/// (looking downstream) and the state of the water at each of them. A row a river shares with whatever it runs into\n/// (a confluence, a lake, the next river through a bend) is worked out once and handed to both pieces, so they meet\n/// on exactly the same vertices carrying exactly the same data, and the surface runs on without a seam.\n/// \u003C/summary\u003E\ninternal sealed class RiverRow\n{\n\t/// \u003Csummary\u003E\n\t/// Columns are this far apart at most; a row always has its two banks.\n\t/// \u003C/summary\u003E\n\tpublic const int MaxColumns = 512;\n\n\t/// \u003Csummary\u003E\n\t/// How far along its river the row sits.\n\t/// \u003C/summary\u003E\n\tpublic float Distance;\n\n\t/// \u003Csummary\u003E\n\t/// Network-local positions, left bank first.\n\t/// \u003C/summary\u003E\n\tpublic Vector3[] Points;\n\n\t/// \u003Csummary\u003E\n\t/// Network-local horizontal water velocity at each point, in units per second.\n\t/// \u003C/summary\u003E\n\tpublic Vector2[] Velocities;\n\n\tpublic float[] Waves;\n\tpublic float[] Foams;\n\n\tpublic int Count =\u003E Points.Length;\n\n\n\n\tpublic RiverRow(int _Count)\n\t{\n\t\tPoints = new Vector3[_Count];\n\t\tVelocities = new Vector2[_Count];\n\t\tWaves = new float[_Count];\n\t\tFoams = new float[_Count];\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// How many points a row of this width gets for a mesh of this cell size: enough for no gap between them to be\n\t/// wider than a cell.\n\t/// \u003C/summary\u003E\n\tpublic static int ColumnCount(float _Width, float _CellSize)\n\t{\n\t\treturn Math.Clamp((int)MathF.Ceiling(_Width / MathF.Max(1.0f, _CellSize)) \u002B 1, 2, MaxColumns);\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Where a column sits across the river, from 0 on the left bank to 1 on the right.\n\t/// \u003C/summary\u003E\n\tpublic static float Across(int _Column, int _Count)\n\t{\n\t\treturn _Count \u003E 1 ? (float)_Column / (_Count - 1) : 0.5f;\n\t}\n\n\n\n\tpublic RiverRow Clone()\n\t{\n\t\tvar row = new RiverRow(Count) { Distance = Distance };\n\n\t\tArray.Copy(Points, row.Points, Count);\n\t\tArray.Copy(Velocities, row.Velocities, Count);\n\t\tArray.Copy(Waves, row.Waves, Count);\n\t\tArray.Copy(Foams, row.Foams, Count);\n\n\t\treturn row;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The same row seen from the other side: right bank first. The data is the same, point for point.\n\t/// \u003C/summary\u003E\n\tpublic RiverRow Reversed()\n\t{\n\t\tvar row = new RiverRow(Count) { Distance = Distance };\n\n\t\tfor (int i = 0; i \u003C Count; i\u002B\u002B)\n\t\t{\n\t\t\tint from = Count - 1 - i;\n\n\t\t\trow.Points[i] = Points[from];\n\t\t\trow.Velocities[i] = Velocities[from];\n\t\t\trow.Waves[i] = Waves[from];\n\t\t\trow.Foams[i] = Foams[from];\n\t\t}\n\n\t\treturn row;\n\t}\n\n\n\n\tpublic Vector3 Centre =\u003E (Points[0] \u002B Points[^1]) * 0.5f;\n\n\tpublic float HalfWidth =\u003E new Vector2(Points[^1].x - Points[0].x, Points[^1].y - Points[0].y).Length * 0.5f;\n\n\n\n\tpublic Vector2 MeanVelocity\n\t{\n\t\tget\n\t\t{\n\t\t\tVector2 sum = Vector2.Zero;\n\n\t\t\tforeach (var velocity in Velocities)\n\t\t\t\tsum \u002B= velocity;\n\n\t\t\treturn sum / MathF.Max(1, Count);\n\t\t}\n\t}\n\n\n\n\tpublic float MeanFoam\n\t{\n\t\tget\n\t\t{\n\t\t\tfloat sum = 0.0f;\n\n\t\t\tforeach (float foam in Foams)\n\t\t\t\tsum \u002B= foam;\n\n\t\t\treturn sum / MathF.Max(1, Count);\n\t\t}\n\t}\n\n\n\n\tpublic void AddToHash(ref StableHash _Hash)\n\t{\n\t\t_Hash.Add(Count);\n\n\t\tfor (int i = 0; i \u003C Count; i\u002B\u002B)\n\t\t{\n\t\t\t_Hash.Add(Points[i]);\n\t\t\t_Hash.Add(Velocities[i]);\n\t\t\t_Hash.Add(Waves[i]);\n\t\t\t_Hash.Add(Foams[i]);\n\t\t}\n\t}\n}\n"},{"Ident":"redsnail.watertool2","Path":"Code/Network/WaterNetwork.Audio.cs","FileName":"WaterNetwork.Audio.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":445731,"IsPrivate":false,"Code":"using Sandbox;\nusing Sandbox.Volumes;\n\nnamespace RedSnail.WaterTool2;\n\npublic sealed partial class WaterNetwork\n{\n\tprivate const string UnderwaterDspPreset = \u0022water.medium\u0022;\n\n\t/// \u003Csummary\u003E\n\t/// Muffles the game\u0027s sound while the camera is under the surface: an infinite DSP volume on this object, switched by\n\t/// the same test as \u003Csee cref=\u0022UnderwaterPostProcessVolume\u0022/\u003E. Hidden, never saved and never networked: every machine\n\t/// switches its own from its own camera, so a client joining is never handed the host\u0027s, switched on.\n\t/// \u003C/summary\u003E\n\tprivate DspVolume m_UnderwaterDsp;\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Takes the volume already on this object when there is one rather than adding a second, and always starts it off,\n\t/// whatever state it came in with.\n\t/// \u003C/summary\u003E\n\tprivate void AcquireUnderwaterDsp()\n\t{\n\t\t// The engine applies no DSP in an editor scene, and nothing listens on a dedicated server.\n\t\tif (Scene.IsEditor || Application.IsHeadless)\n\t\t\treturn;\n\n\t\tm_UnderwaterDsp = GetOrAddComponent\u003CDspVolume\u003E(false);\n\t\tm_UnderwaterDsp.Flags |= ComponentFlags.Hidden | ComponentFlags.NotSaved | ComponentFlags.NotNetworked;\n\t\tm_UnderwaterDsp.SceneVolume = new SceneVolume { Type = SceneVolume.VolumeTypes.Infinite };\n\t\tm_UnderwaterDsp.Dsp = UnderwaterDspPreset;\n\t\tm_UnderwaterDsp.Enabled = false;\n\t}\n\n\n\n\tprivate void ReleaseUnderwaterDsp()\n\t{\n\t\tif (m_UnderwaterDsp.IsValid())\n\t\t\tm_UnderwaterDsp.Enabled = false;\n\t}\n}\n"},{"Ident":"redsnail.watertool2","Path":"Code/Network/WaterNetwork.cs","FileName":"WaterNetwork.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":445731,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Sandbox;\n\nnamespace RedSnail.WaterTool2;\n\n/// \u003Csummary\u003E\n/// The scene\u0027s water: a graph of nodes joined by rivers, and the lakes those rivers run into and out of. It is the\n/// single source of truth for every river, confluence and lake in it; every surface is generated from it, piece by\n/// piece, and rebuilt only where the graph changed. Connected water is built as one surface: a river\u0027s last row of\n/// vertices is the very row its confluence or lake starts from, and every vertex carries the state of the water there\n/// (its flow, its wave strength, its foam), so the water runs from one piece into the next without a seam.\n/// \u003C/summary\u003E\n/// \u003Cremarks\u003E\n/// Runs everywhere, a dedicated server included: the pieces are what swimming, drowning and buoyancy ask about. Only\n/// the GPU side is skipped where nothing renders.\n/// \u003C/remarks\u003E\n[Title(\u0022Water Network\u0022)]\n[Icon(\u0022water\u0022)]\npublic sealed partial class WaterNetwork : Component, Component.ExecuteInEditor\n{\n\t/// \u003Csummary\u003E\n\t/// The network gameplay asks about. Set by the network that was enabled last (so the play scene\u0027s network takes\n\t/// over from the editor scene\u0027s as play starts), and picked up again by any live network when it goes.\n\t/// \u003C/summary\u003E\n\t[SkipHotload] public static WaterNetwork Current { get; private set; }\n\n\t/// \u003Csummary\u003E\n\t/// Undo/redo and scene loads assign whole new lists here instead of mutating the existing ones, so the setters are\n\t/// the one place that reliably sees \u0022the graph changed\u0022 and asks for a reconcile pass.\n\t/// \u003C/summary\u003E\n\t[Property, Hide]\n\tpublic List\u003CWaterNode\u003E Nodes\n\t{\n\t\tget;\n\t\tset\n\t\t{\n\t\t\tfield = value ?? new List\u003CWaterNode\u003E();\n\t\t\tMarkDirty();\n\t\t}\n\t} = [];\n\n\t[Property, Hide]\n\tpublic List\u003CWaterRiver\u003E Rivers\n\t{\n\t\tget;\n\t\tset\n\t\t{\n\t\t\tfield = value ?? new List\u003CWaterRiver\u003E();\n\t\t\tMarkDirty();\n\t\t}\n\t} = [];\n\n\t/// \u003Csummary\u003E\n\t/// Shared counter for node, river and lake ids. Serialized so ids stay unique across undo and reloads.\n\t/// \u003C/summary\u003E\n\t[Property, Hide] public int NextId { get; set; } = 1;\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Every network asks the scene for \u0022the\u0022 network, so a second one would be found by nobody in particular. The\n\t/// one that arrives second takes itself out again.\n\t/// \u003C/summary\u003E\n\tprotected override void OnAwake()\n\t{\n\t\tvar existing = Scene.Get\u003CWaterNetwork\u003E();\n\n\t\tif (!existing.IsValid() || existing == this)\n\t\t\treturn;\n\n\t\tLog.Warning($\u0022Only one {nameof(WaterNetwork)} can exist in a scene: the one added to \\\u0022{GameObject.Name}\\\u0022 has been removed. Use the one on \\\u0022{existing.GameObject.Name}\\\u0022.\u0022);\n\n\t\tDestroy();\n\t}\n\n\n\n\tprotected override void OnEnabled()\n\t{\n\t\tCurrent = this;\n\n\t\tAcquireUnderwaterDsp();\n\t\tMarkDirty();\n\t}\n\n\n\n\tprotected override void OnDisabled()\n\t{\n\t\tReleaseRendering();\n\t\tReleasePieces();\n\t\tReleaseRipples();\n\t\tReleaseUnderwaterDsp();\n\n\t\tif (Current == this)\n\t\t\tCurrent = null;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Undo/redo restore the graph by deserializing into this component; the list setters catch most of it, this catches\n\t/// the rest (and inspector edits).\n\t/// \u003C/summary\u003E\n\tprotected override void OnValidate()\n\t{\n\t\tMarkDirty();\n\t}\n\n\n\n\tprotected override void OnUpdate()\n\t{\n\t\t// Leaving play mode takes the play scene\u0027s network away; the editor\u0027s carries on.\n\t\tif (!Current.IsValid())\n\t\t\tCurrent = this;\n\n\t\tTick();\n\t\tUpdateRipples();\n\n\t\tif (Application.IsHeadless)\n\t\t\treturn;\n\n\t\tUpdateRendering();\n\t}\n\n\n\n\tprivate readonly Dictionary\u003Cint, WaterNode\u003E m_NodeIndex = new();\n\tprivate readonly Dictionary\u003Cint, WaterRiver\u003E m_RiverIndex = new();\n\tprivate readonly Dictionary\u003Cint, List\u003CWaterRiver\u003E\u003E m_NodeRivers = new();\n\tprivate static readonly List\u003CWaterRiver\u003E s_NoRivers = new();\n\n\tprivate int m_GraphRevision;\n\tprivate int m_IndexRevision = -1;\n\n\t/// \u003Csummary\u003E\n\t/// Says the graph\u0027s shape changed, so the lookups below are rebuilt before they are next used.\n\t/// \u003C/summary\u003E\n\tprivate void InvalidateIndex()\n\t{\n\t\tm_GraphRevision\u002B\u002B;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Nodes and rivers by id, and the rivers at each node: everything asks the graph these questions constantly.\n\t/// \u003C/summary\u003E\n\tprivate void EnsureIndex()\n\t{\n\t\tif (m_IndexRevision == m_GraphRevision)\n\t\t\treturn;\n\n\t\tm_IndexRevision = m_GraphRevision;\n\n\t\tm_NodeIndex.Clear();\n\t\tm_RiverIndex.Clear();\n\t\tm_NodeRivers.Clear();\n\n\t\tforeach (var node in Nodes)\n\t\t{\n\t\t\tif (node is not null)\n\t\t\t\tm_NodeIndex[node.Id] = node;\n\t\t}\n\n\t\tforeach (var river in Rivers)\n\t\t{\n\t\t\tif (river is null)\n\t\t\t\tcontinue;\n\n\t\t\tm_RiverIndex[river.Id] = river;\n\n\t\t\tAttach(river.StartNodeId, river);\n\n\t\t\tif (river.EndNodeId != river.StartNodeId)\n\t\t\t\tAttach(river.EndNodeId, river);\n\t\t}\n\t}\n\n\n\n\tprivate void Attach(int _NodeId, WaterRiver _River)\n\t{\n\t\tif (!m_NodeRivers.TryGetValue(_NodeId, out var list))\n\t\t{\n\t\t\tlist = new List\u003CWaterRiver\u003E();\n\t\t\tm_NodeRivers[_NodeId] = list;\n\t\t}\n\n\t\tlist.Add(_River);\n\t}\n\n\n\n\tpublic WaterNode FindNode(int _Id)\n\t{\n\t\tEnsureIndex();\n\n\t\treturn m_NodeIndex.GetValueOrDefault(_Id);\n\t}\n\n\n\n\tpublic WaterRiver FindRiver(int _Id)\n\t{\n\t\tEnsureIndex();\n\n\t\treturn m_RiverIndex.GetValueOrDefault(_Id);\n\t}\n\n\n\n\tpublic WaterRiver FindRiverBetween(int _NodeA, int _NodeB)\n\t{\n\t\tif (_NodeA == _NodeB)\n\t\t\treturn null;\n\n\t\tforeach (var river in GetRiversAt(_NodeA))\n\t\t{\n\t\t\tif (river.Touches(_NodeB))\n\t\t\t\treturn river;\n\t\t}\n\n\t\treturn null;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The rivers at a node. The list belongs to the network: treat it as read only, and copy it before changing the\n\t/// graph while walking it.\n\t/// \u003C/summary\u003E\n\tpublic IReadOnlyList\u003CWaterRiver\u003E GetRiversAt(int _NodeId)\n\t{\n\t\tEnsureIndex();\n\n\t\treturn m_NodeRivers.TryGetValue(_NodeId, out var rivers) ? rivers : s_NoRivers;\n\t}\n\n\n\n\tpublic int GetDegree(int _NodeId)\n\t{\n\t\treturn GetRiversAt(_NodeId).Count;\n\t}\n\n\n\n\tpublic WaterNode FindNearestNode(Vector3 _LocalPosition, float _MaxDistance)\n\t{\n\t\tWaterNode nearest = null;\n\t\tfloat nearestDistance = _MaxDistance;\n\n\t\tforeach (var node in Nodes)\n\t\t{\n\t\t\tfloat distance = Vector3.DistanceBetween(node.Position, _LocalPosition);\n\n\t\t\tif (distance \u003E nearestDistance)\n\t\t\t\tcontinue;\n\n\t\t\tnearest = node;\n\t\t\tnearestDistance = distance;\n\t\t}\n\n\t\treturn nearest;\n\t}\n\n\n\n\tpublic WaterNode AddNode(Vector3 _LocalPosition)\n\t{\n\t\tvar node = new WaterNode { Id = NextId\u002B\u002B, Position = _LocalPosition };\n\n\t\tNodes.Add(node);\n\t\tMarkDirty();\n\n\t\treturn node;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Joins two nodes with a river flowing from the first to the second. Returns null when the join makes no sense\n\t/// (same node, unknown node, a river already runs between them, or either node opens into a lake that already has\n\t/// its river).\n\t/// \u003C/summary\u003E\n\tpublic WaterRiver AddRiver(int _UpstreamNodeId, int _DownstreamNodeId, float _Width, float _Speed, float _Waves, float _Depth)\n\t{\n\t\tif (_UpstreamNodeId == _DownstreamNodeId)\n\t\t\treturn null;\n\n\t\tvar start = FindNode(_UpstreamNodeId);\n\t\tvar end = FindNode(_DownstreamNodeId);\n\n\t\tif (start is null || end is null)\n\t\t\treturn null;\n\n\t\tif (FindRiverBetween(_UpstreamNodeId, _DownstreamNodeId) is not null)\n\t\t\treturn null;\n\n\t\t// A lake opening or a river mouth carries exactly one river: the lake, or the sea, is the rest of the junction.\n\t\tif (IsEndTaken(_UpstreamNodeId) || IsEndTaken(_DownstreamNodeId))\n\t\t\treturn null;\n\n\t\tvar river = new WaterRiver\n\t\t{\n\t\t\tId = NextId\u002B\u002B,\n\t\t\tStartNodeId = _UpstreamNodeId,\n\t\t\tEndNodeId = _DownstreamNodeId,\n\t\t\tStartWidth = _Width,\n\t\t\tEndWidth = _Width,\n\t\t\tSpeed = _Speed,\n\t\t\tWaves = _Waves,\n\t\t\tDepth = _Depth,\n\t\t\tStartTangent = StraightHandle(start.Position, end.Position),\n\t\t\tEndTangent = StraightHandle(end.Position, start.Position)\n\t\t};\n\n\t\tRivers.Add(river);\n\t\tInvalidateIndex();\n\n\t\tRefreshTangentsAround(_UpstreamNodeId);\n\t\tRefreshTangentsAround(_DownstreamNodeId);\n\t\tMarkDirty();\n\n\t\treturn river;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Inserts a node on a river without changing its shape: the river keeps its id and becomes the upstream half, a\n\t/// new river carries on from the node. A split landing within \u003Cparamref name=\u0022_MinEndDistance\u0022/\u003E of an end returns\n\t/// that end\u0027s node instead, so no sliver rivers get made.\n\t/// \u003C/summary\u003E\n\tpublic WaterNode SplitRiver(int _RiverId, float _T, float _MinEndDistance = 25.0f)\n\t{\n\t\tvar river = FindRiver(_RiverId);\n\n\t\tif (river is null || !TryGetCurve(river, out var curve))\n\t\t\treturn null;\n\n\t\tvar table = GetCurveTable(river);\n\t\tfloat distance = _T * table.Length;\n\n\t\tif (distance \u003C= _MinEndDistance)\n\t\t\treturn FindNode(river.StartNodeId);\n\n\t\tif (table.Length - distance \u003C= _MinEndDistance)\n\t\t\treturn FindNode(river.EndNodeId);\n\n\t\tcurve.Split(_T, out var first, out var second);\n\n\t\t// The handles at the split come from the subdivision, which is the only way the halves keep tracing the old\n\t\t// river, so they are hand-placed from the node\u0027s point of view.\n\t\tvar node = new WaterNode { Id = NextId\u002B\u002B, Position = first.P3, AutoTangents = false, CornerRadius = FindNode(river.StartNodeId)?.CornerRadius ?? 150.0f };\n\t\tNodes.Add(node);\n\n\t\tint endNodeId = river.EndNodeId;\n\t\tfloat widthAtSplit = new RiverWidth(river.StartWidth, river.EndWidth, table.Length).At(distance);\n\t\tfloat endWidth = river.EndWidth;\n\n\t\triver.EndNodeId = node.Id;\n\t\triver.EndWidth = widthAtSplit;\n\t\triver.StartTangent = first.P1 - first.P0;\n\t\triver.EndTangent = first.P2 - first.P3;\n\n\t\tRivers.Add(new WaterRiver\n\t\t{\n\t\t\tId = NextId\u002B\u002B,\n\t\t\tStartNodeId = node.Id,\n\t\t\tEndNodeId = endNodeId,\n\t\t\tStartWidth = widthAtSplit,\n\t\t\tEndWidth = endWidth,\n\t\t\tSpeed = river.Speed,\n\t\t\tWaves = river.Waves,\n\t\t\tDepth = river.Depth,\n\t\t\tStartTangent = second.P1 - second.P0,\n\t\t\tEndTangent = second.P2 - second.P3\n\t\t});\n\n\t\tMarkDirty();\n\n\t\treturn node;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Switches a node between automatic and hand-placed tangents. Going manual straightens every handle at the node\n\t/// (a sharp bend) unless \u003Cparamref name=\u0022_Straighten\u0022/\u003E is off, which just freezes the handles as they are.\n\t/// \u003C/summary\u003E\n\tpublic void SetAutoTangents(int _NodeId, bool _Auto, bool _Straighten = true)\n\t{\n\t\tvar node = FindNode(_NodeId);\n\n\t\tif (node is null)\n\t\t\treturn;\n\n\t\tnode.AutoTangents = _Auto;\n\n\t\tif (!_Auto \u0026\u0026 _Straighten)\n\t\t{\n\t\t\tforeach (var river in GetRiversAt(_NodeId))\n\t\t\t{\n\t\t\t\tvar other = FindNode(river.OtherNodeId(_NodeId));\n\n\t\t\t\tif (other is not null)\n\t\t\t\t\tSetHandleInternal(river, _NodeId, StraightHandle(node.Position, other.Position));\n\t\t\t}\n\t\t}\n\n\t\tRefreshTangentsAround(_NodeId);\n\t\tMarkDirty();\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The Bezier handle a river has at one of its nodes, pointing from the node into the river.\n\t/// \u003C/summary\u003E\n\tpublic static Vector3 GetHandle(WaterRiver _River, int _NodeId)\n\t{\n\t\treturn _River.StartNodeId == _NodeId ? _River.StartTangent : _River.EndTangent;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Places one handle by hand. With \u003Cparamref name=\u0022_Mirror\u0022/\u003E, a bend keeps its other handle opposite (its own\n\t/// length kept) so the river stays smooth through it.\n\t/// \u003C/summary\u003E\n\tpublic void SetHandle(int _RiverId, int _NodeId, Vector3 _Handle, bool _Mirror)\n\t{\n\t\tvar river = FindRiver(_RiverId);\n\t\tvar node = FindNode(_NodeId);\n\n\t\tif (river is null || node is null || !river.Touches(_NodeId))\n\t\t\treturn;\n\n\t\tnode.AutoTangents = false;\n\t\tSetHandleInternal(river, _NodeId, _Handle);\n\n\t\tif (_Mirror \u0026\u0026 !_Handle.IsNearZeroLength)\n\t\t{\n\t\t\tvar attached = GetRiversAt(_NodeId).ToList();\n\n\t\t\tif (attached.Count == 2)\n\t\t\t{\n\t\t\t\tvar other = attached[0] == river ? attached[1] : attached[0];\n\t\t\t\tfloat otherLength = GetHandle(other, _NodeId).Length;\n\n\t\t\t\tSetHandleInternal(other, _NodeId, -_Handle.Normal * otherLength);\n\t\t\t}\n\t\t}\n\n\t\tMarkDirty();\n\t}\n\n\n\n\tprivate static void SetHandleInternal(WaterRiver _River, int _NodeId, Vector3 _Handle)\n\t{\n\t\tif (_River.StartNodeId == _NodeId)\n\t\t\t_River.StartTangent = _Handle;\n\t\telse\n\t\t\t_River.EndTangent = _Handle;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Moves a node. A node a river opens into a lake (or the sea) at stays on that lake\u0027s shore (or that coast): it\n\t/// slides round it instead.\n\t/// \u003C/summary\u003E\n\tpublic void MoveNode(int _NodeId, Vector3 _LocalPosition)\n\t{\n\t\tvar node = FindNode(_NodeId);\n\n\t\tif (node is null)\n\t\t\treturn;\n\n\t\tVector3 target = _LocalPosition;\n\n\t\tif (LakeAtOpening(_NodeId) is { } lake \u0026\u0026 GetShore(lake) is { } shore)\n\t\t{\n\t\t\tshore.At(shore.NearestDistance(_LocalPosition), out Vector3 onShore, out _, out _);\n\t\t\ttarget = onShore;\n\t\t}\n\n\t\t// A drag that is holding still would otherwise rebuild the pieces every frame over float noise.\n\t\tif (Vector3.DistanceBetween(node.Position, target) \u003C 0.01f)\n\t\t\treturn;\n\n\t\tnode.Position = target;\n\n\t\tRefreshTangentsAround(_NodeId);\n\t\tMarkDirty();\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Removes a river. A node left with nothing attached goes with it (and stops being a lake opening), the others\n\t/// get their smoothing refreshed.\n\t/// \u003C/summary\u003E\n\tpublic bool RemoveRiver(int _RiverId)\n\t{\n\t\tvar river = FindRiver(_RiverId);\n\n\t\tif (river is null)\n\t\t\treturn false;\n\n\t\tRivers.Remove(river);\n\t\tInvalidateIndex();\n\n\t\tforeach (int nodeId in new[] { river.StartNodeId, river.EndNodeId })\n\t\t{\n\t\t\tif (GetDegree(nodeId) == 0)\n\t\t\t\tRemoveNodeInternal(nodeId);\n\t\t\telse\n\t\t\t\tRefreshTangentsAround(nodeId);\n\t\t}\n\n\t\tMarkDirty();\n\n\t\treturn true;\n\t}\n\n\n\n\tpublic bool RemoveNode(int _NodeId)\n\t{\n\t\tif (FindNode(_NodeId) is null)\n\t\t\treturn false;\n\n\t\tforeach (var river in GetRiversAt(_NodeId).ToList())\n\t\t\tRemoveRiver(river.Id);\n\n\t\t// RemoveRiver already dropped it once it had no rivers left; this covers a node that never had any.\n\t\tRemoveNodeInternal(_NodeId);\n\t\tMarkDirty();\n\n\t\treturn true;\n\t}\n\n\n\n\tprivate void RemoveNodeInternal(int _NodeId)\n\t{\n\t\tNodes.RemoveAll(node =\u003E node.Id == _NodeId);\n\n\t\tforeach (var lake in Lakes)\n\t\t\tlake.Openings.Remove(_NodeId);\n\n\t\tInvalidateIndex();\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// A node that opens into a lake, or into the sea through a coast, and already has its one river.\n\t/// \u003C/summary\u003E\n\tprivate bool IsEndTaken(int _NodeId)\n\t{\n\t\treturn LakeAtOpening(_NodeId) is not null \u0026\u0026 GetDegree(_NodeId) \u003E 0;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Takes a node a river simply passes through out, and joins its two rivers into one. The merged river keeps the\n\t/// handles the two had at their far ends, stretched to the full length (which undoes a split exactly on a straight\n\t/// river and closely on a curved one). Null when the node is not a plain pass-through (a confluence, a river end, a\n\t/// lake opening, or two rivers flowing against each other), in which case nothing changes.\n\t/// \u003C/summary\u003E\n\tpublic WaterRiver DissolveNode(int _NodeId)\n\t{\n\t\tvar node = FindNode(_NodeId);\n\n\t\tif (node is null || LakeAtOpening(_NodeId) is not null)\n\t\t\treturn null;\n\n\t\tvar attached = GetRiversAt(_NodeId).ToList();\n\n\t\tif (attached.Count != 2)\n\t\t\treturn null;\n\n\t\t// The water has to run through the node: one river arriving, the other leaving.\n\t\tvar upstream = attached.FirstOrDefault(river =\u003E river.EndNodeId == _NodeId);\n\t\tvar downstream = attached.FirstOrDefault(river =\u003E river.StartNodeId == _NodeId);\n\n\t\tif (upstream is null || downstream is null || upstream == downstream)\n\t\t\treturn null;\n\n\t\tint startId = upstream.StartNodeId;\n\t\tint endId = downstream.EndNodeId;\n\n\t\tif (startId == endId || FindRiverBetween(startId, endId) is not null)\n\t\t\treturn null;\n\n\t\tfloat firstLength = GetCurveTable(upstream)?.Length ?? 0.0f;\n\t\tfloat secondLength = GetCurveTable(downstream)?.Length ?? 0.0f;\n\t\tfloat total = firstLength \u002B secondLength;\n\t\tvar main = secondLength \u003E firstLength ? downstream : upstream;\n\n\t\tvar merged = new WaterRiver\n\t\t{\n\t\t\tId = NextId\u002B\u002B,\n\t\t\tStartNodeId = startId,\n\t\t\tEndNodeId = endId,\n\t\t\tStartWidth = upstream.StartWidth,\n\t\t\tEndWidth = downstream.EndWidth,\n\t\t\tSpeed = main.Speed,\n\t\t\tWaves = main.Waves,\n\t\t\tDepth = main.Depth,\n\t\t\tStartTangent = upstream.StartTangent * (firstLength \u003E 0.0f ? total / firstLength : 1.0f),\n\t\t\tEndTangent = downstream.EndTangent * (secondLength \u003E 0.0f ? total / secondLength : 1.0f)\n\t\t};\n\n\t\tRivers.Remove(upstream);\n\t\tRivers.Remove(downstream);\n\t\tNodes.Remove(node);\n\t\tRivers.Add(merged);\n\t\tInvalidateIndex();\n\n\t\tRefreshTangentsAround(startId);\n\t\tRefreshTangentsAround(endId);\n\t\tMarkDirty();\n\n\t\treturn merged;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Turns a river round so its water flows the other way: its ends, handles and widths swap.\n\t/// \u003C/summary\u003E\n\tpublic void ReverseRiver(int _RiverId)\n\t{\n\t\tvar river = FindRiver(_RiverId);\n\n\t\tif (river is null)\n\t\t\treturn;\n\n\t\t(river.StartNodeId, river.EndNodeId) = (river.EndNodeId, river.StartNodeId);\n\t\t(river.StartTangent, river.EndTangent) = (river.EndTangent, river.StartTangent);\n\t\t(river.StartWidth, river.EndWidth) = (river.EndWidth, river.StartWidth);\n\n\t\tInvalidateIndex();\n\t\tMarkDirty();\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Turns round the whole run of rivers a river belongs to: every river joined to it through plain bends, up to the\n\t/// confluences, lakes and ends either side. That is what reversing \u0022a river\u0022 means to whoever drew it as one.\n\t/// \u003C/summary\u003E\n\tpublic void ReverseRun(int _RiverId)\n\t{\n\t\tforeach (var river in GetRun(_RiverId))\n\t\t\tReverseRiver(river.Id);\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The rivers joined to one through plain bends (nodes with exactly two rivers that are not lake openings).\n\t/// \u003C/summary\u003E\n\tpublic List\u003CWaterRiver\u003E GetRun(int _RiverId)\n\t{\n\t\tvar run = new List\u003CWaterRiver\u003E();\n\t\tvar first = FindRiver(_RiverId);\n\n\t\tif (first is null)\n\t\t\treturn run;\n\n\t\tvar seen = new HashSet\u003Cint\u003E { first.Id };\n\t\tvar queue = new Queue\u003CWaterRiver\u003E();\n\n\t\tqueue.Enqueue(first);\n\n\t\twhile (queue.Count \u003E 0)\n\t\t{\n\t\t\tvar river = queue.Dequeue();\n\t\t\trun.Add(river);\n\n\t\t\tforeach (int nodeId in new[] { river.StartNodeId, river.EndNodeId })\n\t\t\t{\n\t\t\t\tif (GetDegree(nodeId) != 2 || LakeAtOpening(nodeId) is not null)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tforeach (var other in GetRiversAt(nodeId))\n\t\t\t\t{\n\t\t\t\t\tif (seen.Add(other.Id))\n\t\t\t\t\t\tqueue.Enqueue(other);\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn run;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The curve of a river in network space. A river opening into a lake leaves its shore square on, so the two\n\t/// surfaces meet cleanly.\n\t/// \u003C/summary\u003E\n\tpublic bool TryGetCurve(WaterRiver _River, out WaterCurve _Curve)\n\t{\n\t\tvar start = FindNode(_River.StartNodeId);\n\t\tvar end = FindNode(_River.EndNodeId);\n\n\t\tif (start is null || end is null)\n\t\t{\n\t\t\t_Curve = default;\n\t\t\treturn false;\n\t\t}\n\n\t\tVector3 startHandle = _River.StartTangent;\n\t\tVector3 endHandle = _River.EndTangent;\n\n\t\tif (TryLakeOutward(_River.StartNodeId, out Vector3 startOutward))\n\t\t\tstartHandle = startOutward * MathF.Max(1.0f, startHandle.Length);\n\n\t\tif (TryLakeOutward(_River.EndNodeId, out Vector3 endOutward))\n\t\t\tendHandle = endOutward * MathF.Max(1.0f, endHandle.Length);\n\n\t\t_Curve = new WaterCurve(start.Position, start.Position \u002B startHandle, end.Position \u002B endHandle, end.Position);\n\n\t\treturn true;\n\t}\n\n\n\n\tprivate readonly Dictionary\u003Cint, WaterCurveTable\u003E m_CurveTables = new();\n\n\t/// \u003Csummary\u003E\n\t/// The arc-length table of a river, rebuilt only when its curve actually changed.\n\t/// \u003C/summary\u003E\n\tpublic WaterCurveTable GetCurveTable(WaterRiver _River)\n\t{\n\t\tif (_River is null || !TryGetCurve(_River, out var curve))\n\t\t\treturn null;\n\n\t\tif (m_CurveTables.TryGetValue(_River.Id, out var table) \u0026\u0026 table.Curve.Equals(curve))\n\t\t\treturn table;\n\n\t\ttable = WaterCurveTable.Create(curve);\n\t\tm_CurveTables[_River.Id] = table;\n\n\t\treturn table;\n\t}\n\n\n\n\tprivate void PruneCurveTables()\n\t{\n\t\tvar live = new HashSet\u003Cint\u003E(Rivers.Select(river =\u003E river.Id));\n\t\tvar stale = m_CurveTables.Keys.Where(id =\u003E !live.Contains(id)).ToList();\n\n\t\tforeach (int id in stale)\n\t\t\tm_CurveTables.Remove(id);\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The width profile a river is built with, as the last reconcile worked it out (a river through a bend shares its\n\t/// width there with the next). Its own widths when nothing has been worked out yet.\n\t/// \u003C/summary\u003E\n\tpublic RiverWidth WidthOf(WaterRiver _River)\n\t{\n\t\tif (m_Widths.TryGetValue(_River.Id, out var width))\n\t\t\treturn width;\n\n\t\treturn new RiverWidth(_River.StartWidth, _River.EndWidth, GetCurveTable(_River)?.Length ?? 1.0f);\n\t}\n}\n"},{"Ident":"redsnail.watertool2","Path":"Code/Network/WaterNetwork.Ripples.cs","FileName":"WaterNetwork.Ripples.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":445731,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\nusing Sandbox;\n\nnamespace RedSnail.WaterTool2;\n\npublic sealed partial class WaterNetwork\n{\n\t// Interactive ripples: expanding rings stamped onto the surface where something enters or moves on the water. Each\n\t// one goes to the shader as two rows: (centre.xy, start time, strength) and (wavelength, ring width, _, _). The same\n\t// formula runs in advancedwater.shader and in ComputeRippleHeight, so what floats bobs on the rings it sees.\n\n\tprivate const int MaxRipples = 64;\n\tprivate const int RippleRows = 2;\n\n\t[Property(Title = \u0022Amplitude\u0022), Group(\u0022Ripples\u0022), Order(3)] public float RippleAmplitude { get; set; } = 8.0f;\n\t[Property(Title = \u0022Expansion Speed\u0022), Group(\u0022Ripples\u0022), Order(3)] public float RippleSpeed { get; set; } = 100.0f;\n\n\t/// \u003Csummary\u003E\n\t/// Ring spacing for ripples spawned without one of their own. Smaller makes more, tighter rings.\n\t/// \u003C/summary\u003E\n\t[Property(Title = \u0022Default Wavelength\u0022), Group(\u0022Ripples\u0022), Order(3)] public float RippleWavelength { get; set; } = 120.0f;\n\n\t/// \u003Csummary\u003E\n\t/// Ring size for ripples spawned without one of their own. Larger makes a bigger, broader ripple.\n\t/// \u003C/summary\u003E\n\t[Property(Title = \u0022Default Ring Width\u0022), Group(\u0022Ripples\u0022), Order(3)] public float RippleWidth { get; set; } = 50.0f;\n\n\t[Property(Title = \u0022Damping\u0022), Group(\u0022Ripples\u0022), Order(3)] public float RippleDamping { get; set; } = 1.0f;\n\t[Property(Title = \u0022Lifetime\u0022), Group(\u0022Ripples\u0022), Order(3)] public float RippleLifetime { get; set; } = 3.0f;\n\n\tprivate struct Ripple\n\t{\n\t\tpublic Vector2 Centre;\n\t\tpublic float StartTime;\n\t\tpublic float Strength;\n\t\tpublic float Wavelength;\n\t\tpublic float Width;\n\t}\n\n\tprivate readonly List\u003CRipple\u003E m_Ripples = new();\n\tprivate readonly Vector4[] m_RippleData = new Vector4[MaxRipples * RippleRows];\n\tprivate GpuBuffer\u003CVector4\u003E m_RippleBuffer;\n\tprivate int m_UploadedRipples;\n\n\t/// \u003Csummary\u003E\n\t/// Everywhere the uploaded ripples reach, in plan (min.xy, max.xy): the shader leaves every vertex outside it alone.\n\t/// \u003C/summary\u003E\n\tprivate Vector4 m_RippleBounds;\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Spawns an expanding ripple on the water at a world position.\n\t/// \u003C/summary\u003E\n\t/// \u003Cparam name=\u0022_WorldPosition\u0022\u003EWhere the ripple starts (only X and Y count).\u003C/param\u003E\n\t/// \u003Cparam name=\u0022_Strength\u0022\u003EScales its height (1 is an ordinary splash).\u003C/param\u003E\n\t/// \u003Cparam name=\u0022_Wavelength\u0022\u003ERing spacing; 0 or less uses the network\u0027s default.\u003C/param\u003E\n\t/// \u003Cparam name=\u0022_Width\u0022\u003ERing size; 0 or less uses the network\u0027s default.\u003C/param\u003E\n\tpublic static void AddRipple(Vector3 _WorldPosition, float _Strength = 1.0f, float _Wavelength = -1.0f, float _Width = -1.0f)\n\t{\n\t\tif (Current.IsValid())\n\t\t\tCurrent.AddRippleInternal(_WorldPosition, _Strength, _Wavelength, _Width);\n\t}\n\n\n\n\tprivate void AddRippleInternal(Vector3 _WorldPosition, float _Strength, float _Wavelength, float _Width)\n\t{\n\t\tif (_Strength \u003C= 0.0f)\n\t\t\treturn;\n\n\t\t// The oldest goes when the list is full, so the freshest splashes always show.\n\t\tif (m_Ripples.Count \u003E= MaxRipples)\n\t\t\tm_Ripples.RemoveAt(0);\n\n\t\tm_Ripples.Add(new Ripple\n\t\t{\n\t\t\tCentre = new Vector2(_WorldPosition.x, _WorldPosition.y),\n\t\t\tStartTime = Time.Now,\n\t\t\tStrength = _Strength,\n\t\t\tWavelength = _Wavelength \u003E 0.0f ? _Wavelength : RippleWavelength,\n\t\t\tWidth = _Width \u003E 0.0f ? _Width : RippleWidth\n\t\t});\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Drops the ripples that have died out. Runs everywhere: a dedicated server\u0027s buoyancy reads them too.\n\t/// \u003C/summary\u003E\n\tprivate void UpdateRipples()\n\t{\n\t\tfor (int i = m_Ripples.Count - 1; i \u003E= 0; i--)\n\t\t{\n\t\t\tif (Time.Now - m_Ripples[i].StartTime \u003E RippleLifetime)\n\t\t\t\tm_Ripples.RemoveAt(i);\n\t\t}\n\t}\n\n\n\n\tprivate void UploadRipples()\n\t{\n\t\tm_UploadedRipples = Math.Min(m_Ripples.Count, MaxRipples);\n\n\t\tvar min = new Vector2(float.MaxValue, float.MaxValue);\n\t\tvar max = new Vector2(float.MinValue, float.MinValue);\n\n\t\tfor (int i = 0; i \u003C m_UploadedRipples; i\u002B\u002B)\n\t\t{\n\t\t\tvar ripple = m_Ripples[i];\n\t\t\tint row = i * RippleRows;\n\n\t\t\tm_RippleData[row \u002B 0] = new Vector4(ripple.Centre.x, ripple.Centre.y, ripple.StartTime, ripple.Strength);\n\t\t\tm_RippleData[row \u002B 1] = new Vector4(ripple.Wavelength, ripple.Width, 0.0f, 0.0f);\n\n\t\t\t// As far as its ring has spread (a moment more to spare), and the four ring widths past it the shader still\n\t\t\t// counts. A ripple without a width reaches everywhere.\n\t\t\tfloat reach = ripple.Width \u003E 0.001f\n\t\t\t\t? (MathF.Max(0.0f, Time.Now - ripple.StartTime) \u002B 0.1f) * MathF.Abs(RippleSpeed) \u002B ripple.Width * 4.0f\n\t\t\t\t: 1e30f;\n\n\t\t\tmin = new Vector2(MathF.Min(min.x, ripple.Centre.x - reach), MathF.Min(min.y, ripple.Centre.y - reach));\n\t\t\tmax = new Vector2(MathF.Max(max.x, ripple.Centre.x \u002B reach), MathF.Max(max.y, ripple.Centre.y \u002B reach));\n\t\t}\n\n\t\tm_RippleBounds = m_UploadedRipples \u003E 0 ? new Vector4(min.x, min.y, max.x, max.y) : Vector4.Zero;\n\n\t\tif (!m_RippleBuffer.IsValid())\n\t\t\tm_RippleBuffer = new GpuBuffer\u003CVector4\u003E(MaxRipples * RippleRows, GpuBuffer.UsageFlags.Structured);\n\n\t\tm_RippleBuffer.SetData(m_RippleData.AsSpan(0, m_UploadedRipples * RippleRows));\n\t}\n\n\n\n\tprivate void ApplyRippleAttributes(RenderAttributes _Attributes)\n\t{\n\t\t_Attributes.Set(\u0022RippleCount\u0022, m_UploadedRipples);\n\t\t_Attributes.Set(\u0022RippleBounds\u0022, m_RippleBounds);\n\t\t_Attributes.Set(\u0022RippleAmplitude\u0022, RippleAmplitude);\n\t\t_Attributes.Set(\u0022RippleSpeed\u0022, RippleSpeed);\n\t\t_Attributes.Set(\u0022RippleDamping\u0022, RippleDamping);\n\n\t\tif (m_RippleBuffer.IsValid())\n\t\t\t_Attributes.Set(\u0022RippleData\u0022, m_RippleBuffer);\n\t}\n\n\n\n\tprivate void ReleaseRipples()\n\t{\n\t\tm_RippleBuffer?.Dispose();\n\t\tm_RippleBuffer = null;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// How far the ripples lift (or drop) the surface at a world point. Mirrors ComputeRipples() in the shader.\n\t/// \u003C/summary\u003E\n\tpublic float ComputeRippleHeight(Vector2 _Point)\n\t{\n\t\tif (m_Ripples.Count == 0)\n\t\t\treturn 0.0f;\n\n\t\tfloat height = 0.0f;\n\n\t\tforeach (var ripple in m_Ripples)\n\t\t{\n\t\t\tfloat age = Time.Now - ripple.StartTime;\n\n\t\t\tif (age \u003C 0.0f || age \u003E RippleLifetime)\n\t\t\t\tcontinue;\n\n\t\t\tfloat frequency = ripple.Wavelength \u003E 0.001f ? MathF.PI * 2.0f / ripple.Wavelength : 0.0f;\n\t\t\tfloat inverseWidthSquared = ripple.Width \u003E 0.001f ? 1.0f / (ripple.Width * ripple.Width) : 0.0f;\n\n\t\t\tfloat distance = (_Point - ripple.Centre).Length;\n\t\t\tfloat offset = distance - age * RippleSpeed;\n\n\t\t\tfloat spatial = MathF.Exp(-offset * offset * inverseWidthSquared);\n\t\t\tfloat fade = MathF.Exp(-age * RippleDamping);\n\n\t\t\theight \u002B= MathF.Sin(offset * frequency) * spatial * fade * RippleAmplitude * ripple.Strength;\n\t\t}\n\n\t\treturn height;\n\t}\n}\n"},{"Ident":"redsnail.watertool2","Path":"Code/Network/WaterNode.cs","FileName":"WaterNode.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":445731,"IsPrivate":false,"Code":"using Sandbox;\n\nnamespace RedSnail.WaterTool2;\n\n/// \u003Csummary\u003E\n/// A point of the water graph: a river\u0027s source or end, a bend where a river passes through, a confluence once three\n/// or more rivers meet there, or the mouth where a river opens into a lake. Positions are in network-local space, and\n/// a node\u0027s height is the height of the water surface there.\n/// \u003C/summary\u003E\npublic sealed class WaterNode\n{\n\tpublic int Id { get; set; }\n\n\tpublic Vector3 Position { get; set; }\n\n\t/// \u003Csummary\u003E\n\t/// While set, the network keeps the tangent handles of every river at this node in sync with its neighbours:\n\t/// smooth through a bend, straight at a river end and into a confluence. Cleared once the handles are placed by\n\t/// hand.\n\t/// \u003C/summary\u003E\n\tpublic bool AutoTangents { get; set; } = true;\n\n\t/// \u003Csummary\u003E\n\t/// Radius of the rounded banks where rivers meet at this node. 0 gives sharp corners.\n\t/// \u003C/summary\u003E\n\t[Range(0.0f, 2000.0f)] public float CornerRadius { get; set { field = value.Clamp(0.0f, 100000.0f); } } = 150.0f;\n}\n"},{"Ident":"redsnail.watertool2","Path":"Code/Network/WaterRiver.cs","FileName":"WaterRiver.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":445731,"IsPrivate":false,"Code":"using Sandbox;\n\nnamespace RedSnail.WaterTool2;\n\n/// \u003Csummary\u003E\n/// A river between two nodes: a cubic Bezier whose handles hang off the nodes. The water always flows from the start\n/// node to the end node, so a river reads upstream to downstream; reversing a river swaps its ends.\n/// \u003C/summary\u003E\npublic sealed class WaterRiver\n{\n\tpublic const float MinWidth = 32.0f;\n\tpublic const float MaxWidth = 16384.0f;\n\n\tpublic int Id { get; set; }\n\n\t/// \u003Csummary\u003E\n\t/// The upstream node.\n\t/// \u003C/summary\u003E\n\tpublic int StartNodeId { get; set; }\n\n\t/// \u003Csummary\u003E\n\t/// The downstream node.\n\t/// \u003C/summary\u003E\n\tpublic int EndNodeId { get; set; }\n\n\t/// \u003Csummary\u003E\n\t/// Bezier handle leaving the start node into the river (P1 - P0).\n\t/// \u003C/summary\u003E\n\tpublic Vector3 StartTangent { get; set; }\n\n\t/// \u003Csummary\u003E\n\t/// Bezier handle leaving the end node into the river (P2 - P3).\n\t/// \u003C/summary\u003E\n\tpublic Vector3 EndTangent { get; set; }\n\n\t/// \u003Csummary\u003E\n\t/// Width at the upstream end. The banks ease from this to \u003Csee cref=\u0022EndWidth\u0022/\u003E along the river.\n\t/// \u003C/summary\u003E\n\t[Range(MinWidth, 4000.0f)] public float StartWidth { get; set { field = value.Clamp(MinWidth, MaxWidth); } } = 400.0f;\n\n\t/// \u003Csummary\u003E\n\t/// Width at the downstream end.\n\t/// \u003C/summary\u003E\n\t[Range(MinWidth, 4000.0f)] public float EndWidth { get; set { field = value.Clamp(MinWidth, MaxWidth); } } = 400.0f;\n\n\t/// \u003Csummary\u003E\n\t/// How fast the water runs on level ground, in units per second. A river with nothing flowing into it starts at\n\t/// this speed; slopes speed the water up and it settles back towards this on the flat. Rivers joining another\n\t/// carry their own speed into it.\n\t/// \u003C/summary\u003E\n\t[Range(0.0f, 1000.0f)] public float Speed { get; set { field = value.Clamp(0.0f, 10000.0f); } } = 120.0f;\n\n\t/// \u003Csummary\u003E\n\t/// Wave strength, relative to the network\u0027s wave profile (a lake is 1 by default). Rivers are usually calmer than\n\t/// the lakes they run into; the change is blended where they meet.\n\t/// \u003C/summary\u003E\n\t[Range(0.0f, 2.0f)] public float Waves { get; set { field = value.Clamp(0.0f, 10.0f); } } = 0.35f;\n\n\t/// \u003Csummary\u003E\n\t/// How deep the water is under its surface. Only gameplay reads it: swimming, drowning and buoyancy.\n\t/// \u003C/summary\u003E\n\t[Range(10.0f, 2000.0f)] public float Depth { get; set { field = value.Clamp(1.0f, 100000.0f); } } = 250.0f;\n\n\n\n\tpublic bool Touches(int _NodeId)\n\t{\n\t\treturn StartNodeId == _NodeId || EndNodeId == _NodeId;\n\t}\n\n\n\n\tpublic int OtherNodeId(int _NodeId)\n\t{\n\t\treturn StartNodeId == _NodeId ? EndNodeId : StartNodeId;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The width at one of the river\u0027s ends, by node.\n\t/// \u003C/summary\u003E\n\tpublic float WidthAt(int _NodeId)\n\t{\n\t\treturn StartNodeId == _NodeId ? StartWidth : EndWidth;\n\t}\n}\n"},{"Ident":"redsnail.watertool2","Path":"Network/WaterNetwork.Lakes.cs","FileName":"WaterNetwork.Lakes.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":445731,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing Sandbox;\n\nnamespace RedSnail.WaterTool2;\n\npublic sealed partial class WaterNetwork\n{\n\t/// \u003Csummary\u003E\n\t/// The lakes of the network. Like the nodes and rivers, a whole new list lands here on undo and reload, so the\n\t/// setter is where \u0022the graph changed\u0022 is noticed.\n\t/// \u003C/summary\u003E\n\t[Property, Hide]\n\tpublic List\u003CWaterLake\u003E Lakes\n\t{\n\t\tget;\n\t\tset\n\t\t{\n\t\t\tfield = value ?? new List\u003CWaterLake\u003E();\n\t\t\tMarkDirty();\n\t\t}\n\t} = [];\n\n\tprivate readonly Dictionary\u003Cint, (long Key, LakeShore Shore)\u003E m_Shores = new();\n\n\n\n\tpublic WaterLake FindLake(int _Id)\n\t{\n\t\treturn Lakes.FirstOrDefault(lake =\u003E lake.Id == _Id);\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The lake a node opens into, or null when the node is not on a lake\u0027s shore.\n\t/// \u003C/summary\u003E\n\tpublic WaterLake LakeAtOpening(int _NodeId)\n\t{\n\t\tforeach (var lake in Lakes)\n\t\t{\n\t\t\tif (lake.Openings.Contains(_NodeId))\n\t\t\t\treturn lake;\n\t\t}\n\n\t\treturn null;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// A lake\u0027s shore, rebuilt only when the lake\u0027s shape changed.\n\t/// \u003C/summary\u003E\n\tpublic LakeShore GetShore(WaterLake _Lake)\n\t{\n\t\tif (_Lake is null)\n\t\t\treturn null;\n\n\t\tvar hash = StableHash.Create();\n\t\t_Lake.AddToHash(ref hash);\n\t\thash.Add(CellSize);\n\n\t\tif (m_Shores.TryGetValue(_Lake.Id, out var cached) \u0026\u0026 cached.Key == hash.Value)\n\t\t\treturn cached.Shore;\n\n\t\tvar shore = LakeShore.Build(_Lake, CellSize);\n\t\tm_Shores[_Lake.Id] = (hash.Value, shore);\n\n\t\treturn shore;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Adds a lake with the given shore points (network space) at a water level. The points are kept in the order they\n\t/// were laid, turned counter-clockwise if they were laid the other way.\n\t/// \u003C/summary\u003E\n\tpublic WaterLake AddLake(IEnumerable\u003CVector3\u003E _LocalPoints, float _Height, float _Waves = 1.0f, float _Depth = 500.0f, bool _Smooth = true)\n\t{\n\t\tvar lake = new WaterLake\n\t\t{\n\t\t\tId = NextId\u002B\u002B,\n\t\t\tPoints = _LocalPoints.Select(point =\u003E point.WithZ(_Height)).ToList(),\n\t\t\tHeight = _Height,\n\t\t\tWaves = _Waves,\n\t\t\tDepth = _Depth,\n\t\t\tSmooth = _Smooth\n\t\t};\n\n\t\tif (lake.SignedArea() \u003C 0.0f)\n\t\t\tlake.Points.Reverse();\n\n\t\tLakes.Add(lake);\n\t\tMarkDirty();\n\n\t\treturn lake;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The coast whose land a point (network space, in plan) is on, or null out at sea.\n\t/// \u003C/summary\u003E\n\tpublic WaterLake CoastAt(Vector3 _Local)\n\t{\n\t\tforeach (var lake in Lakes)\n\t\t{\n\t\t\tif (lake.IsCoast \u0026\u0026 GetShore(lake) is { } shore \u0026\u0026 shore.Contains(_Local))\n\t\t\t\treturn lake;\n\t\t}\n\n\t\treturn null;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// For a point out at sea (network space, in plan): the coast nearest to it, and the point of that coast\u0027s shore\n\t/// nearest to it, where a river would open into the sea. Null on land (unless \u003Cparamref name=\u0022_FromLand\u0022/\u003E: a river\n\t/// end inland of the coast), or when there is no coast.\n\t/// \u003C/summary\u003E\n\tpublic WaterLake NearestCoast(Vector3 _Local, out Vector3 _OnShore, bool _FromLand = false)\n\t{\n\t\t_OnShore = default;\n\n\t\tif (!_FromLand \u0026\u0026 CoastAt(_Local) is not null)\n\t\t\treturn null;\n\n\t\tWaterLake best = null;\n\t\tfloat bestOffset = float.MaxValue;\n\n\t\tforeach (var lake in Lakes)\n\t\t{\n\t\t\tif (!lake.IsCoast || GetShore(lake) is not { } shore)\n\t\t\t\tcontinue;\n\n\t\t\tfloat at = shore.NearestDistance(_Local, out float offset);\n\n\t\t\tif (offset \u003E= bestOffset)\n\t\t\t\tcontinue;\n\n\t\t\tshore.At(at, out _OnShore, out _, out _);\n\t\t\tbest = lake;\n\t\t\tbestOffset = offset;\n\t\t}\n\n\t\treturn best;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Keeps every coast at sea level: when the level changes, the coasts and the rivers opening into the sea through\n\t/// them rise or fall with it.\n\t/// \u003C/summary\u003E\n\tprivate void SyncCoasts()\n\t{\n\t\tforeach (var coast in Lakes)\n\t\t{\n\t\t\tif (!coast.IsCoast || MathF.Abs(coast.Height - SeaLevel) \u003C 0.001f)\n\t\t\t\tcontinue;\n\n\t\t\tfloat rise = SeaLevel - coast.Height;\n\n\t\t\tcoast.Height = SeaLevel;\n\n\t\t\tfor (int i = 0; i \u003C coast.Points.Count; i\u002B\u002B)\n\t\t\t\tcoast.Points[i] = coast.Points[i].WithZ(SeaLevel);\n\n\t\t\t// The shore moved: everything worked out from it is stale.\n\t\t\tInvalidateIndex();\n\n\t\t\tforeach (int nodeId in coast.Openings)\n\t\t\t{\n\t\t\t\tif (FindNode(nodeId) is not { } node)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tnode.Position \u002B= Vector3.Up * rise;\n\t\t\t\tRefreshTangentsAround(nodeId);\n\t\t\t}\n\t\t}\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Adds a node on a lake\u0027s shore for a river to open into it at, at the point of the shore nearest to where it is\n\t/// asked for. Returns the node, or null when the lake is gone.\n\t/// \u003C/summary\u003E\n\tpublic WaterNode AddOpening(int _LakeId, Vector3 _NearLocal)\n\t{\n\t\tvar lake = FindLake(_LakeId);\n\t\tvar shore = GetShore(lake);\n\n\t\tif (lake is null || shore is null)\n\t\t\treturn null;\n\n\t\tshore.At(shore.NearestDistance(_NearLocal), out Vector3 point, out _, out _);\n\n\t\tvar node = new WaterNode { Id = NextId\u002B\u002B, Position = point, AutoTangents = false };\n\n\t\tNodes.Add(node);\n\t\tInvalidateIndex();\n\n\t\tlake.Openings.Add(node.Id);\n\t\tMarkDirty();\n\n\t\treturn node;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Makes a river end that is already there open into a lake: it moves onto the shore, and the river turns to meet\n\t/// the shore square on. Nothing happens if the node already opens into a lake, or carries more than one river.\n\t/// \u003C/summary\u003E\n\tpublic bool JoinOpening(int _LakeId, int _NodeId)\n\t{\n\t\tvar lake = FindLake(_LakeId);\n\t\tvar node = FindNode(_NodeId);\n\n\t\tif (lake is null || node is null || LakeAtOpening(_NodeId) is not null || GetDegree(_NodeId) \u003E 1)\n\t\t\treturn false;\n\n\t\tlake.Openings.Add(_NodeId);\n\t\tnode.AutoTangents = false;\n\n\t\tSnapOpenings(lake);\n\t\tRefreshTangentsAround(_NodeId);\n\t\tMarkDirty();\n\n\t\treturn true;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Unhooks a node from the lake it opens into. The node and its river stay where they are.\n\t/// \u003C/summary\u003E\n\tpublic void RemoveOpening(int _NodeId)\n\t{\n\t\tforeach (var lake in Lakes)\n\t\t\tlake.Openings.Remove(_NodeId);\n\n\t\tMarkDirty();\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Puts every one of a lake\u0027s opening nodes back on its shore, at its water level (a lake that has been moved or\n\t/// reshaped takes its openings with it), and drops the ones whose nodes have gone.\n\t/// \u003C/summary\u003E\n\tpublic void SnapOpenings(WaterLake _Lake)\n\t{\n\t\tif (_Lake is null)\n\t\t\treturn;\n\n\t\tvar shore = GetShore(_Lake);\n\n\t\tfor (int i = _Lake.Openings.Count - 1; i \u003E= 0; i--)\n\t\t{\n\t\t\tvar node = FindNode(_Lake.Openings[i]);\n\n\t\t\tif (node is null || GetDegree(node.Id) \u003E 1)\n\t\t\t{\n\t\t\t\t_Lake.Openings.RemoveAt(i);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (shore is null)\n\t\t\t\tcontinue;\n\n\t\t\tshore.At(shore.NearestDistance(node.Position), out Vector3 point, out _, out _);\n\n\t\t\tif (node.Position.Distance(point) \u003C 0.01f)\n\t\t\t\tcontinue;\n\n\t\t\tnode.Position = point;\n\t\t\tRefreshTangentsAround(node.Id);\n\t\t}\n\t}\n\n\n\n\tpublic void SnapAllOpenings()\n\t{\n\t\tforeach (var lake in Lakes)\n\t\t\tSnapOpenings(lake);\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Moves a lake (its height too), taking its openings with it, so the rivers into it bend to follow. A coast only\n\t/// moves across: it stays at sea level.\n\t/// \u003C/summary\u003E\n\tpublic void MoveLake(int _LakeId, Vector3 _Centre)\n\t{\n\t\tvar lake = FindLake(_LakeId);\n\n\t\tif (lake is null)\n\t\t\treturn;\n\n\t\tVector3 delta = _Centre - lake.Centre;\n\n\t\tif (lake.IsCoast)\n\t\t\tdelta = delta.WithZ(0.0f);\n\n\t\t// A drag that is holding still would otherwise rebuild the lake every frame over float noise.\n\t\tif (delta.Length \u003C 0.01f)\n\t\t\treturn;\n\n\t\tfor (int i = 0; i \u003C lake.Points.Count; i\u002B\u002B)\n\t\t\tlake.Points[i] \u002B= delta.WithZ(0.0f);\n\n\t\tlake.Height \u002B= delta.z;\n\n\t\tforeach (int nodeId in lake.Openings)\n\t\t{\n\t\t\tif (FindNode(nodeId) is not { } node)\n\t\t\t\tcontinue;\n\n\t\t\tnode.Position \u002B= delta;\n\t\t\tRefreshTangentsAround(nodeId);\n\t\t}\n\n\t\tSnapOpenings(lake);\n\t\tMarkDirty();\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Changes a lake\u0027s water level; its openings rise or fall with it. A coast\u0027s level is the sea\u0027s.\n\t/// \u003C/summary\u003E\n\tpublic void SetLakeHeight(int _LakeId, float _Height)\n\t{\n\t\tvar lake = FindLake(_LakeId);\n\n\t\tif (lake is null || lake.IsCoast)\n\t\t\treturn;\n\n\t\tMoveLake(_LakeId, lake.Centre.WithZ(_Height));\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Moves one of a lake\u0027s shore points (only its X and Y count).\n\t/// \u003C/summary\u003E\n\tpublic void SetLakePoint(int _LakeId, int _Index, Vector3 _Local)\n\t{\n\t\tvar lake = FindLake(_LakeId);\n\n\t\tif (lake is null || _Index \u003C 0 || _Index \u003E= lake.Points.Count)\n\t\t\treturn;\n\n\t\tif (lake.Points[_Index].WithZ(0.0f).Distance(_Local.WithZ(0.0f)) \u003C 0.01f)\n\t\t\treturn;\n\n\t\tlake.Points[_Index] = _Local.WithZ(lake.Height);\n\n\t\tSnapOpenings(lake);\n\t\tMarkDirty();\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Inserts a shore point before the given index.\n\t/// \u003C/summary\u003E\n\tpublic void InsertLakePoint(int _LakeId, int _Index, Vector3 _Local)\n\t{\n\t\tvar lake = FindLake(_LakeId);\n\n\t\tif (lake is null)\n\t\t\treturn;\n\n\t\tlake.Points.Insert(Math.Clamp(_Index, 0, lake.Points.Count), _Local.WithZ(lake.Height));\n\n\t\tSnapOpenings(lake);\n\t\tMarkDirty();\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Removes a shore point. A lake keeps at least three.\n\t/// \u003C/summary\u003E\n\tpublic bool RemoveLakePoint(int _LakeId, int _Index)\n\t{\n\t\tvar lake = FindLake(_LakeId);\n\n\t\tif (lake is null || lake.Points.Count \u003C= WaterLake.MinPoints || _Index \u003C 0 || _Index \u003E= lake.Points.Count)\n\t\t\treturn false;\n\n\t\tlake.Points.RemoveAt(_Index);\n\n\t\tSnapOpenings(lake);\n\t\tMarkDirty();\n\n\t\treturn true;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Removes a lake. Its opening nodes stay where they are, with their rivers; they are simply river ends again.\n\t/// \u003C/summary\u003E\n\tpublic void RemoveLake(int _LakeId)\n\t{\n\t\tvar lake = FindLake(_LakeId);\n\n\t\tif (lake is null)\n\t\t\treturn;\n\n\t\tLakes.Remove(lake);\n\t\tm_Shores.Remove(_LakeId);\n\t\tMarkDirty();\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The way out of the lake a node opens into (or the sea), at that node: what a river leaving there has to run along,\n\t/// so it meets the shore square on. Every curve through the node asks, many times an edit, and a coast\u0027s shore is long:\n\t/// the answer is kept until the graph or the node changes.\n\t/// \u003C/summary\u003E\n\tpublic bool TryLakeOutward(int _NodeId, out Vector3 _Outward)\n\t{\n\t\t_Outward = Vector3.Zero;\n\n\t\tif (Lakes.Count == 0)\n\t\t\treturn false;\n\n\t\tvar lake = LakeAtOpening(_NodeId);\n\t\tvar node = FindNode(_NodeId);\n\n\t\tif (lake is null || node is null)\n\t\t\treturn false;\n\n\t\tif (m_Outwards.TryGetValue(_NodeId, out var cached) \u0026\u0026 cached.Revision == m_GraphRevision \u0026\u0026 cached.LakeId == lake.Id \u0026\u0026 cached.Position == node.Position)\n\t\t{\n\t\t\t_Outward = cached.Outward;\n\t\t\treturn cached.Found;\n\t\t}\n\n\t\tbool found = FindLakeOutward(lake, node, out _Outward);\n\n\t\tm_Outwards[_NodeId] = (m_GraphRevision, lake.Id, node.Position, _Outward, found);\n\n\t\treturn found;\n\t}\n\n\n\n\tprivate readonly Dictionary\u003Cint, (int Revision, int LakeId, Vector3 Position, Vector3 Outward, bool Found)\u003E m_Outwards = new();\n\n\n\n\tprivate bool FindLakeOutward(WaterLake _Lake, WaterNode _Node, out Vector3 _Outward)\n\t{\n\t\t_Outward = Vector3.Zero;\n\n\t\tvar shore = GetShore(_Lake);\n\n\t\tif (shore is null)\n\t\t\treturn false;\n\n\t\tshore.At(shore.NearestDistance(_Node.Position), out _, out Vector3 outward, out _);\n\n\t\t_Outward = outward.WithZ(0.0f);\n\n\t\tif (_Outward.IsNearZeroLength)\n\t\t\treturn false;\n\n\t\t_Outward = _Outward.Normal;\n\n\t\treturn true;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// How far a lake\u0027s shore flares into the river that opens into it at a node: what the lake asks for, but never\n\t/// more than the river can give or the shore can spare.\n\t/// \u003C/summary\u003E\n\tpublic float OpeningFlare(WaterLake _Lake, int _NodeId)\n\t{\n\t\tfloat flare = _Lake.EntranceRadius;\n\n\t\tvar river = GetRiversAt(_NodeId).FirstOrDefault();\n\t\tvar table = river is null ? null : GetCurveTable(river);\n\n\t\tif (table is not null)\n\t\t\tflare = MathF.Min(flare, table.Length * 0.4f);\n\n\t\tvar shore = GetShore(_Lake);\n\n\t\tif (shore is not null)\n\t\t\tflare = MathF.Min(flare, shore.Length * 0.1f);\n\n\t\treturn MathF.Max(0.0f, flare);\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// How far a river is held back from the shore of the lake it opens into: the lake\u0027s surface fills the flares\n\t/// between the two, so the river starts at their far end. At a coast it is the estuary that fills them, so with the\n\t/// sea off the river runs all the way.\n\t/// \u003C/summary\u003E\n\tpublic float LakeTrimAt(int _NodeId)\n\t{\n\t\tvar lake = LakeAtOpening(_NodeId);\n\n\t\tif (lake is null || (lake.IsCoast \u0026\u0026 !SeaEnabled))\n\t\t\treturn 0.0f;\n\n\t\treturn OpeningFlare(lake, _NodeId);\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The lake under a point in network space (in plan), if any. Coasts are not lakes: their water is outside them.\n\t/// \u003C/summary\u003E\n\tpublic WaterLake LakeUnder(Vector3 _Local)\n\t{\n\t\tforeach (var lake in Lakes)\n\t\t{\n\t\t\tif (lake.IsCoast)\n\t\t\t\tcontinue;\n\n\t\t\tvar shore = GetShore(lake);\n\n\t\t\tif (shore is not null \u0026\u0026 shore.Contains(_Local))\n\t\t\t\treturn lake;\n\t\t}\n\n\t\treturn null;\n\t}\n}\n"},{"Ident":"redsnail.watertool2","Path":"PostProcessing/WobbleEffect.cs","FileName":"WobbleEffect.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":445731,"IsPrivate":false,"Code":"using Sandbox;\nusing Sandbox.Rendering;\n\nnamespace RedSnail.WaterTool2;\n\n/// \u003Csummary\u003E\n/// A gentle screen-space ripple: the view wavering under the water.\n/// \u003C/summary\u003E\n[Title(\u0022Wobble Effect\u0022)]\n[Category(\u0022Post Processing\u0022)]\n[Icon(\u0022waves\u0022)]\npublic sealed class WobbleEffect : BasePostProcess\u003CWobbleEffect\u003E\n{\n\tpublic const string ShaderPath = \u0022watertool2/shaders/pp_wobble.shader\u0022;\n\n\t[Property, Range(0.1f, 100.0f)] private float Frequency { get; set; } = 20.0f;\n\t[Property, Range(0.1f, 10.0f)] private float Amplitude { get; set; } = 1.0f;\n\t[Property, Range(0.1f, 10.0f)] private float Speed { get; set; } = 1.0f;\n\n\n\n\tpublic override void Render()\n\t{\n\t\tfloat amplitude = GetWeighted(x =\u003E x.Amplitude);\n\n\t\tif (amplitude.AlmostEqual(0.0f))\n\t\t\treturn;\n\n\t\tAttributes.Set(\u0022Frequency\u0022, Frequency);\n\t\tAttributes.Set(\u0022Amplitude\u0022, amplitude);\n\t\tAttributes.Set(\u0022Speed\u0022, Speed);\n\n\t\tMaterial shader = Material.FromShader(ShaderPath);\n\t\tBlitMode blit = BlitMode.WithBackbuffer(shader, Stage.BeforePostProcess, 70);\n\t\tBlit(blit, \u0022Wobble Effect\u0022);\n\t}\n}\n"},{"Ident":"redsnail.watertool2","Path":"Code/Gameplay/Buoyancy.cs","FileName":"Buoyancy.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":445731,"IsPrivate":false,"Code":"using Sandbox;\n\nnamespace RedSnail.WaterTool2;\n\n/// \u003Csummary\u003E\n/// Floats a rigidbody on the water: springs at nine points of its hull push it up to the surface (waves and ripples\n/// included), drag slows it in the water, the waves\u0027 motion carries it about, and the current of a river or of the plume\n/// where a river enters a lake drags it along. It splashes ripples as it lands and as it moves. It finds the water\n/// inside exclusion volumes all the same: the hull it floats is usually one.\n/// \u003C/summary\u003E\n[Title(\u0022Buoyancy\u0022)]\n[Category(\u0022Water Tool 2\u0022)]\n[Icon(\u0022sailing\u0022)]\npublic sealed class Buoyancy : Component\n{\n\tprivate Collider m_Collider;\n\n\tprivate const float WaterDensity = 1000.0f; // kg/m3\n\n\t[Property, Group(\u0022Buoyancy\u0022)] private float SpringStiffness { get; set; } = 500.0f;\n\t[Property, Group(\u0022Buoyancy\u0022)] private float Damping { get; set; } = 5.0f;\n\t[Property, Group(\u0022Buoyancy\u0022), Range(0.1f, 1.0f)] private float HullSpread { get; set; } = 0.6f;\n\t[Property, Group(\u0022Buoyancy\u0022)] private float SurfaceOffset { get; set; } = 0.0f;\n\n\t[Property, Group(\u0022Drag\u0022)] private float DragCoefficient { get; set; } = 1.0f;\n\t[Property, Group(\u0022Drag\u0022)] private float AngularDragCoefficient { get; set; } = 2.0f;\n\n\t/// \u003Csummary\u003E\n\t/// How much the waves and the current carry the body along. 0 for a moored boat that should only bob.\n\t/// \u003C/summary\u003E\n\t[Property, Group(\u0022Wave Transport\u0022), Range(0.0f, 1.0f)] private float HorizontalDisplacementStrength { get; set; } = 1.0f;\n\t[Property, Group(\u0022Wave Transport\u0022), Range(0.1f, 10.0f)] private float Drag { get; set; } = 1.5f;\n\n\t[Property] private float AirLeakRate { get; set; } = 0.0f;\n\n\t[Property, Group(\u0022Ripples\u0022)] private bool EmitEntryRipple { get; set; } = true;\n\n\t/// \u003Csummary\u003E\n\t/// Ring spacing of the entry splash: smaller makes more, tighter rings.\n\t/// \u003C/summary\u003E\n\t[Property, Group(\u0022Ripples\u0022), Range(20.0f, 400.0f)] private float EntryRippleWavelength { get; set; } = 120.0f;\n\n\t/// \u003Csummary\u003E\n\t/// Ring size of the entry splash: larger makes a bigger, broader ripple.\n\t/// \u003C/summary\u003E\n\t[Property, Group(\u0022Ripples\u0022), Range(10.0f, 500.0f)] private float EntryRippleWidth { get; set; } = 50.0f;\n\n\t/// \u003Csummary\u003E\n\t/// A steady trail of ripples while the hull moves across the surface (a boat\u0027s wake).\n\t/// \u003C/summary\u003E\n\t[Property, Group(\u0022Ripples\u0022)] private bool EmitWakeRipple { get; set; } = true;\n\t[Property, Group(\u0022Ripples\u0022)] private float WakeRippleStrength { get; set; } = 0.1f;\n\n\t/// \u003Csummary\u003E\n\t/// The horizontal speed (units/s) below which no wake is left.\n\t/// \u003C/summary\u003E\n\t[Property, Group(\u0022Ripples\u0022)] private float WakeRippleMinSpeed { get; set; } = 20.0f;\n\n\t/// \u003Csummary\u003E\n\t/// Seconds between wake ripples: lower makes a denser trail (and uses more of the ripple budget).\n\t/// \u003C/summary\u003E\n\t[Property, Group(\u0022Ripples\u0022)] private float WakeRippleInterval { get; set; } = 0.0333f;\n\t[Property, Group(\u0022Ripples\u0022), Range(20.0f, 400.0f)] private float WakeRippleWavelength { get; set; } = 120.0f;\n\n\t[Sync] public float AirVolume { get; private set; } = 1.0f;\n\t[Sync] public float WaterHeight { get; private set; } = float.MinValue;\n\t[Sync] public bool IsTouchingWater { get; private set; }\n\n\tprivate bool m_WasBelowSurface;\n\tprivate float m_WakeTimer;\n\n\tpublic bool IsUnderwater =\u003E IsTouchingWater \u0026\u0026 WorldPosition.z \u003C= WaterHeight;\n\n\n\n\tprotected override void OnAwake()\n\t{\n\t\tm_Collider = GetComponent\u003CCollider\u003E();\n\t}\n\n\n\n\tprotected override void OnFixedUpdate()\n\t{\n\t\tif (IsProxy)\n\t\t\treturn;\n\n\t\tif (!m_Collider.IsValid() || m_Collider.IsTrigger || !m_Collider.Rigidbody.IsValid())\n\t\t\treturn;\n\n\t\t// The water inside exclusion volumes too: cut out of the answer, a boat would find no water under its own hull\n\t\t// and sink.\n\t\tfloat waveHeight = WaterNetwork.GetWaterHeightAt(WorldPosition, true);\n\n\t\tif (waveHeight \u003E float.MinValue)\n\t\t{\n\t\t\tWaterHeight = waveHeight;\n\n\t\t\tHandleEntryRipple();\n\n\t\t\t// Water under us always has a height, even while we fly far above it, so touching it means the hull is\n\t\t\t// actually in it: its lowest point at or under the surface. Measured from the collider\u0027s world bounds\n\t\t\t// rather than the object\u0027s origin, which can sit anywhere inside them - testing the origin against a\n\t\t\t// whole collider height of slack counted anything hovering above the water as floating in it, which is\n\t\t\t// why aircraft were being dragged by the current and leaving a wake.\n\t\t\tBBox worldBounds = m_Collider.LocalBounds.Transform(WorldTransform);\n\t\t\tbool isTouchingWater = worldBounds.Mins.z \u003C= WaterHeight;\n\n\t\t\tIsTouchingWater = isTouchingWater;\n\n\t\t\tif (isTouchingWater)\n\t\t\t{\n\t\t\t\tApplyWaterResistance();\n\t\t\t\tApplyAngularDrag();\n\t\t\t\tApplyBuoyancy();\n\t\t\t\tApplyWaveTransport();\n\t\t\t\tApplyCurrentForce();\n\n\t\t\t\tHandleWakeRipple();\n\t\t\t}\n\t\t}\n\t\telse\n\t\t{\n\t\t\tIsTouchingWater = false;\n\t\t\tWaterHeight = float.MinValue;\n\t\t\tm_WasBelowSurface = false;\n\t\t}\n\n\t\t// Drains while submerged, recovers above water.\n\t\tUpdateAirVolume();\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// A splash the moment the body drops through the surface; gentle bobbing through the surface line doesn\u0027t count.\n\t/// \u003C/summary\u003E\n\tprivate void HandleEntryRipple()\n\t{\n\t\tbool belowSurface = WorldPosition.z \u003C= WaterHeight;\n\n\t\tif (EmitEntryRipple \u0026\u0026 belowSurface \u0026\u0026 !m_WasBelowSurface)\n\t\t{\n\t\t\tfloat impactSpeed = float.Max(0.0f, -m_Collider.Rigidbody.Velocity.z);\n\n\t\t\tif (impactSpeed \u003E 40.0f)\n\t\t\t{\n\t\t\t\tfloat strength = (impactSpeed / 150.0f).Clamp(0.3f, 2.5f);\n\t\t\t\tWaterNetwork.AddRipple(WorldPosition.WithZ(WaterHeight), strength, EntryRippleWavelength, EntryRippleWidth);\n\t\t\t}\n\t\t}\n\n\t\tm_WasBelowSurface = belowSurface;\n\t}\n\n\n\n\tprivate void HandleWakeRipple()\n\t{\n\t\tif (!EmitWakeRipple)\n\t\t\treturn;\n\n\t\tfloat horizontalSpeed = m_Collider.Rigidbody.Velocity.WithZ(0.0f).Length;\n\n\t\tif (horizontalSpeed \u003C WakeRippleMinSpeed)\n\t\t\treturn;\n\n\t\tm_WakeTimer -= Time.Delta;\n\n\t\tif (m_WakeTimer \u003E 0.0f)\n\t\t\treturn;\n\n\t\tfloat strength = (horizontalSpeed / 1000.0f).Clamp(0.1f, 1.0f) * WakeRippleStrength * 10.0f;\n\n\t\tWaterNetwork.AddRipple(WorldPosition.WithZ(WaterHeight), strength, WakeRippleWavelength, m_Collider.LocalBounds.Extents.x);\n\n\t\tm_WakeTimer = WakeRippleInterval;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// How far under the surface a point is, as a fraction of the collider\u0027s height (0 at the surface, 1 fully under).\n\t/// \u003C/summary\u003E\n\tprivate float GetSubmersionAtPoint(Vector3 _WorldPoint, float _WaterHeight)\n\t{\n\t\tfloat colliderHeight = m_Collider.LocalBounds.Size.z;\n\n\t\tif (colliderHeight \u003C= 0.0f)\n\t\t\treturn 0.0f;\n\n\t\treturn ((_WaterHeight - _WorldPoint.z) / colliderHeight).Clamp(0.0f, 1.0f);\n\t}\n\n\n\n\tprivate void UpdateAirVolume()\n\t{\n\t\tif (WorldPosition.z \u003C WaterHeight)\n\t\t\tAirVolume -= Time.Delta * AirLeakRate;\n\t\telse\n\t\t\tAirVolume \u002B= Time.Delta * AirLeakRate;\n\n\t\tAirVolume = AirVolume.Clamp(0.0f, 1.0f);\n\t}\n\n\n\n\tprivate void ApplyWaterResistance()\n\t{\n\t\tVector3 velocity = m_Collider.Rigidbody.Velocity;\n\t\tfloat speed = velocity.Length * 0.0254f; // inches to metres\n\n\t\tif (speed \u003C 0.01f)\n\t\t\treturn;\n\n\t\tfloat submersion = GetSubmersionAtPoint(WorldPosition, WaterHeight);\n\n\t\t// Frontal area, square metres\n\t\tBBox worldBounds = m_Collider.LocalBounds.Transform(WorldTransform);\n\t\tfloat area = (worldBounds.Size.z * worldBounds.Size.x) * 0.00064516f;\n\n\t\t// F = -0.5 * rho * v^2 * Cd * A\n\t\tVector3 dragForce = -0.5f * WaterDensity * speed * speed * DragCoefficient * area * velocity.Normal * submersion;\n\n\t\tm_Collider.Rigidbody.ApplyForce(dragForce);\n\t}\n\n\n\n\tprivate void ApplyAngularDrag()\n\t{\n\t\tVector3 angularVelocity = m_Collider.Rigidbody.AngularVelocity;\n\n\t\tif (angularVelocity.LengthSquared \u003C 0.0001f)\n\t\t\treturn;\n\n\t\tfloat submersion = GetSubmersionAtPoint(WorldPosition, WaterHeight);\n\n\t\tm_Collider.Rigidbody.AngularVelocity \u002B= -angularVelocity * AngularDragCoefficient * submersion * Time.Delta;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// A spring and a damper at each of nine points over the hull, each pushing up by how far under its own bit of\n\t/// surface the point is, so the body tilts with the waves under it.\n\t/// \u003C/summary\u003E\n\tprivate void ApplyBuoyancy()\n\t{\n\t\tBBox localBounds = m_Collider.LocalBounds;\n\t\tVector3 center = localBounds.Center;\n\t\tVector3 extents = localBounds.Extents;\n\n\t\tfloat sx = extents.x * HullSpread;\n\t\tfloat sy = extents.y * HullSpread;\n\n\t\tvar points = new[]\n\t\t{\n\t\t\tcenter,\n\t\t\tcenter \u002B new Vector3(sx, 0, 0),\n\t\t\tcenter \u002B new Vector3(-sx, 0, 0),\n\t\t\tcenter \u002B new Vector3(0, sy, 0),\n\t\t\tcenter \u002B new Vector3(0, -sy, 0),\n\t\t\tcenter \u002B new Vector3(sx, sy, 0),\n\t\t\tcenter \u002B new Vector3(-sx, sy, 0),\n\t\t\tcenter \u002B new Vector3(sx, -sy, 0),\n\t\t\tcenter \u002B new Vector3(-sx, -sy, 0)\n\t\t};\n\n\t\tfloat mass = m_Collider.Rigidbody.Mass;\n\t\tVector3 angularVelocity = m_Collider.Rigidbody.AngularVelocity;\n\n\t\tforeach (Vector3 localPoint in points)\n\t\t{\n\t\t\tVector3 worldPoint = WorldTransform.PointToWorld(localPoint);\n\n\t\t\tfloat pointWaterHeight = WaterNetwork.GetWaterHeightAt(worldPoint, true);\n\n\t\t\tif (pointWaterHeight == float.MinValue)\n\t\t\t\tpointWaterHeight = WaterHeight;\n\n\t\t\t// How far below the surface this point is (positive under it); the offset raises the effective water level.\n\t\t\tfloat depth = (pointWaterHeight \u002B SurfaceOffset) - worldPoint.z;\n\n\t\t\tif (depth \u003C= 0.0f)\n\t\t\t\tcontinue;\n\n\t\t\tfloat springForce = depth * SpringStiffness * mass * AirVolume / points.Length;\n\n\t\t\tVector3 pointVelocity = m_Collider.Rigidbody.Velocity \u002B Vector3.Cross(angularVelocity, worldPoint - WorldPosition);\n\t\t\tfloat damperForce = -pointVelocity.z * Damping * mass / points.Length;\n\n\t\t\tm_Collider.Rigidbody.ApplyForceAt(worldPoint, Vector3.Up * (springForce \u002B damperForce));\n\t\t}\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The waves\u0027 orbital motion pulls the body along with it.\n\t/// \u003C/summary\u003E\n\tprivate void ApplyWaveTransport()\n\t{\n\t\tif (HorizontalDisplacementStrength \u003C= 0.0f)\n\t\t\treturn;\n\n\t\tVector3 displacement = WaterNetwork.GetWaveDisplacementAt(WorldPosition, true);\n\t\tVector3 horizontal = new Vector3(displacement.x, displacement.y, 0) * HorizontalDisplacementStrength;\n\n\t\tVector3 relative = horizontal - m_Collider.Rigidbody.Velocity.WithZ(0.0f);\n\n\t\tm_Collider.Rigidbody.ApplyForce(relative * (m_Collider.Rigidbody.Mass * Drag));\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The current drags the body towards its own speed: down a river, out across a lake from a river\u0027s mouth.\n\t/// \u003C/summary\u003E\n\tprivate void ApplyCurrentForce()\n\t{\n\t\tif (HorizontalDisplacementStrength \u003C= 0.0f)\n\t\t\treturn;\n\n\t\tVector3 flow = WaterNetwork.GetFlowVelocityAt(WorldPosition, true);\n\n\t\tif (flow.LengthSquared \u003C 0.01f)\n\t\t\treturn;\n\n\t\tVector3 relative = flow - m_Collider.Rigidbody.Velocity.WithZ(0.0f);\n\n\t\tm_Collider.Rigidbody.ApplyForce(relative * HorizontalDisplacementStrength * (m_Collider.Rigidbody.Mass * Drag));\n\t}\n}\n"},{"Ident":"redsnail.watertool2","Path":"Code/Network/WaterNetwork.Build.cs","FileName":"WaterNetwork.Build.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":445731,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Threading.Tasks;\nusing Sandbox;\n\nnamespace RedSnail.WaterTool2;\n\npublic sealed partial class WaterNetwork\n{\n\t/// \u003Csummary\u003E\n\t/// Bumped whenever the way pieces are built changes, so pieces built the old way are rebuilt.\n\t/// \u003Cpara\u003E\n\t/// A change to a builder alone leaves every hashed input identical, so nothing rebuilds and the old geometry is\n\t/// still what you are looking at. Forget this and you will be debugging the bug you just fixed.\n\t/// \u003C/para\u003E\n\t/// \u003C/summary\u003E\n\tprivate const int GeneratorVersion = 8;\n\n\t/// \u003Csummary\u003E\n\t/// A river never gets shorter than this between whatever stops it at either end.\n\t/// \u003C/summary\u003E\n\tprivate const float MinSurfaceLength = 8.0f;\n\n\tprivate sealed class LakeBuild\n\t{\n\t\tpublic long Signature;\n\t\tpublic float Depth;\n\t\tpublic Task\u003CLakeBuilder.Result\u003E Task;\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// A piece of the sea (a river mouth, a chunk of the coast zone) being built on a worker thread in the editor.\n\t/// \u003C/summary\u003E\n\tprivate sealed class PieceBuild\n\t{\n\t\tpublic long Signature;\n\t\tpublic float Depth;\n\t\tpublic Task\u003CWaterMeshData\u003E Task;\n\t}\n\n\tprivate readonly Dictionary\u003CWaterPieceKey, PieceBuild\u003E m_PieceBuilds = new();\n\tprivate readonly Dictionary\u003CWaterPieceKey, (long Signature, float Depth, Func\u003CWaterMeshData\u003E Build)\u003E m_PieceQueue = new();\n\n\t/// \u003Csummary\u003E\n\t/// The signatures of river mouths that couldn\u0027t be built: their blocks go back to the coast zone.\n\t/// \u003C/summary\u003E\n\tprivate readonly HashSet\u003Clong\u003E m_FailedMouths = new();\n\n\t/// \u003Csummary\u003E\n\t/// Pieces whose inputs gave nothing to draw, by the signature they were built from.\n\t/// \u003C/summary\u003E\n\tprivate readonly Dictionary\u003CWaterPieceKey, long\u003E m_EmptyPieces = new();\n\n\tprivate bool m_IsDirty = true;\n\tprivate Transform m_BuiltTransform;\n\tprivate long m_BuiltTransformHash;\n\n\tprivate readonly Dictionary\u003CWaterPieceKey, WaterPiece\u003E m_Pieces = new();\n\n\t/// \u003Csummary\u003E\n\t/// The signature of the lake tiles in place, by lake, and the lake builds running on worker threads (with the next\n\t/// build of the same lake waiting for the running one to finish).\n\t/// \u003C/summary\u003E\n\tprivate readonly Dictionary\u003Cint, long\u003E m_LakeSignatures = new();\n\tprivate readonly Dictionary\u003Cint, LakeBuild\u003E m_LakeBuilds = new();\n\tprivate readonly Dictionary\u003Cint, LakeBuildInput\u003E m_LakeQueue = new();\n\tprivate readonly HashSet\u003Clong\u003E m_ReportedFailures = new();\n\n\t// What the last reconcile worked out from the graph.\n\tprivate readonly Dictionary\u003Cint, RiverWidth\u003E m_Widths = new();\n\tprivate readonly Dictionary\u003Cint, JunctionLayout\u003E m_Junctions = new();\n\tprivate readonly Dictionary\u003Cint, (float Start, float End)\u003E m_Trims = new();\n\tprivate readonly Dictionary\u003Cint, RiverFlow\u003E m_Flows = new();\n\tprivate readonly Dictionary\u003C(int RiverId, bool AtStart), RiverRow\u003E m_EndRows = new();\n\tprivate readonly Dictionary\u003Cint, List\u003CLakeOpening\u003E\u003E m_LakeOpenings = new();\n\n\t/// \u003Csummary\u003E\n\t/// Every piece of water currently built.\n\t/// \u003C/summary\u003E\n\tinternal IReadOnlyCollection\u003CWaterPiece\u003E Pieces =\u003E m_Pieces.Values;\n\n\t/// \u003Csummary\u003E\n\t/// True while lakes are still being built in the background.\n\t/// \u003C/summary\u003E\n\tpublic bool IsRebuilding =\u003E m_LakeBuilds.Count \u003E 0;\n\n\t/// \u003Csummary\u003E\n\t/// Bumped every time a piece is added, replaced or removed.\n\t/// \u003C/summary\u003E\n\tpublic int PieceRevision { get; private set; }\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Asks for a reconcile pass on the next update: the graph is compared against the pieces that exist and only what\n\t/// differs is rebuilt.\n\t/// \u003C/summary\u003E\n\tpublic void MarkDirty()\n\t{\n\t\tm_IsDirty = true;\n\n\t\t// Undo, reloads and the inspector all land here with a graph nobody told us about piece by piece.\n\t\tInvalidateIndex();\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Throws every piece away and builds the whole network again.\n\t/// \u003C/summary\u003E\n\t[Button(\u0022Rebuild All\u0022, \u0022refresh\u0022)]\n\tpublic void RebuildAll()\n\t{\n\t\tReleasePieces();\n\t\tMarkDirty();\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// One reconcile pass when something changed, then whatever lake builds have finished. Driven from the component\u0027s\n\t/// own update.\n\t/// \u003C/summary\u003E\n\tprivate void Tick()\n\t{\n\t\t// Moving the network\u0027s GameObject moves all of its water.\n\t\tif (!m_IsDirty \u0026\u0026 TransformHash(WorldTransform) != m_BuiltTransformHash)\n\t\t\tm_IsDirty = true;\n\n\t\tif (m_IsDirty)\n\t\t{\n\t\t\tm_IsDirty = false;\n\t\t\tReconcile();\n\t\t}\n\n\t\tPollLakeBuilds();\n\t\tPollPieceBuilds();\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Works out everything the pieces are built from, then rebuilds every piece whose inputs changed and drops the ones\n\t/// nothing asks for any more. Stateless on purpose: it copes with undo, reloads and hot reloads alike, because every\n\t/// piece carries the signature of what it was built from.\n\t/// \u003C/summary\u003E\n\tprivate void Reconcile()\n\t{\n\t\tm_BuiltTransform = WorldTransform;\n\t\tm_BuiltTransformHash = TransformHash(m_BuiltTransform);\n\n\t\tPruneCurveTables();\n\t\tPruneShores();\n\n\t\t// The coast lies at sea level, wherever it has been moved to since; a lake\u0027s openings (the coast\u0027s too) belong to\n\t\t// its shore, wherever the lake has been moved to since.\n\t\tSyncCoasts();\n\t\tSnapAllOpenings();\n\n\t\tComputeWidths();\n\t\tComputeJunctions();\n\t\tComputeTrims();\n\t\tComputeFlows();\n\t\tComputeEndRows();\n\t\tComputeLakeOpenings();\n\t\tComputeMouths();\n\n\t\tvar wanted = new HashSet\u003CWaterPieceKey\u003E();\n\n\t\tReconcileRivers(wanted, m_BuiltTransformHash);\n\t\tReconcileJunctions(wanted, m_BuiltTransformHash);\n\n\t\t// The river mouths before the coast zone: a mouth that can\u0027t be built gives its block back to the zone.\n\t\tReconcileMouths(wanted, m_BuiltTransformHash);\n\t\tUpdateCoastZone(m_BuiltTransformHash);\n\t\tReconcileCoast(wanted);\n\n\t\tReconcileLakes(m_BuiltTransformHash);\n\n\t\tforeach (var key in m_Pieces.Keys.ToList())\n\t\t{\n\t\t\tif (wanted.Contains(key))\n\t\t\t\tcontinue;\n\n\t\t\t// A lake looks after its own tiles: a finished build replaces them all at once, whenever it lands (straight\n\t\t\t// away in a game, later in the editor), and they only go here once the lake itself is gone.\n\t\t\tif (key.Kind == WaterPieceKind.Lake \u0026\u0026 FindLake(key.Owner) is not null)\n\t\t\t\tcontinue;\n\n\t\t\tm_Pieces[key].Release();\n\t\t\tm_Pieces.Remove(key);\n\t\t\tPieceRevision\u002B\u002B;\n\t\t}\n\n\t\tforeach (var key in m_EmptyPieces.Keys.ToList())\n\t\t{\n\t\t\tif (!wanted.Contains(key))\n\t\t\t\tm_EmptyPieces.Remove(key);\n\t\t}\n\n\t\tforeach (int lakeId in m_LakeSignatures.Keys.ToList())\n\t\t{\n\t\t\tif (FindLake(lakeId) is null)\n\t\t\t\tm_LakeSignatures.Remove(lakeId);\n\t\t}\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Whether a piece is built from these inputs already: there, or known to come out empty (a chunk of the coast zone\n\t/// that is all land), which is not built again and again.\n\t/// \u003C/summary\u003E\n\tprivate bool IsBuilt(WaterPieceKey _Key, long _Signature)\n\t{\n\t\tif (m_Pieces.TryGetValue(_Key, out var piece) \u0026\u0026 piece.Signature == _Signature)\n\t\t\treturn true;\n\n\t\treturn m_EmptyPieces.TryGetValue(_Key, out long empty) \u0026\u0026 empty == _Signature;\n\t}\n\n\n\n\tprivate void PruneShores()\n\t{\n\t\tvar live = new HashSet\u003Cint\u003E(Lakes.Select(lake =\u003E lake.Id));\n\n\t\tforeach (int id in m_Shores.Keys.Where(id =\u003E !live.Contains(id)).ToList())\n\t\t\tm_Shores.Remove(id);\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The width profile of every river. Where a river simply bends on into the next, both share one width at the node\n\t/// (the average of what each asks for), so the row they share fits both.\n\t/// \u003C/summary\u003E\n\tprivate void ComputeWidths()\n\t{\n\t\tm_Widths.Clear();\n\n\t\tforeach (var river in Rivers)\n\t\t{\n\t\t\tvar table = GetCurveTable(river);\n\n\t\t\tif (table is null)\n\t\t\t\tcontinue;\n\n\t\t\tm_Widths[river.Id] = new RiverWidth(SharedWidth(river, river.StartNodeId), SharedWidth(river, river.EndNodeId), table.Length);\n\t\t}\n\t}\n\n\n\n\tprivate float SharedWidth(WaterRiver _River, int _NodeId)\n\t{\n\t\tfloat own = _River.WidthAt(_NodeId);\n\t\tvar rivers = GetRiversAt(_NodeId);\n\n\t\tif (rivers.Count != 2 || LakeAtOpening(_NodeId) is not null)\n\t\t\treturn own;\n\n\t\tvar other = rivers[0] == _River ? rivers[1] : rivers[0];\n\n\t\treturn (own \u002B other.WidthAt(_NodeId)) * 0.5f;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Lays out every confluence. A river too short for the fillets at both its ends gets those fillets shrunk until they\n\t/// fit on it; only corners that cannot fit even sharp are clamped.\n\t/// \u003C/summary\u003E\n\tprivate void ComputeJunctions()\n\t{\n\t\tm_Junctions.Clear();\n\n\t\tvar radii = new Dictionary\u003Cint, float\u003E();\n\n\t\tforeach (var node in Nodes)\n\t\t\tradii[node.Id] = MathF.Max(0.0f, node.CornerRadius);\n\n\t\tvar layouts = BuildJunctions(radii);\n\t\tvar shrink = new Dictionary\u003Cint, float\u003E();\n\n\t\tforeach (var river in Rivers)\n\t\t{\n\t\t\tvar table = GetCurveTable(river);\n\n\t\t\tif (table is null)\n\t\t\t\tcontinue;\n\n\t\t\tvar startArm = layouts.GetValueOrDefault(river.StartNodeId)?.FindArm(river.Id);\n\t\t\tvar endArm = layouts.GetValueOrDefault(river.EndNodeId)?.FindArm(river.Id);\n\t\t\tfloat sharp = (startArm?.SharpTrim ?? 0.0f) \u002B (endArm?.SharpTrim ?? 0.0f);\n\t\t\tfloat fillet = (startArm is null ? 0.0f : startArm.RawTrim - startArm.SharpTrim) \u002B (endArm is null ? 0.0f : endArm.RawTrim - endArm.SharpTrim);\n\t\t\tfloat available = MathF.Max(0.0f, table.Length - MinSurfaceLength - EndTrimAt(river.StartNodeId) - EndTrimAt(river.EndNodeId));\n\n\t\t\tif (fillet \u003C= 0.0f || sharp \u002B fillet \u003C= available)\n\t\t\t\tcontinue;\n\n\t\t\t// The fillet\u0027s share of a trim is proportional to the radius, so this factor makes it fit exactly.\n\t\t\tfloat factor = Math.Clamp((available - sharp) / fillet, 0.0f, 1.0f);\n\n\t\t\tforeach (int nodeId in new[] { river.StartNodeId, river.EndNodeId })\n\t\t\t{\n\t\t\t\tif (layouts.ContainsKey(nodeId))\n\t\t\t\t\tshrink[nodeId] = MathF.Min(shrink.GetValueOrDefault(nodeId, 1.0f), factor);\n\t\t\t}\n\t\t}\n\n\t\tif (shrink.Count \u003E 0)\n\t\t{\n\t\t\tforeach (var (nodeId, factor) in shrink)\n\t\t\t\tradii[nodeId] *= factor;\n\n\t\t\tlayouts = BuildJunctions(radii);\n\t\t}\n\n\t\tforeach (var (nodeId, layout) in layouts)\n\t\t\tm_Junctions[nodeId] = layout;\n\t}\n\n\n\n\tprivate Dictionary\u003Cint, JunctionLayout\u003E BuildJunctions(Dictionary\u003Cint, float\u003E _Radii)\n\t{\n\t\tvar layouts = new Dictionary\u003Cint, JunctionLayout\u003E();\n\n\t\tforeach (var node in Nodes)\n\t\t{\n\t\t\tif (GetDegree(node.Id) \u003C 2 || LakeAtOpening(node.Id) is not null)\n\t\t\t\tcontinue;\n\n\t\t\tvar layout = JunctionLayout.Create(this, node, _Radii.GetValueOrDefault(node.Id), m_Widths);\n\n\t\t\tif (layout is not null)\n\t\t\t\tlayouts[node.Id] = layout;\n\t\t}\n\n\t\treturn layouts;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// How far a river is held back at a node it ends at where something else takes over: a lake\u0027s flares, or an\n\t/// estuary\u0027s where it opens into the sea.\n\t/// \u003C/summary\u003E\n\tprivate float EndTrimAt(int _NodeId)\n\t{\n\t\treturn LakeTrimAt(_NodeId);\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// How far each river is held back at each end: past its confluence\u0027s corners, or past the flares of the lake it\n\t/// opens into, or of its estuary. A river too short for both is shared out, and the confluence takes the same\n\t/// numbers so the outline still lands on the river\u0027s rows.\n\t/// \u003C/summary\u003E\n\tprivate void ComputeTrims()\n\t{\n\t\tm_Trims.Clear();\n\n\t\tforeach (var river in Rivers)\n\t\t{\n\t\t\tvar table = GetCurveTable(river);\n\n\t\t\tif (table is null || !m_Widths.ContainsKey(river.Id))\n\t\t\t\tcontinue;\n\n\t\t\tvar startArm = m_Junctions.GetValueOrDefault(river.StartNodeId)?.FindArm(river.Id);\n\t\t\tvar endArm = m_Junctions.GetValueOrDefault(river.EndNodeId)?.FindArm(river.Id);\n\n\t\t\tfloat start = MathF.Max(startArm?.Trim ?? 0.0f, EndTrimAt(river.StartNodeId));\n\t\t\tfloat end = MathF.Max(endArm?.Trim ?? 0.0f, EndTrimAt(river.EndNodeId));\n\t\t\tfloat available = MathF.Max(0.0f, table.Length - MinSurfaceLength);\n\n\t\t\tif (start \u002B end \u003E available \u0026\u0026 start \u002B end \u003E 0.0f)\n\t\t\t{\n\t\t\t\tfloat scale = available / (start \u002B end);\n\n\t\t\t\tstart *= scale;\n\t\t\t\tend *= scale;\n\t\t\t}\n\n\t\t\tif (startArm is not null)\n\t\t\t\tstartArm.Trim = start;\n\n\t\t\tif (endArm is not null)\n\t\t\t\tendArm.Trim = end;\n\n\t\t\tm_Trims[river.Id] = (start, end);\n\t\t}\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// How fast the water runs everywhere, worked out downstream: a river nothing flows into starts at its own speed,\n\t/// a river below a confluence starts with the speeds flowing into it (weighted by how wide each is), and along\n\t/// every river the water speeds up on slopes and settles back to the river\u0027s own speed on the flat.\n\t/// \u003C/summary\u003E\n\tprivate void ComputeFlows()\n\t{\n\t\tm_Flows.Clear();\n\n\t\tvar incoming = new Dictionary\u003Cint, List\u003CWaterRiver\u003E\u003E();\n\t\tvar outgoing = new Dictionary\u003Cint, List\u003CWaterRiver\u003E\u003E();\n\n\t\tforeach (var river in Rivers)\n\t\t{\n\t\t\tif (!m_Widths.ContainsKey(river.Id))\n\t\t\t\tcontinue;\n\n\t\t\tGetList(incoming, river.EndNodeId).Add(river);\n\t\t\tGetList(outgoing, river.StartNodeId).Add(river);\n\t\t}\n\n\t\tvar pending = new Dictionary\u003Cint, int\u003E();\n\t\tvar queue = new Queue\u003CWaterRiver\u003E();\n\t\tvar endSpeeds = new Dictionary\u003Cint, float\u003E();\n\n\t\tforeach (var river in Rivers)\n\t\t{\n\t\t\tif (!m_Widths.ContainsKey(river.Id))\n\t\t\t\tcontinue;\n\n\t\t\tint feeding = incoming.TryGetValue(river.StartNodeId, out var list) ? list.Count : 0;\n\t\t\tpending[river.Id] = feeding;\n\n\t\t\tif (feeding == 0)\n\t\t\t\tqueue.Enqueue(river);\n\t\t}\n\n\t\twhile (queue.Count \u003E 0)\n\t\t{\n\t\t\tvar river = queue.Dequeue();\n\t\t\tvar flow = SolveFlow(river, StartSpeed(river, incoming, endSpeeds));\n\n\t\t\tendSpeeds[river.Id] = flow.Speeds[^1];\n\n\t\t\tif (!outgoing.TryGetValue(river.EndNodeId, out var below))\n\t\t\t\tcontinue;\n\n\t\t\tforeach (var next in below)\n\t\t\t{\n\t\t\t\tif (pending.ContainsKey(next.Id) \u0026\u0026 --pending[next.Id] == 0)\n\t\t\t\t\tqueue.Enqueue(next);\n\t\t\t}\n\t\t}\n\n\t\t// Rivers flowing round in a loop never come up: they start from their own speed.\n\t\tforeach (var river in Rivers)\n\t\t{\n\t\t\tif (m_Widths.ContainsKey(river.Id) \u0026\u0026 !m_Flows.ContainsKey(river.Id))\n\t\t\t\tSolveFlow(river, river.Speed);\n\t\t}\n\t}\n\n\n\n\tprivate static List\u003CWaterRiver\u003E GetList(Dictionary\u003Cint, List\u003CWaterRiver\u003E\u003E _Map, int _Key)\n\t{\n\t\tif (!_Map.TryGetValue(_Key, out var list))\n\t\t{\n\t\t\tlist = new List\u003CWaterRiver\u003E();\n\t\t\t_Map[_Key] = list;\n\t\t}\n\n\t\treturn list;\n\t}\n\n\n\n\tprivate float StartSpeed(WaterRiver _River, Dictionary\u003Cint, List\u003CWaterRiver\u003E\u003E _Incoming, Dictionary\u003Cint, float\u003E _EndSpeeds)\n\t{\n\t\tif (!_Incoming.TryGetValue(_River.StartNodeId, out var feeding) || feeding.Count == 0)\n\t\t\treturn _River.Speed;\n\n\t\tfloat sum = 0.0f;\n\t\tfloat weight = 0.0f;\n\n\t\tforeach (var upstream in feeding)\n\t\t{\n\t\t\tif (!_EndSpeeds.TryGetValue(upstream.Id, out float speed))\n\t\t\t\tcontinue;\n\n\t\t\tfloat width = m_Widths[upstream.Id].End;\n\n\t\t\tsum \u002B= speed * width;\n\t\t\tweight \u002B= width;\n\t\t}\n\n\t\treturn weight \u003E 0.0f ? sum / weight : _River.Speed;\n\t}\n\n\n\n\tprivate RiverFlow SolveFlow(WaterRiver _River, float _StartSpeed)\n\t{\n\t\tvar table = GetCurveTable(_River);\n\t\tvar width = m_Widths[_River.Id];\n\t\tvar trims = m_Trims.GetValueOrDefault(_River.Id);\n\n\t\tfloat length = table.Length;\n\t\tint count = Math.Max(2, (int)MathF.Ceiling(length / MathF.Max(16.0f, CellSize)) \u002B 1);\n\t\tfloat step = length / (count - 1);\n\t\tvar speeds = new float[count];\n\n\t\tfloat speed = MathF.Min(_StartSpeed, MaxSpeed);\n\t\tfloat previousHeight = table.PositionAt(0.0f).z;\n\t\tfloat settle = MathF.Exp(-step / SpeedSmoothing);\n\n\t\tspeeds[0] = RiverFlow.Quantize(speed);\n\n\t\tfor (int i = 1; i \u003C count; i\u002B\u002B)\n\t\t{\n\t\t\tfloat height = table.PositionAt(i * step).z;\n\t\t\tfloat drop = (previousHeight - height) / MathF.Max(0.001f, step);\n\t\t\tfloat target = MathF.Min(_River.Speed * Math.Clamp(1.0f \u002B SlopeSpeedup * drop, 0.25f, 8.0f), MaxSpeed);\n\n\t\t\tspeed = target \u002B (speed - target) * settle;\n\t\t\tspeeds[i] = RiverFlow.Quantize(speed);\n\t\t\tpreviousHeight = height;\n\t\t}\n\n\t\tvar flow = new RiverFlow\n\t\t{\n\t\t\tLength = length,\n\t\t\tStep = step,\n\t\t\tSpeeds = speeds,\n\t\t\tTrimStart = trims.Start,\n\t\t\tTrimEnd = trims.End,\n\t\t\tWaves = _River.Waves,\n\t\t\tWavesStart = WaveTarget(_River, _River.StartNodeId),\n\t\t\tWavesEnd = WaveTarget(_River, _River.EndNodeId),\n\t\t\tBlendStart = WaveBlend * width.Start,\n\t\t\tBlendEnd = WaveBlend * width.End\n\t\t};\n\n\t\tm_Flows[_River.Id] = flow;\n\n\t\treturn flow;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The wave strength a river has to arrive at on its row at a node: the lake\u0027s when it opens into one, halfway to\n\t/// the next river\u0027s when it bends on into it, its own otherwise (a confluence blends its arms itself, an estuary\n\t/// hands it over to the sea\u0027s).\n\t/// \u003C/summary\u003E\n\tprivate float WaveTarget(WaterRiver _River, int _NodeId)\n\t{\n\t\tif (LakeAtOpening(_NodeId) is { IsCoast: false } lake)\n\t\t\treturn lake.Waves;\n\n\t\tif (IsSmoothBend(_NodeId))\n\t\t{\n\t\t\tvar rivers = GetRiversAt(_NodeId);\n\t\t\tvar other = rivers[0] == _River ? rivers[1] : rivers[0];\n\n\t\t\treturn (_River.Waves \u002B other.Waves) * 0.5f;\n\t\t}\n\n\t\treturn _River.Waves;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// A node a river simply bends on through: two rivers, no confluence to fill between them, no lake.\n\t/// \u003C/summary\u003E\n\tprivate bool IsSmoothBend(int _NodeId)\n\t{\n\t\treturn GetDegree(_NodeId) == 2 \u0026\u0026 !m_Junctions.ContainsKey(_NodeId) \u0026\u0026 LakeAtOpening(_NodeId) is null;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The row each river starts and ends on, worked out once and handed to both pieces that share it. At a bend the\n\t/// two rivers share a single row, laid square to the way the water runs through the node.\n\t/// \u003C/summary\u003E\n\tprivate void ComputeEndRows()\n\t{\n\t\tm_EndRows.Clear();\n\n\t\tvar bendRows = new Dictionary\u003Cint, RiverRow\u003E();\n\n\t\tforeach (var river in Rivers)\n\t\t{\n\t\t\tif (!m_Flows.ContainsKey(river.Id))\n\t\t\t\tcontinue;\n\n\t\t\tm_EndRows[(river.Id, true)] = EndRow(river, true, bendRows);\n\t\t\tm_EndRows[(river.Id, false)] = EndRow(river, false, bendRows);\n\t\t}\n\t}\n\n\n\n\tprivate RiverRow EndRow(WaterRiver _River, bool _AtStart, Dictionary\u003Cint, RiverRow\u003E _BendRows)\n\t{\n\t\tvar table = GetCurveTable(_River);\n\t\tvar width = m_Widths[_River.Id];\n\t\tvar flow = m_Flows[_River.Id];\n\t\tvar trims = m_Trims.GetValueOrDefault(_River.Id);\n\n\t\tint nodeId = _AtStart ? _River.StartNodeId : _River.EndNodeId;\n\t\tfloat trim = _AtStart ? trims.Start : trims.End;\n\t\tfloat distance = _AtStart ? trim : table.Length - trim;\n\n\t\tif (trim \u003C= 0.0f \u0026\u0026 IsSmoothBend(nodeId))\n\t\t{\n\t\t\tif (!_BendRows.TryGetValue(nodeId, out var shared))\n\t\t\t{\n\t\t\t\tshared = BuildBendRow(nodeId);\n\t\t\t\t_BendRows[nodeId] = shared;\n\t\t\t}\n\n\t\t\tif (shared is not null)\n\t\t\t\treturn OrientRow(shared, table, distance);\n\t\t}\n\n\t\treturn RiverBuilder.BuildRow(table, width, flow, distance, CellSize, BankDrag, FoamFor);\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The row two rivers share at a bend: square to the average of the way the two run through the node, as wide as\n\t/// both are there, carrying the average of their water.\n\t/// \u003C/summary\u003E\n\tprivate RiverRow BuildBendRow(int _NodeId)\n\t{\n\t\tvar node = FindNode(_NodeId);\n\t\tvar rivers = GetRiversAt(_NodeId);\n\n\t\tif (node is null || rivers.Count != 2)\n\t\t\treturn null;\n\n\t\tvar a = rivers[0];\n\t\tvar b = rivers[1];\n\t\tvar tableA = GetCurveTable(a);\n\t\tvar tableB = GetCurveTable(b);\n\n\t\tif (tableA is null || tableB is null || !m_Flows.TryGetValue(a.Id, out var flowA) || !m_Flows.TryGetValue(b.Id, out var flowB))\n\t\t\treturn null;\n\n\t\tbool startA = a.StartNodeId == _NodeId;\n\t\tbool startB = b.StartNodeId == _NodeId;\n\t\tfloat distanceA = startA ? 0.0f : tableA.Length;\n\t\tfloat distanceB = startB ? 0.0f : tableB.Length;\n\n\t\t// The way each river runs downstream at the node, and the way each leaves the node.\n\t\tVector3 downstreamA = Flat(tableA.TangentAt(distanceA));\n\t\tVector3 downstreamB = Flat(tableB.TangentAt(distanceB));\n\t\tVector3 leavingA = startA ? downstreamA : -downstreamA;\n\t\tVector3 leavingB = startB ? downstreamB : -downstreamB;\n\n\t\tVector3 axis = leavingA - leavingB;\n\t\taxis = axis.IsNearZeroLength ? leavingA : axis.Normal;\n\n\t\tVector3 right = WaterCurve.RightOf(axis);\n\t\tfloat half = m_Widths[a.Id].HalfAt(distanceA);\n\t\tint count = RiverRow.ColumnCount(half * 2.0f, CellSize);\n\n\t\tfloat speedA = flowA.SpeedAt(distanceA);\n\t\tfloat speedB = flowB.SpeedAt(distanceB);\n\t\tfloat waves = (flowA.WavesAt(distanceA) \u002B flowB.WavesAt(distanceB)) * 0.5f;\n\t\tfloat foam = FoamFor((speedA \u002B speedB) * 0.5f);\n\n\t\tvar row = new RiverRow(count);\n\n\t\tfor (int i = 0; i \u003C count; i\u002B\u002B)\n\t\t{\n\t\t\tfloat across = RiverRow.Across(i, count);\n\t\t\tfloat bank = RiverBuilder.BankFactor(across, BankDrag);\n\t\t\tVector3 velocity = (downstreamA * speedA \u002B downstreamB * speedB) * (0.5f * bank);\n\n\t\t\trow.Points[i] = node.Position \u002B right * (-half \u002B 2.0f * half * across);\n\t\t\trow.Velocities[i] = new Vector2(velocity.x, velocity.y);\n\t\t\trow.Waves[i] = waves;\n\t\t\trow.Foams[i] = foam;\n\t\t}\n\n\t\treturn row;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// A shared row as one of its rivers sees it: left bank first looking down that river.\n\t/// \u003C/summary\u003E\n\tprivate static RiverRow OrientRow(RiverRow _Row, WaterCurveTable _Table, float _Distance)\n\t{\n\t\tVector3 right = WaterCurve.RightOf(_Table.TangentAt(_Distance));\n\t\tVector3 across = _Row.Points[^1] - _Row.Points[0];\n\n\t\tvar row = Vector3.Dot(right, across) \u003E= 0.0f ? _Row.Clone() : _Row.Reversed();\n\t\trow.Distance = _Distance;\n\n\t\treturn row;\n\t}\n\n\n\n\tprivate static Vector3 Flat(Vector3 _Direction)\n\t{\n\t\tVector3 flat = _Direction.WithZ(0.0f);\n\n\t\treturn flat.IsNearZeroLength ? Vector3.Forward : flat.Normal;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Where every river meets every lake: the opening\u0027s place round the shore, and the river\u0027s row there in the order\n\t/// the shore runs. Openings that would overlap the one before them round the shore are left out.\n\t/// \u003C/summary\u003E\n\tprivate void ComputeLakeOpenings()\n\t{\n\t\tm_LakeOpenings.Clear();\n\n\t\tforeach (var lake in Lakes)\n\t\t{\n\t\t\tvar openings = new List\u003CLakeOpening\u003E();\n\t\t\tvar shore = GetShore(lake);\n\n\t\t\tm_LakeOpenings[lake.Id] = openings;\n\n\t\t\tif (shore is null)\n\t\t\t\tcontinue;\n\n\t\t\tforeach (int nodeId in lake.Openings)\n\t\t\t{\n\t\t\t\tvar node = FindNode(nodeId);\n\t\t\t\tvar rivers = GetRiversAt(nodeId);\n\n\t\t\t\tif (node is null || rivers.Count != 1)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tvar river = rivers[0];\n\t\t\t\tbool inflow = river.EndNodeId == nodeId;\n\n\t\t\t\tif (!m_EndRows.TryGetValue((river.Id, !inflow), out var row) || row is null || row.Count \u003C 2)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tvar table = GetCurveTable(river);\n\t\t\t\tvar trims = m_Trims.GetValueOrDefault(river.Id);\n\n\t\t\t\tfloat at = shore.NearestDistance(node.Position);\n\t\t\t\tshore.At(at, out _, out Vector3 outward, out Vector3 direction);\n\n\t\t\t\t// The row in the order the shore runs.\n\t\t\t\tvar ordered = Vector3.Dot(row.Points[^1] - row.Points[0], direction) \u003E= 0.0f ? row : row.Reversed();\n\n\t\t\t\t// The way the river heads away from the lake at its row.\n\t\t\t\tVector3 tangent = table.TangentAt(row.Distance);\n\t\t\t\tVector3 away = (inflow ? -tangent : tangent).WithZ(0.0f);\n\n\t\t\t\topenings.Add(new LakeOpening\n\t\t\t\t{\n\t\t\t\t\tNodeId = nodeId,\n\t\t\t\t\tRiver = river,\n\t\t\t\t\tInflow = inflow,\n\t\t\t\t\tAt = at,\n\t\t\t\t\tHalfWidth = row.HalfWidth,\n\t\t\t\t\tFlare = inflow ? trims.End : trims.Start,\n\t\t\t\t\tRow = ordered,\n\t\t\t\t\tAway = away.IsNearZeroLength ? outward : away.Normal\n\t\t\t\t});\n\t\t\t}\n\n\t\t\topenings.Sort((x, y) =\u003E x.At.CompareTo(y.At));\n\n\t\t\t// Two openings fighting over the same stretch of shore: the later one round the shore is left out.\n\t\t\tfor (int i = openings.Count - 1; i \u003E= 1 \u0026\u0026 openings.Count \u003E 1; i--)\n\t\t\t{\n\t\t\t\tvar current = openings[i];\n\t\t\t\tvar previous = openings[i - 1];\n\n\t\t\t\tif (current.At - current.Reach \u003C previous.At \u002B previous.Reach)\n\t\t\t\t\topenings.RemoveAt(i);\n\t\t\t}\n\n\t\t\tif (openings.Count \u003E 1)\n\t\t\t{\n\t\t\t\tvar last = openings[^1];\n\t\t\t\tvar first = openings[0];\n\n\t\t\t\tif (last.At \u002B last.Reach \u003E shore.Length \u002B first.At - first.Reach)\n\t\t\t\t\topenings.RemoveAt(openings.Count - 1);\n\t\t\t}\n\t\t}\n\t}\n\n\n\n\tprivate static long TransformHash(in Transform _Transform)\n\t{\n\t\tvar hash = StableHash.Create();\n\n\t\thash.Add(_Transform.Position);\n\t\thash.Add(_Transform.Rotation.Forward);\n\t\thash.Add(_Transform.Rotation.Up);\n\t\thash.Add(_Transform.Scale);\n\n\t\treturn hash.Value;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Rebuilds every stretch of river whose inputs changed. A river is cut into stretches of about the chunk length,\n\t/// each with rows every cell; a stretch\u0027s end rows are worked out the same way by both stretches that share them, and\n\t/// a river\u0027s very first and last rows are the shared rows of whatever it meets.\n\t/// \u003C/summary\u003E\n\tprivate void ReconcileRivers(HashSet\u003CWaterPieceKey\u003E _Wanted, long _TransformHash)\n\t{\n\t\tforeach (var river in Rivers)\n\t\t{\n\t\t\tif (!m_Flows.TryGetValue(river.Id, out var flow) || !m_Widths.TryGetValue(river.Id, out var width))\n\t\t\t\tcontinue;\n\n\t\t\tvar table = GetCurveTable(river);\n\t\t\tvar trims = m_Trims.GetValueOrDefault(river.Id);\n\n\t\t\tfloat start = trims.Start;\n\t\t\tfloat end = table.Length - trims.End;\n\n\t\t\tif (end - start \u003C 1.0f)\n\t\t\t\tcontinue;\n\n\t\t\tvar startRow = m_EndRows[(river.Id, true)];\n\t\t\tvar endRow = m_EndRows[(river.Id, false)];\n\n\t\t\tint chunks = Math.Max(1, (int)MathF.Ceiling((end - start) / MathF.Max(CellSize * 4.0f, ChunkLength)));\n\n\t\t\tfor (int k = 0; k \u003C chunks; k\u002B\u002B)\n\t\t\t{\n\t\t\t\tfloat from = k == 0 ? start : start \u002B (end - start) * k / chunks;\n\t\t\t\tfloat to = k == chunks - 1 ? end : start \u002B (end - start) * (k \u002B 1) / chunks;\n\n\t\t\t\tvar key = new WaterPieceKey(WaterPieceKind.River, river.Id, k);\n\t\t\t\t_Wanted.Add(key);\n\n\t\t\t\tvar hash = StableHash.Create();\n\n\t\t\t\thash.Add(GeneratorVersion);\n\t\t\t\thash.Add((int)WaterPieceKind.River);\n\t\t\t\thash.Add(_TransformHash);\n\t\t\t\thash.Add(CellSize);\n\t\t\t\thash.Add(BankDrag);\n\t\t\t\thash.Add(FoamAmount);\n\t\t\t\thash.Add(FoamStartSpeed);\n\t\t\t\thash.Add(FoamFullSpeed);\n\t\t\t\thash.Add(table.Curve.P0);\n\t\t\t\thash.Add(table.Curve.P1);\n\t\t\t\thash.Add(table.Curve.P2);\n\t\t\t\thash.Add(table.Curve.P3);\n\t\t\t\twidth.AddToHash(ref hash);\n\t\t\t\thash.Add(from);\n\t\t\t\thash.Add(to);\n\t\t\t\tflow.AddToHash(ref hash, from, to);\n\n\t\t\t\tif (k == 0)\n\t\t\t\t\tstartRow.AddToHash(ref hash);\n\n\t\t\t\tif (k == chunks - 1)\n\t\t\t\t\tendRow.AddToHash(ref hash);\n\n\t\t\t\tif (IsBuilt(key, hash.Value))\n\t\t\t\t\tcontinue;\n\n\t\t\t\tvar rows = new List\u003CRiverRow\u003E();\n\n\t\t\t\tforeach (float distance in EvenRows(from, to, CellSize))\n\t\t\t\t{\n\t\t\t\t\tif (k == 0 \u0026\u0026 distance == from)\n\t\t\t\t\t\trows.Add(startRow);\n\t\t\t\t\telse if (k == chunks - 1 \u0026\u0026 distance == to)\n\t\t\t\t\t\trows.Add(endRow);\n\t\t\t\t\telse\n\t\t\t\t\t\trows.Add(RiverBuilder.BuildRow(table, width, flow, distance, CellSize, BankDrag, FoamFor));\n\t\t\t\t}\n\n\t\t\t\tSetPiece(key, hash.Value, RiverBuilder.Build(rows, m_BuiltTransform), river.Depth);\n\t\t\t}\n\t\t}\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Rows every spacing along a stretch, its exact ends included.\n\t/// \u003C/summary\u003E\n\tprivate static List\u003Cfloat\u003E EvenRows(float _Start, float _End, float _Spacing)\n\t{\n\t\tfloat length = MathF.Max(0.0f, _End - _Start);\n\t\tint steps = Math.Max(1, (int)MathF.Ceiling(length / MathF.Max(1.0f, _Spacing)));\n\t\tvar rows = new List\u003Cfloat\u003E(steps \u002B 1);\n\n\t\tfor (int i = 0; i \u003C= steps; i\u002B\u002B)\n\t\t\trows.Add(i == steps ? _End : _Start \u002B length * i / steps);\n\n\t\treturn rows;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Rebuilds every confluence whose outline changed (an outline holds the rows of every river at it, so it changes\n\t/// whenever any of them does).\n\t/// \u003C/summary\u003E\n\tprivate void ReconcileJunctions(HashSet\u003CWaterPieceKey\u003E _Wanted, long _TransformHash)\n\t{\n\t\tforeach (var (nodeId, layout) in m_Junctions)\n\t\t{\n\t\t\tvar node = FindNode(nodeId);\n\n\t\t\tif (node is null)\n\t\t\t\tcontinue;\n\n\t\t\tvar outline = layout.BuildOutline(arm =\u003E m_EndRows.GetValueOrDefault((arm.River.Id, arm.AtStart)), 0);\n\n\t\t\tif (outline is null || outline.Count \u003C 3)\n\t\t\t\tcontinue;\n\n\t\t\tvar key = new WaterPieceKey(WaterPieceKind.Junction, nodeId, 0);\n\t\t\t_Wanted.Add(key);\n\n\t\t\tvar hash = StableHash.Create();\n\n\t\t\thash.Add(GeneratorVersion);\n\t\t\thash.Add((int)WaterPieceKind.Junction);\n\t\t\thash.Add(_TransformHash);\n\t\t\thash.Add(CellSize);\n\t\t\tAddOutlineToHash(ref hash, outline);\n\n\t\t\tif (IsBuilt(key, hash.Value))\n\t\t\t\tcontinue;\n\n\t\t\tfloat depth = layout.Arms.Max(arm =\u003E arm.River.Depth);\n\n\t\t\tSetPiece(key, hash.Value, JunctionBuilder.Build(outline, node.Position, CellSize, m_BuiltTransform), depth);\n\t\t}\n\t}\n\n\n\n\tprivate static void AddOutlineToHash(ref StableHash _Hash, List\u003COutlineVertex\u003E _Outline)\n\t{\n\t\t_Hash.Add(_Outline.Count);\n\n\t\tforeach (var vertex in _Outline)\n\t\t{\n\t\t\t_Hash.Add(vertex.Position);\n\t\t\t_Hash.Add(vertex.Row);\n\t\t\t_Hash.Add(vertex.Velocity);\n\t\t\t_Hash.Add(vertex.Waves);\n\t\t\t_Hash.Add(vertex.Foam);\n\t\t}\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Starts a build for every lake whose outline, openings or settings changed. In the editor lakes are built on a\n\t/// worker thread (a big lake takes a moment), keeping their old tiles until the new ones are ready; in a game they\n\t/// are built straight away, so they are there before anything floats on them.\n\t/// \u003C/summary\u003E\n\tprivate void ReconcileLakes(long _TransformHash)\n\t{\n\t\tforeach (var lake in Lakes)\n\t\t{\n\t\t\tvar shore = GetShore(lake);\n\n\t\t\t// A coast has no surface of its own: the sea is outside it, and its estuaries are built with the sea.\n\t\t\tif (shore is null || lake.IsCoast)\n\t\t\t{\n\t\t\t\tRemoveLakeTiles(lake.Id);\n\t\t\t\tm_LakeQueue.Remove(lake.Id);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tvar openings = m_LakeOpenings.GetValueOrDefault(lake.Id) ?? new List\u003CLakeOpening\u003E();\n\t\t\tvar outline = LakeOutline.Build(shore, openings, 0);\n\t\t\tvar jets = new LakeJet[openings.Count];\n\n\t\t\tfor (int i = 0; i \u003C openings.Count; i\u002B\u002B)\n\t\t\t{\n\t\t\t\tvar opening = openings[i];\n\t\t\t\tvar row = opening.Row;\n\t\t\t\tVector3 inward = -opening.Away;\n\n\t\t\t\tjets[i] = new LakeJet(new Vector2(row.Centre.x, row.Centre.y), new Vector2(inward.x, inward.y).Normal, row.HalfWidth, row.MeanVelocity, row.MeanFoam, PlumeLength * row.HalfWidth * 2.0f);\n\t\t\t}\n\n\t\t\tvar hash = StableHash.Create();\n\n\t\t\thash.Add(GeneratorVersion);\n\t\t\thash.Add((int)WaterPieceKind.Lake);\n\t\t\thash.Add(_TransformHash);\n\t\t\thash.Add(CellSize);\n\t\t\thash.Add(LakeTileSize);\n\t\t\thash.Add(PlumeLength);\n\n\t\t\t// With rings the lake is only meshed round its river mouths, so how wide that band is changes what is\n\t\t\t// built, not just what is drawn.\n\t\t\thash.Add(LakeRings ? 1 : 0);\n\t\t\thash.Add(LakeBandWidth);\n\t\t\tlake.AddToHash(ref hash);\n\t\t\tAddOutlineToHash(ref hash, outline);\n\n\t\t\tlong signature = hash.Value;\n\n\t\t\tif (m_LakeSignatures.TryGetValue(lake.Id, out long current) \u0026\u0026 current == signature)\n\t\t\t{\n\t\t\t\tm_LakeQueue.Remove(lake.Id);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tvar input = new LakeBuildInput\n\t\t\t{\n\t\t\t\tLakeId = lake.Id,\n\t\t\t\tSignature = signature,\n\t\t\t\tOutline = outline,\n\t\t\t\tJets = jets,\n\t\t\t\tJetSlot = RegisterLakeJets(lake.Id, jets),\n\t\t\t\tHeight = lake.Height,\n\t\t\t\tWaves = lake.Waves,\n\t\t\t\tCellSize = CellSize,\n\t\t\t\tTileSize = LakeTileSize,\n\t\t\t\tTransform = m_BuiltTransform,\n\t\t\t\tRings = LakeRings,\n\t\t\t\tBandWidth = LakeBandWidth\n\t\t\t};\n\n\t\t\tif (!Scene.IsEditor)\n\t\t\t{\n\t\t\t\tApplyLake(lake.Id, signature, LakeBuilder.Build(input), lake.Depth);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (m_LakeBuilds.TryGetValue(lake.Id, out var running))\n\t\t\t{\n\t\t\t\t// One build at a time per lake: the newest inputs wait for the running one to finish.\n\t\t\t\tif (running.Signature != signature)\n\t\t\t\t\tm_LakeQueue[lake.Id] = input;\n\t\t\t\telse\n\t\t\t\t\tm_LakeQueue.Remove(lake.Id);\n\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tStartLakeBuild(input, lake.Depth);\n\t\t}\n\t}\n\n\n\n\tprivate void StartLakeBuild(LakeBuildInput _Input, float _Depth)\n\t{\n\t\tm_LakeBuilds[_Input.LakeId] = new LakeBuild\n\t\t{\n\t\t\tSignature = _Input.Signature,\n\t\t\tDepth = _Depth,\n\t\t\tTask = GameTask.RunInThreadAsync(() =\u003E LakeBuilder.Build(_Input))\n\t\t};\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Puts the tiles of every finished lake build in place, and starts whatever build was waiting behind it.\n\t/// \u003C/summary\u003E\n\tprivate void PollLakeBuilds()\n\t{\n\t\tif (m_LakeBuilds.Count == 0)\n\t\t\treturn;\n\n\t\tforeach (var (lakeId, build) in m_LakeBuilds.ToList())\n\t\t{\n\t\t\tif (!build.Task.IsCompleted)\n\t\t\t\tcontinue;\n\n\t\t\tm_LakeBuilds.Remove(lakeId);\n\n\t\t\tvar lake = FindLake(lakeId);\n\n\t\t\tif (build.Task.IsFaulted)\n\t\t\t\tLog.Warning($\u0022[WaterTool2] Building lake #{lakeId} failed: {build.Task.Exception?.InnerException?.Message}\u0022);\n\t\t\telse if (lake is not null)\n\t\t\t\tApplyLake(lakeId, build.Signature, build.Task.Result, lake.Depth);\n\n\t\t\tif (lake is not null \u0026\u0026 m_LakeQueue.Remove(lakeId, out var next))\n\t\t\t\tStartLakeBuild(next, lake.Depth);\n\n\t\t\t// The graph may have moved on while the lake was building (and back again): check it against the result.\n\t\t\tm_IsDirty = true;\n\t\t}\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Replaces a lake\u0027s tiles with freshly built ones. A null build is a shore that crosses itself: the lake is left\n\t/// empty, with a warning, until it is fixed.\n\t/// \u003C/summary\u003E\n\tprivate void ApplyLake(int _LakeId, long _Signature, LakeBuilder.Result _Result, float _Depth)\n\t{\n\t\tRemoveLakeTiles(_LakeId);\n\n\t\tm_LakeSignatures[_LakeId] = _Signature;\n\n\t\tif (_Result?.Tiles is null)\n\t\t{\n\t\t\tSetLakeMask(_LakeId, null);\n\n\t\t\tif (m_ReportedFailures.Add(_Signature))\n\t\t\t\tLog.Warning($\u0022[WaterTool2] Lake #{_LakeId} can\u0027t be built: its shore crosses itself, or a river opening into it folds back over it.\u0022);\n\n\t\t\treturn;\n\t\t}\n\n\t\tSetLakeMask(_LakeId, _Result.Mask);\n\n\t\tfor (int i = 0; i \u003C _Result.Tiles.Count; i\u002B\u002B)\n\t\t\tSetPiece(new WaterPieceKey(WaterPieceKind.Lake, _LakeId, i), _Signature, _Result.Tiles[i], _Depth);\n\t}\n\n\n\n\tprivate void RemoveLakeTiles(int _LakeId)\n\t{\n\t\tforeach (var key in m_Pieces.Keys.Where(key =\u003E key.Kind == WaterPieceKind.Lake \u0026\u0026 key.Owner == _LakeId).ToList())\n\t\t{\n\t\t\tm_Pieces[key].Release();\n\t\t\tm_Pieces.Remove(key);\n\t\t\tPieceRevision\u002B\u002B;\n\t\t}\n\t}\n\n\n\n\tprivate void SetPiece(WaterPieceKey _Key, long _Signature, WaterMeshData _Mesh, float _Depth)\n\t{\n\t\tif (m_Pieces.TryGetValue(_Key, out var old))\n\t\t\told.Release();\n\n\t\tif (_Mesh is null || _Mesh.VertexCount == 0)\n\t\t{\n\t\t\tm_Pieces.Remove(_Key);\n\t\t\tm_EmptyPieces[_Key] = _Signature;\n\t\t\tPieceRevision\u002B\u002B;\n\t\t\treturn;\n\t\t}\n\n\t\tvar piece = new WaterPiece(_Key, _Signature, _Mesh, _Depth);\n\n\t\tif (!Application.IsHeadless)\n\t\t\tpiece.Upload();\n\n\t\tm_Pieces[_Key] = piece;\n\t\tm_EmptyPieces.Remove(_Key);\n\t\tPieceRevision\u002B\u002B;\n\t}\n\n\n\n\tprivate void ReleasePieces()\n\t{\n\t\tforeach (var piece in m_Pieces.Values)\n\t\t\tpiece.Release();\n\n\t\tm_Pieces.Clear();\n\t\tm_EmptyPieces.Clear();\n\t\tm_LakeSignatures.Clear();\n\t\tm_LakeBuilds.Clear();\n\t\tm_LakeQueue.Clear();\n\t\tm_PieceBuilds.Clear();\n\t\tm_PieceQueue.Clear();\n\t\tPieceRevision\u002B\u002B;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Builds a piece of the sea: straight away in a game, so it is there before anything floats on it; in the editor on\n\t/// a worker thread, keeping the piece there was until the new one is ready, so dragging a river about never waits on\n\t/// it. One build at a time per piece: the newest inputs wait for the running one to finish. The build must only read\n\t/// what it was handed.\n\t/// \u003C/summary\u003E\n\tprivate void BuildPiece(WaterPieceKey _Key, long _Signature, float _Depth, Func\u003CWaterMeshData\u003E _Build)\n\t{\n\t\tif (!Scene.IsEditor)\n\t\t{\n\t\t\t// A build that throws counts as one that gave nothing, as on a worker thread, rather than cutting the reconcile\n\t\t\t// short before the rest of the sea is in place.\n\t\t\tWaterMeshData mesh = null;\n\n\t\t\ttry\n\t\t\t{\n\t\t\t\tmesh = _Build();\n\t\t\t}\n\t\t\tcatch (Exception exception)\n\t\t\t{\n\t\t\t\tLog.Warning($\u0022[WaterTool2] Building a piece of the sea failed: {exception.Message}\u0022);\n\t\t\t}\n\n\t\t\tApplyPiece(_Key, _Signature, mesh, _Depth);\n\t\t\treturn;\n\t\t}\n\n\t\tif (m_PieceBuilds.TryGetValue(_Key, out var running))\n\t\t{\n\t\t\tif (running.Signature == _Signature)\n\t\t\t\tm_PieceQueue.Remove(_Key);\n\t\t\telse\n\t\t\t\tm_PieceQueue[_Key] = (_Signature, _Depth, _Build);\n\n\t\t\treturn;\n\t\t}\n\n\t\tm_PieceBuilds[_Key] = new PieceBuild { Signature = _Signature, Depth = _Depth, Task = GameTask.RunInThreadAsync(_Build) };\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Puts every finished piece in place, and starts whatever build was waiting behind it.\n\t/// \u003C/summary\u003E\n\tprivate void PollPieceBuilds()\n\t{\n\t\tif (m_PieceBuilds.Count == 0)\n\t\t\treturn;\n\n\t\tforeach (var (key, build) in m_PieceBuilds.ToList())\n\t\t{\n\t\t\tif (!build.Task.IsCompleted)\n\t\t\t\tcontinue;\n\n\t\t\tm_PieceBuilds.Remove(key);\n\n\t\t\t// A build that threw gave nothing: recorded as such, so the same inputs aren\u0027t built again and again.\n\t\t\tif (build.Task.IsFaulted)\n\t\t\t\tLog.Warning($\u0022[WaterTool2] Building a piece of the sea failed: {build.Task.Exception?.InnerException?.Message}\u0022);\n\n\t\t\tApplyPiece(key, build.Signature, build.Task.IsFaulted ? null : build.Task.Result, build.Depth);\n\n\t\t\tif (m_PieceQueue.Remove(key, out var next))\n\t\t\t\tm_PieceBuilds[key] = new PieceBuild { Signature = next.Signature, Depth = next.Depth, Task = GameTask.RunInThreadAsync(next.Build) };\n\n\t\t\t// The graph may have moved on while it was building: check it against the result.\n\t\t\tm_IsDirty = true;\n\t\t}\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// A finished piece into place. A river mouth that couldn\u0027t be built is remembered, so the next reconcile hands its\n\t/// block back to the coast zone.\n\t/// \u003C/summary\u003E\n\tprivate void ApplyPiece(WaterPieceKey _Key, long _Signature, WaterMeshData _Mesh, float _Depth)\n\t{\n\t\tif (_Mesh is null \u0026\u0026 _Key.Kind == WaterPieceKind.Estuary)\n\t\t{\n\t\t\tif (m_FailedMouths.Add(_Signature))\n\t\t\t\tLog.Warning($\u0022[WaterTool2] The river mouth at node #{_Key.Owner} can\u0027t be built: the river or the coast folds back over it.\u0022);\n\n\t\t\tm_IsDirty = true;\n\t\t}\n\n\t\tSetPiece(_Key, _Signature, _Mesh, _Depth);\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The confluence layout at a node, as the last reconcile worked it out. Editor tools draw it.\n\t/// \u003C/summary\u003E\n\tinternal JunctionLayout JunctionAt(int _NodeId)\n\t{\n\t\treturn m_Junctions.GetValueOrDefault(_NodeId);\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The flow worked out for a river, for overlays.\n\t/// \u003C/summary\u003E\n\tinternal RiverFlow FlowOf(int _RiverId)\n\t{\n\t\treturn m_Flows.GetValueOrDefault(_RiverId);\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The slowest and fastest the water runs along a river, as the last reconcile worked it out. False before the river\n\t/// has been worked out.\n\t/// \u003C/summary\u003E\n\tpublic bool TryGetSpeedRange(int _RiverId, out float _Slowest, out float _Fastest)\n\t{\n\t\t_Slowest = 0.0f;\n\t\t_Fastest = 0.0f;\n\n\t\tif (!m_Flows.TryGetValue(_RiverId, out var flow) || flow.Speeds is null || flow.Speeds.Length == 0)\n\t\t\treturn false;\n\n\t\t_Slowest = flow.Speeds.Min();\n\t\t_Fastest = flow.Speeds.Max();\n\n\t\treturn true;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The openings of a lake as the last reconcile worked them out.\n\t/// \u003C/summary\u003E\n\tinternal IReadOnlyList\u003CLakeOpening\u003E OpeningsOf(int _LakeId)\n\t{\n\t\treturn m_LakeOpenings.GetValueOrDefault(_LakeId);\n\t}\n}\n"},{"Ident":"redsnail.watertool2","Path":"Code/Waves/WaterWaves.cs","FileName":"WaterWaves.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":445731,"IsPrivate":false,"Code":"using System;\nusing Sandbox;\n\nnamespace RedSnail.WaterTool2;\n\n/// \u003Csummary\u003E\n/// The CPU side of the water\u0027s motion. Every function here mirrors one in advancedwater.shader term for term, so what\n/// floats and swims rides the very surface the player sees.\n/// \u003C/summary\u003E\npublic static class WaterWaves\n{\n\t/// \u003Csummary\u003E\n\t/// Each Gerstner octave turns this many radians from the one before, so the octaves cross instead of stacking.\n\t/// \u003C/summary\u003E\n\tpublic const float OctaveAngleStep = 1.2f;\n\n\t/// \u003Csummary\u003E\n\t/// Size, in world units, of the slow noise that offsets the flow cycle across the surface, so the two-phase cross\n\t/// fade of flowing water never pulses everywhere at once.\n\t/// \u003C/summary\u003E\n\tpublic const float PhaseNoiseScale = 750.0f;\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The still water\u0027s waves (detail and swell) at a world point: XY is the orbital motion, Z the height.\n\t/// Mirrors WaveDisplacement() in the shader.\n\t/// \u003C/summary\u003E\n\tpublic static Vector3 Displacement(Vector2 _Point, WaterDefinition _Profile, float _Time)\n\t{\n\t\tVector3 detail = Gerstner(_Point, _Profile.WavesScale, _Profile.WavesSpeed, _Profile.WavesDirection, _Profile.WavesOctaves, _Profile.WavesLacunarity, _Profile.WavesPersistence, _Profile.WavesSteepness, _Time) * _Profile.WavesIntensity;\n\t\tVector3 swell = Gerstner(_Point, _Profile.SwellScale, _Profile.SwellSpeed, _Profile.SwellDirection, _Profile.SwellOctaves, _Profile.SwellLacunarity, _Profile.SwellPersistence, _Profile.SwellSteepness, _Time) * _Profile.SwellIntensity;\n\n\t\treturn detail \u002B swell;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The waves carried along by flowing water: the still waves sampled twice, each copy sliding downstream with the\n\t/// flow for one cycle before it starts over, the two half a cycle apart and cross-faded so neither restart is ever\n\t/// seen. Every point uses its own flow, and the result only depends on the point and its flow, so two pieces that\n\t/// share a vertex always move it the same. Mirrors FlowingWaves() in the shader.\n\t/// \u003C/summary\u003E\n\tpublic static Vector3 FlowingDisplacement(Vector2 _Point, Vector2 _Flow, WaterDefinition _Profile, float _Time, float _Cycle)\n\t{\n\t\tif (_Flow.LengthSquared \u003C 0.0001f || _Cycle \u003C= 0.0f)\n\t\t\treturn Displacement(_Point, _Profile, _Time);\n\n\t\tfloat phase = _Time / _Cycle \u002B PhaseNoise(_Point);\n\t\tfloat phase0 = Frac(phase);\n\t\tfloat phase1 = Frac(phase \u002B 0.5f);\n\t\tfloat weight0 = 1.0f - MathF.Abs(2.0f * phase0 - 1.0f);\n\n\t\tVector3 first = Displacement(_Point - _Flow * ((phase0 - 0.5f) * _Cycle), _Profile, _Time);\n\t\tVector3 second = Displacement(_Point - _Flow * ((phase1 - 0.5f) * _Cycle), _Profile, _Time);\n\n\t\treturn first * weight0 \u002B second * (1.0f - weight0);\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// How fast the surface itself moves at a point (the waves\u0027 orbital motion), by stepping the displacement a little\n\t/// either side in time.\n\t/// \u003C/summary\u003E\n\tpublic static Vector3 SurfaceVelocity(Vector2 _Point, Vector2 _Flow, float _WaveScale, WaterDefinition _Profile, float _Time, float _Cycle)\n\t{\n\t\tconst float step = 0.05f;\n\n\t\tVector3 before = FlowingDisplacement(_Point, _Flow, _Profile, _Time - step, _Cycle);\n\t\tVector3 after = FlowingDisplacement(_Point, _Flow, _Profile, _Time \u002B step, _Cycle);\n\n\t\treturn (after - before) * (_WaveScale / (2.0f * step));\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Smooth value noise in [0, 1), one cell every \u003Csee cref=\u0022PhaseNoiseScale\u0022/\u003E units. Mirrors FlowPhaseNoise() in the\n\t/// shader.\n\t/// \u003C/summary\u003E\n\tpublic static float PhaseNoise(Vector2 _Point)\n\t{\n\t\tfloat x = _Point.x / PhaseNoiseScale;\n\t\tfloat y = _Point.y / PhaseNoiseScale;\n\t\tfloat ix = MathF.Floor(x);\n\t\tfloat iy = MathF.Floor(y);\n\t\tfloat fx = x - ix;\n\t\tfloat fy = y - iy;\n\t\tfloat ux = fx * fx * (3.0f - 2.0f * fx);\n\t\tfloat uy = fy * fy * (3.0f - 2.0f * fy);\n\n\t\tfloat a = Hash(ix, iy);\n\t\tfloat b = Hash(ix \u002B 1.0f, iy);\n\t\tfloat c = Hash(ix, iy \u002B 1.0f);\n\t\tfloat d = Hash(ix \u002B 1.0f, iy \u002B 1.0f);\n\n\t\tfloat bottom = a \u002B (b - a) * ux;\n\t\tfloat top = c \u002B (d - c) * ux;\n\n\t\treturn bottom \u002B (top - bottom) * uy;\n\t}\n\n\n\n\tprivate static float Hash(float _X, float _Y)\n\t{\n\t\tfloat a = Frac(_X * 0.1031f);\n\t\tfloat b = Frac(_Y * 0.1031f);\n\t\tfloat c = Frac(_X * 0.1031f);\n\t\tfloat s = a * (b \u002B 33.33f) \u002B b * (c \u002B 33.33f) \u002B c * (a \u002B 33.33f);\n\n\t\ta \u002B= s;\n\t\tb \u002B= s;\n\t\tc \u002B= s;\n\n\t\treturn Frac((a \u002B b) * c);\n\t}\n\n\n\n\tprivate static float Frac(float _Value)\n\t{\n\t\treturn _Value - MathF.Floor(_Value);\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// A Gerstner wave sum, each octave smaller, faster and turned from the last. Mirrors ComputeGerstner() in the\n\t/// shader.\n\t/// \u003C/summary\u003E\n\tprivate static Vector3 Gerstner(Vector2 _Point, float _Scale, float _Speed, Vector2 _Direction, int _Octaves, float _Lacunarity, float _Persistence, float _Steepness, float _Time)\n\t{\n\t\tif (_Octaves \u003C= 0)\n\t\t\treturn Vector3.Zero;\n\n\t\tVector2 direction = _Direction.LengthSquared \u003E 0.000001f ? _Direction.Normal : new Vector2(1.0f, 0.0f);\n\t\tfloat time = _Time * _Speed;\n\n\t\tVector3 displacement = Vector3.Zero;\n\t\tfloat amplitude = 1.0f;\n\t\tfloat frequency = _Scale;\n\t\tfloat total = 0.0f;\n\n\t\tfor (int octave = 0; octave \u003C _Octaves; octave\u002B\u002B)\n\t\t{\n\t\t\tfloat angle = octave * OctaveAngleStep;\n\t\t\tfloat cos = MathF.Cos(angle);\n\t\t\tfloat sin = MathF.Sin(angle);\n\t\t\tvar octaveDirection = new Vector2(direction.x * cos - direction.y * sin, direction.x * sin \u002B direction.y * cos);\n\n\t\t\tfloat phase = frequency * (octaveDirection.x * _Point.x \u002B octaveDirection.y * _Point.y) \u002B time * frequency * 0.5f;\n\n\t\t\tdisplacement.x \u002B= _Steepness * amplitude * octaveDirection.x * MathF.Cos(phase);\n\t\t\tdisplacement.y \u002B= _Steepness * amplitude * octaveDirection.y * MathF.Cos(phase);\n\t\t\tdisplacement.z \u002B= amplitude * MathF.Sin(phase);\n\n\t\t\ttotal \u002B= amplitude;\n\t\t\tamplitude *= _Persistence;\n\t\t\tfrequency *= _Lacunarity;\n\t\t}\n\n\t\treturn total \u003E 0.0f ? displacement / total : Vector3.Zero;\n\t}\n}\n"},{"Ident":"redsnail.watertool2","Path":"Network/WaterNetwork.Sea.cs","FileName":"WaterNetwork.Sea.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":445731,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\nusing Sandbox;\nusing Sandbox.Rendering;\n\nnamespace RedSnail.WaterTool2;\n\n/// \u003Csummary\u003E\n/// The sea: one infinite surface at sea level, drawn round the camera out to the horizon. Round the land it gives way\n/// to the coast zone (see WaterNetwork.Coast), which it is masked out over, along with the land itself.\n/// \u003C/summary\u003E\npublic sealed partial class WaterNetwork\n{\n\t/// \u003Csummary\u003E\n\t/// Pieces of water whose surface comes this close above sea level cut the sea away under them, so the two never\n\t/// draw over each other.\n\t/// \u003C/summary\u003E\n\tprivate const float SeaHoleMargin = 64.0f;\n\n\tprivate const int MaxSeaRings = 12;\n\n\t/// \u003Csummary\u003E\n\t/// The most cells the grid over the sea holes has along either side.\n\t/// \u003C/summary\u003E\n\tprivate const int MaxSeaHoleGrid = 128;\n\n\t/// \u003Csummary\u003E\n\t/// An infinite sea at \u003Csee cref=\u0022SeaLevel\u0022/\u003E, drawn in rings round the camera, each twice as coarse as the one\n\t/// inside it, out to the horizon.\n\t/// \u003C/summary\u003E\n\t[Property(Title = \u0022Enabled\u0022), Group(\u0022Sea\u0022), Order(5)]\n\tpublic bool SeaEnabled\n\t{\n\t\tget;\n\t\tset\n\t\t{\n\t\t\tfield = value;\n\t\t\tMarkDirty();\n\t\t}\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// The sea\u0027s level, in network space. The coast lies at it, and the rivers opening into the sea end at it (the next\n\t/// reconcile moves them). The coast is found at this level: build it again after moving it.\n\t/// \u003C/summary\u003E\n\t[Property(Title = \u0022Sea Level\u0022), Group(\u0022Sea\u0022), Order(5)]\n\tpublic float SeaLevel\n\t{\n\t\tget;\n\t\tset\n\t\t{\n\t\t\tfield = value;\n\t\t\tMarkDirty();\n\t\t}\n\t}\n\n\t/// \u003Csummary\u003E\n\t/// The sea\u0027s waves: long swell and chop of their own, apart from the rivers\u0027 and lakes\u0027. Ocean waves when empty.\n\t/// \u003C/summary\u003E\n\t[Property(Title = \u0022Wave Profile\u0022), Group(\u0022Sea\u0022), Order(5)] public WaterDefinition SeaProfile { get; set; }\n\n\t/// \u003Csummary\u003E\n\t/// Scales the sea\u0027s waves.\n\t/// \u003C/summary\u003E\n\t[Property(Title = \u0022Waves\u0022), Group(\u0022Sea\u0022), Order(5), Range(0.0f, 2.0f)] public float SeaWaves { get; set { field = value.Clamp(0.0f, 10.0f); } } = 1.0f;\n\n\t/// \u003Csummary\u003E\n\t/// How deep the sea is, for swimming, drowning and buoyancy.\n\t/// \u003C/summary\u003E\n\t[Property(Title = \u0022Depth\u0022), Group(\u0022Sea\u0022), Order(5)] public float SeaDepth { get; set { field = value.Clamp(1.0f, 1000000.0f); } } = 5000.0f;\n\n\t/// \u003Csummary\u003E\n\t/// The size of the finest ring\u0027s cells, round the camera; each ring further out doubles it. The coast zone is built\n\t/// on the same cells, so it is the sea\u0027s own surface point for point.\n\t/// \u003C/summary\u003E\n\t[Property(Title = \u0022Cell Size\u0022), Group(\u0022Sea\u0022), Order(5), Range(16.0f, 256.0f)]\n\tpublic float SeaCellSize\n\t{\n\t\tget;\n\t\tset\n\t\t{\n\t\t\tfield = value.Clamp(4.0f, 4096.0f);\n\t\t\tMarkDirty();\n\t\t}\n\t} = 32.0f;\n\n\t/// \u003Csummary\u003E\n\t/// How many rings the sea is drawn in: each one reaches twice as far as the one inside it.\n\t/// \u003C/summary\u003E\n\t[Property(Title = \u0022Rings\u0022), Group(\u0022Sea\u0022), Order(5), Range(2, 12)] public int SeaRings { get; set { field = value.Clamp(1, MaxSeaRings); } } = 7;\n\n\t/// \u003Csummary\u003E\n\t/// How many cells across each ring is - the sea\u0027s and every lake\u0027s alike, since all of them are drawn from the one\n\t/// grid. Under Surface rather than Sea for that reason: a scene with no sea at all still pays for this on its lakes.\n\t/// \u003Cpara\u003E\n\t/// With the cell size fixed, this sets how far a ring reaches rather than how fine it is, and the vertices go up\n\t/// with its square. Halving it and adding one more ring keeps the same reach for roughly a third of the vertices,\n\t/// and costs only that water a given distance away is tessellated one step coarser.\n\t/// \u003C/para\u003E\n\t/// \u003C/summary\u003E\n\t[Property(Title = \u0022Ring Cells\u0022), Group(\u0022Surface\u0022), Order(0), Range(32, 256)] public int SeaRingCells { get; set { field = Math.Max(16, value.Clamp(16, 512) / 8 * 8); } } = 96;\n\n\t/// \u003Csummary\u003E\n\t/// The sea\u0027s wave profile: its own, or ocean waves.\n\t/// \u003C/summary\u003E\n\tpublic WaterDefinition ResolvedSeaProfile =\u003E SeaProfile.IsValid() ? SeaProfile : WaterDefinition.SeaFallback;\n\n\t/// \u003Csummary\u003E\n\t/// The sea\u0027s level in the world.\n\t/// \u003C/summary\u003E\n\tpublic float WorldSeaLevel =\u003E WorldTransform.PointToWorld(new Vector3(0.0f, 0.0f, SeaLevel)).z;\n\n\t/// \u003Csummary\u003E\n\t/// What the sea is drawing right now, for the editor: the coast zone\u0027s chunks, the river mouths, and the cut-outs the\n\t/// water near sea level makes in the infinite sea (every pixel of the sea near one tests it).\n\t/// \u003C/summary\u003E\n\tpublic string SeaStats\n\t{\n\t\tget\n\t\t{\n\t\t\tint chunks = 0;\n\t\t\tint mouths = 0;\n\t\t\tlong chunkTriangles = 0;\n\t\t\tlong mouthTriangles = 0;\n\n\t\t\tforeach (var piece in m_Pieces.Values)\n\t\t\t{\n\t\t\t\tif (piece.Key.Kind == WaterPieceKind.Coast)\n\t\t\t\t{\n\t\t\t\t\tchunks\u002B\u002B;\n\t\t\t\t\tchunkTriangles \u002B= piece.Mesh.TriangleCount;\n\t\t\t\t}\n\t\t\t\telse if (piece.Key.Kind == WaterPieceKind.Estuary)\n\t\t\t\t{\n\t\t\t\t\tmouths\u002B\u002B;\n\t\t\t\t\tmouthTriangles \u002B= piece.Mesh.TriangleCount;\n\t\t\t\t}\n\t\t\t}\n\n\t\t\treturn $\u0022Coast zone: {chunks} chunks, {Count(chunkTriangles)} triangles\\nRiver mouths: {mouths}, {Count(mouthTriangles)} triangles\\nSea cut-outs: {m_SeaHoleCount}\u0022;\n\t\t}\n\t}\n\n\n\n\tprivate static string Count(long _Value)\n\t{\n\t\tif (_Value \u003E= 1000000)\n\t\t\treturn $\u0022{_Value / 1000000.0:0.0}M\u0022;\n\n\t\tif (_Value \u003E= 1000)\n\t\t\treturn $\u0022{_Value / 1000.0:0.0}K\u0022;\n\n\t\treturn _Value.ToString();\n\t}\n\n\n\n\t// \u2500\u2500 The sea\u0027s surface \u2500\u2500\n\t// One grid of cells, drawn once per ring: ring k centred near the camera (snapped to twice its cell size, so the ring\n\t// inside it lands exactly on its grid), with cells twice the size of ring k - 1\u0027s and a hole where ring k - 1 is.\n\n\tprivate GpuBuffer\u003CWaterVertex\u003E m_RingVertices;\n\tprivate GpuBuffer\u003Cuint\u003E m_RingIndices;\n\tprivate int m_RingIndexCount;\n\tprivate int m_RingMeshCells;\n\tprivate int m_RingCount;\n\n\tprivate GpuBuffer\u003CVector4\u003E m_RingBuffer;\n\tprivate readonly Vector4[] m_RingData = new Vector4[MaxSeaRings];\n\tprivate RenderAttributes[] m_RingAttributes = Array.Empty\u003CRenderAttributes\u003E();\n\n\tprivate GpuBuffer\u003CVector4\u003E m_SeaHoleBuffer;\n\tprivate int m_SeaHoleCapacity;\n\tprivate int m_SeaHoleCount;\n\tprivate Vector4 m_SeaHoleBounds;\n\tprivate GpuBuffer\u003Cint\u003E m_SeaHoleGridBuffer;\n\tprivate int m_SeaHoleGridCapacity;\n\tprivate Vector2 m_SeaHoleGridSize = Vector2.One;\n\tprivate int m_SeaHoleRevision = -1;\n\tprivate int m_SeaHoleZoneRevision = -1;\n\tprivate float m_SeaHoleLevel = float.NaN;\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The rings round this frame\u0027s camera, the coast zone the sea is masked out over, and the holes the water near sea\n\t/// level cuts in it.\n\t/// \u003C/summary\u003E\n\tprivate void UpdateSea()\n\t{\n\t\tif (!SeaEnabled)\n\t\t{\n\t\t\tm_RingCount = 0;\n\t\t\treturn;\n\t\t}\n\n\t\tEnsureRingMesh();\n\n\t\tm_RingCount = Math.Clamp(SeaRings, 1, MaxSeaRings);\n\n\t\tVector3 viewer = m_HasCullFrustum ? m_CameraPosition : WorldPosition;\n\t\tfloat half = SeaRingCells * 0.5f;\n\n\t\tfor (int k = 0; k \u003C m_RingCount; k\u002B\u002B)\n\t\t{\n\t\t\tfloat cell = SeaCellSize * (1 \u003C\u003C k);\n\t\t\tfloat snap = cell * 2.0f;\n\n\t\t\tm_RingData[k] = new Vector4(MathF.Round(viewer.x / snap) * snap, MathF.Round(viewer.y / snap) * snap, cell, half * cell);\n\t\t}\n\n\t\tif (!m_RingBuffer.IsValid())\n\t\t\tm_RingBuffer = new GpuBuffer\u003CVector4\u003E(MaxSeaRings, GpuBuffer.UsageFlags.Structured);\n\n\t\tm_RingBuffer.SetData(m_RingData.AsSpan(0, MaxSeaRings));\n\n\t\tUploadCoastZone();\n\t\tUpdateSeaHoles();\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The grid every ring is drawn from: its vertices at whole-cell steps from its middle.\n\t/// \u003C/summary\u003E\n\tprivate void EnsureRingMesh()\n\t{\n\t\tint cells = SeaRingCells;\n\n\t\tif (m_RingVertices.IsValid() \u0026\u0026 m_RingMeshCells == cells)\n\t\t\treturn;\n\n\t\tm_RingVertices?.Dispose();\n\t\tm_RingIndices?.Dispose();\n\n\t\tint side = cells \u002B 1;\n\t\tvar vertices = new WaterVertex[side * side];\n\n\t\tfor (int y = 0; y \u003C side; y\u002B\u002B)\n\t\t{\n\t\t\tfor (int x = 0; x \u003C side; x\u002B\u002B)\n\t\t\t{\n\t\t\t\tvertices[y * side \u002B x] = new WaterVertex\n\t\t\t\t{\n\t\t\t\t\tPosition = new Vector3(x - cells * 0.5f, y - cells * 0.5f, 0.0f),\n\t\t\t\t\tNormal = Vector3.Up,\n\t\t\t\t\tTangent = new Vector4(1.0f, 0.0f, 0.0f, 1.0f),\n\t\t\t\t\tTexCoord = Vector2.Zero,\n\t\t\t\t\tTexCoord2 = Vector2.Zero,\n\t\t\t\t\tColor = new Color(0.0f, 0.0f, 1.0f, 0.0f)\n\t\t\t\t};\n\t\t\t}\n\t\t}\n\n\t\t// Two triangles a cell, always split the same way: the coast zone and the river mouths rebuild the surface from\n\t\t// it, and the coast zone\u0027s cells are split the same way too.\n\t\tvar indices = new uint[cells * cells * 6];\n\t\tint cursor = 0;\n\n\t\tfor (int y = 0; y \u003C cells; y\u002B\u002B)\n\t\t{\n\t\t\tfor (int x = 0; x \u003C cells; x\u002B\u002B)\n\t\t\t{\n\t\t\t\tuint i0 = (uint)(y * side \u002B x);\n\t\t\t\tuint i1 = i0 \u002B 1;\n\t\t\t\tuint i2 = i0 \u002B (uint)side;\n\t\t\t\tuint i3 = i2 \u002B 1;\n\n\t\t\t\tindices[cursor\u002B\u002B] = i0;\n\t\t\t\tindices[cursor\u002B\u002B] = i1;\n\t\t\t\tindices[cursor\u002B\u002B] = i2;\n\t\t\t\tindices[cursor\u002B\u002B] = i1;\n\t\t\t\tindices[cursor\u002B\u002B] = i3;\n\t\t\t\tindices[cursor\u002B\u002B] = i2;\n\t\t\t}\n\t\t}\n\n\t\tm_RingVertices = new GpuBuffer\u003CWaterVertex\u003E(vertices.Length, GpuBuffer.UsageFlags.Vertex);\n\t\tm_RingVertices.SetData(vertices);\n\n\t\tm_RingIndices = new GpuBuffer\u003Cuint\u003E(indices.Length, GpuBuffer.UsageFlags.Index);\n\t\tm_RingIndices.SetData(indices);\n\n\t\tm_RingIndexCount = indices.Length;\n\t\tm_RingMeshCells = cells;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Every hole the pieces near sea level cut in the sea, packed for the shader: two rows per hole (its bounds, then\n\t/// whether it is a disk or a polygon, where its points start, how many there are, and a disk\u0027s radius), then every\n\t/// polygon\u0027s points; and a grid over them, so the sea only ever tests the holes near it. Holes inside the coast zone\n\t/// are left out: the sea is masked out there already.\n\t/// \u003C/summary\u003E\n\tprivate void UpdateSeaHoles()\n\t{\n\t\tfloat level = WorldSeaLevel;\n\n\t\tif (m_SeaHoleRevision == PieceRevision \u0026\u0026 m_SeaHoleZoneRevision == m_CoastZoneRevision \u0026\u0026 m_SeaHoleLevel == level)\n\t\t\treturn;\n\n\t\tm_SeaHoleRevision = PieceRevision;\n\t\tm_SeaHoleZoneRevision = m_CoastZoneRevision;\n\t\tm_SeaHoleLevel = level;\n\n\t\tvar holes = new List\u003CSeaHole\u003E();\n\t\tint points = 0;\n\n\t\tforeach (var piece in m_Pieces.Values)\n\t\t{\n\t\t\tforeach (var hole in piece.Mesh.SeaHoles)\n\t\t\t{\n\t\t\t\tif (hole.Lowest \u003E level \u002B SeaHoleMargin)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tif (m_CoastZone is { } zone \u0026\u0026 zone.IsMasked(hole.Min, m_MouthTiles) \u0026\u0026 zone.IsMasked(hole.Max, m_MouthTiles)\n\t\t\t\t\t\u0026\u0026 zone.IsMasked(new Vector2(hole.Min.x, hole.Max.y), m_MouthTiles) \u0026\u0026 zone.IsMasked(new Vector2(hole.Max.x, hole.Min.y), m_MouthTiles))\n\t\t\t\t\tcontinue;\n\n\t\t\t\tholes.Add(hole);\n\t\t\t\tpoints \u002B= hole.Points?.Length ?? 0;\n\t\t\t}\n\t\t}\n\n\t\tm_SeaHoleCount = holes.Count;\n\n\t\tif (holes.Count == 0)\n\t\t{\n\t\t\tm_SeaHoleBounds = Vector4.Zero;\n\t\t\treturn;\n\t\t}\n\n\t\tint rows = holes.Count * 2 \u002B points;\n\n\t\tif (!m_SeaHoleBuffer.IsValid() || m_SeaHoleCapacity \u003C rows)\n\t\t{\n\t\t\tm_SeaHoleBuffer?.Dispose();\n\t\t\tm_SeaHoleCapacity = Math.Max(rows, m_SeaHoleCapacity * 2);\n\t\t\tm_SeaHoleBuffer = new GpuBuffer\u003CVector4\u003E(m_SeaHoleCapacity, GpuBuffer.UsageFlags.Structured);\n\t\t}\n\n\t\tvar data = new Vector4[rows];\n\t\tint cursor = holes.Count * 2;\n\t\tvar min = new Vector2(float.MaxValue, float.MaxValue);\n\t\tvar max = new Vector2(float.MinValue, float.MinValue);\n\n\t\tfor (int i = 0; i \u003C holes.Count; i\u002B\u002B)\n\t\t{\n\t\t\tvar hole = holes[i];\n\n\t\t\tdata[i * 2] = new Vector4(hole.Min.x, hole.Min.y, hole.Max.x, hole.Max.y);\n\n\t\t\tmin = new Vector2(MathF.Min(min.x, hole.Min.x), MathF.Min(min.y, hole.Min.y));\n\t\t\tmax = new Vector2(MathF.Max(max.x, hole.Max.x), MathF.Max(max.y, hole.Max.y));\n\n\t\t\tif (hole.Points is null)\n\t\t\t{\n\t\t\t\tdata[i * 2 \u002B 1] = new Vector4(0.0f, 0.0f, 0.0f, hole.Radius);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tdata[i * 2 \u002B 1] = new Vector4(1.0f, cursor, hole.Points.Length, 0.0f);\n\n\t\t\tforeach (var point in hole.Points)\n\t\t\t\tdata[cursor\u002B\u002B] = new Vector4(point.x, point.y, 0.0f, 0.0f);\n\t\t}\n\n\t\tm_SeaHoleBuffer.SetData(data.AsSpan());\n\t\tm_SeaHoleBounds = new Vector4(min.x, min.y, max.x, max.y);\n\n\t\tUpdateSeaHoleGrid(holes, min, max);\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The grid over the sea holes: per cell where its list of holes starts and how many it has, then the lists one after\n\t/// another, each hole listed in every cell its bounds reach into. A pixel of the sea tests only its own cell\u0027s holes,\n\t/// however many a river near sea level cuts. Cells are about the size of a hole (the middle one, so a single big lake\n\t/// doesn\u0027t make them all coarse), at most \u003Csee cref=\u0022MaxSeaHoleGrid\u0022/\u003E along either side.\n\t/// \u003C/summary\u003E\n\tprivate void UpdateSeaHoleGrid(List\u003CSeaHole\u003E _Holes, Vector2 _Min, Vector2 _Max)\n\t{\n\t\tvar sizes = new float[_Holes.Count];\n\n\t\tfor (int i = 0; i \u003C _Holes.Count; i\u002B\u002B)\n\t\t\tsizes[i] = MathF.Max(_Holes[i].Max.x - _Holes[i].Min.x, _Holes[i].Max.y - _Holes[i].Min.y);\n\n\t\tArray.Sort(sizes);\n\n\t\t// The same extent the shader divides by.\n\t\tfloat width = MathF.Max(_Max.x - _Min.x, 0.001f);\n\t\tfloat height = MathF.Max(_Max.y - _Min.y, 0.001f);\n\t\tfloat cell = MathF.Max(MathF.Max(sizes[sizes.Length / 2], 1.0f), MathF.Max(width, height) / MaxSeaHoleGrid);\n\t\tint columns = Math.Clamp((int)MathF.Ceiling(width / cell), 1, MaxSeaHoleGrid);\n\t\tint rows = Math.Clamp((int)MathF.Ceiling(height / cell), 1, MaxSeaHoleGrid);\n\t\tint cells = columns * rows;\n\n\t\t// The cells a hole reaches into, taken a hair wide, so the GPU\u0027s rounding never finds a pixel of it in a cell it\n\t\t// isn\u0027t listed in.\n\t\tvoid Range(SeaHole _Hole, out int _X0, out int _Y0, out int _X1, out int _Y1)\n\t\t{\n\t\t\t_X0 = Math.Clamp((int)MathF.Floor((_Hole.Min.x - _Min.x) / width * columns - 0.01f), 0, columns - 1);\n\t\t\t_Y0 = Math.Clamp((int)MathF.Floor((_Hole.Min.y - _Min.y) / height * rows - 0.01f), 0, rows - 1);\n\t\t\t_X1 = Math.Clamp((int)MathF.Floor((_Hole.Max.x - _Min.x) / width * columns \u002B 0.01f), 0, columns - 1);\n\t\t\t_Y1 = Math.Clamp((int)MathF.Floor((_Hole.Max.y - _Min.y) / height * rows \u002B 0.01f), 0, rows - 1);\n\t\t}\n\n\t\tvar counts = new int[cells];\n\n\t\tforeach (var hole in _Holes)\n\t\t{\n\t\t\tRange(hole, out int x0, out int y0, out int x1, out int y1);\n\n\t\t\tfor (int y = y0; y \u003C= y1; y\u002B\u002B)\n\t\t\t{\n\t\t\t\tfor (int x = x0; x \u003C= x1; x\u002B\u002B)\n\t\t\t\t\tcounts[y * columns \u002B x]\u002B\u002B;\n\t\t\t}\n\t\t}\n\n\t\tint listed = 0;\n\n\t\tforeach (int count in counts)\n\t\t\tlisted \u002B= count;\n\n\t\tvar grid = new int[cells * 2 \u002B listed];\n\t\tint cursor = 0;\n\n\t\tfor (int c = 0; c \u003C cells; c\u002B\u002B)\n\t\t{\n\t\t\tgrid[c * 2] = cursor;\n\t\t\tcursor \u002B= counts[c];\n\t\t}\n\n\t\tfor (int i = 0; i \u003C _Holes.Count; i\u002B\u002B)\n\t\t{\n\t\t\tRange(_Holes[i], out int x0, out int y0, out int x1, out int y1);\n\n\t\t\tfor (int y = y0; y \u003C= y1; y\u002B\u002B)\n\t\t\t{\n\t\t\t\tfor (int x = x0; x \u003C= x1; x\u002B\u002B)\n\t\t\t\t{\n\t\t\t\t\tint slot = (y * columns \u002B x) * 2;\n\t\t\t\t\tgrid[cells * 2 \u002B grid[slot] \u002B grid[slot \u002B 1]\u002B\u002B] = i;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tif (!m_SeaHoleGridBuffer.IsValid() || m_SeaHoleGridCapacity \u003C grid.Length)\n\t\t{\n\t\t\tm_SeaHoleGridBuffer?.Dispose();\n\t\t\tm_SeaHoleGridCapacity = Math.Max(grid.Length, m_SeaHoleGridCapacity * 2);\n\t\t\tm_SeaHoleGridBuffer = new GpuBuffer\u003Cint\u003E(m_SeaHoleGridCapacity, GpuBuffer.UsageFlags.Structured);\n\t\t}\n\n\t\tm_SeaHoleGridBuffer.SetData(grid.AsSpan());\n\t\tm_SeaHoleGridSize = new Vector2(columns, rows);\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// What the shader needs to know about the sea, on every draw: the coast zone and the river mouths rebuild the sea\u0027s\n\t/// surface from it, the rings draw it.\n\t/// \u003C/summary\u003E\n\tprivate void ApplySeaAttributes(RenderAttributes _Attributes)\n\t{\n\t\tResolvedSeaProfile.ApplyTo(_Attributes, \u0022Sea\u0022);\n\n\t\t_Attributes.Set(\u0022SeaScale\u0022, SeaWaves);\n\t\t_Attributes.Set(\u0022SeaLevel\u0022, WorldSeaLevel);\n\t\t_Attributes.Set(\u0022OceanRingCount\u0022, m_RingCount);\n\t\t_Attributes.Set(\u0022OceanGridCells\u0022, SeaRingCells);\n\t\t_Attributes.Set(\u0022SeaHoleCount\u0022, m_SeaHoleCount);\n\t\t_Attributes.Set(\u0022SeaHoleBounds\u0022, m_SeaHoleBounds);\n\t\t_Attributes.Set(\u0022SeaHoleGridSize\u0022, m_SeaHoleGridSize);\n\n\t\tif (m_RingBuffer.IsValid())\n\t\t\t_Attributes.Set(\u0022OceanRings\u0022, m_RingBuffer);\n\n\t\tif (m_SeaHoleBuffer.IsValid())\n\t\t\t_Attributes.Set(\u0022SeaHoles\u0022, m_SeaHoleBuffer);\n\n\t\tif (m_SeaHoleGridBuffer.IsValid())\n\t\t\t_Attributes.Set(\u0022SeaHoleGrid\u0022, m_SeaHoleGridBuffer);\n\n\t\tApplyCoastAttributes(_Attributes);\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The attributes each ring is drawn with: everything every piece gets, plus which ring it is.\n\t/// \u003C/summary\u003E\n\tprivate void UpdateRingAttributes()\n\t{\n\t\tif (m_RingAttributes.Length \u003C m_RingCount)\n\t\t{\n\t\t\tvar grown = new RenderAttributes[m_RingCount];\n\n\t\t\tfor (int i = 0; i \u003C grown.Length; i\u002B\u002B)\n\t\t\t\tgrown[i] = i \u003C m_RingAttributes.Length ? m_RingAttributes[i] : new RenderAttributes();\n\n\t\t\tm_RingAttributes = grown;\n\t\t}\n\n\t\tfor (int k = 0; k \u003C m_RingCount; k\u002B\u002B)\n\t\t{\n\t\t\tvar attributes = m_RingAttributes[k];\n\n\t\t\tApplySharedAttributes(attributes);\n\n\t\t\tattributes.Set(\u0022OceanRing\u0022, true);\n\t\t\tattributes.Set(\u0022RingIndex\u0022, k);\n\t\t}\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Records the rings. The finest is drawn first; each ring hides the part of itself the one inside it covers.\n\t/// \u003C/summary\u003E\n\tprivate void DrawSea(CommandList _CommandList, Material _Material)\n\t{\n\t\tif (m_RingCount == 0 || !m_RingVertices.IsValid() || !m_RingIndices.IsValid())\n\t\t\treturn;\n\n\t\tfor (int k = 0; k \u003C m_RingCount; k\u002B\u002B)\n\t\t\t_CommandList.DrawIndexed(m_RingVertices, m_RingIndices, _Material, 0, m_RingIndexCount, m_RingAttributes[k]);\n\t}\n\n\n\n\tprivate void ReleaseSea()\n\t{\n\t\tm_RingVertices?.Dispose();\n\t\tm_RingVertices = null;\n\n\t\tm_RingIndices?.Dispose();\n\t\tm_RingIndices = null;\n\n\t\tm_RingBuffer?.Dispose();\n\t\tm_RingBuffer = null;\n\n\t\tm_SeaHoleBuffer?.Dispose();\n\t\tm_SeaHoleBuffer = null;\n\t\tm_SeaHoleCapacity = 0;\n\t\tm_SeaHoleCount = 0;\n\n\t\tm_SeaHoleGridBuffer?.Dispose();\n\t\tm_SeaHoleGridBuffer = null;\n\t\tm_SeaHoleGridCapacity = 0;\n\t\tm_SeaHoleRevision = -1;\n\t\tm_SeaHoleZoneRevision = -1;\n\n\t\tReleaseCoast();\n\n\t\tm_RingCount = 0;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The sea\u0027s waves at a world point, at full strength (no ripples).\n\t/// \u003C/summary\u003E\n\tprivate Vector3 SeaDisplacementAt(Vector2 _Point)\n\t{\n\t\treturn WaterWaves.Displacement(_Point, ResolvedSeaProfile, Time.Now) * SeaWaves;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The open sea at a position: everywhere outside the coast zone (whose own surface carries its water), at sea level,\n\t/// down to its depth.\n\t/// \u003C/summary\u003E\n\tprivate bool SampleSea(Vector3 _Position, out WaterSample _Sample)\n\t{\n\t\t_Sample = default;\n\n\t\tif (!SeaEnabled)\n\t\t\treturn false;\n\n\t\tfloat level = WorldSeaLevel;\n\n\t\tif (_Position.z \u003C level - SeaDepth || IsInCoastZone(_Position))\n\t\t\treturn false;\n\n\t\tvar point = new Vector2(_Position.x, _Position.y);\n\t\tVector3 displacement = SeaDisplacementAt(point);\n\t\tdisplacement.z \u002B= ComputeRippleHeight(point);\n\n\t\t_Sample = new WaterSample(level, displacement, Vector3.Zero, SeaWaves, 0.0f, SeaDepth, 1.0f);\n\n\t\treturn true;\n\t}\n}\n"},{"Ident":"redsnail.watertool2","Path":"Building/EstuaryBuilder.cs","FileName":"EstuaryBuilder.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":445731,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\nusing Sandbox;\n\nnamespace RedSnail.WaterTool2;\n\n/// \u003Csummary\u003E\n/// Everything a river mouth is built from, copied out of the network so the build can run on a worker thread.\n/// \u003C/summary\u003E\ninternal sealed class MouthBuildInput\n{\n\t/// \u003Csummary\u003E\n\t/// The outline, in network space: the coast with the river\u0027s opening cut in, closed along the block\u0027s edge.\n\t/// \u003C/summary\u003E\n\tpublic List\u003COutlineVertex\u003E Outline;\n\n\t/// \u003Csummary\u003E\n\t/// The river\u0027s water carrying out into the sea, in network space.\n\t/// \u003C/summary\u003E\n\tpublic LakeJet Jet;\n\n\t/// \u003Csummary\u003E\n\t/// The river\u0027s own wave strength and water level on its last row.\n\t/// \u003C/summary\u003E\n\tpublic float Waves;\n\n\tpublic float Height;\n\n\t/// \u003Csummary\u003E\n\t/// The block the mouth is built in, in the world (in plan): its water is all sea by its edge.\n\t/// \u003C/summary\u003E\n\tpublic Vector2 Min;\n\n\tpublic Vector2 Max;\n\n\tpublic float SeaLevel;\n\tpublic float CellSize;\n\tpublic Transform Transform;\n}\n\n\n\n/// \u003Csummary\u003E\n/// Builds the water where a river opens into the sea: a block of the coast zone round the opening, bounded by the\n/// coast. Its outline takes in the river\u0027s last row point for point (the river runs into it as into a lake), and its\n/// edge out at sea is the sea itself, on the very points the rest of the coast zone has there. In between, the river\u0027s\n/// water carries out as a jet, the way it carries into a lake, handing over to the sea\u0027s as it spreads and slows, and\n/// all of it gone before the block\u0027s edge.\n/// \u003C/summary\u003E\ninternal static class EstuaryBuilder\n{\n\t/// \u003Csummary\u003E\n\t/// How far in from the block\u0027s edge the river\u0027s water has all given way to the sea, as a share of the block\u0027s size.\n\t/// \u003C/summary\u003E\n\tprivate const float EdgeFade = 0.2f;\n\n\t/// \u003Csummary\u003E\n\t/// Below these the river\u0027s water is left out of the mouth altogether: too little of it to see, and the sea alone\n\t/// costs half as much to draw as the two blended, still water less than flowing.\n\t/// \u003C/summary\u003E\n\tprivate const float MinPresence = 0.002f;\n\n\tprivate const float MinSpeed = 1.0f;\n\tprivate const float MinFoam = 0.01f;\n\n\n\n\tpublic static WaterMeshData Build(MouthBuildInput _Input)\n\t{\n\t\tvar outline = SurfaceMesher.Subdivide(_Input.Outline, _Input.CellSize);\n\t\tvar flat = new List\u003CVector2\u003E(outline.Count);\n\n\t\tforeach (var vertex in outline)\n\t\t\tflat.Add(new Vector2(vertex.Position.x, vertex.Position.y));\n\n\t\tif (!SurfaceMesher.Triangulate(flat, _Input.CellSize, out var points, out var triangles))\n\t\t\treturn null;\n\n\t\tint count = points.Count;\n\t\tvar mesh = new WaterMeshData(count);\n\t\tvar transform = _Input.Transform;\n\t\tfloat fadeWidth = MathF.Max(1.0f, MathF.Min(_Input.Max.x - _Input.Min.x, _Input.Max.y - _Input.Min.y) * EdgeFade);\n\n\t\tfor (int i = 0; i \u003C count; i\u002B\u002B)\n\t\t{\n\t\t\tbool onOutline = i \u003C outline.Count;\n\t\t\tvar vertex = onOutline ? outline[i] : default;\n\n\t\t\tif (onOutline \u0026\u0026 vertex.IsFixed)\n\t\t\t{\n\t\t\t\t// The river\u0027s own row, exactly as the river has it.\n\t\t\t\tmesh.Positions[i] = vertex.Position;\n\t\t\t\tmesh.Velocities[i] = vertex.Velocity;\n\t\t\t\tmesh.Waves[i] = vertex.Waves;\n\t\t\t\tmesh.Foams[i] = vertex.Foam;\n\t\t\t\tmesh.SeaBlend[i] = 0.0f;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (onOutline \u0026\u0026 vertex.SeaEdge)\n\t\t\t{\n\t\t\t\t// The sea: still, unfoamed, and at its level.\n\t\t\t\tmesh.Positions[i] = vertex.Position.WithZ(_Input.SeaLevel);\n\t\t\t\tmesh.Waves[i] = _Input.Waves;\n\t\t\t\tmesh.SeaBlend[i] = 1.0f;\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tvar point = new Vector2(points[i].x, points[i].y);\n\n\t\t\t// How far from the block\u0027s edge, where it must all be sea.\n\t\t\tVector3 world = transform.PointToWorld(new Vector3(point.x, point.y, _Input.SeaLevel));\n\t\t\tfloat edge = MathF.Min(MathF.Min(world.x - _Input.Min.x, _Input.Max.x - world.x), MathF.Min(world.y - _Input.Min.y, _Input.Max.y - world.y));\n\t\t\tfloat fade = LakeJet.SmoothStep(0.0f, fadeWidth, edge);\n\n\t\t\tfloat presence = _Input.Jet.Presence(point) * fade;\n\t\t\tVector2 velocity = _Input.Jet.Evaluate(point, out float foam) * fade;\n\t\t\tfoam = Math.Clamp(foam * fade, 0.0f, 1.0f);\n\n\t\t\tif (presence \u003C MinPresence)\n\t\t\t\tpresence = 0.0f;\n\t\t\telse if (presence \u003E 1.0f - MinPresence)\n\t\t\t\tpresence = 1.0f;\n\n\t\t\tif (velocity.LengthSquared \u003C MinSpeed * MinSpeed)\n\t\t\t\tvelocity = Vector2.Zero;\n\n\t\t\tif (foam \u003C MinFoam)\n\t\t\t\tfoam = 0.0f;\n\n\t\t\tmesh.Velocities[i] = velocity;\n\t\t\tmesh.Foams[i] = foam;\n\t\t\tmesh.Waves[i] = _Input.Waves;\n\t\t\tmesh.SeaBlend[i] = 1.0f - presence;\n\n\t\t\t// The shore and the flares keep the heights the outline gives them; inside, the river\u0027s level gives way to the\n\t\t\t// sea\u0027s with its water.\n\t\t\tmesh.Positions[i] = onOutline\n\t\t\t\t? vertex.Position\n\t\t\t\t: new Vector3(point.x, point.y, _Input.SeaLevel \u002B (_Input.Height - _Input.SeaLevel) * presence);\n\t\t}\n\n\t\tmesh.Finish(transform, triangles);\n\n\t\treturn mesh;\n\t}\n}\n"},{"Ident":"redsnail.watertool2","Path":"Code/Building/CoastScanner.cs","FileName":"CoastScanner.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":445731,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\nusing Sandbox;\n\nnamespace RedSnail.WaterTool2;\n\n/// \u003Csummary\u003E\n/// Turns a scan of the ground into coastlines: closed loops round every piece of land the open sea reaches. The scan is\n/// a grid of heights relative to the coast\u0027s height (land where positive); the open sea is whatever below that the\n/// scan\u0027s edge connects to, so a basin inland, however low, is land and the sea never floods it.\n/// \u003C/summary\u003E\ninternal static class CoastScanner\n{\n\t/// \u003Csummary\u003E\n\t/// The coastlines in a scan: \u003Cparamref name=\u0022_Field\u0022/\u003E holds, at every grid point (row after row, \u003Cparamref\n\t/// name=\u0022_Width\u0022/\u003E to a row), how far the ground is above the coast\u0027s height. The scan\u0027s edge is taken as open sea.\n\t/// Each loop is in the world (in plan), simplified to within a quarter of a grid step; loops round less land than\n\t/// \u003Cparamref name=\u0022_MinArea\u0022/\u003E are left out. The field is changed in place.\n\t/// \u003C/summary\u003E\n\tpublic static List\u003CVector2[]\u003E Extract(float[] _Field, int _Width, int _Height, Vector2 _Origin, float _Step, float _MinArea)\n\t{\n\t\tvar loops = new List\u003CVector2[]\u003E();\n\n\t\tif (_Width \u003C 3 || _Height \u003C 3)\n\t\t\treturn loops;\n\n\t\t// The scan\u0027s edge is the open sea, whatever is there.\n\t\tfor (int i = 0; i \u003C _Width; i\u002B\u002B)\n\t\t{\n\t\t\t_Field[i] = MathF.Min(_Field[i], -1.0f);\n\t\t\t_Field[(_Height - 1) * _Width \u002B i] = MathF.Min(_Field[(_Height - 1) * _Width \u002B i], -1.0f);\n\t\t}\n\n\t\tfor (int j = 0; j \u003C _Height; j\u002B\u002B)\n\t\t{\n\t\t\t_Field[j * _Width] = MathF.Min(_Field[j * _Width], -1.0f);\n\t\t\t_Field[j * _Width \u002B _Width - 1] = MathF.Min(_Field[j * _Width \u002B _Width - 1], -1.0f);\n\t\t}\n\n\t\tFillBasins(_Field, _Width, _Height);\n\n\t\tvar next = Contour(_Field, _Width, _Height);\n\t\tvar visited = new HashSet\u003Cint\u003E();\n\n\t\tforeach (int start in next.Keys)\n\t\t{\n\t\t\tif (visited.Contains(start))\n\t\t\t\tcontinue;\n\n\t\t\tvar loop = new List\u003CVector2\u003E();\n\t\t\tint edge = start;\n\t\t\tbool closed = false;\n\n\t\t\twhile (visited.Add(edge))\n\t\t\t{\n\t\t\t\tloop.Add(Crossing(_Field, _Width, _Origin, _Step, edge));\n\n\t\t\t\tif (!next.TryGetValue(edge, out int following))\n\t\t\t\t\tbreak;\n\n\t\t\t\tedge = following;\n\t\t\t\tclosed = edge == start;\n\t\t\t}\n\n\t\t\tif (!closed || loop.Count \u003C 3)\n\t\t\t\tcontinue;\n\n\t\t\tvar simplified = SimplifyClosed(loop, _Step * 0.25f);\n\n\t\t\t// Land is on the right of the way round, so a loop round land runs clockwise; one the other way round would be\n\t\t\t// sea shut in by land, which the fill has already made land.\n\t\t\tfloat area = SignedArea(simplified);\n\n\t\t\tif (simplified.Count \u003C 3 || area \u003E 0.0f || -area \u003C _MinArea)\n\t\t\t\tcontinue;\n\n\t\t\tloops.Add(simplified.ToArray());\n\t\t}\n\n\t\treturn loops;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Everything below the coast\u0027s height that the open sea doesn\u0027t reach (through the grid, edge to edge) becomes land.\n\t/// \u003C/summary\u003E\n\tprivate static void FillBasins(float[] _Field, int _Width, int _Height)\n\t{\n\t\tvar sea = new bool[_Field.Length];\n\t\tvar queue = new Queue\u003Cint\u003E();\n\n\t\tfor (int i = 0; i \u003C _Field.Length; i\u002B\u002B)\n\t\t{\n\t\t\tint x = i % _Width;\n\t\t\tint y = i / _Width;\n\n\t\t\tif ((x == 0 || y == 0 || x == _Width - 1 || y == _Height - 1) \u0026\u0026 _Field[i] \u003C= 0.0f)\n\t\t\t{\n\t\t\t\tsea[i] = true;\n\t\t\t\tqueue.Enqueue(i);\n\t\t\t}\n\t\t}\n\n\t\twhile (queue.Count \u003E 0)\n\t\t{\n\t\t\tint i = queue.Dequeue();\n\t\t\tint x = i % _Width;\n\t\t\tint y = i / _Width;\n\n\t\t\tVisit(x - 1, y);\n\t\t\tVisit(x \u002B 1, y);\n\t\t\tVisit(x, y - 1);\n\t\t\tVisit(x, y \u002B 1);\n\t\t}\n\n\t\tfor (int i = 0; i \u003C _Field.Length; i\u002B\u002B)\n\t\t{\n\t\t\tif (!sea[i] \u0026\u0026 _Field[i] \u003C= 0.0f)\n\t\t\t\t_Field[i] = 0.01f;\n\t\t}\n\n\t\tvoid Visit(int _X, int _Y)\n\t\t{\n\t\t\tif (_X \u003C 0 || _Y \u003C 0 || _X \u003E= _Width || _Y \u003E= _Height)\n\t\t\t\treturn;\n\n\t\t\tint index = _Y * _Width \u002B _X;\n\n\t\t\tif (sea[index] || _Field[index] \u003E 0.0f)\n\t\t\t\treturn;\n\n\t\t\tsea[index] = true;\n\t\t\tqueue.Enqueue(index);\n\t\t}\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Marching squares: every grid cell the coast crosses gives a piece of it, from edge to edge, with the land on its\n\t/// right. Edges are numbered so a piece leaving one cell through an edge is the piece that enters the next cell\n\t/// through it: the result maps every crossed edge to the next one along the coast.\n\t/// \u003C/summary\u003E\n\tprivate static Dictionary\u003Cint, int\u003E Contour(float[] _Field, int _Width, int _Height)\n\t{\n\t\tvar next = new Dictionary\u003Cint, int\u003E();\n\t\tvar edges = new int[4];\n\t\tvar corners = new bool[4];\n\t\tvar crossEdges = new int[4];\n\t\tvar crossIntoLand = new bool[4];\n\n\t\tfor (int y = 0; y \u003C _Height - 1; y\u002B\u002B)\n\t\t{\n\t\t\tfor (int x = 0; x \u003C _Width - 1; x\u002B\u002B)\n\t\t\t{\n\t\t\t\tfloat f00 = _Field[y * _Width \u002B x];\n\t\t\t\tfloat f10 = _Field[y * _Width \u002B x \u002B 1];\n\t\t\t\tfloat f11 = _Field[(y \u002B 1) * _Width \u002B x \u002B 1];\n\t\t\t\tfloat f01 = _Field[(y \u002B 1) * _Width \u002B x];\n\n\t\t\t\t// Round the cell counter-clockwise: bottom, right, top, left.\n\t\t\t\tcorners[0] = f00 \u003E 0.0f;\n\t\t\t\tcorners[1] = f10 \u003E 0.0f;\n\t\t\t\tcorners[2] = f11 \u003E 0.0f;\n\t\t\t\tcorners[3] = f01 \u003E 0.0f;\n\n\t\t\t\tif (corners[0] == corners[1] \u0026\u0026 corners[1] == corners[2] \u0026\u0026 corners[2] == corners[3])\n\t\t\t\t\tcontinue;\n\n\t\t\t\tedges[0] = HorizontalEdge(x, y, _Width);\n\t\t\t\tedges[1] = VerticalEdge(x \u002B 1, y, _Width);\n\t\t\t\tedges[2] = HorizontalEdge(x, y \u002B 1, _Width);\n\t\t\t\tedges[3] = VerticalEdge(x, y, _Width);\n\n\t\t\t\tint crossings = 0;\n\n\t\t\t\tfor (int k = 0; k \u003C 4; k\u002B\u002B)\n\t\t\t\t{\n\t\t\t\t\tbool from = corners[k];\n\t\t\t\t\tbool to = corners[(k \u002B 1) % 4];\n\n\t\t\t\t\tif (from == to)\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tcrossEdges[crossings] = edges[k];\n\t\t\t\t\tcrossIntoLand[crossings] = to;\n\t\t\t\t\tcrossings\u002B\u002B;\n\t\t\t\t}\n\n\t\t\t\t// A piece runs from where the way round goes into the land to where it comes out, which keeps the land on\n\t\t\t\t// its right. A saddle has two: they cut off the land corners when the middle is sea, the sea corners when\n\t\t\t\t// it is land.\n\t\t\t\tbool middleLand = f00 \u002B f10 \u002B f11 \u002B f01 \u003E 0.0f;\n\n\t\t\t\tfor (int k = 0; k \u003C crossings; k\u002B\u002B)\n\t\t\t\t{\n\t\t\t\t\tif (!crossIntoLand[k])\n\t\t\t\t\t\tcontinue;\n\n\t\t\t\t\tint partner = crossings == 4 \u0026\u0026 middleLand ? (k \u002B crossings - 1) % crossings : (k \u002B 1) % crossings;\n\n\t\t\t\t\tnext[crossEdges[k]] = crossEdges[partner];\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\treturn next;\n\t}\n\n\n\n\tprivate static int HorizontalEdge(int _X, int _Y, int _Width)\n\t{\n\t\treturn (_Y * _Width \u002B _X) * 2;\n\t}\n\n\n\n\tprivate static int VerticalEdge(int _X, int _Y, int _Width)\n\t{\n\t\treturn (_Y * _Width \u002B _X) * 2 \u002B 1;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Where the coast crosses a grid edge, between its two points\u0027 heights.\n\t/// \u003C/summary\u003E\n\tprivate static Vector2 Crossing(float[] _Field, int _Width, Vector2 _Origin, float _Step, int _Edge)\n\t{\n\t\tint cell = _Edge / 2;\n\t\tint x = cell % _Width;\n\t\tint y = cell / _Width;\n\t\tbool vertical = (_Edge \u0026 1) == 1;\n\n\t\tfloat a = _Field[y * _Width \u002B x];\n\t\tfloat b = vertical ? _Field[(y \u002B 1) * _Width \u002B x] : _Field[y * _Width \u002B x \u002B 1];\n\t\tfloat t = Math.Clamp(a / (a - b), 0.01f, 0.99f);\n\n\t\treturn vertical\n\t\t\t? new Vector2(_Origin.x \u002B x * _Step, _Origin.y \u002B (y \u002B t) * _Step)\n\t\t\t: new Vector2(_Origin.x \u002B (x \u002B t) * _Step, _Origin.y \u002B y * _Step);\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Douglas-Peucker on a closed loop: split at the point furthest from the first, each half simplified on its own.\n\t/// \u003C/summary\u003E\n\tprivate static List\u003CVector2\u003E SimplifyClosed(List\u003CVector2\u003E _Loop, float _Tolerance)\n\t{\n\t\tif (_Loop.Count \u003C 8)\n\t\t\treturn _Loop;\n\n\t\tint far = 0;\n\t\tfloat farthest = -1.0f;\n\n\t\tfor (int i = 1; i \u003C _Loop.Count; i\u002B\u002B)\n\t\t{\n\t\t\tfloat distance = _Loop[i].Distance(_Loop[0]);\n\n\t\t\tif (distance \u003C= farthest)\n\t\t\t\tcontinue;\n\n\t\t\tfarthest = distance;\n\t\t\tfar = i;\n\t\t}\n\n\t\tvar keep = new bool[_Loop.Count \u002B 1];\n\t\tkeep[0] = true;\n\t\tkeep[far] = true;\n\t\tkeep[_Loop.Count] = true;\n\n\t\tSimplify(_Loop, 0, far, _Tolerance, keep);\n\t\tSimplify(_Loop, far, _Loop.Count, _Tolerance, keep);\n\n\t\tvar result = new List\u003CVector2\u003E();\n\n\t\tfor (int i = 0; i \u003C _Loop.Count; i\u002B\u002B)\n\t\t{\n\t\t\tif (keep[i])\n\t\t\t\tresult.Add(_Loop[i]);\n\t\t}\n\n\t\treturn result;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Marks which points between two kept ones stay (index \u003Cc\u003ECount\u003C/c\u003E is the first point again), without recursion.\n\t/// \u003C/summary\u003E\n\tprivate static void Simplify(List\u003CVector2\u003E _Loop, int _From, int _To, float _Tolerance, bool[] _Keep)\n\t{\n\t\tvar stack = new Stack\u003C(int From, int To)\u003E();\n\t\tstack.Push((_From, _To));\n\n\t\twhile (stack.Count \u003E 0)\n\t\t{\n\t\t\tvar (from, to) = stack.Pop();\n\n\t\t\tif (to - from \u003C 2)\n\t\t\t\tcontinue;\n\n\t\t\tVector2 a = _Loop[from];\n\t\t\tVector2 b = _Loop[to % _Loop.Count];\n\t\t\tint worst = -1;\n\t\t\tfloat worstDistance = _Tolerance;\n\n\t\t\tfor (int i = from \u002B 1; i \u003C to; i\u002B\u002B)\n\t\t\t{\n\t\t\t\tfloat distance = DistanceToSegment(_Loop[i], a, b);\n\n\t\t\t\tif (distance \u003C= worstDistance)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tworst = i;\n\t\t\t\tworstDistance = distance;\n\t\t\t}\n\n\t\t\tif (worst \u003C 0)\n\t\t\t\tcontinue;\n\n\t\t\t_Keep[worst] = true;\n\t\t\tstack.Push((from, worst));\n\t\t\tstack.Push((worst, to));\n\t\t}\n\t}\n\n\n\n\tprivate static float DistanceToSegment(Vector2 _Point, Vector2 _A, Vector2 _B)\n\t{\n\t\tVector2 span = _B - _A;\n\t\tfloat lengthSquared = span.LengthSquared;\n\t\tfloat t = lengthSquared \u003E 0.0f ? Math.Clamp(Vector2.Dot(_Point - _A, span) / lengthSquared, 0.0f, 1.0f) : 0.0f;\n\n\t\treturn (_A \u002B span * t).Distance(_Point);\n\t}\n\n\n\n\tprivate static float SignedArea(List\u003CVector2\u003E _Loop)\n\t{\n\t\tfloat area = 0.0f;\n\n\t\tfor (int i = 0; i \u003C _Loop.Count; i\u002B\u002B)\n\t\t{\n\t\t\tVector2 a = _Loop[i];\n\t\t\tVector2 b = _Loop[(i \u002B 1) % _Loop.Count];\n\n\t\t\tarea \u002B= a.x * b.y - b.x * a.y;\n\t\t}\n\n\t\treturn area * 0.5f;\n\t}\n}\n"},{"Ident":"redsnail.watertool2","Path":"Code/Building/JunctionBuilder.cs","FileName":"JunctionBuilder.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":445731,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\nusing Sandbox;\n\nnamespace RedSnail.WaterTool2;\n\n/// \u003Csummary\u003E\n/// Builds the water where rivers meet: the confluence\u0027s outline triangulated with points all over its inside, and the\n/// water\u0027s state (flow, wave strength, foam and height) spread smoothly from the rows of the rivers into the middle.\n/// The rows are held exactly as the rivers have them, so each river runs into the confluence without a seam, and in\n/// between the currents meet and turn into each other.\n/// \u003C/summary\u003E\ninternal static class JunctionBuilder\n{\n\tpublic static WaterMeshData Build(List\u003COutlineVertex\u003E _Outline, Vector3 _Centre, float _CellSize, in Transform _Transform)\n\t{\n\t\tvar outline = SurfaceMesher.Subdivide(_Outline, _CellSize);\n\t\tvar flat = new List\u003CVector2\u003E(outline.Count);\n\n\t\tforeach (var vertex in outline)\n\t\t\tflat.Add(new Vector2(vertex.Position.x, vertex.Position.y));\n\n\t\tif (!SurfaceMesher.Triangulate(flat, _CellSize, out var points, out var triangles))\n\t\t\treturn BuildFan(outline, _Centre, _Transform);\n\n\t\tint count = points.Count;\n\t\tvar mesh = new WaterMeshData(count);\n\t\tvar fixedState = new bool[count];\n\t\tvar fixedHeight = new bool[count];\n\n\t\t// What the inside starts from before it is relaxed: the average of the rows.\n\t\tVector2 velocitySum = Vector2.Zero;\n\t\tfloat wavesSum = 0.0f;\n\t\tfloat foamSum = 0.0f;\n\t\tfloat heightSum = 0.0f;\n\t\tint rowPoints = 0;\n\n\t\tforeach (var vertex in outline)\n\t\t{\n\t\t\tif (!vertex.IsFixed)\n\t\t\t\tcontinue;\n\n\t\t\tvelocitySum \u002B= vertex.Velocity;\n\t\t\twavesSum \u002B= vertex.Waves;\n\t\t\tfoamSum \u002B= vertex.Foam;\n\t\t\theightSum \u002B= vertex.Position.z;\n\t\t\trowPoints\u002B\u002B;\n\t\t}\n\n\t\tfloat divisor = MathF.Max(1, rowPoints);\n\t\tVector2 velocityStart = velocitySum / divisor;\n\t\tfloat wavesStart = wavesSum / divisor;\n\t\tfloat foamStart = foamSum / divisor;\n\t\tfloat heightStart = rowPoints \u003E 0 ? heightSum / divisor : _Centre.z;\n\n\t\tfor (int i = 0; i \u003C count; i\u002B\u002B)\n\t\t{\n\t\t\tif (i \u003C outline.Count)\n\t\t\t{\n\t\t\t\tvar vertex = outline[i];\n\n\t\t\t\tmesh.Positions[i] = vertex.Position;\n\t\t\t\tfixedHeight[i] = true;\n\n\t\t\t\tif (vertex.IsFixed)\n\t\t\t\t{\n\t\t\t\t\tmesh.Velocities[i] = vertex.Velocity;\n\t\t\t\t\tmesh.Waves[i] = vertex.Waves;\n\t\t\t\t\tmesh.Foams[i] = vertex.Foam;\n\t\t\t\t\tfixedState[i] = true;\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tmesh.Positions[i] = new Vector3(points[i].x, points[i].y, heightStart);\n\t\t\t}\n\n\t\t\tmesh.Velocities[i] = velocityStart;\n\t\t\tmesh.Waves[i] = wavesStart;\n\t\t\tmesh.Foams[i] = foamStart;\n\t\t}\n\n\t\tRelax(mesh, triangles, fixedState, fixedHeight, false);\n\n\t\tmesh.Finish(_Transform, triangles, true);\n\n\t\treturn mesh;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Spreads the water\u0027s state inward from the rows: every point that is not on a row becomes the average of its\n\t/// neighbours, again and again until it settles (successive over-relaxation, so a few dozen sweeps are enough).\n\t/// The banks\u0027 heights are kept, the inside\u0027s eased between them. With \u003Cparamref name=\u0022_SeaBlend\u0022/\u003E the hand-over to\n\t/// the sea is spread the same way.\n\t/// \u003C/summary\u003E\n\tinternal static void Relax(WaterMeshData _Mesh, List\u003Cint\u003E _Triangles, bool[] _FixedState, bool[] _FixedHeight, bool _SeaBlend)\n\t{\n\t\tint count = _Mesh.VertexCount;\n\t\tvar neighbours = new List\u003Cint\u003E[count];\n\n\t\tfor (int i = 0; i \u003C count; i\u002B\u002B)\n\t\t\tneighbours[i] = new List\u003Cint\u003E(6);\n\n\t\tfor (int t = 0; t \u002B 2 \u003C _Triangles.Count; t \u002B= 3)\n\t\t{\n\t\t\tfor (int k = 0; k \u003C 3; k\u002B\u002B)\n\t\t\t{\n\t\t\t\tint a = _Triangles[t \u002B k];\n\t\t\t\tint b = _Triangles[t \u002B (k \u002B 1) % 3];\n\n\t\t\t\tif (!neighbours[a].Contains(b))\n\t\t\t\t\tneighbours[a].Add(b);\n\n\t\t\t\tif (!neighbours[b].Contains(a))\n\t\t\t\t\tneighbours[b].Add(a);\n\t\t\t}\n\t\t}\n\n\t\tconst float overRelaxation = 1.7f;\n\t\tint sweeps = Math.Clamp((int)(MathF.Sqrt(count) * 3.0f), 30, 400);\n\n\t\tfor (int sweep = 0; sweep \u003C sweeps; sweep\u002B\u002B)\n\t\t{\n\t\t\tfor (int i = 0; i \u003C count; i\u002B\u002B)\n\t\t\t{\n\t\t\t\tvar around = neighbours[i];\n\n\t\t\t\tif (around.Count == 0)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tif (!_FixedState[i])\n\t\t\t\t{\n\t\t\t\t\tVector2 velocity = Vector2.Zero;\n\t\t\t\t\tfloat waves = 0.0f;\n\t\t\t\t\tfloat foam = 0.0f;\n\n\t\t\t\t\tforeach (int n in around)\n\t\t\t\t\t{\n\t\t\t\t\t\tvelocity \u002B= _Mesh.Velocities[n];\n\t\t\t\t\t\twaves \u002B= _Mesh.Waves[n];\n\t\t\t\t\t\tfoam \u002B= _Mesh.Foams[n];\n\t\t\t\t\t}\n\n\t\t\t\t\tfloat inverse = 1.0f / around.Count;\n\n\t\t\t\t\t_Mesh.Velocities[i] \u002B= (velocity * inverse - _Mesh.Velocities[i]) * overRelaxation;\n\t\t\t\t\t_Mesh.Waves[i] \u002B= (waves * inverse - _Mesh.Waves[i]) * overRelaxation;\n\t\t\t\t\t_Mesh.Foams[i] \u002B= (foam * inverse - _Mesh.Foams[i]) * overRelaxation;\n\n\t\t\t\t\tif (_SeaBlend)\n\t\t\t\t\t{\n\t\t\t\t\t\tfloat blend = 0.0f;\n\n\t\t\t\t\t\tforeach (int n in around)\n\t\t\t\t\t\t\tblend \u002B= _Mesh.SeaBlend[n];\n\n\t\t\t\t\t\t_Mesh.SeaBlend[i] \u002B= (blend * inverse - _Mesh.SeaBlend[i]) * overRelaxation;\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\tif (!_FixedHeight[i])\n\t\t\t\t{\n\t\t\t\t\tfloat height = 0.0f;\n\n\t\t\t\t\tforeach (int n in around)\n\t\t\t\t\t\theight \u002B= _Mesh.Positions[n].z;\n\n\t\t\t\t\tvar position = _Mesh.Positions[i];\n\t\t\t\t\tposition.z \u002B= (height / around.Count - position.z) * overRelaxation;\n\t\t\t\t\t_Mesh.Positions[i] = position;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\t// Over-relaxation can overshoot a hair past the rows\u0027 range; nothing here can be negative.\n\t\tfor (int i = 0; i \u003C count; i\u002B\u002B)\n\t\t{\n\t\t\t_Mesh.Waves[i] = MathF.Max(0.0f, _Mesh.Waves[i]);\n\t\t\t_Mesh.Foams[i] = Math.Clamp(_Mesh.Foams[i], 0.0f, 1.0f);\n\t\t\t_Mesh.SeaBlend[i] = Math.Clamp(_Mesh.SeaBlend[i], 0.0f, 1.0f);\n\t\t}\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The fallback for an outline that could not be triangulated properly (it folds over itself somewhere): a fan from\n\t/// the node, so the confluence is at least covered.\n\t/// \u003C/summary\u003E\n\tprivate static WaterMeshData BuildFan(List\u003COutlineVertex\u003E _Outline, Vector3 _Centre, in Transform _Transform)\n\t{\n\t\tint count = _Outline.Count;\n\t\tvar mesh = new WaterMeshData(count \u002B 1);\n\t\tvar indices = new List\u003Cint\u003E(count * 3);\n\n\t\tVector2 velocity = Vector2.Zero;\n\t\tfloat waves = 0.0f;\n\t\tfloat foam = 0.0f;\n\t\tint rowPoints = 0;\n\n\t\tfor (int i = 0; i \u003C count; i\u002B\u002B)\n\t\t{\n\t\t\tvar vertex = _Outline[i];\n\n\t\t\tmesh.Positions[i] = vertex.Position;\n\t\t\tmesh.Velocities[i] = vertex.Velocity;\n\t\t\tmesh.Waves[i] = vertex.Waves;\n\t\t\tmesh.Foams[i] = vertex.Foam;\n\n\t\t\tif (vertex.IsFixed)\n\t\t\t{\n\t\t\t\tvelocity \u002B= vertex.Velocity;\n\t\t\t\twaves \u002B= vertex.Waves;\n\t\t\t\tfoam \u002B= vertex.Foam;\n\t\t\t\trowPoints\u002B\u002B;\n\t\t\t}\n\t\t}\n\n\t\tfloat divisor = MathF.Max(1, rowPoints);\n\n\t\tmesh.Positions[count] = _Centre;\n\t\tmesh.Velocities[count] = velocity / divisor;\n\t\tmesh.Waves[count] = waves / divisor;\n\t\tmesh.Foams[count] = foam / divisor;\n\n\t\tfor (int i = 0; i \u003C count; i\u002B\u002B)\n\t\t{\n\t\t\tif (_Outline[i].IsFixed)\n\t\t\t\tcontinue;\n\n\t\t\tmesh.Velocities[i] = mesh.Velocities[count];\n\t\t\tmesh.Waves[i] = mesh.Waves[count];\n\t\t\tmesh.Foams[i] = mesh.Foams[count];\n\t\t}\n\n\t\tfor (int i = 0; i \u003C count; i\u002B\u002B)\n\t\t{\n\t\t\tindices.Add(count);\n\t\t\tindices.Add(i);\n\t\t\tindices.Add((i \u002B 1) % count);\n\t\t}\n\n\t\tmesh.Finish(_Transform, indices, true);\n\n\t\treturn mesh;\n\t}\n}\n"}]}