{"TotalCount":93,"Files":[{"Ident":"redsnail.roadtool2","Path":"Network/RoadBorderTaper.cs","FileName":"RoadBorderTaper.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":443665,"IsPrivate":false,"Code":"using System;\r\nusing Sandbox;\r\n\r\nnamespace RedSnail.RoadTool2;\r\n\r\n/// \u003Csummary\u003E\r\n/// How one side\u0027s border tapers at either end of a segment: over the given length from the node its relief (kerb\r\n/// height, verge drop) runs to the share of itself given for that end \u2014 nothing when the other border is of another\r\n/// kind, the height the two meet at when it is of the same kind \u2014 and its width runs to the width the two meet at,\r\n/// so the two borders meet flush at the node. A zero length is no taper. An end marked as a spill has a country road\r\n/// on the other side, whose gravel is blended onto the border there. A gore end is the nose where this road and\r\n/// another diverge from one edge: the border there grows from nothing as the square of the distance, the way the gap\r\n/// between two roads parting from a common tangent opens up, so the two borders fill the gore between them without\r\n/// crossing.\r\n/// \u003C/summary\u003E\r\n/// \u003Cparam name=\u0022StartRelief\u0022\u003E\r\n/// The share of the profile\u0027s own relief the border has at the start node: 0 flattens it into the road, 1 leaves\r\n/// it as it is, and anything else brings it to a height it shares with the border on the other side (above 1 for\r\n/// the lower of the two).\r\n/// \u003C/param\u003E\r\n/// \u003Cparam name=\u0022StartOffset\u0022\u003E\r\n/// How far from the start node the taper ends: 0 at a plain pass-through, the arm\u0027s trim at a junction, where the\r\n/// corner starts. Everything nearer the node than that \u2014 the corner itself \u2014 is built in the shape the taper runs\r\n/// to, so the two roads round a corner meet in one cross-section instead of turning into each other on the arc.\r\n/// \u003C/param\u003E\r\npublic readonly record struct RoadBorderTaper(float StartLength, float StartWidth, float StartRelief, bool StartSpill, float EndLength, float EndWidth, float EndRelief, bool EndSpill, bool StartGore = false, bool EndGore = false, float StartOffset = 0.0f, float EndOffset = 0.0f)\r\n{\r\n\t/// \u003Csummary\u003E\r\n\t/// The share of the profile\u0027s relief in force at a curve distance (1 away from any taper, that end\u0027s relief at\r\n\t/// its node, and beyond its offset), how far along a taper the point is (0 outside one), the width the border is\r\n\t/// that far towards, and whether that taper\u0027s neighbour spills onto it. The two ends\u0027 tapers, offsets included,\r\n\t/// are each held to half the segment, so no point is ever inside both.\r\n\t/// \u003C/summary\u003E\r\n\tpublic float ReliefAt(float _Along, float _Length, out float _Towards, out float _TargetWidth, out bool _Spill)\r\n\t{\r\n\t\tfloat relief = 1.0f;\r\n\r\n\t\t_Towards = 0.0f;\r\n\t\t_TargetWidth = 0.0f;\r\n\t\t_Spill = false;\r\n\r\n\t\tif (StartLength \u003E 0.0f \u0026\u0026 _Along \u003C StartOffset \u002B StartLength)\r\n\t\t{\r\n\t\t\tfloat progress = Math.Clamp((_Along - StartOffset) / StartLength, 0.0f, 1.0f);\r\n\r\n\t\t\t_Towards = Towards(progress, StartGore);\r\n\t\t\t_TargetWidth = StartWidth;\r\n\t\t\t_Spill = StartSpill;\r\n\t\t\trelief = MathX.Lerp(StartRelief, 1.0f, progress);\r\n\t\t}\r\n\r\n\t\tif (EndLength \u003E 0.0f \u0026\u0026 _Length - _Along \u003C EndOffset \u002B EndLength)\r\n\t\t{\r\n\t\t\tfloat progress = Math.Clamp((_Length - _Along - EndOffset) / EndLength, 0.0f, 1.0f);\r\n\t\t\tfloat towards = Towards(progress, EndGore);\r\n\r\n\t\t\tif (towards \u003E _Towards)\r\n\t\t\t{\r\n\t\t\t\t_Towards = towards;\r\n\t\t\t\t_TargetWidth = EndWidth;\r\n\t\t\t\t_Spill = EndSpill;\r\n\t\t\t\trelief = MathX.Lerp(EndRelief, 1.0f, progress);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn relief;\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// How far towards the node\u0027s width the border is at a progress along the taper (0 at the node, 1 at its far\r\n\t/// end): straight along a plain taper, and along a gore the square, so the width is the square of the progress.\r\n\t/// \u003C/summary\u003E\r\n\tprivate static float Towards(float _Progress, bool _Gore)\r\n\t{\r\n\t\treturn _Gore ? 1.0f - _Progress * _Progress : 1.0f - _Progress;\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The factor the border\u0027s nominal width is scaled by at a curve distance, on its way to the neighbour\u0027s.\r\n\t/// \u003C/summary\u003E\r\n\tpublic float WidthScaleAt(float _Along, float _Length, float _NominalWidth)\r\n\t{\r\n\t\tReliefAt(_Along, _Length, out float towards, out float targetWidth, out _);\r\n\r\n\t\tif (towards \u003C= 0.0f || _NominalWidth \u003C= 0.001f)\r\n\t\t\treturn 1.0f;\r\n\r\n\t\treturn (_NominalWidth \u002B (targetWidth - _NominalWidth) * towards) / _NominalWidth;\r\n\t}\r\n\r\n\r\n\r\n\tpublic void AddToHash(ref StableHash _Hash)\r\n\t{\r\n\t\t_Hash.Add(StartLength);\r\n\t\t_Hash.Add(StartWidth);\r\n\t\t_Hash.Add(StartRelief);\r\n\t\t_Hash.Add(StartSpill ? 1 : 0);\r\n\t\t_Hash.Add(StartGore ? 1 : 0);\r\n\t\t_Hash.Add(StartOffset);\r\n\t\t_Hash.Add(EndLength);\r\n\t\t_Hash.Add(EndWidth);\r\n\t\t_Hash.Add(EndRelief);\r\n\t\t_Hash.Add(EndSpill ? 1 : 0);\r\n\t\t_Hash.Add(EndGore ? 1 : 0);\r\n\t\t_Hash.Add(EndOffset);\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Whether the border tapers at the end a node is at.\r\n\t/// \u003C/summary\u003E\r\n\tpublic bool TapersAt(bool _AtStart)\r\n\t{\r\n\t\treturn _AtStart ? StartLength \u003E 0.0f : EndLength \u003E 0.0f;\r\n\t}\r\n}\r\n\r\n/// \u003Csummary\u003E\r\n/// The tapers of a segment\u0027s two borders, looking along the segment.\r\n/// \u003C/summary\u003E\r\npublic readonly record struct SegmentBorderTapers(RoadBorderTaper Left, RoadBorderTaper Right)\r\n{\r\n\tpublic RoadBorderTaper Side(bool _Left)\r\n\t{\r\n\t\treturn _Left ? Left : Right;\r\n\t}\r\n\r\n\tpublic void AddToHash(ref StableHash _Hash)\r\n\t{\r\n\t\tLeft.AddToHash(ref _Hash);\r\n\t\tRight.AddToHash(ref _Hash);\r\n\t}\r\n}\r\n"},{"Ident":"redsnail.roadtool2","Path":"Network/RoadSurfaceBuilder.cs","FileName":"RoadSurfaceBuilder.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":443665,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\nusing Sandbox;\nusing Sandbox.Utility;\n\nnamespace RedSnail.RoadTool2;\n\n/// \u003Csummary\u003E\n/// Generates the road surface of one chunk: a strip of cells between cross-section frames at the rows the chunk is\n/// built on (even distances along the segment\u0027s curve, thinned where the road type allows it).\n/// \u003C/summary\u003E\ninternal static class RoadSurfaceBuilder\n{\n\t/// \u003Csummary\u003E\n\t/// How far one corner of a cell may sit off the plane of the other three before two triangles stop doing for it.\n\t/// A road that climbs as it turns has level rows that swing round from one to the next, so its inside edge\n\t/// climbs more steeply than its outside edge and every cell is twisted. Two triangles then give the middle of the\n\t/// road one slope up to the diagonal and another after it: a step in every cell, which the centre line, lying on\n\t/// the surface as built, shows as a staircase.\n\t/// \u003C/summary\u003E\n\tprivate const float MaxTwist = 0.25f;\n\n\t/// \u003Csummary\u003E\n\t/// The widest strip a twisted road is cut into lengthways.\n\t/// \u003C/summary\u003E\n\tprivate const float MaxColumnWidth = 125.0f;\n\n\t/// \u003Csummary\u003E\n\t/// A trail\u0027s cross-section, wall to wall, as (share of its width from its left wall\u0027s top, share of its depth):\n\t/// walls easing over a third of the width each way down to a flat bottom.\n\t/// \u003C/summary\u003E\n\tprivate static readonly Vector2[] TrailShape =\n\t{\n\t\tnew(0.0f, 0.0f), new(0.1167f, 0.2593f), new(0.2333f, 0.7407f), new(0.35f, 1.0f),\n\t\tnew(0.65f, 1.0f), new(0.7667f, 0.7407f), new(0.8833f, 0.2593f), new(1.0f, 0.0f)\n\t};\n\n\t/// \u003Csummary\u003E\n\t/// How close a trail\u0027s wall may come to the road\u0027s edge.\n\t/// \u003C/summary\u003E\n\tprivate const float TrailMargin = 2.0f;\n\n\t/// \u003Csummary\u003E\n\t/// The least room between two points across a row, so a trail squeezed against the edge or another trail never\n\t/// folds a row back on itself.\n\t/// \u003C/summary\u003E\n\tprivate const float MinColumnGap = 0.5f;\n\n\t/// \u003Csummary\u003E\n\t/// The least room between two rows: a row nearer than this to another is not worth having.\n\t/// \u003C/summary\u003E\n\tprivate const float MinRowGap = 1.0f;\n\n\t/// \u003Csummary\u003E\n\t/// The rows a wandering trail is laid on are this share of its wander\u0027s wavelength apart (one over its chaos\n\t/// scale), and never closer than \u003Csee cref=\u0022MinWanderStep\u0022/\u003E.\n\t/// \u003C/summary\u003E\n\tprivate const float WanderShare = 0.25f;\n\tprivate const float MinWanderStep = 20.0f;\n\n\t/// \u003Csummary\u003E\n\t/// The region of the noise field trails read their wander from, one more step along for each seed, clear of the\n\t/// country side border\u0027s regions.\n\t/// \u003C/summary\u003E\n\tprivate const float TrailBand = 5000.0f;\n\tprivate const float TrailBandStep = 1000.0f;\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The two edge points of the road at a distance along the curve, each its own distance out from the centreline\n\t/// there. Junctions use this for the rows they share with the arm chunks, so both sides of the seam are computed\n\t/// the same way.\n\t/// \u003C/summary\u003E\n\tpublic static void CrossSection(RoadCurveTable _Table, float _Distance, in RoadWidth _Width, float _Lift, out Vector3 _Left, out Vector3 _Right)\n\t{\n\t\t_Table.Frame(_Distance, out Vector3 position, out Vector3 tangent);\n\n\t\tposition \u002B= Vector3.Up * _Lift;\n\n\t\tVector3 right = RoadCurve.RightOf(tangent);\n\n\t\t_Left = position - right * _Width.LeftAt(_Distance);\n\t\t_Right = position \u002B right * _Width.RightAt(_Distance);\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// How a stretch of road is cut into triangles: 0 when two per cell will do, which is everywhere the road does not\n\t/// climb and turn at once, otherwise the number of columns every cell is cut into lengthways, each fanned into four\n\t/// triangles round its middle. In its own column a fan climbs evenly from one row to the next however much the\n\t/// column twists, and narrow columns twist little, so the surface follows the road\u0027s true shape. The columns fall\n\t/// on the lane boundaries, so the lines painted there run along edges of the mesh itself. Worked out from the\n\t/// corners without the surface\u0027s lift, so the paint, which lays itself on these cells, comes to the same answer.\n\t/// \u003C/summary\u003E\n\tpublic static int Columns(IReadOnlyList\u003CVector3\u003E _Left, IReadOnlyList\u003CVector3\u003E _Right, in RoadWidth _Width, int _Lanes)\n\t{\n\t\tbool twisted = false;\n\n\t\tfor (int i = 0; i \u002B 1 \u003C _Left.Count \u0026\u0026 !twisted; i\u002B\u002B)\n\t\t\ttwisted = Twist(_Left[i], _Right[i], _Right[i \u002B 1], _Left[i \u002B 1]) \u003E MaxTwist;\n\n\t\tif (!twisted)\n\t\t\treturn 0;\n\n\t\tint lanes = Math.Max(1, _Lanes);\n\n\t\treturn lanes * Math.Max(1, (int)MathF.Ceiling(_Width.MaxHalf * 2.0f / (lanes * MaxColumnWidth)));\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The same, for the rows of a stretch of road rather than their corners.\n\t/// \u003C/summary\u003E\n\tpublic static int Columns(RoadCurveTable _Table, IReadOnlyList\u003Cfloat\u003E _Rows, in RoadWidth _Width, int _Lanes)\n\t{\n\t\tvar left = new Vector3[_Rows.Count];\n\t\tvar right = new Vector3[_Rows.Count];\n\n\t\tfor (int i = 0; i \u003C _Rows.Count; i\u002B\u002B)\n\t\t\tCrossSection(_Table, _Rows[i], _Width, 0.0f, out left[i], out right[i]);\n\n\t\treturn Columns(left, right, _Width, _Lanes);\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The surface of a stretch of road. \u003Cparamref name=\u0022_Profile\u0022/\u003E\u0027s trails and skirt shape it across, coming out of\n\t/// that shape where \u003Cparamref name=\u0022_Fade\u0022/\u003E says the segment stops; where \u003Cparamref name=\u0022_Blend\u0022/\u003E says another\n\t/// surface runs on into it, it is drawn with the profile\u0027s blend material. Without them the surface is flat across.\n\t/// \u003C/summary\u003E\n\tpublic static PolygonMesh Build(RoadCurveTable _Table, float _StartDistance, float _EndDistance, in RoadWidth _Width, float _Spacing, in RoadSimplify _Simplify, int _Lanes, float _TextureRepeat, bool _FitWidth, float _SurfaceOffset, Material _Material,\n\t\tRoadProfile _Profile = null, in RoadTrailFade _Fade = default, in RoadSurfaceBlend _Blend = default)\n\t{\n\t\tvar mesh = new PolygonMesh();\n\n\t\t// The rows the borders and the bridge are built on too, so the pieces meet exactly.\n\t\tvar rows = RoadRows.Build(_Table, _StartDistance, _EndDistance, _Spacing, _Width, _Simplify);\n\t\tfloat repeat = MathF.Max(1.0f, _TextureRepeat);\n\t\tvar lefts = new Vector3[rows.Count];\n\t\tvar rights = new Vector3[rows.Count];\n\n\t\tfor (int i = 0; i \u003C rows.Count; i\u002B\u002B)\n\t\t\tCrossSection(_Table, rows[i], _Width, 0.0f, out lefts[i], out rights[i]);\n\n\t\tint columns = Columns(lefts, rights, _Width, _Lanes);\n\n\t\tif (_Profile is not null)\n\t\t{\n\t\t\tvar trails = _Fade.IsNone ? new List\u003CRoadTrail\u003E() : FittingTrails(_Profile.ActiveTrails, _Width);\n\t\t\tfloat skirt = !_Fade.IsNone \u0026\u0026 _Profile.HasSkirt ? _Profile.SkirtWidth : 0.0f;\n\t\t\tvar blend = _Profile.RoadBlendMaterial is not null ? _Blend : default;\n\n\t\t\tif (trails.Count \u003E 0 || skirt \u003E 0.0f || !blend.IsNone)\n\t\t\t{\n\t\t\t\tvar shape = new Shape(trails, _Fade, skirt, _Profile.SkirtDepth, blend, _Profile.RoadBlendMaterial);\n\n\t\t\t\tBuildShaped(mesh, rows, lefts, rights, _Width, columns \u003E 0, repeat, _FitWidth, _SurfaceOffset, _Material, shape);\n\n\t\t\t\treturn mesh;\n\t\t\t}\n\t\t}\n\n\t\tint points = Math.Max(1, columns) \u002B 1;\n\t\tVector3 lift = Vector3.Up * _SurfaceOffset;\n\n\t\tvar positions = new Vector3[rows.Count, points];\n\t\tvar handles = new HalfEdgeMesh.VertexHandle[rows.Count, points];\n\t\tvar uvs = new Vector2[rows.Count, points];\n\n\t\tfor (int i = 0; i \u003C rows.Count; i\u002B\u002B)\n\t\t{\n\t\t\tfloat distance = rows[i];\n\n\t\t\t// U runs across the road from the centreline, V along it, so a tiling material follows the road instead\n\t\t\t// of the world, and an edge that moves out takes its texture with it. Fitted to the width, U runs from 0\n\t\t\t// on the left edge to 1 on the right instead, so a texture painted kerb to kerb spans the road once.\n\t\t\tfloat v = distance / repeat;\n\t\t\tvar uvLeft = new Vector2(_FitWidth ? 0.0f : -_Width.LeftAt(distance) / repeat, v);\n\t\t\tvar uvRight = new Vector2(_FitWidth ? 1.0f : _Width.RightAt(distance) / repeat, v);\n\n\t\t\tfor (int k = 0; k \u003C points; k\u002B\u002B)\n\t\t\t{\n\t\t\t\tpositions[i, k] = ColumnPoint(lefts[i], rights[i], k, points - 1) \u002B lift;\n\t\t\t\thandles[i, k] = mesh.AddVertices(positions[i, k])[0];\n\t\t\t\tuvs[i, k] = k == 0 ? uvLeft : k == points - 1 ? uvRight : Vector2.Lerp(uvLeft, uvRight, (float)k / (points - 1));\n\t\t\t}\n\t\t}\n\n\t\tfor (int i = 0; i \u003C rows.Count - 1; i\u002B\u002B)\n\t\t{\n\t\t\tif (columns == 0)\n\t\t\t{\n\t\t\t\t// Two triangles rather than a quad: the cell is flat to within a hair, but a quad that is not quite flat\n\t\t\t\t// is the mesh\u0027s to split (or to drop), and the paint laid on top has to know which way it went.\n\t\t\t\tMeshUtility.AddTexturedTriangle(mesh, _Material, handles[i, 0], handles[i, 1], handles[i \u002B 1, 1], uvs[i, 0], uvs[i, 1], uvs[i \u002B 1, 1]);\n\t\t\t\tMeshUtility.AddTexturedTriangle(mesh, _Material, handles[i, 0], handles[i \u002B 1, 1], handles[i \u002B 1, 0], uvs[i, 0], uvs[i \u002B 1, 1], uvs[i \u002B 1, 0]);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tfor (int k = 0; k \u003C columns; k\u002B\u002B)\n\t\t\t{\n\t\t\t\tvar middle = (positions[i, k] \u002B positions[i, k \u002B 1] \u002B positions[i \u002B 1, k \u002B 1] \u002B positions[i \u002B 1, k]) * 0.25f;\n\t\t\t\tvar middleUv = (uvs[i, k] \u002B uvs[i, k \u002B 1] \u002B uvs[i \u002B 1, k \u002B 1] \u002B uvs[i \u002B 1, k]) * 0.25f;\n\t\t\t\tvar centre = mesh.AddVertices(middle)[0];\n\n\t\t\t\t// Round the column the way the plain cell is wound, each side of it with the middle.\n\t\t\t\tMeshUtility.AddTexturedTriangle(mesh, _Material, handles[i, k], handles[i, k \u002B 1], centre, uvs[i, k], uvs[i, k \u002B 1], middleUv);\n\t\t\t\tMeshUtility.AddTexturedTriangle(mesh, _Material, handles[i, k \u002B 1], handles[i \u002B 1, k \u002B 1], centre, uvs[i, k \u002B 1], uvs[i \u002B 1, k \u002B 1], middleUv);\n\t\t\t\tMeshUtility.AddTexturedTriangle(mesh, _Material, handles[i \u002B 1, k \u002B 1], handles[i \u002B 1, k], centre, uvs[i \u002B 1, k \u002B 1], uvs[i \u002B 1, k], middleUv);\n\t\t\t\tMeshUtility.AddTexturedTriangle(mesh, _Material, handles[i \u002B 1, k], handles[i, k], centre, uvs[i \u002B 1, k], uvs[i, k], middleUv);\n\t\t\t}\n\t\t}\n\n\t\treturn mesh;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The trails a road is wide enough for, left to right. Decided from the narrower of the segment\u0027s two ends (its\n\t/// width blends evenly from one to the other), so every chunk of the segment has the same trails and the chunks\n\t/// meet.\n\t/// \u003C/summary\u003E\n\tprivate static List\u003CRoadTrail\u003E FittingTrails(IReadOnlyList\u003CRoadTrail\u003E _Trails, in RoadWidth _Width)\n\t{\n\t\tvar fitting = new List\u003CRoadTrail\u003E();\n\n\t\tif (_Trails is null)\n\t\t\treturn fitting;\n\n\t\tfloat narrowest = MathF.Min(_Width.WidthAt(0.0f), _Width.WidthAt(_Width.Length));\n\n\t\tforeach (var trail in _Trails)\n\t\t{\n\t\t\tif (trail is null || !trail.IsVisible || trail.Width \u002B TrailMargin * 2.0f \u003E narrowest)\n\t\t\t\tcontinue;\n\n\t\t\t// Left to right, keeping the listed order between two at the same offset.\n\t\t\tint at = fitting.Count;\n\n\t\t\twhile (at \u003E 0 \u0026\u0026 fitting[at - 1].Offset \u003E trail.Offset)\n\t\t\t\tat--;\n\n\t\t\tfitting.Insert(at, trail);\n\t\t}\n\n\t\treturn fitting;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// What a shaped surface is built with: its trails, left to right; where they and the skirt come out of the road at\n\t/// the segment\u0027s ends; the skirt\u0027s width and depth under banks (0 wide for none); and where another surface runs on\n\t/// into the road, with the material that blend is drawn with.\n\t/// \u003C/summary\u003E\n\tprivate readonly record struct Shape(List\u003CRoadTrail\u003E Trails, RoadTrailFade Fade, float SkirtWidth, float SkirtDepth, RoadSurfaceBlend Blend, Material BlendMaterial);\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The surface of a stretch of road with shape across it. Its rows are the plain surface\u0027s, with more between them\n\t/// wherever a trail wanders or anything comes out of the road or blends into it at an end; those are laid on the\n\t/// straight lines between the plain rows\u0027 edges, so the road\u0027s outline is exactly the plain one\u0027s and its borders\n\t/// meet it the same. Each row is cut across at the road\u0027s two edges and at the walls and bottom of every trail, and\n\t/// kept in order across, so a trail pushed against the edge or another trail flattens out rather than folding the\n\t/// surface over; under banks it carries on past each edge as a skirt, down under the ground, all the way along (the\n\t/// rounded end and the junction corners carry it on round). A trail wanders by noise read where the road is, which\n\t/// is the same in every chunk and on into the next road, so it never jumps.\n\t/// Where another surface blends into the road, the cells are drawn with the blend material, every point of a row\n\t/// mixed the same (a mix that changed across a cell would be read differently by its two triangles). The blend\u0027s\n\t/// coordinates start out where it meets that surface as that surface\u0027s own (the blend\u0027s second layer carries it\n\t/// straight on) and move over to the road\u0027s own as the road takes over (with the road material\u0027s texture transform\n\t/// applied, as the blend\u0027s first layer takes the coordinates as they come): each layer is laid exactly where it is\n\t/// all there is, and the two give way to each other over the same stretch they move over in.\n\t/// \u003C/summary\u003E\n\tprivate static void BuildShaped(PolygonMesh _Mesh, List\u003Cfloat\u003E _Rows, Vector3[] _Lefts, Vector3[] _Rights, in RoadWidth _Width, bool _Twisted, float _Repeat, bool _FitWidth, float _SurfaceOffset, Material _Material,\n\t\tin Shape _Shape)\n\t{\n\t\t// Where the centre line lies across each plain row, as a share of the way from its left edge.\n\t\tvar centres = new float[_Rows.Count];\n\n\t\tfor (int i = 0; i \u003C _Rows.Count; i\u002B\u002B)\n\t\t{\n\t\t\tfloat left = _Width.LeftAt(_Rows[i]);\n\t\t\tfloat right = _Width.RightAt(_Rows[i]);\n\n\t\t\tcentres[i] = left \u002B right \u003E 0.001f ? left / (left \u002B right) : 0.5f;\n\t\t}\n\n\t\tvar trails = _Shape.Trails;\n\t\tvar rows = ShapedRows(_Rows, _Shape);\n\t\tint trailCount = trails.Count;\n\t\tint shape = TrailShape.Length;\n\t\tbool skirted = _Shape.SkirtWidth \u003E 0.0f;\n\t\tbool blending = _Shape.BlendMaterial is not null \u0026\u0026 !_Shape.Blend.IsNone;\n\t\tvar frames = new (Vector3 Left, Vector3 Right, float Width, float Centre, float Distance, float Strength, float Weight)[rows.Count];\n\t\tvar keys = new (float Across, float Depth)[rows.Count][];\n\n\t\t// Each row\u0027s frame, and its points across as (distance from its left edge, depth): for now the road\u0027s edges and\n\t\t// the trails\u0027 walls and bottoms.\n\t\tfor (int r = 0; r \u003C rows.Count; r\u002B\u002B)\n\t\t{\n\t\t\tvar (distance, index, t) = rows[r];\n\t\t\tint next = Math.Min(index \u002B 1, _Rows.Count - 1);\n\t\t\tVector3 left = Vector3.Lerp(_Lefts[index], _Lefts[next], t);\n\t\t\tVector3 right = Vector3.Lerp(_Rights[index], _Rights[next], t);\n\t\t\tfloat width = Flat(right - left).Length;\n\t\t\tfloat centre = MathX.Lerp(centres[index], centres[next], t);\n\t\t\tfloat strength = _Shape.Fade.StrengthAt(distance);\n\t\t\tfloat weight = blending ? _Shape.Blend.WeightAt(distance) : 0.0f;\n\t\t\tVector3 middle = Vector3.Lerp(left, right, centre);\n\t\t\tvar key = new (float Across, float Depth)[trailCount * shape \u002B 2];\n\n\t\t\tframes[r] = (left, right, width, centre, distance, strength, weight);\n\t\t\tkey[0] = (0.0f, 0.0f);\n\n\t\t\tfor (int k = 0; k \u003C trailCount; k\u002B\u002B)\n\t\t\t{\n\t\t\t\tvar trail = trails[k];\n\t\t\t\tfloat half = trail.Width * 0.5f;\n\t\t\t\tfloat wander = 0.0f;\n\n\t\t\t\t// Noise is 0..1; centred, it wanders roughly as far as the chaos either way.\n\t\t\t\tif (trail.Chaos \u003E 0.0f)\n\t\t\t\t\twander = (Noise.Perlin(middle.x * trail.ChaosScale \u002B TrailBand \u002B trail.Seed * TrailBandStep, middle.y * trail.ChaosScale) - 0.5f) * 2.0f * trail.Chaos;\n\n\t\t\t\t// Kept inside the road, however far it wanders.\n\t\t\t\tfloat low = half \u002B TrailMargin;\n\t\t\t\tfloat high = width - half - TrailMargin;\n\t\t\t\tfloat across = width * centre \u002B trail.Offset \u002B wander;\n\n\t\t\t\tacross = high \u003E= low ? Math.Clamp(across, low, high) : width * 0.5f;\n\n\t\t\t\tfor (int p = 0; p \u003C shape; p\u002B\u002B)\n\t\t\t\t\tkey[1 \u002B k * shape \u002B p] = (across - half \u002B TrailShape[p].x * trail.Width, trail.Depth * strength * TrailShape[p].y);\n\t\t\t}\n\n\t\t\tkey[^1] = (width, 0.0f);\n\n\t\t\t// In order across, never closer than a hair, with the road\u0027s own edges left where they are.\n\t\t\tfor (int p = 1; p \u003C key.Length - 1; p\u002B\u002B)\n\t\t\t\tkey[p].Across = MathF.Max(key[p].Across, key[p - 1].Across \u002B MinColumnGap);\n\n\t\t\tfor (int p = key.Length - 2; p \u003E= 1; p--)\n\t\t\t\tkey[p].Across = MathF.Min(key[p].Across, key[p \u002B 1].Across - MinColumnGap);\n\n\t\t\tkeys[r] = key;\n\t\t}\n\n\t\t// The flat stretch before each trail and after the last runs from one key point (a multiple of the shape\u0027s\n\t\t// length along) to the next. A road that twists has them cut lengthways like a plain twisted road\u0027s cells, into\n\t\t// as many columns on every row as the widest of them needs.\n\t\tvar pieces = new int[trailCount \u002B 1];\n\n\t\tfor (int s = 0; s \u003C= trailCount; s\u002B\u002B)\n\t\t{\n\t\t\tpieces[s] = 1;\n\n\t\t\tif (!_Twisted)\n\t\t\t\tcontinue;\n\n\t\t\tfloat widest = 0.0f;\n\n\t\t\tforeach (var key in keys)\n\t\t\t\twidest = MathF.Max(widest, key[s * shape \u002B 1].Across - key[s * shape].Across);\n\n\t\t\tpieces[s] = Math.Max(1, (int)MathF.Ceiling(widest / MaxColumnWidth));\n\t\t}\n\n\t\tVector3 lift = Vector3.Up * _SurfaceOffset;\n\t\tvar (textureScale, textureOffset) = RoadProfile.TextureTransform(_Material);\n\t\tVector2 second = RoadProfile.SecondLayerScale(_Shape.BlendMaterial);\n\t\tvar grid = new Vertex[rows.Count][];\n\t\tvar points = new List\u003C(float Across, float Depth)\u003E();\n\n\t\t// Under banks, the skirt past each edge.\n\t\tfloat skirt = skirted ? MathF.Max(MinColumnGap, _Shape.SkirtWidth) : 0.0f;\n\t\tfloat drop = skirted ? _Shape.SkirtDepth : 0.0f;\n\n\t\tfor (int r = 0; r \u003C rows.Count; r\u002B\u002B)\n\t\t{\n\t\t\tvar (left, right, width, centre, distance, _, weight) = frames[r];\n\t\t\tvar key = keys[r];\n\t\t\tfloat v = distance / _Repeat;\n\t\t\tfloat leftHalf = width * centre;\n\n\t\t\t// The surface blending in here, if any: the one at whichever end\u0027s blend reaches this far.\n\t\t\tvar source = _Shape.Blend.StartWeightAt(distance) \u003E= _Shape.Blend.EndWeightAt(distance) ? _Shape.Blend.StartSource : _Shape.Blend.EndSource;\n\n\t\t\tpoints.Clear();\n\n\t\t\tif (skirted)\n\t\t\t\tpoints.Add((-skirt, drop));\n\n\t\t\tint leftEdge = points.Count;\n\n\t\t\tfor (int p = 0; p \u003C key.Length; p\u002B\u002B)\n\t\t\t{\n\t\t\t\tpoints.Add(key[p]);\n\n\t\t\t\tif (p % shape != 0 || p \u002B 1 \u003E= key.Length)\n\t\t\t\t\tcontinue;\n\n\t\t\t\tint span = p / shape;\n\n\t\t\t\tfor (int c = 1; c \u003C pieces[span]; c\u002B\u002B)\n\t\t\t\t\tpoints.Add((MathX.Lerp(key[p].Across, key[p \u002B 1].Across, (float)c / pieces[span]), 0.0f));\n\t\t\t}\n\n\t\t\tint rightEdge = points.Count - 1;\n\n\t\t\tif (skirted)\n\t\t\t\tpoints.Add((width \u002B skirt, drop));\n\n\t\t\tvar row = new Vertex[points.Count];\n\n\t\t\tfor (int p = 0; p \u003C points.Count; p\u002B\u002B)\n\t\t\t{\n\t\t\t\tvar (across, depth) = points[p];\n\t\t\t\tfloat share = width \u003E 0.001f ? across / width : 0.0f;\n\n\t\t\t\t// The edges exactly where the plain surface has them; inside, on the row\u0027s straight line, sunk by the\n\t\t\t\t// trail there; the skirts on out along the same line, sunk under the banks.\n\t\t\t\tVector3 position = p == leftEdge ? left : p == rightEdge ? right : left \u002B (right - left) * share;\n\n\t\t\t\tposition \u002B= lift - Vector3.Up * depth;\n\n\t\t\t\t// A texture fitted to the width is turned back on itself at the edge down the skirt, so it carries on at\n\t\t\t\t// its own size rather than starting again (or being drawn out from its edge).\n\t\t\t\tvar uv = new Vector2(_FitWidth ? SkirtShare(share) : (across - leftHalf) / _Repeat, v);\n\t\t\t\tvar blendUv = Vector2.Zero;\n\n\t\t\t\tif (blending)\n\t\t\t\t{\n\t\t\t\t\tblendUv = new Vector2(uv.x * textureScale.x \u002B textureOffset.x, uv.y * textureScale.y \u002B textureOffset.y);\n\n\t\t\t\t\tif (weight \u003E 0.0f)\n\t\t\t\t\t{\n\t\t\t\t\t\tVector2 sample = source.SampleAt(distance, across - leftHalf, leftHalf, width - leftHalf, position);\n\n\t\t\t\t\t\tblendUv = Vector2.Lerp(blendUv, new Vector2(sample.x / second.x, sample.y / second.y), weight);\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\trow[p] = new Vertex(position, uv, blendUv, weight, _Mesh.AddVertices(position)[0]);\n\t\t\t}\n\n\t\t\tgrid[r] = row;\n\t\t}\n\n\t\tfor (int r = 0; r \u003C rows.Count - 1; r\u002B\u002B)\n\t\t{\n\t\t\tvar near = grid[r];\n\t\t\tvar far = grid[r \u002B 1];\n\n\t\t\t// A cell that has any of the other surface in it is drawn with the blend; the skirts never are, so what shows\n\t\t\t// of them where the ground dips is always this road\u0027s own surface.\n\t\t\tbool blendRow = blending \u0026\u0026 MathF.Max(frames[r].Weight, frames[r \u002B 1].Weight) \u003E 0.0f;\n\n\t\t\tfor (int p = 0; p \u003C near.Length - 1; p\u002B\u002B)\n\t\t\t{\n\t\t\t\tbool skirtCell = skirted \u0026\u0026 (p == 0 || p == near.Length - 2);\n\t\t\t\tbool blend = blendRow \u0026\u0026 !skirtCell;\n\t\t\t\tvar material = blend ? _Shape.BlendMaterial : _Material;\n\n\t\t\t\tif (!_Twisted)\n\t\t\t\t{\n\t\t\t\t\t// Split the way the plain surface\u0027s cells are.\n\t\t\t\t\tTriangle(_Mesh, material, blend, near[p], near[p \u002B 1], far[p \u002B 1]);\n\t\t\t\t\tTriangle(_Mesh, material, blend, near[p], far[p \u002B 1], far[p]);\n\t\t\t\t\tcontinue;\n\t\t\t\t}\n\n\t\t\t\tvar middle = new Vertex(\n\t\t\t\t\t(near[p].Position \u002B near[p \u002B 1].Position \u002B far[p \u002B 1].Position \u002B far[p].Position) * 0.25f,\n\t\t\t\t\t(near[p].Uv \u002B near[p \u002B 1].Uv \u002B far[p \u002B 1].Uv \u002B far[p].Uv) * 0.25f,\n\t\t\t\t\t(near[p].BlendUv \u002B near[p \u002B 1].BlendUv \u002B far[p \u002B 1].BlendUv \u002B far[p].BlendUv) * 0.25f,\n\t\t\t\t\t(near[p].Weight \u002B far[p].Weight) * 0.5f,\n\t\t\t\t\tdefault);\n\n\t\t\t\tmiddle = middle with { Handle = _Mesh.AddVertices(middle.Position)[0] };\n\n\t\t\t\tTriangle(_Mesh, material, blend, near[p], near[p \u002B 1], middle);\n\t\t\t\tTriangle(_Mesh, material, blend, near[p \u002B 1], far[p \u002B 1], middle);\n\t\t\t\tTriangle(_Mesh, material, blend, far[p \u002B 1], far[p], middle);\n\t\t\t\tTriangle(_Mesh, material, blend, far[p], near[p], middle);\n\t\t\t}\n\t\t}\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// One point of a shaped surface: where it is, its texture coordinates as the road\u0027s own material takes them and\n\t/// as a blend\u0027s first layer must be given them, how much of another surface is mixed in there, and its vertex.\n\t/// \u003C/summary\u003E\n\tprivate readonly record struct Vertex(Vector3 Position, Vector2 Uv, Vector2 BlendUv, float Weight, HalfEdgeMesh.VertexHandle Handle);\n\n\n\n\tprivate static void Triangle(PolygonMesh _Mesh, Material _Material, bool _Blend, in Vertex _A, in Vertex _B, in Vertex _C)\n\t{\n\t\tif (!_Blend)\n\t\t{\n\t\t\tMeshUtility.AddTexturedTriangle(_Mesh, _Material, _A.Handle, _B.Handle, _C.Handle, _A.Uv, _B.Uv, _C.Uv);\n\t\t\treturn;\n\t\t}\n\n\t\tvar face = MeshUtility.AddTexturedTriangle(_Mesh, _Material, _A.Handle, _B.Handle, _C.Handle, _A.BlendUv, _B.BlendUv, _C.BlendUv);\n\n\t\t// A blendable material\u0027s first layer is this road, its second the surface blending into it, mixed by the red.\n\t\tMeshUtility.SetFaceBlends(_Mesh, face, new[] { BlendColour(_A.Weight), BlendColour(_B.Weight), BlendColour(_C.Weight) });\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The vertex blend that mixes a blendable material\u0027s second layer in by \u003Cparamref name=\u0022_Weight\u0022/\u003E.\n\t/// \u003C/summary\u003E\n\tinternal static Color32 BlendColour(float _Weight)\n\t{\n\t\treturn new Color32((byte)Math.Clamp(MathF.Round(_Weight * 255.0f), 0.0f, 255.0f), 0, 0, 255);\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Where a point a share of the way across a road samples a texture fitted to the road\u0027s width, past either edge\n\t/// (down a skirt) turned back on itself there: the texture carries on at its own size, the way it runs inside, its\n\t/// edge where the road\u0027s is.\n\t/// \u003C/summary\u003E\n\tinternal static float SkirtShare(float _Share)\n\t{\n\t\treturn _Share \u003C 0.0f ? -_Share : _Share \u003E 1.0f ? 2.0f - _Share : _Share;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The rows a shaped surface is laid on, as (distance along the curve, the plain row at or before it, how far on\n\t/// towards the next): the plain rows, and between them a row at every step of a fade or a blend and every so often\n\t/// where a trail wanders, so the trails rise and swing smoothly, and the blend mixes smoothly, even where the plain\n\t/// rows are far apart.\n\t/// \u003C/summary\u003E\n\tprivate static List\u003C(float Distance, int Row, float T)\u003E ShapedRows(List\u003Cfloat\u003E _Rows, in Shape _Shape)\n\t{\n\t\tfloat step = 0.0f;\n\n\t\tforeach (var trail in _Shape.Trails)\n\t\t{\n\t\t\tif (trail.Chaos \u003C= 0.0f)\n\t\t\t\tcontinue;\n\n\t\t\tfloat own = MathF.Max(MinWanderStep, WanderShare / trail.ChaosScale);\n\n\t\t\tstep = step \u003E 0.0f ? MathF.Min(step, own) : own;\n\t\t}\n\n\t\tvar knots = new List\u003Cfloat\u003E(_Shape.Fade.Knots());\n\n\t\tif (_Shape.BlendMaterial is not null)\n\t\t\tknots.AddRange(_Shape.Blend.Knots());\n\n\t\tvar rows = new List\u003C(float Distance, int Row, float T)\u003E(_Rows.Count * 2);\n\t\tvar cuts = new List\u003Cfloat\u003E();\n\n\t\tfor (int i = 0; i \u003C _Rows.Count; i\u002B\u002B)\n\t\t{\n\t\t\trows.Add((_Rows[i], i, 0.0f));\n\n\t\t\tif (i == _Rows.Count - 1)\n\t\t\t\tbreak;\n\n\t\t\tfloat from = _Rows[i];\n\t\t\tfloat to = _Rows[i \u002B 1];\n\t\t\tfloat gap = to - from;\n\n\t\t\tif (gap \u003C= MinRowGap * 2.0f)\n\t\t\t\tcontinue;\n\n\t\t\tcuts.Clear();\n\n\t\t\tforeach (float knot in knots)\n\t\t\t{\n\t\t\t\tif (knot \u003E from \u0026\u0026 knot \u003C to)\n\t\t\t\t\tcuts.Add(knot);\n\t\t\t}\n\n\t\t\tif (step \u003E 0.0f)\n\t\t\t{\n\t\t\t\tint count = (int)MathF.Ceiling(gap / step);\n\n\t\t\t\tfor (int j = 1; j \u003C count; j\u002B\u002B)\n\t\t\t\t\tcuts.Add(from \u002B gap * j / count);\n\t\t\t}\n\n\t\t\tcuts.Sort();\n\n\t\t\tfloat previous = from;\n\n\t\t\tforeach (float cut in cuts)\n\t\t\t{\n\t\t\t\tif (cut - previous \u003C MinRowGap || to - cut \u003C MinRowGap)\n\t\t\t\t\tcontinue;\n\n\t\t\t\trows.Add((cut, i, (cut - from) / gap));\n\t\t\t\tprevious = cut;\n\t\t\t}\n\t\t}\n\n\t\treturn rows;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The height of one cell of road surface, as it is built, over a point in plan. A cell with no columns is split\n\t/// from its near left corner to its far right one, so which of its two triangles the point falls on is which side\n\t/// of that diagonal it lies; a cut-up cell is found the column the point lies in, then the triangle of that\n\t/// column\u0027s fan. The triangle\u0027s plane is used even for a point just off the cell (paint hanging over the road\u0027s\n\t/// edge), which keeps that paint on the surface\u0027s own plane.\n\t/// \u003C/summary\u003E\n\tpublic static float CellHeight(Vector3 _NearLeft, Vector3 _NearRight, Vector3 _FarRight, Vector3 _FarLeft, int _Columns, Vector2 _Point)\n\t{\n\t\tif (_Columns \u003C= 0)\n\t\t{\n\t\t\tVector2 diagonal = Flat(_FarRight) - Flat(_NearLeft);\n\t\t\tfloat side = Cross(diagonal, _Point - Flat(_NearLeft));\n\t\t\tfloat nearRightSide = Cross(diagonal, Flat(_NearRight) - Flat(_NearLeft));\n\n\t\t\treturn side * nearRightSide \u003E= 0.0f\n\t\t\t\t? PlaneHeight(_NearLeft, _NearRight, _FarRight, _Point)\n\t\t\t\t: PlaneHeight(_NearLeft, _FarRight, _FarLeft, _Point);\n\t\t}\n\n\t\t// The first column line with the point on its left (the cell\u0027s left edge\u0027s side) closes the point\u0027s column;\n\t\t// past the last line it is the rightmost column, edge or no edge.\n\t\tint column = _Columns - 1;\n\n\t\tfor (int k = 1; k \u003C _Columns; k\u002B\u002B)\n\t\t{\n\t\t\tVector2 near = Flat(ColumnPoint(_NearLeft, _NearRight, k, _Columns));\n\t\t\tVector2 line = Flat(ColumnPoint(_FarLeft, _FarRight, k, _Columns)) - near;\n\n\t\t\tif (Cross(line, _Point - near) * Cross(line, Flat(_NearLeft) - near) \u003E 0.0f)\n\t\t\t{\n\t\t\t\tcolumn = k - 1;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tVector3 nearLeft = ColumnPoint(_NearLeft, _NearRight, column, _Columns);\n\t\tVector3 nearRight = ColumnPoint(_NearLeft, _NearRight, column \u002B 1, _Columns);\n\t\tVector3 farRight = ColumnPoint(_FarLeft, _FarRight, column \u002B 1, _Columns);\n\t\tVector3 farLeft = ColumnPoint(_FarLeft, _FarRight, column, _Columns);\n\t\tVector3 middle = (nearLeft \u002B nearRight \u002B farRight \u002B farLeft) * 0.25f;\n\n\t\t// The fan\u0027s triangle the point is inside has no weight below zero; off the column, the one it is least\n\t\t// outside of.\n\t\tfloat best = float.MinValue;\n\t\tfloat height = middle.z;\n\n\t\tFanTriangle(nearLeft, nearRight, middle, _Point, ref best, ref height);\n\t\tFanTriangle(nearRight, farRight, middle, _Point, ref best, ref height);\n\t\tFanTriangle(farRight, farLeft, middle, _Point, ref best, ref height);\n\t\tFanTriangle(farLeft, nearLeft, middle, _Point, ref best, ref height);\n\n\t\treturn height;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Where a row meets one of the lines that cut a cell into columns: the row\u0027s own ends for the outermost two, so\n\t/// the surface meets its borders exactly, evenly between them for the rest.\n\t/// \u003C/summary\u003E\n\tprivate static Vector3 ColumnPoint(Vector3 _Left, Vector3 _Right, int _Column, int _Columns)\n\t{\n\t\tif (_Column \u003C= 0)\n\t\t\treturn _Left;\n\n\t\tif (_Column \u003E= _Columns)\n\t\t\treturn _Right;\n\n\t\treturn Vector3.Lerp(_Left, _Right, (float)_Column / _Columns);\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// How far a cell\u0027s far left corner sits above or below the plane through its other three: nothing for a road that\n\t/// is level, or straight, there.\n\t/// \u003C/summary\u003E\n\tprivate static float Twist(Vector3 _NearLeft, Vector3 _NearRight, Vector3 _FarRight, Vector3 _FarLeft)\n\t{\n\t\treturn MathF.Abs(_FarLeft.z - PlaneHeight(_NearLeft, _NearRight, _FarRight, Flat(_FarLeft)));\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Takes one triangle of a fan as the point\u0027s when the point lies further inside it (its least weight is larger)\n\t/// than inside any tried before.\n\t/// \u003C/summary\u003E\n\tprivate static void FanTriangle(Vector3 _A, Vector3 _B, Vector3 _C, Vector2 _Point, ref float _Best, ref float _Height)\n\t{\n\t\tVector2 a = Flat(_A);\n\t\tVector2 b = Flat(_B);\n\t\tVector2 c = Flat(_C);\n\t\tfloat area = Cross(b - a, c - a);\n\n\t\tif (MathF.Abs(area) \u003C 0.0001f)\n\t\t\treturn;\n\n\t\tfloat weightA = Cross(b - _Point, c - _Point) / area;\n\t\tfloat weightB = Cross(c - _Point, a - _Point) / area;\n\t\tfloat weightC = 1.0f - weightA - weightB;\n\t\tfloat least = MathF.Min(weightA, MathF.Min(weightB, weightC));\n\n\t\tif (least \u003C= _Best)\n\t\t\treturn;\n\n\t\t_Best = least;\n\t\t_Height = weightA * _A.z \u002B weightB * _B.z \u002B weightC * _C.z;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The height of the plane through three points over a point in plan.\n\t/// \u003C/summary\u003E\n\tprivate static float PlaneHeight(Vector3 _A, Vector3 _B, Vector3 _C, Vector2 _Point)\n\t{\n\t\tVector2 a = Flat(_A);\n\t\tVector2 b = Flat(_B);\n\t\tVector2 c = Flat(_C);\n\t\tfloat area = Cross(b - a, c - a);\n\n\t\tif (MathF.Abs(area) \u003C 0.0001f)\n\t\t\treturn _A.z;\n\n\t\tfloat weightA = Cross(b - _Point, c - _Point) / area;\n\t\tfloat weightB = Cross(c - _Point, a - _Point) / area;\n\n\t\treturn weightA * _A.z \u002B weightB * _B.z \u002B (1.0f - weightA - weightB) * _C.z;\n\t}\n\n\n\n\tprivate static Vector2 Flat(Vector3 _Vector)\n\t{\n\t\treturn new Vector2(_Vector.x, _Vector.y);\n\t}\n\n\n\n\tprivate static float Cross(Vector2 _A, Vector2 _B)\n\t{\n\t\treturn _A.x * _B.y - _A.y * _B.x;\n\t}\n}\n"},{"Ident":"redsnail.roadtool2","Path":"Editor/RoadBorderDebugDump.cs","FileName":"RoadBorderDebugDump.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":443665,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing System.IO;\r\nusing Editor;\r\nusing Sandbox;\r\n\r\nnamespace RedSnail.RoadTool2.Editor;\r\n\r\n/// \u003Csummary\u003E\r\n/// Writes each network\u0027s border debug record to Libraries/RoadTool2/debug/borders.txt whenever its border pieces\r\n/// have been rebuilt with the overlay on, so the numbers can be read outside the editor.\r\n/// \u003C/summary\u003E\r\npublic static class RoadBorderDebugDump\r\n{\r\n\tprivate static readonly Dictionary\u003CGuid, int\u003E s_Written = new();\r\n\r\n\r\n\r\n\t[EditorEvent.Frame]\r\n\tpublic static void OnFrame()\r\n\t{\r\n\t\tvar scene = SceneEditorSession.Active?.Scene;\r\n\r\n\t\tif (scene is null)\r\n\t\t\treturn;\r\n\r\n\t\tvar network = scene.Get\u003CRoadNetwork\u003E();\r\n\r\n\t\tif (!network.IsValid() || !network.DebugBorders || network.IsRebuilding)\r\n\t\t\treturn;\r\n\r\n\t\tif (s_Written.TryGetValue(network.Id, out int revision) \u0026\u0026 revision == network.DebugRevision)\r\n\t\t\treturn;\r\n\r\n\t\ts_Written[network.Id] = network.DebugRevision;\r\n\r\n\t\ttry\r\n\t\t{\r\n\t\t\tstring path = GetPath(network);\r\n\r\n\t\t\tDirectory.CreateDirectory(Path.GetDirectoryName(path));\r\n\t\t\tFile.WriteAllText(path, network.BuildDebugRecord());\r\n\r\n\t\t\tLog.Info($\u0022Road Tool 2: border debug written to {path}\u0022);\r\n\t\t}\r\n\t\tcatch (Exception exception)\r\n\t\t{\r\n\t\t\tLog.Warning($\u0022Road Tool 2: could not write the border debug record: {exception.Message}\u0022);\r\n\t\t}\r\n\t}\r\n\r\n\r\n\r\n\tprivate static string GetPath(RoadNetwork _Network)\r\n\t{\r\n\t\tstring root = Project.Current.GetRootPath();\r\n\t\tstring library = Path.Combine(root, \u0022Libraries\u0022, \u0022RoadTool2\u0022);\r\n\r\n\t\t// The library folder may have been renamed; find it by its project file.\r\n\t\tif (!Directory.Exists(library))\r\n\t\t{\r\n\t\t\tforeach (string directory in Directory.GetDirectories(Path.Combine(root, \u0022Libraries\u0022)))\r\n\t\t\t{\r\n\t\t\t\tif (File.Exists(Path.Combine(directory, \u0022roadtool2.sbproj\u0022)))\r\n\t\t\t\t{\r\n\t\t\t\t\tlibrary = directory;\r\n\t\t\t\t\tbreak;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tstring name = string.Concat(_Network.GameObject.Name.Split(Path.GetInvalidFileNameChars())).Replace(\u0027 \u0027, \u0027_\u0027);\r\n\r\n\t\treturn Path.Combine(library, \u0022debug\u0022, $\u0022borders_{name}.txt\u0022);\r\n\t}\r\n}\r\n"},{"Ident":"redsnail.roadtool2","Path":"Code/Profiles/BridgeStyle.cs","FileName":"BridgeStyle.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":443665,"IsPrivate":false,"Code":"using System.Text.Json.Serialization;\r\nusing Sandbox;\r\n\r\nnamespace RedSnail.RoadTool2;\r\n\r\n/// \u003Csummary\u003E\r\n/// What stands along the two edges of a bridge deck.\r\n/// \u003C/summary\u003E\r\npublic enum BridgeSideStyle\r\n{\r\n\t/// \u003Csummary\u003E\r\n\t/// Nothing above the deck: its side face is all there is.\r\n\t/// \u003C/summary\u003E\r\n\tNone,\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// A solid parapet wall.\r\n\t/// \u003C/summary\u003E\r\n\tWall,\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Posts at intervals with horizontal rails running between them.\r\n\t/// \u003C/summary\u003E\r\n\tRailing,\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// A prefab of your own repeated along the edge (a fence panel, a lamp, a cable anchor...).\r\n\t/// \u003C/summary\u003E\r\n\tPrefab\r\n}\r\n\r\n/// \u003Csummary\u003E\r\n/// What holds a bridge deck up.\r\n/// \u003C/summary\u003E\r\npublic enum BridgeSupportStyle\r\n{\r\n\tNone,\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Pillars at intervals, from the underside of the deck down into the ground.\r\n\t/// \u003C/summary\u003E\r\n\tPillars,\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// A prefab of your own at intervals under the deck (a pier, a tower...).\r\n\t/// \u003C/summary\u003E\r\n\tPrefab\r\n}\r\n\r\npublic enum BridgePillarShape\r\n{\r\n\tSquare,\r\n\tRound\r\n}\r\n\r\n/// \u003Csummary\u003E\r\n/// One pillar under the middle of the deck, or one under each edge.\r\n/// \u003C/summary\u003E\r\npublic enum BridgePillarLayout\r\n{\r\n\tSingle,\r\n\tPair\r\n}\r\n\r\n/// \u003Csummary\u003E\r\n/// How a stretch of road becomes a bridge: the deck under it, what stands along the deck\u0027s edges, and what holds it\r\n/// up. Each part is picked from a set of built-in designs or handed to a prefab of your own, so new kinds of bridge\r\n/// (cable-stayed, trusses...) are new designs of a part rather than a new kind of road. Roads reference a style, so\r\n/// every bridge built from it changes together when the asset is edited.\r\n/// \u003C/summary\u003E\r\n[AssetType(Name = \u0022Bridge Style\u0022, Extension = \u0022bridg\u0022, Category = \u0022Road Tool 2\u0022)]\r\npublic sealed class BridgeStyle : GameResource\r\n{\r\n\tprivate const string DefaultMaterial = \u0022roadtool2/materials/concrete.vmat\u0022;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Material of the deck\u0027s sides and underside (and of the walls and pillars when they have none of their own).\r\n\t/// \u003C/summary\u003E\r\n\t[Group(\u0022Deck\u0022)] public Material DeckMaterial { get; set; }\r\n\t[Group(\u0022Deck\u0022), Range(10.0f, 10000.0f)] public float DeckTextureRepeat { get; set { field = value.Clamp(1.0f, 100000.0f); } } = 500.0f;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The deck\u0027s thickness below the road surface.\r\n\t/// \u003C/summary\u003E\r\n\t[Group(\u0022Deck\u0022), Range(5.0f, 500.0f)] public float DeckDepth { get; set { field = value.Clamp(1.0f, 10000.0f); } } = 60.0f;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// A bare ledge of deck outside the side (wall, railing) on each edge. 0 ends the deck at the side\u0027s outer face.\r\n\t/// \u003C/summary\u003E\r\n\t[Group(\u0022Deck\u0022), Range(0.0f, 300.0f)] public float DeckOverhang { get; set { field = value.Clamp(0.0f, 10000.0f); } } = 0.0f;\r\n\r\n\t[Group(\u0022Side\u0022)] public BridgeSideStyle Side { get; set; } = BridgeSideStyle.Wall;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Material of the wall or the railing. Empty uses the deck\u0027s.\r\n\t/// \u003C/summary\u003E\r\n\t[Group(\u0022Side\u0022), ShowIf(nameof(HasBuiltSide), true)] public Material SideMaterial { get; set; }\r\n\t[Group(\u0022Side\u0022), ShowIf(nameof(HasBuiltSide), true), Range(10.0f, 10000.0f)] public float SideTextureRepeat { get; set { field = value.Clamp(1.0f, 100000.0f); } } = 100.0f;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The wall\u0027s thickness, or the railing\u0027s post size; also the width of the strip a prefab side stands on.\r\n\t/// \u003C/summary\u003E\r\n\t[Group(\u0022Side\u0022), HideIf(nameof(Side), BridgeSideStyle.None), Range(1.0f, 200.0f)] public float SideWidth { get; set { field = value.Clamp(0.1f, 10000.0f); } } = 20.0f;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Height of the wall or railing above the road\u0027s border (the pavement top when there is one).\r\n\t/// \u003C/summary\u003E\r\n\t[Group(\u0022Side\u0022), ShowIf(nameof(HasBuiltSide), true), Range(5.0f, 300.0f)] public float SideHeight { get; set { field = value.Clamp(0.1f, 10000.0f); } } = 45.0f;\r\n\r\n\t[Group(\u0022Railing\u0022), ShowIf(nameof(Side), BridgeSideStyle.Railing), Range(50.0f, 1000.0f)] public float PostSpacing { get; set { field = value.Clamp(1.0f, 100000.0f); } } = 200.0f;\r\n\t[Group(\u0022Railing\u0022), ShowIf(nameof(Side), BridgeSideStyle.Railing), Range(1, 6)] public int RailCount { get; set { field = value.Clamp(1, 32); } } = 2;\r\n\t[Group(\u0022Railing\u0022), ShowIf(nameof(Side), BridgeSideStyle.Railing), Range(1.0f, 50.0f)] public float RailSize { get; set { field = value.Clamp(0.1f, 1000.0f); } } = 6.0f;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Placed on the deck\u0027s edge strip with its forward along the road and its right pointing away from the road.\r\n\t/// \u003C/summary\u003E\r\n\t[Group(\u0022Side\u0022), ShowIf(nameof(Side), BridgeSideStyle.Prefab)] public GameObject SidePrefab { get; set; }\r\n\t[Group(\u0022Side\u0022), ShowIf(nameof(Side), BridgeSideStyle.Prefab), Range(10.0f, 2000.0f)] public float SideSpacing { get; set { field = value.Clamp(1.0f, 100000.0f); } } = 200.0f;\r\n\r\n\t[Group(\u0022Supports\u0022)] public BridgeSupportStyle Supports { get; set; } = BridgeSupportStyle.Pillars;\r\n\t[Group(\u0022Supports\u0022), HideIf(nameof(Supports), BridgeSupportStyle.None), Range(200.0f, 10000.0f)] public float SupportSpacing { get; set { field = value.Clamp(1.0f, 100000.0f); } } = 1500.0f;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The pillars\u0027 material. Empty uses the deck\u0027s.\r\n\t/// \u003C/summary\u003E\r\n\t[Group(\u0022Supports\u0022), ShowIf(nameof(Supports), BridgeSupportStyle.Pillars)] public Material SupportMaterial { get; set; }\r\n\t[Group(\u0022Supports\u0022), ShowIf(nameof(Supports), BridgeSupportStyle.Pillars)] public BridgePillarShape PillarShape { get; set; } = BridgePillarShape.Square;\r\n\t[Group(\u0022Supports\u0022), ShowIf(nameof(Supports), BridgeSupportStyle.Pillars)] public BridgePillarLayout PillarLayout { get; set; } = BridgePillarLayout.Single;\r\n\t[Group(\u0022Supports\u0022), ShowIf(nameof(Supports), BridgeSupportStyle.Pillars), Range(10.0f, 1000.0f)] public float PillarSize { get; set { field = value.Clamp(1.0f, 10000.0f); } } = 100.0f;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// For a pair of pillars: how far in from the deck\u0027s edges they stand.\r\n\t/// \u003C/summary\u003E\r\n\t[Group(\u0022Supports\u0022), ShowIf(nameof(Supports), BridgeSupportStyle.Pillars), Range(0.0f, 500.0f)] public float PillarInset { get; set { field = value.Clamp(0.0f, 10000.0f); } } = 20.0f;\r\n\t[Group(\u0022Supports\u0022), ShowIf(nameof(Supports), BridgeSupportStyle.Pillars), Range(3, 32)] public int PillarSegments { get; set { field = value.Clamp(3, 64); } } = 12;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// How far a pillar carries on below the ground it lands on, so it never floats off a slope.\r\n\t/// \u003C/summary\u003E\r\n\t[Group(\u0022Supports\u0022), HideIf(nameof(Supports), BridgeSupportStyle.None), Range(0.0f, 500.0f)] public float SupportSink { get; set { field = value.Clamp(0.0f, 10000.0f); } } = 50.0f;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// How far below the deck a support reaches when there is no ground under it to land on.\r\n\t/// \u003C/summary\u003E\r\n\t[Group(\u0022Supports\u0022), HideIf(nameof(Supports), BridgeSupportStyle.None), Range(100.0f, 10000.0f)] public float SupportFallbackHeight { get; set { field = value.Clamp(1.0f, 100000.0f); } } = 1000.0f;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Placed on the ground under the middle of the deck (or the fallback height below it), with its forward along\r\n\t/// the road. It is up to the prefab to reach the deck.\r\n\t/// \u003C/summary\u003E\r\n\t[Group(\u0022Supports\u0022), ShowIf(nameof(Supports), BridgeSupportStyle.Prefab)] public GameObject SupportPrefab { get; set; }\r\n\r\n\t[Hide, JsonIgnore] public bool HasBuiltSide =\u003E Side is BridgeSideStyle.Wall or BridgeSideStyle.Railing;\r\n\r\n\t[Hide, JsonIgnore] public Material ResolvedDeckMaterial =\u003E DeckMaterial ?? Material.Load(DefaultMaterial);\r\n\r\n\t[Hide, JsonIgnore] public Material ResolvedSideMaterial =\u003E SideMaterial ?? ResolvedDeckMaterial;\r\n\r\n\t[Hide, JsonIgnore] public Material ResolvedSupportMaterial =\u003E SupportMaterial ?? ResolvedDeckMaterial;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// How wide the strip along each deck edge is that the side occupies (nothing for a bare deck).\r\n\t/// \u003C/summary\u003E\r\n\t[Hide, JsonIgnore] public float SideStripWidth =\u003E Side == BridgeSideStyle.None ? 0.0f : SideWidth;\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Folds everything the bridge geometry is built from into a hash, so pieces built with an older version of\r\n\t/// the style are noticed.\r\n\t/// \u003C/summary\u003E\r\n\tpublic void AddToHash(ref StableHash _Hash)\r\n\t{\r\n\t\t_Hash.Add(DeckMaterial?.ResourcePath);\r\n\t\t_Hash.Add(DeckTextureRepeat);\r\n\t\t_Hash.Add(DeckDepth);\r\n\t\t_Hash.Add(DeckOverhang);\r\n\t\t_Hash.Add((int)Side);\r\n\t\t_Hash.Add(SideMaterial?.ResourcePath);\r\n\t\t_Hash.Add(SideTextureRepeat);\r\n\t\t_Hash.Add(SideWidth);\r\n\t\t_Hash.Add(SideHeight);\r\n\t\t_Hash.Add(PostSpacing);\r\n\t\t_Hash.Add(RailCount);\r\n\t\t_Hash.Add(RailSize);\r\n\t\t_Hash.Add(RoadPropSet.PrefabKey(SidePrefab));\r\n\t\t_Hash.Add(SideSpacing);\r\n\t\t_Hash.Add((int)Supports);\r\n\t\t_Hash.Add(SupportSpacing);\r\n\t\t_Hash.Add(SupportMaterial?.ResourcePath);\r\n\t\t_Hash.Add((int)PillarShape);\r\n\t\t_Hash.Add((int)PillarLayout);\r\n\t\t_Hash.Add(PillarSize);\r\n\t\t_Hash.Add(PillarInset);\r\n\t\t_Hash.Add(PillarSegments);\r\n\t\t_Hash.Add(SupportSink);\r\n\t\t_Hash.Add(SupportFallbackHeight);\r\n\t\t_Hash.Add(RoadPropSet.PrefabKey(SupportPrefab));\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The asset was saved: every network with a bridge in this style has stale pieces now.\r\n\t/// \u003C/summary\u003E\r\n\tprotected override void PostReload()\r\n\t{\r\n\t\tbase.PostReload();\r\n\r\n\t\tRoadNetwork.Editor_MarkDirty();\r\n\t}\r\n\r\n\r\n\r\n\tprotected override Bitmap CreateAssetTypeIcon(int _Width, int _Height)\r\n\t{\r\n\t\treturn CreateSimpleAssetTypeIcon(\u0022architecture\u0022, _Width, _Height, \u0022#7fb2ff\u0022, \u0022black\u0022);\r\n\t}\r\n}\r\n"},{"Ident":"redsnail.roadtool2","Path":"Code/Utility/MeshUtility.cs","FileName":"MeshUtility.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":443665,"IsPrivate":false,"Code":"using System.Collections.Generic;\r\nusing Sandbox;\r\n\r\nnamespace RedSnail.RoadTool2;\r\n\r\npublic static class MeshUtility\r\n{\r\n\tpublic static HalfEdgeMesh.VertexHandle GetOrAddVertex(PolygonMesh _Mesh, Dictionary\u003CVector3, HalfEdgeMesh.VertexHandle\u003E _Cache, Vector3 _Pos)\r\n\t{\r\n\t\tif (!_Cache.TryGetValue(_Pos, out var handle))\r\n\t\t{\r\n\t\t\thandle = _Mesh.AddVertices(_Pos)[0];\r\n\t\t\t_Cache[_Pos] = handle;\r\n\t\t}\r\n\r\n\t\treturn handle;\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Adds a quad face; returns an invalid handle when the mesh refused it (a duplicate vertex, a topology clash).\r\n\t/// \u003C/summary\u003E\r\n\tpublic static HalfEdgeMesh.FaceHandle AddTexturedQuad(PolygonMesh _Mesh, Material _Material,\r\n\t\tHalfEdgeMesh.VertexHandle _A, HalfEdgeMesh.VertexHandle _B,\r\n\t\tHalfEdgeMesh.VertexHandle _C, HalfEdgeMesh.VertexHandle _D,\r\n\t\tVector2 _UvA, Vector2 _UvB, Vector2 _UvC, Vector2 _UvD)\r\n\t{\r\n\t\tif (HasDuplicateVertex(_A, _B, _C, _D))\r\n\t\t\treturn default;\r\n\r\n\t\tvar face = _Mesh.AddFace(_A, _B, _C, _D);\r\n\r\n\t\tif (!face.IsValid)\r\n\t\t\treturn default;\r\n\r\n\t\t_Mesh.SetFaceMaterial(face, _Material);\r\n\t\t_Mesh.SetFaceTextureCoords(face, new List\u003CVector2\u003E { _UvA, _UvB, _UvC, _UvD });\r\n\r\n\t\treturn face;\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Adds a triangle face; returns an invalid handle when the mesh refused it.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static HalfEdgeMesh.FaceHandle AddTexturedTriangle(PolygonMesh _Mesh, Material _Material,\r\n\t\tHalfEdgeMesh.VertexHandle _A, HalfEdgeMesh.VertexHandle _B,\r\n\t\tHalfEdgeMesh.VertexHandle _C,\r\n\t\tVector2 _UvA, Vector2 _UvB, Vector2 _UvC)\r\n\t{\r\n\t\tif (HasDuplicateVertex(_A, _B, _C))\r\n\t\t\treturn default;\r\n\r\n\t\tvar face = _Mesh.AddFace(_A, _B, _C);\r\n\r\n\t\tif (!face.IsValid)\r\n\t\t\treturn default;\r\n\r\n\t\t_Mesh.SetFaceMaterial(face, _Material);\r\n\t\t_Mesh.SetFaceTextureCoords(face, new List\u003CVector2\u003E { _UvA, _UvB, _UvC });\r\n\r\n\t\treturn face;\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Paints a face\u0027s vertices with blend weights (what a blendable material mixes its layers by), in the order\r\n\t/// the face\u0027s vertices were given.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static void SetFaceBlends(PolygonMesh _Mesh, HalfEdgeMesh.FaceHandle _Face, IReadOnlyList\u003CColor32\u003E _Blends)\r\n\t{\r\n\t\tif (!_Face.IsValid || !_Mesh.GetFaceVerticesConnectedToFace(_Face, out var edges))\r\n\t\t\treturn;\r\n\r\n\t\tint count = System.Math.Min(edges.Length, _Blends.Count);\r\n\r\n\t\tfor (int i = 0; i \u003C count; i\u002B\u002B)\r\n\t\t\t_Mesh.SetVertexBlend(edges[i], _Blends[i]);\r\n\t}\r\n\r\n\r\n\r\n\tprivate static bool HasDuplicateVertex(HalfEdgeMesh.VertexHandle _A, HalfEdgeMesh.VertexHandle _B, HalfEdgeMesh.VertexHandle _C)\r\n\t{\r\n\t\treturn _A.Equals(_B) || _A.Equals(_C) || _B.Equals(_C);\r\n\t}\r\n\r\n\r\n\r\n\tprivate static bool HasDuplicateVertex(HalfEdgeMesh.VertexHandle _A, HalfEdgeMesh.VertexHandle _B, HalfEdgeMesh.VertexHandle _C, HalfEdgeMesh.VertexHandle _D)\r\n\t{\r\n\t\treturn _A.Equals(_B) || _A.Equals(_C) || _A.Equals(_D) ||\r\n\t\t\t_B.Equals(_C) || _B.Equals(_D) ||\r\n\t\t\t_C.Equals(_D);\r\n\t}\r\n}\r\n"},{"Ident":"redsnail.roadtool2","Path":"Geometry/RoadCurveTable.cs","FileName":"RoadCurveTable.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":443665,"IsPrivate":false,"Code":"using System;\r\nusing Sandbox;\r\n\r\nnamespace RedSnail.RoadTool2;\r\n\r\n/// \u003Csummary\u003E\r\n/// Arc-length table over a \u003Csee cref=\u0022RoadCurve\u0022/\u003E, so the road can be sampled at even distances (mesh rows, chunk\r\n/// boundaries) instead of at even parameter values, which bunch up around tight bends. The samples double as a\r\n/// polyline for picking.\r\n/// \u003C/summary\u003E\r\npublic sealed class RoadCurveTable\r\n{\r\n\tprivate readonly Vector3[] m_Positions;\r\n\tprivate readonly float[] m_Distances;\r\n\r\n\tpublic RoadCurve Curve { get; }\r\n\r\n\tpublic float Length =\u003E m_Distances[^1];\r\n\r\n\tpublic int SampleCount =\u003E m_Positions.Length;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The box the curve itself runs through. Picking widens it by the road\u0027s own reach and skips the road\r\n\t/// altogether when the cursor\u0027s ray misses it, which is most of them in a city.\r\n\t/// \u003C/summary\u003E\r\n\tpublic BBox Bounds { get; }\r\n\r\n\r\n\r\n\tpublic RoadCurveTable(RoadCurve _Curve, int _Samples)\r\n\t{\r\n\t\tCurve = _Curve;\r\n\r\n\t\tint count = Math.Max(1, _Samples);\r\n\t\tm_Positions = new Vector3[count \u002B 1];\r\n\t\tm_Distances = new float[count \u002B 1];\r\n\t\tm_Positions[0] = _Curve.P0;\r\n\r\n\t\tvar bounds = new BBox(_Curve.P0, _Curve.P0);\r\n\r\n\t\tfor (int i = 1; i \u003C= count; i\u002B\u002B)\r\n\t\t{\r\n\t\t\tm_Positions[i] = _Curve.Evaluate((float)i / count);\r\n\t\t\tm_Distances[i] = m_Distances[i - 1] \u002B Vector3.DistanceBetween(m_Positions[i - 1], m_Positions[i]);\r\n\t\t\tbounds = bounds.AddPoint(m_Positions[i]);\r\n\t\t}\r\n\r\n\t\tBounds = bounds;\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Builds a table with a sample density that suits the curve\u0027s length.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static RoadCurveTable Create(RoadCurve _Curve)\r\n\t{\r\n\t\tint samples = Math.Clamp((int)(_Curve.ApproximateLength() / 20.0f), 16, 1024);\r\n\r\n\t\treturn new RoadCurveTable(_Curve, samples);\r\n\t}\r\n\r\n\r\n\r\n\tpublic Vector3 SamplePosition(int _Index)\r\n\t{\r\n\t\treturn m_Positions[_Index];\r\n\t}\r\n\r\n\r\n\r\n\tpublic float SampleDistance(int _Index)\r\n\t{\r\n\t\treturn m_Distances[_Index];\r\n\t}\r\n\r\n\r\n\r\n\tpublic float DistanceToT(float _Distance)\r\n\t{\r\n\t\tif (_Distance \u003C= 0.0f)\r\n\t\t\treturn 0.0f;\r\n\r\n\t\tif (_Distance \u003E= Length)\r\n\t\t\treturn 1.0f;\r\n\r\n\t\tint low = 0;\r\n\t\tint high = m_Distances.Length - 1;\r\n\r\n\t\twhile (high - low \u003E 1)\r\n\t\t{\r\n\t\t\tint mid = (low \u002B high) / 2;\r\n\r\n\t\t\tif (m_Distances[mid] \u003C= _Distance)\r\n\t\t\t\tlow = mid;\r\n\t\t\telse\r\n\t\t\t\thigh = mid;\r\n\t\t}\r\n\r\n\t\tfloat span = m_Distances[high] - m_Distances[low];\r\n\t\tfloat fraction = span \u003E 0.0f ? (_Distance - m_Distances[low]) / span : 0.0f;\r\n\r\n\t\treturn (low \u002B fraction) / (m_Distances.Length - 1);\r\n\t}\r\n\r\n\r\n\r\n\tpublic Vector3 PositionAt(float _Distance)\r\n\t{\r\n\t\treturn Curve.Evaluate(DistanceToT(_Distance));\r\n\t}\r\n\r\n\r\n\r\n\tpublic Vector3 TangentAt(float _Distance)\r\n\t{\r\n\t\treturn Curve.Tangent(DistanceToT(_Distance));\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Where the road is at a distance and which way it runs there, in one go: everything that lays something\r\n\t/// across the road wants both, and asking for them separately searches the table twice.\r\n\t/// \u003C/summary\u003E\r\n\tpublic void Frame(float _Distance, out Vector3 _Position, out Vector3 _Tangent)\r\n\t{\r\n\t\tfloat t = DistanceToT(_Distance);\r\n\r\n\t\t_Position = Curve.Evaluate(t);\r\n\t\t_Tangent = Curve.Tangent(t);\r\n\t}\r\n}\r\n"},{"Ident":"redsnail.roadtool2","Path":"Network/RoadJunctionBuilder.cs","FileName":"RoadJunctionBuilder.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":443665,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\nusing Sandbox;\n\nnamespace RedSnail.RoadTool2;\n\n/// \u003Csummary\u003E\n/// Generates the surface of a junction: the layout\u0027s polygon fanned out from the node. Each triangle of the fan is\n/// planar, so none can be dropped by the mesh builder whatever the arms\u0027 heights do.\n/// \u003C/summary\u003E\ninternal static class RoadJunctionBuilder\n{\n\t/// \u003Csummary\u003E\n\t/// How far below its foot a skirt\u0027s closed-off end reaches: well under any ground dipping beside it.\n\t/// \u003C/summary\u003E\n\tprivate const float SkirtCloseDepth = 20.0f;\n\n\t/// \u003Csummary\u003E\n\t/// Each arm\u0027s texture runs on into the junction over the arm\u0027s own stretch of the outline (see\n\t/// \u003Csee cref=\u0022RoadJunctionLayout.PolygonArms\u0022/\u003E) and meets the next arm\u0027s on a line from the node to the middle\n\t/// of the corner between them, where the borders meet too (or, for a corner on one of the rows, to where the outline\n\t/// comes closest to the node). A road texture with something across its width (lanes,\n\t/// worn wheel tracks, dark edges) turns the corner with the road instead of being cut by a projection laid over\n\t/// it, and nothing is stretched; a road that curves on its way in has its texture bend with it (see\n\t/// \u003Csee cref=\u0022RoadFanBuilder\u0022/\u003E). An arm with a different road surface from the junction\u0027s still has the\n\t/// junction\u0027s surface turn into it the same way (carried on across it instead, a texture fitted to the main road\u0027s\n\t/// width would run off its edges and start again); a road that blends the junction\u0027s surface into its own (see\n\t/// \u003Csee cref=\u0022RoadProfile.RoadBlendMaterial\u0022/\u003E) starts doing so across its mouth (see \u003Csee cref=\u0022RoadMouthBlend\u0022/\u003E),\n\t/// where its share of the corners starts, and carries the blend on from its row. An arm whose road has banks has its\n\t/// road\u0027s surface carried on down under the ground past its half of each corner, as its road\u0027s own is past its edges.\n\t/// \u003Cparamref name=\u0022_ProfileOf\u0022/\u003E gives each arm\u0027s road type, and \u003Cparamref name=\u0022_BlendOf\u0022/\u003E its road\u0027s blend.\n\t/// \u003C/summary\u003E\n\tpublic static PolygonMesh Build(RoadJunctionLayout _Layout, RoadJunctionLayout.Arm _Main, Func\u003CRoadJunctionLayout.Arm, bool\u003E _SameSurface, float _TextureRepeat, bool _FitWidth, Material _Material,\n\t\tFunc\u003CRoadJunctionLayout.Arm, RoadProfile\u003E _ProfileOf = null, Func\u003CRoadJunctionLayout.Arm, RoadSurfaceBlend\u003E _BlendOf = null)\n\t{\n\t\tvar mesh = new PolygonMesh();\n\t\tvar polygon = _Layout.Polygon;\n\t\tvar owners = _Layout.PolygonArms;\n\n\t\tif (polygon.Count \u003C 3)\n\t\t\treturn mesh;\n\n\t\tint mainIndex = _Main is null ? -1 : _Layout.Arms.IndexOf(_Main);\n\n\t\tif (owners is null || owners.Count != polygon.Count || mainIndex \u003C 0)\n\t\t\treturn Build(_Layout, _TextureRepeat, _Material);\n\n\t\tvar armMappings = new RoadArmMapping[_Layout.Arms.Count];\n\t\tvar mappings = new IFanMapping[_Layout.Arms.Count];\n\t\tvar own = new bool[_Layout.Arms.Count];\n\t\tbool allSame = true;\n\n\t\tfor (int i = 0; i \u003C mappings.Length; i\u002B\u002B)\n\t\t{\n\t\t\tvar arm = _Layout.Arms[i];\n\n\t\t\tarmMappings[i] = Mapping(arm, _TextureRepeat, _FitWidth);\n\t\t\tmappings[i] = armMappings[i];\n\t\t\town[i] = true;\n\t\t\tallSame \u0026= i == mainIndex || _SameSurface(arm);\n\t\t}\n\n\t\t// A road splitting in two round a nose far out from the node (a highway\u0027s exit or entry, a fork) is laid out\n\t\t// as roads of its own instead (see RoadSplitBuilder), when its texture\u0027s edges are what has to wrap the nose.\n\t\tif (_FitWidth \u0026\u0026 allSame \u0026\u0026 RoadSplitBuilder.TryBuild(_Layout, armMappings, _Material, out var split))\n\t\t{\n\t\t\tAddSkirts(split, _Layout, mappings, _ProfileOf, _Material);\n\n\t\t\treturn split;\n\t\t}\n\n\t\tvar points = new List\u003CVector3\u003E();\n\t\tvar arms = new List\u003Cint\u003E();\n\t\tvar blends = new IFanBlend[_Layout.Arms.Count];\n\n\t\tOutline(_Layout, mainIndex, points, arms);\n\n\t\tif (_ProfileOf is not null \u0026\u0026 _BlendOf is not null)\n\t\t{\n\t\t\tfor (int i = 0; i \u003C blends.Length; i\u002B\u002B)\n\t\t\t\tblends[i] = i == mainIndex ? null : MouthBlend(_Layout, points, arms, i, _ProfileOf, _BlendOf);\n\t\t}\n\n\t\tRoadFanBuilder.Build(mesh, _Material, _Layout.Centre, points, arms, mappings, own, null, true, blends);\n\t\tAddSkirts(mesh, _Layout, mappings, _ProfileOf, _Material);\n\n\t\treturn mesh;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The outline the surface is fanned out to, with an edge cut straight across from one arm\u0027s row to the next arm\u0027s\n\t/// halved, and the arm each edge belongs to: each takes the half on its side.\n\t/// \u003C/summary\u003E\n\tprivate static void Outline(RoadJunctionLayout _Layout, int _MainIndex, List\u003CVector3\u003E _Points, List\u003Cint\u003E _Arms)\n\t{\n\t\tvar polygon = _Layout.Polygon;\n\t\tvar owners = _Layout.PolygonArms;\n\n\t\tfor (int i = 0; i \u003C polygon.Count; i\u002B\u002B)\n\t\t{\n\t\t\tint next = (i \u002B 1) % polygon.Count;\n\n\t\t\t_Points.Add(polygon[i]);\n\n\t\t\tif (owners[i] \u003E= 0)\n\t\t\t{\n\t\t\t\t_Arms.Add(owners[i]);\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tint before = OwnerNear(owners, i, -1);\n\t\t\tint after = OwnerNear(owners, next, 1);\n\n\t\t\t_Arms.Add(before \u003E= 0 ? before : _MainIndex);\n\n\t\t\tif (before \u003E= 0 \u0026\u0026 after \u003E= 0)\n\t\t\t{\n\t\t\t\t_Points.Add((polygon[i] \u002B polygon[next]) * 0.5f);\n\t\t\t\t_Arms.Add(after);\n\t\t\t}\n\t\t}\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Where a road blending the junction\u0027s surface into its own starts its blend across its mouth (see\n\t/// \u003Csee cref=\u0022RoadMouthBlend\u0022/\u003E): the line from the middle of the corner on one side of the arm to the middle of the\n\t/// corner on the other, where the arm\u0027s share of the outline starts and ends, and its skirt and banks with it. In the\n\t/// arm\u0027s own terms: how far from the node the line crosses the road\u0027s centreline (never past the row), and how much\n\t/// further from the node it lies for each unit out to the road\u0027s right. False where the arm has no share of the\n\t/// outline, or the whole of it.\n\t/// \u003C/summary\u003E\n\tinternal static bool Mouth(RoadJunctionLayout _Layout, RoadJunctionLayout.Arm _Arm, RoadJunctionLayout.Arm _Main, out float _Centre, out float _Slope)\n\t{\n\t\t_Centre = 0.0f;\n\t\t_Slope = 0.0f;\n\n\t\tint mainIndex = _Main is null ? -1 : _Layout.Arms.IndexOf(_Main);\n\n\t\tif (_Layout.Polygon.Count \u003C 3 || _Layout.PolygonArms is null || _Layout.PolygonArms.Count != _Layout.Polygon.Count || mainIndex \u003C 0)\n\t\t\treturn false;\n\n\t\tvar points = new List\u003CVector3\u003E();\n\t\tvar arms = new List\u003Cint\u003E();\n\n\t\tOutline(_Layout, mainIndex, points, arms);\n\n\t\treturn Mouth(_Layout, points, arms, _Layout.Arms.IndexOf(_Arm), out _Centre, out _Slope);\n\t}\n\n\n\n\tprivate static bool Mouth(RoadJunctionLayout _Layout, List\u003CVector3\u003E _Points, List\u003Cint\u003E _Arms, int _Index, out float _Centre, out float _Slope)\n\t{\n\t\t_Centre = 0.0f;\n\t\t_Slope = 0.0f;\n\n\t\tint count = _Points.Count;\n\t\tint first = -1;\n\n\t\tif (_Index \u003C 0)\n\t\t\treturn false;\n\n\t\t// The arm\u0027s stretch, from the edge it takes over at to the last before it hands over.\n\t\tfor (int k = 0; k \u003C count; k\u002B\u002B)\n\t\t{\n\t\t\tif (_Arms[k] == _Index \u0026\u0026 _Arms[(k \u002B count - 1) % count] != _Index)\n\t\t\t{\n\t\t\t\tfirst = k;\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\n\t\tif (first \u003C 0)\n\t\t\treturn false;\n\n\t\tint last = first;\n\n\t\twhile (_Arms[(last \u002B 1) % count] == _Index)\n\t\t\tlast = (last \u002B 1) % count;\n\n\t\tvar arm = _Layout.Arms[_Index];\n\t\tvar mapping = Mapping(arm, 1.0f, false);\n\t\tVector2 from = mapping.Measure(_Points[first]);\n\t\tVector2 to = mapping.Measure(_Points[(last \u002B 1) % count]);\n\t\tfloat fromNode = arm.AtStart ? from.y : arm.Length - from.y;\n\t\tfloat toNode = arm.AtStart ? to.y : arm.Length - to.y;\n\t\tfloat across = to.x - from.x;\n\n\t\t_Slope = MathF.Abs(across) \u003E 1.0f ? (toNode - fromNode) / across : 0.0f;\n\t\t_Centre = Math.Clamp((fromNode \u002B toNode) * 0.5f - _Slope * (from.x \u002B to.x) * 0.5f, 0.0f, arm.Trim);\n\n\t\treturn true;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The blend across an arm\u0027s mouth, or null where its road does not blend the junction\u0027s surface into its own there.\n\t/// It starts where the road\u0027s own blend says, which is where the mouth\u0027s line crosses the road\u0027s centreline.\n\t/// \u003C/summary\u003E\n\tprivate static IFanBlend MouthBlend(RoadJunctionLayout _Layout, List\u003CVector3\u003E _Points, List\u003Cint\u003E _Arms, int _Index,\n\t\tFunc\u003CRoadJunctionLayout.Arm, RoadProfile\u003E _ProfileOf, Func\u003CRoadJunctionLayout.Arm, RoadSurfaceBlend\u003E _BlendOf)\n\t{\n\t\tvar arm = _Layout.Arms[_Index];\n\t\tvar profile = _ProfileOf(arm);\n\n\t\tif (profile?.RoadBlendMaterial is null || arm.Segment.Bridge is not null)\n\t\t\treturn null;\n\n\t\tvar blend = _BlendOf(arm);\n\n\t\tif (blend.IsNone || !(arm.AtStart ? blend.AtStart : blend.AtEnd) || !Mouth(_Layout, _Points, _Arms, _Index, out _, out float slope))\n\t\t\treturn null;\n\n\t\tfloat centre = arm.AtStart ? blend.StartAt : arm.Length - blend.EndAt;\n\n\t\treturn new RoadMouthBlend(arm, profile, blend, arm.AtStart ? blend.StartSource : blend.EndSource, centre, slope);\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Under banks (see \u003Csee cref=\u0022RoadProfile.SkirtWidth\u0022/\u003E), each stretch of the outline an arm with a skirt owns (its\n\t/// half of the corner either side of it) gets a skirt carried on out past it and down, so the ground coming over the\n\t/// kerb never shows a gap beneath it: the arm\u0027s road\u0027s own skirt carried on round the corner, in that road\u0027s surface\n\t/// and mapping, so whatever of it the ground leaves showing matches the road\u0027s. Its end on the arm\u0027s row heads out\n\t/// along the row, where the road\u0027s skirt carries on from it; where it meets the next arm\u0027s half of the corner\n\t/// instead it is closed off, down past its foot, so nothing can be seen under it from that side. A strip of its\n\t/// own, so the mesh never has to join it to the fan\u0027s rim.\n\t/// \u003C/summary\u003E\n\tprivate static void AddSkirts(PolygonMesh _Mesh, RoadJunctionLayout _Layout, IReadOnlyList\u003CIFanMapping\u003E _Mappings, Func\u003CRoadJunctionLayout.Arm, RoadProfile\u003E _ProfileOf, Material _Material)\n\t{\n\t\tif (_ProfileOf is null)\n\t\t\treturn;\n\n\t\tvar polygon = _Layout.Polygon;\n\t\tvar owners = _Layout.PolygonArms;\n\t\tint count = polygon.Count;\n\t\tvar rows = new HashSet\u003Cint\u003E(_Layout.RowStarts);\n\t\tvar profiles = new RoadProfile[_Layout.Arms.Count];\n\n\t\t// A bridge\u0027s deck has no skirt, so nor does its share of the corners.\n\t\tfor (int i = 0; i \u003C profiles.Length; i\u002B\u002B)\n\t\t\tprofiles[i] = _Layout.Arms[i].Segment.Bridge is null ? _ProfileOf(_Layout.Arms[i]) : null;\n\n\t\tfor (int first = 0; first \u003C count; first\u002B\u002B)\n\t\t{\n\t\t\tint owner = owners[first];\n\n\t\t\t// A stretch starts where an arm\u0027s half of a corner does.\n\t\t\tif (!Skirted(first) || (Skirted(Previous(first)) \u0026\u0026 owners[Previous(first)] == owner))\n\t\t\t\tcontinue;\n\n\t\t\tvar profile = profiles[owner];\n\t\t\tvar arm = _Layout.Arms[owner];\n\t\t\tvar mapping = new RoadArmMapping(arm.Table, arm.AtStart, arm.Trim, arm.Widths, profile.RoadTextureRepeat, profile.RoadTextureFitsWidth, true);\n\t\t\tvar material = profile.ResolvedRoadMaterial;\n\t\t\tbool fit = profile.RoadTextureFitsWidth;\n\t\t\tvar vertices = new List\u003CVector3\u003E { polygon[first] };\n\t\t\tint last = first;\n\n\t\t\twhile (Next(last) != first \u0026\u0026 Skirted(Next(last)) \u0026\u0026 owners[Next(last)] == owner)\n\t\t\t\tlast = Next(last);\n\n\t\t\tfor (int e = first; ; e = Next(e))\n\t\t\t{\n\t\t\t\tvertices.Add(polygon[Next(e)]);\n\n\t\t\t\tif (e == last)\n\t\t\t\t\tbreak;\n\t\t\t}\n\n\t\t\t// Out from each point square to the outline there; along the row at a row\u0027s end, as the road\u0027s skirt goes.\n\t\t\tvar outwards = new Vector3[vertices.Count];\n\n\t\t\tfor (int j = 0; j \u003C vertices.Count; j\u002B\u002B)\n\t\t\t{\n\t\t\t\tint before = j == 0 ? Previous(first) : -1;\n\t\t\t\tint after = j == vertices.Count - 1 ? Next(last) : -1;\n\n\t\t\t\tif (before \u003E= 0 \u0026\u0026 rows.Contains(before))\n\t\t\t\t\toutwards[j] = Flat(polygon[first] - polygon[before]).Normal;\n\t\t\t\telse if (after \u003E= 0 \u0026\u0026 rows.Contains(after))\n\t\t\t\t\toutwards[j] = Flat(polygon[after] - polygon[Next(after)]).Normal;\n\t\t\t\telse\n\t\t\t\t\toutwards[j] = (EdgeOutward(j == 0 ? polygon[before] : vertices[j - 1], vertices[j]) \u002B EdgeOutward(vertices[j], j == vertices.Count - 1 ? polygon[Next(after)] : vertices[j \u002B 1])).Normal;\n\t\t\t}\n\n\t\t\tvar top = new HalfEdgeMesh.VertexHandle[vertices.Count];\n\t\t\tvar bottom = new HalfEdgeMesh.VertexHandle[vertices.Count];\n\t\t\tvar bottoms = new Vector3[vertices.Count];\n\n\t\t\tfor (int j = 0; j \u003C vertices.Count; j\u002B\u002B)\n\t\t\t{\n\t\t\t\tbottoms[j] = vertices[j] \u002B outwards[j] * profile.SkirtWidth - Vector3.Up * profile.SkirtDepth;\n\t\t\t\ttop[j] = _Mesh.AddVertices(vertices[j])[0];\n\t\t\t\tbottom[j] = _Mesh.AddVertices(bottoms[j])[0];\n\t\t\t}\n\n\t\t\t// The outline runs counter-clockwise seen from above, the junction on its left: wound so the strip faces up.\n\t\t\tfor (int j = 0; j \u003C vertices.Count - 1; j\u002B\u002B)\n\t\t\t{\n\t\t\t\tVector2 topA = SkirtUv(mapping, vertices[j], fit);\n\t\t\t\tVector2 topB = SkirtUv(mapping, vertices[j \u002B 1], fit);\n\t\t\t\tVector2 bottomA = SkirtUv(mapping, bottoms[j], fit);\n\t\t\t\tVector2 bottomB = SkirtUv(mapping, bottoms[j \u002B 1], fit);\n\n\t\t\t\tMeshUtility.AddTexturedTriangle(_Mesh, material, top[j], bottom[j], bottom[j \u002B 1], topA, bottomA, bottomB);\n\t\t\t\tMeshUtility.AddTexturedTriangle(_Mesh, material, top[j], bottom[j \u002B 1], top[j \u002B 1], topA, bottomB, topB);\n\t\t\t}\n\n\t\t\t// Closed off where it stops beside another arm\u0027s half of the corner.\n\t\t\tif (!rows.Contains(Previous(first)))\n\t\t\t\tCloseSkirt(_Mesh, material, vertices[0], bottoms[0], vertices[1] - vertices[0], profile, mapping, fit);\n\n\t\t\tif (!rows.Contains(Next(last)))\n\t\t\t\tCloseSkirt(_Mesh, material, vertices[^1], bottoms[^1], vertices[^2] - vertices[^1], profile, mapping, fit);\n\t\t}\n\n\t\tbool Skirted(int _Edge) =\u003E owners[_Edge] \u003E= 0 \u0026\u0026 !rows.Contains(_Edge) \u0026\u0026 profiles[owners[_Edge]] is { HasSkirt: true };\n\t\tint Previous(int _Edge) =\u003E (_Edge \u002B count - 1) % count;\n\t\tint Next(int _Edge) =\u003E (_Edge \u002B 1) % count;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// A point of a skirt in its road\u0027s own mapping: carried on out past the edge at the texture\u0027s own size, a texture\n\t/// fitted to the width turned back on itself there (see \u003Csee cref=\u0022RoadSurfaceBuilder.SkirtShare\u0022/\u003E).\n\t/// \u003C/summary\u003E\n\tprivate static Vector2 SkirtUv(RoadArmMapping _Mapping, Vector3 _Point, bool _FitWidth)\n\t{\n\t\tVector2 uv = _Mapping.Uv(_Point);\n\n\t\treturn _FitWidth ? new Vector2(RoadSurfaceBuilder.SkirtShare(uv.x), uv.y) : uv;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Closes off a skirt where it stops beside another arm\u0027s half of a corner: a face straight down from its end (its\n\t/// top on the kerb, its bottom out at its foot) to well under its foot, facing away from it (\u003Cparamref name=\u0022_Into\u0022/\u003E\n\t/// runs back along it), so the ground dipping beside it never shows a way in under it.\n\t/// \u003C/summary\u003E\n\tprivate static void CloseSkirt(PolygonMesh _Mesh, Material _Material, Vector3 _Top, Vector3 _Bottom, Vector3 _Into, RoadProfile _Profile, RoadArmMapping _Mapping, bool _FitWidth)\n\t{\n\t\tfloat repeat = MathF.Max(1.0f, _Profile.RoadTextureRepeat);\n\t\tfloat topDrop = _Profile.SkirtDepth \u002B SkirtCloseDepth;\n\t\tVector3 topFoot = _Top - Vector3.Up * topDrop;\n\t\tVector3 bottomFoot = _Bottom - Vector3.Up * SkirtCloseDepth;\n\t\tVector2 topUv = SkirtUv(_Mapping, _Top, _FitWidth);\n\t\tVector2 bottomUv = SkirtUv(_Mapping, _Bottom, _FitWidth);\n\t\tVector2 topFootUv = topUv \u002B new Vector2(0.0f, topDrop / repeat);\n\t\tVector2 bottomFootUv = bottomUv \u002B new Vector2(0.0f, SkirtCloseDepth / repeat);\n\n\t\tvar top = _Mesh.AddVertices(_Top)[0];\n\t\tvar bottom = _Mesh.AddVertices(_Bottom)[0];\n\t\tvar below = _Mesh.AddVertices(bottomFoot)[0];\n\t\tvar under = _Mesh.AddVertices(topFoot)[0];\n\n\t\t// Wound to face away from the skirt it closes.\n\t\tif (Vector3.Dot(Vector3.Cross(_Bottom - _Top, bottomFoot - _Top), _Into) \u003E 0.0f)\n\t\t{\n\t\t\tMeshUtility.AddTexturedTriangle(_Mesh, _Material, top, below, bottom, topUv, bottomFootUv, bottomUv);\n\t\t\tMeshUtility.AddTexturedTriangle(_Mesh, _Material, top, under, below, topUv, topFootUv, bottomFootUv);\n\t\t}\n\t\telse\n\t\t{\n\t\t\tMeshUtility.AddTexturedTriangle(_Mesh, _Material, top, bottom, below, topUv, bottomUv, bottomFootUv);\n\t\t\tMeshUtility.AddTexturedTriangle(_Mesh, _Material, top, below, under, topUv, bottomFootUv, topFootUv);\n\t\t}\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Out of the junction, flat, from the edge of its outline between two points (which runs counter-clockwise).\n\t/// \u003C/summary\u003E\n\tprivate static Vector3 EdgeOutward(Vector3 _From, Vector3 _To)\n\t{\n\t\tVector3 along = Flat(_To - _From).Normal;\n\n\t\treturn new Vector3(along.y, -along.x, 0.0f);\n\t}\n\n\n\n\tprivate static Vector3 Flat(Vector3 _Vector)\n\t{\n\t\treturn _Vector.WithZ(0.0f);\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The plain top-down projection, for an outline whose arms were never noted (built before they were).\n\t/// \u003C/summary\u003E\n\tpublic static PolygonMesh Build(RoadJunctionLayout _Layout, float _TextureRepeat, Material _Material)\n\t{\n\t\tvar mesh = new PolygonMesh();\n\t\tvar polygon = _Layout.Polygon;\n\n\t\tif (polygon.Count \u003C 3)\n\t\t\treturn mesh;\n\n\t\tvar centre = mesh.AddVertices(_Layout.Centre)[0];\n\t\tvar ring = mesh.AddVertices(polygon.ToArray());\n\t\tVector2 centreUv = PlanarUv(_Layout.Centre, _TextureRepeat);\n\n\t\tfor (int i = 0; i \u003C polygon.Count; i\u002B\u002B)\n\t\t{\n\t\t\tint next = (i \u002B 1) % polygon.Count;\n\n\t\t\tMeshUtility.AddTexturedTriangle(mesh, _Material, centre, ring[i], ring[next],\n\t\t\t\tcentreUv, PlanarUv(polygon[i], _TextureRepeat), PlanarUv(polygon[next], _TextureRepeat));\n\t\t}\n\n\t\treturn mesh;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// An arm\u0027s mapping, with the node held inside the arm\u0027s texture: a lane that sits off to one side of the road\u0027s\n\t/// centreline (a ramp starting from the side of a highway) can end beside the node rather than across it, and its\n\t/// texture\u0027s edges would otherwise be drawn out across the junction from the node.\n\t/// \u003C/summary\u003E\n\tprivate static RoadArmMapping Mapping(RoadJunctionLayout.Arm _Arm, float _TextureRepeat, bool _FitWidth)\n\t{\n\t\treturn new RoadArmMapping(_Arm.Table, _Arm.AtStart, _Arm.Trim, _Arm.Widths, _TextureRepeat, _FitWidth, true);\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The arm owning the nearest edge that has one, walking round the outline one way from an edge.\n\t/// \u003C/summary\u003E\n\tprivate static int OwnerNear(IReadOnlyList\u003Cint\u003E _Owners, int _From, int _Step)\n\t{\n\t\tfor (int k = 0; k \u003C _Owners.Count; k\u002B\u002B)\n\t\t{\n\t\t\tint owner = _Owners[((_From \u002B _Step * k) % _Owners.Count \u002B _Owners.Count) % _Owners.Count];\n\n\t\t\tif (owner \u003E= 0)\n\t\t\t\treturn owner;\n\t\t}\n\n\t\treturn -1;\n\t}\n\n\n\n\tprivate static Vector2 PlanarUv(Vector3 _Position, float _TextureRepeat)\n\t{\n\t\treturn new Vector2(_Position.x, _Position.y) / _TextureRepeat;\n\t}\n}\n"},{"Ident":"redsnail.roadtool2","Path":"Network/RoadSplitBuilder.cs","FileName":"RoadSplitBuilder.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":443665,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\nusing Sandbox;\n\nnamespace RedSnail.RoadTool2;\n\n/// \u003Csummary\u003E\n/// The surface of a junction where one road splits in two around a nose (a highway exit or entry, a fork), for a road\n/// texture fitted to the road\u0027s width. Fanned out from the node like any junction, such a junction reaches its nose\n/// thousands of units out in slivers, and no mapping laid over those can wrap the texture\u0027s edge round the nose: it\n/// smears, and the branches\u0027 lane edges show as lines across the gore. Here only the trunk\u0027s share (the road the\n/// split comes from) is fanned. Each branch is laid like a road of its own, in rows across it from the node out to\n/// its row, between its outer kerb and a spine from the node through the apex (where the branches\u0027 inner edges\n/// cross) to the nose\u0027s tip; its texture is fitted across that, edge on the outer kerb and round the nose, and held\n/// just short of its edge along the spine, which is no kerb.\n/// \u003C/summary\u003E\ninternal static class RoadSplitBuilder\n{\n\t/// \u003Csummary\u003E\n\t/// How far short of its edge (in U) a branch\u0027s texture is held along the spine.\n\t/// \u003C/summary\u003E\n\tprivate const float SpineMargin = 0.05f;\n\n\t/// \u003Csummary\u003E\n\t/// A nose sharper than this (the sine of its corner\u0027s half angle) is what makes a split.\n\t/// \u003C/summary\u003E\n\tprivate const float MaxHalfAngleSin = 0.5f;\n\n\t/// \u003Csummary\u003E\n\t/// A nose nearer the node than this many times the wider branch\u0027s width is fanned like any other corner.\n\t/// \u003C/summary\u003E\n\tprivate const float MinReach = 2.0f;\n\n\t/// \u003Csummary\u003E\n\t/// The spine\u0027s points from the node to the apex are this share of the wider branch\u0027s width apart; from the apex\n\t/// to the tip, and along each row, this share of the branch\u0027s own. Close enough that the surface strays no more\n\t/// than a few units from the plain fan the ground under a junction is shaped to, even round a steep nose.\n\t/// \u003C/summary\u003E\n\tprivate const float RowStep = 0.25f;\n\tprivate const float PointStep = 0.0625f;\n\n\t/// \u003Csummary\u003E\n\t/// How far (as a share of the junction\u0027s area) the triangles may cover more or less than its outline before\n\t/// something is taken to have gone wrong and the junction is fanned instead.\n\t/// \u003C/summary\u003E\n\tprivate const double AreaTolerance = 0.001;\n\n\t/// \u003Csummary\u003E\n\t/// A point of a branch\u0027s strip and its texture coordinates.\n\t/// \u003C/summary\u003E\n\tprivate readonly record struct Mark(Vector3 Position, Vector2 Uv);\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Builds the junction\u0027s surface as a split, when it is one: three arms, two of which (the branches) meet at a\n\t/// sharp, filleted nose well out from the node, beyond the point their inner edges cross. Anything else, or\n\t/// anything the rows would not lay out cleanly, is left to the fan. \u003Cparamref name=\u0022_Mappings\u0022/\u003E are the arms\u0027 own\n\t/// mappings, in the layout\u0027s order.\n\t/// \u003C/summary\u003E\n\tpublic static bool TryBuild(RoadJunctionLayout _Layout, IReadOnlyList\u003CRoadArmMapping\u003E _Mappings, Material _Material, out PolygonMesh _Mesh)\n\t{\n\t\t_Mesh = null;\n\n\t\tvar polygon = _Layout.Polygon;\n\t\tvar rows = _Layout.RowStarts;\n\t\tint count = polygon.Count;\n\n\t\tif (_Layout.Arms.Count != 3 || rows is null || rows.Count != 3 || _Mappings.Count != 3 || count \u003C 3)\n\t\t\treturn false;\n\n\t\tforeach (int row in rows)\n\t\t{\n\t\t\tif (row \u003C 0 || row \u003E= count)\n\t\t\t\treturn false;\n\t\t}\n\n\t\tRoadJunctionLayout.CornerPath nose = null;\n\n\t\tforeach (var path in _Layout.CornerPaths)\n\t\t{\n\t\t\tif (path.Fold is null || path.Fold.HalfAngleSin \u003E= MaxHalfAngleSin)\n\t\t\t\tcontinue;\n\n\t\t\tif (nose is not null)\n\t\t\t\treturn false;\n\n\t\t\tnose = path;\n\t\t}\n\n\t\tif (nose is null)\n\t\t\treturn false;\n\n\t\t// Counter-clockwise: the trunk, then the branch whose left edge runs to the nose, then the other.\n\t\tint first = _Layout.Arms.IndexOf(nose.ArmA);\n\t\tint second = _Layout.Arms.IndexOf(nose.ArmB);\n\t\tint trunk = 3 - first - second;\n\n\t\tif (first \u003C 0 || second != (first \u002B 1) % 3 || trunk != (second \u002B 1) % 3)\n\t\t\treturn false;\n\n\t\t// The trunk comes in from the far side: a branch at a right angle to it is a corner, not a split.\n\t\tvar trunkDirection = _Layout.Arms[trunk].Direction;\n\n\t\tif (Vector2.Dot(trunkDirection, _Layout.Arms[first].Direction) \u003E -0.5f || Vector2.Dot(trunkDirection, _Layout.Arms[second].Direction) \u003E -0.5f)\n\t\t\treturn false;\n\n\t\t// The nose\u0027s points are the polygon\u0027s from the first branch\u0027s row on, its middle the tip.\n\t\tint noseStart = (rows[first] \u002B 1) % count;\n\n\t\tif (Wrap(rows[second] - noseStart, count) != nose.Points.Count - 1 || nose.MidIndex \u003C= 0 || nose.MidIndex \u003E= nose.Points.Count - 1)\n\t\t\treturn false;\n\n\t\tint tip = (noseStart \u002B nose.MidIndex) % count;\n\t\tvar node = _Layout.Centre;\n\t\tVector3 tipPoint = polygon[tip];\n\t\tvar apex = OnCone(_Layout, new Vector3(nose.Fold.Apex.x, nose.Fold.Apex.y, node.z));\n\t\tfloat reach = Flat(tipPoint - node).Length;\n\t\tfloat width = MathF.Max(RowWidth(_Layout.Arms[first]), RowWidth(_Layout.Arms[second]));\n\n\t\t// The apex has to lie between the node and the nose, the nose well out.\n\t\tif (reach \u003C MinReach * width || Vector2.Dot(Flat(apex - node), Flat(tipPoint - node)) \u003C= 0.0f || Flat(apex - node).Length \u003E= reach)\n\t\t\treturn false;\n\n\t\t// Where the trunk\u0027s share ends on its two kerbs: their points nearest the node.\n\t\tint outerFirst = Nearest(polygon, (rows[trunk] \u002B 1) % count, rows[first], node);\n\t\tint outerSecond = Nearest(polygon, (rows[second] \u002B 1) % count, rows[trunk], node);\n\n\t\tif (outerFirst \u003C 0 || outerSecond \u003C 0)\n\t\t\treturn false;\n\n\t\t// The spine, shared by both branches: from the node to the apex, and on down the gore to the tip.\n\t\tvar spine = new List\u003CVector3\u003E { node };\n\n\t\tAddSpan(spine, node, apex, width * RowStep, _Layout);\n\t\tAddSpan(spine, apex, tipPoint, width * PointStep, _Layout);\n\t\tspine.RemoveAt(spine.Count - 1);\n\n\t\t// Each branch\u0027s two sides, from the node\u0027s end out to its row: its outer kerb, and the spine and its half of\n\t\t// the nose.\n\t\tvar firstOuter = Walk(polygon, outerFirst, rows[first]);\n\t\tvar firstInner = Walk(polygon, noseStart, tip);\n\t\tvar secondOuter = Walk(polygon, (rows[second] \u002B 1) % count, outerSecond);\n\t\tvar secondInner = Walk(polygon, tip, rows[second]);\n\n\t\tfirstInner.Reverse();\n\t\tsecondOuter.Reverse();\n\t\tfirstInner.InsertRange(0, spine);\n\t\tsecondInner.InsertRange(0, spine);\n\n\t\t// Rows across a branch need both its sides to run steadily away from the node; anything else is fanned.\n\t\tif (!Outward(firstOuter, _Layout.Arms[first], _Mappings[first]) || !Outward(firstInner, _Layout.Arms[first], _Mappings[first])\n\t\t\t|| !Outward(secondOuter, _Layout.Arms[second], _Mappings[second]) || !Outward(secondInner, _Layout.Arms[second], _Mappings[second]))\n\t\t\treturn false;\n\n\t\tvar firstTriangles = BuildBranch(_Layout, _Layout.Arms[first], _Mappings[first], firstOuter, firstInner, spine.Count);\n\t\tvar secondTriangles = BuildBranch(_Layout, _Layout.Arms[second], _Mappings[second], secondOuter, secondInner, spine.Count);\n\n\t\tif (firstTriangles is null || secondTriangles is null)\n\t\t\treturn false;\n\n\t\t// The trunk\u0027s share fanned from the node, and both branches, have to cover the outline exactly: no more (two\n\t\t// triangles over one spot) and no less (a hole).\n\t\tvar share = Walk(polygon, outerSecond, outerFirst);\n\t\tdouble outline = 0.0;\n\t\tdouble covered = 0.0;\n\n\t\tfor (int i = 0; i \u003C count; i\u002B\u002B)\n\t\t\toutline \u002B= Cross(polygon[i], polygon[(i \u002B 1) % count], node);\n\n\t\tfor (int i = 0; i \u003C share.Count - 1; i\u002B\u002B)\n\t\t\tcovered \u002B= Cross(share[i], share[i \u002B 1], node);\n\n\t\tforeach (var triangle in firstTriangles)\n\t\t\tcovered \u002B= Cross(triangle[1].Position, triangle[2].Position, triangle[0].Position);\n\n\t\tforeach (var triangle in secondTriangles)\n\t\t\tcovered \u002B= Cross(triangle[1].Position, triangle[2].Position, triangle[0].Position);\n\n\t\tif (outline \u003C= 0.0 || Math.Abs(covered - outline) \u003E outline * AreaTolerance)\n\t\t\treturn false;\n\n\t\tvar mesh = new PolygonMesh();\n\t\tvar vertices = new Dictionary\u003CVector2, HalfEdgeMesh.VertexHandle\u003E();\n\n\t\tHalfEdgeMesh.VertexHandle Vertex(Vector3 _Position)\n\t\t{\n\t\t\tvar key = Flat(_Position);\n\n\t\t\tif (!vertices.TryGetValue(key, out var handle))\n\t\t\t{\n\t\t\t\thandle = mesh.AddVertices(_Position)[0];\n\t\t\t\tvertices[key] = handle;\n\t\t\t}\n\n\t\t\treturn handle;\n\t\t}\n\n\t\t// The trunk first, then each branch from the node out, so every face joins on to those before it.\n\t\tRoadFanBuilder.Build(mesh, _Material, node, share, new int[share.Count], new IFanMapping[] { _Mappings[trunk] }, new[] { true }, Vertex, false);\n\n\t\tforeach (var triangle in firstTriangles)\n\t\t\tMeshUtility.AddTexturedTriangle(mesh, _Material, Vertex(triangle[0].Position), Vertex(triangle[1].Position), Vertex(triangle[2].Position), triangle[0].Uv, triangle[1].Uv, triangle[2].Uv);\n\n\t\tforeach (var triangle in secondTriangles)\n\t\t\tMeshUtility.AddTexturedTriangle(mesh, _Material, Vertex(triangle[0].Position), Vertex(triangle[1].Position), Vertex(triangle[2].Position), triangle[0].Uv, triangle[1].Uv, triangle[2].Uv);\n\n\t\t_Mesh = mesh;\n\n\t\treturn true;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// One branch\u0027s triangles, facing up, in the order they join on to one another. \u003Cparamref name=\u0022_Outer\u0022/\u003E runs\n\t/// along its outer kerb from the trunk\u0027s share to its row; \u003Cparamref name=\u0022_Inner\u0022/\u003E along the spine and then, from\n\t/// \u003Cparamref name=\u0022_KerbFrom\u0022/\u003E on, round the nose\u0027s half from its tip to the row. A row crosses the branch from each\n\t/// point of the inner side to the point of the outer kerb as far along it (as a share of the way, so the first row is\n\t/// the trunk\u0027s fan\u0027s end spoke and the last the branch\u0027s own row); the band between two rows is zipped from the kerb\n\t/// in, with whatever of the kerb\u0027s own points lie between them fanned from the first row\u0027s first point in. Null when\n\t/// the rows would fold over one another anywhere.\n\t/// \u003C/summary\u003E\n\tprivate static List\u003CMark[]\u003E BuildBranch(RoadJunctionLayout _Layout, RoadJunctionLayout.Arm _Arm, RoadArmMapping _Mapping, List\u003CVector3\u003E _Outer, List\u003CVector3\u003E _Inner,\n\t\tint _KerbFrom)\n\t{\n\t\tif (_Outer.Count \u003C 2 || _Inner.Count - _KerbFrom \u003C 2)\n\t\t\treturn null;\n\n\t\t// The branch\u0027s texture runs from its edge on the outer kerb to its other edge round the nose.\n\t\tfloat outerU = _Mapping.KerbUv(_Outer[^1]).x;\n\t\tfloat innerEdgeU = _Mapping.KerbUv(_Inner[^1]).x;\n\t\tbool innerHigh = innerEdgeU \u003E outerU;\n\n\t\tfloat InnerU(int _Index)\n\t\t{\n\t\t\tif (_Index \u003E= _KerbFrom)\n\t\t\t\treturn innerEdgeU;\n\n\t\t\tfloat u = _Mapping.Uv(_Inner[_Index]).x;\n\n\t\t\treturn innerHigh ? MathF.Min(u, innerEdgeU - SpineMargin) : MathF.Max(u, innerEdgeU \u002B SpineMargin);\n\t\t}\n\n\t\tMark MarkAt(Vector3 _Point, float _U)\n\t\t{\n\t\t\treturn new Mark(_Point, new Vector2(_U, _Mapping.Uv(_Point).y));\n\t\t}\n\n\t\tfloat[] outerAt = Levels(_Outer, _Arm, _Mapping);\n\t\tfloat[] innerAt = Levels(_Inner, _Arm, _Mapping);\n\t\tfloat outerSpan = outerAt[^1] - outerAt[0];\n\t\tfloat innerSpan = innerAt[^1] - innerAt[0];\n\n\t\tif (outerSpan \u003C 1.0f || innerSpan \u003C 1.0f)\n\t\t\treturn null;\n\n\t\tfloat step = MathF.Max(1.0f, RowWidth(_Arm) * PointStep);\n\t\tvar rows = new List\u003C(Mark[] Points, int Next)\u003E(_Inner.Count);\n\n\t\tfor (int k = 0; k \u003C _Inner.Count; k\u002B\u002B)\n\t\t{\n\t\t\tbool last = k == _Inner.Count - 1;\n\t\t\tVector3 outerPoint;\n\t\t\tint next;\n\n\t\t\tif (k == 0)\n\t\t\t{\n\t\t\t\touterPoint = _Outer[0];\n\t\t\t\tnext = 1;\n\t\t\t}\n\t\t\telse if (last)\n\t\t\t{\n\t\t\t\touterPoint = _Outer[^1];\n\t\t\t\tnext = _Outer.Count;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\touterPoint = PointAt(_Outer, outerAt, outerAt[0] \u002B (innerAt[k] - innerAt[0]) / innerSpan * outerSpan, out next);\n\t\t\t}\n\n\t\t\tVector3 innerPoint = _Inner[k];\n\t\t\tfloat innerU = InnerU(k);\n\n\t\t\t// The first row is the trunk\u0027s fan\u0027s end spoke, whole.\n\t\t\tint pieces = k == 0 ? 1 : Math.Max(1, (int)MathF.Ceiling(Flat(innerPoint - outerPoint).Length / step));\n\t\t\tvar row = new Mark[pieces \u002B 1];\n\n\t\t\tfor (int j = 0; j \u003C= pieces; j\u002B\u002B)\n\t\t\t{\n\t\t\t\tfloat f = (float)j / pieces;\n\t\t\t\tVector3 point = j == 0 ? outerPoint : j == pieces ? innerPoint : Vector3.Lerp(outerPoint, innerPoint, f);\n\n\t\t\t\t// Inside, on the surface the plain fan would have; the branch\u0027s own row straight, as its road\u0027s is.\n\t\t\t\tif (j \u003E 0 \u0026\u0026 j \u003C pieces \u0026\u0026 !last)\n\t\t\t\t\tpoint = OnCone(_Layout, point);\n\n\t\t\t\trow[j] = MarkAt(point, MathX.Lerp(outerU, innerU, f));\n\t\t\t}\n\n\t\t\trows.Add((row, next));\n\t\t}\n\n\t\tvar triangles = new List\u003CMark[]\u003E();\n\n\t\tfor (int k = 0; k \u003C rows.Count - 1; k\u002B\u002B)\n\t\t{\n\t\t\tvar (a, aNext) = rows[k];\n\t\t\tvar (b, bNext) = rows[k \u002B 1];\n\n\t\t\t// The kerb\u0027s own points between the two rows, fanned from the first row\u0027s first point in.\n\t\t\tvar kerb = new List\u003CMark\u003E { a[0] };\n\n\t\t\tfor (int i = aNext; i \u003C bNext \u0026\u0026 i \u003C _Outer.Count; i\u002B\u002B)\n\t\t\t{\n\t\t\t\tif (Flat(_Outer[i] - a[0].Position).Length \u003E 0.01f \u0026\u0026 Flat(_Outer[i] - b[0].Position).Length \u003E 0.01f)\n\t\t\t\t\tkerb.Add(MarkAt(_Outer[i], outerU));\n\t\t\t}\n\n\t\t\tif (kerb.Count \u003E 1)\n\t\t\t{\n\t\t\t\tkerb.Add(b[0]);\n\n\t\t\t\tfor (int j = 0; j \u003C kerb.Count - 1; j\u002B\u002B)\n\t\t\t\t\tAdd(triangles, kerb[j \u002B 1], kerb[j], a[1]);\n\n\t\t\t\tZip(triangles, a, 1, b);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tZip(triangles, a, 0, b);\n\t\t\t}\n\t\t}\n\n\t\t// One winding for the whole branch, facing up; a triangle against it means the rows fold over somewhere.\n\t\tdouble area = 0.0;\n\n\t\tforeach (var triangle in triangles)\n\t\t\tarea \u002B= Cross(triangle[1].Position, triangle[2].Position, triangle[0].Position);\n\n\t\tif (area \u003C 0.0)\n\t\t{\n\t\t\tforeach (var triangle in triangles)\n\t\t\t\t(triangle[1], triangle[2]) = (triangle[2], triangle[1]);\n\t\t}\n\n\t\tforeach (var triangle in triangles)\n\t\t{\n\t\t\tif (Cross(triangle[1].Position, triangle[2].Position, triangle[0].Position) \u003C= 0.0)\n\t\t\t\treturn null;\n\t\t}\n\n\t\treturn triangles;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Triangles between two rows of a band (\u003Cparamref name=\u0022_A\u0022/\u003E from \u003Cparamref name=\u0022_From\u0022/\u003E on, and\n\t/// \u003Cparamref name=\u0022_B\u0022/\u003E), both running from the kerb in, in the order their points come along them.\n\t/// \u003C/summary\u003E\n\tprivate static void Zip(List\u003CMark[]\u003E _Triangles, Mark[] _A, int _From, Mark[] _B)\n\t{\n\t\tfloat[] atA = Fractions(_A, _From);\n\t\tfloat[] atB = Fractions(_B, 0);\n\t\tint a = _From;\n\t\tint b = 0;\n\n\t\twhile (a \u003C _A.Length - 1 || b \u003C _B.Length - 1)\n\t\t{\n\t\t\tif (b == _B.Length - 1 || (a \u003C _A.Length - 1 \u0026\u0026 atA[a \u002B 1] \u003C= atB[b \u002B 1]))\n\t\t\t{\n\t\t\t\tAdd(_Triangles, _A[a], _A[a \u002B 1], _B[b]);\n\t\t\t\ta\u002B\u002B;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tAdd(_Triangles, _A[a], _B[b \u002B 1], _B[b]);\n\t\t\t\tb\u002B\u002B;\n\t\t\t}\n\t\t}\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Adds a triangle unless its points are in a line (rows that share a point on the kerb, points along a straight\n\t/// kerb), which would make no face.\n\t/// \u003C/summary\u003E\n\tprivate static void Add(List\u003CMark[]\u003E _Triangles, Mark _A, Mark _B, Mark _C)\n\t{\n\t\tif (Math.Abs(Cross(_B.Position, _C.Position, _A.Position)) \u003C 0.002)\n\t\t\treturn;\n\n\t\t_Triangles.Add(new[] { _A, _B, _C });\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// How far along a row each of its points is from \u003Cparamref name=\u0022_From\u0022/\u003E, as a share of the rest of its length.\n\t/// \u003C/summary\u003E\n\tprivate static float[] Fractions(Mark[] _Row, int _From)\n\t{\n\t\tvar at = new float[_Row.Length];\n\n\t\tfor (int i = _From \u002B 1; i \u003C _Row.Length; i\u002B\u002B)\n\t\t\tat[i] = at[i - 1] \u002B Flat(_Row[i].Position - _Row[i - 1].Position).Length;\n\n\t\tfloat length = at[^1];\n\n\t\tfor (int i = _From; i \u003C at.Length; i\u002B\u002B)\n\t\t\tat[i] = length \u003E 0.0f ? at[i] / length : 0.0f;\n\n\t\treturn at;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Points from \u003Cparamref name=\u0022_From\u0022/\u003E to \u003Cparamref name=\u0022_To\u0022/\u003E along a straight line, the first left out (it is\n\t/// already there) and the rest on the junction\u0027s surface.\n\t/// \u003C/summary\u003E\n\tprivate static void AddSpan(List\u003CVector3\u003E _Points, Vector3 _From, Vector3 _To, float _Step, RoadJunctionLayout _Layout)\n\t{\n\t\tint pieces = Math.Max(1, (int)MathF.Ceiling(Flat(_To - _From).Length / MathF.Max(1.0f, _Step)));\n\n\t\tfor (int j = 1; j \u003C= pieces; j\u002B\u002B)\n\t\t\t_Points.Add(j == pieces ? _To : OnCone(_Layout, Vector3.Lerp(_From, _To, (float)j / pieces)));\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Whether a line runs steadily out from the node along an arm: no point of it more than a unit back from the\n\t/// furthest out before it.\n\t/// \u003C/summary\u003E\n\tprivate static bool Outward(List\u003CVector3\u003E _Points, RoadJunctionLayout.Arm _Arm, RoadArmMapping _Mapping)\n\t{\n\t\tfloat furthest = float.MinValue;\n\n\t\tforeach (var point in _Points)\n\t\t{\n\t\t\tfloat fromNode = FromNode(point, _Arm, _Mapping);\n\n\t\t\tif (fromNode \u003C furthest - 1.0f)\n\t\t\t\treturn false;\n\n\t\t\tfurthest = MathF.Max(furthest, fromNode);\n\t\t}\n\n\t\treturn true;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// How far out from the node along the arm each point of a line is, never less than the point before\u0027s.\n\t/// \u003C/summary\u003E\n\tprivate static float[] Levels(List\u003CVector3\u003E _Points, RoadJunctionLayout.Arm _Arm, RoadArmMapping _Mapping)\n\t{\n\t\tvar at = new float[_Points.Count];\n\n\t\tfor (int i = 0; i \u003C _Points.Count; i\u002B\u002B)\n\t\t{\n\t\t\tfloat fromNode = FromNode(_Points[i], _Arm, _Mapping);\n\n\t\t\tat[i] = i == 0 ? fromNode : MathF.Max(fromNode, at[i - 1]);\n\t\t}\n\n\t\treturn at;\n\t}\n\n\n\n\tprivate static float FromNode(Vector3 _Point, RoadJunctionLayout.Arm _Arm, RoadArmMapping _Mapping)\n\t{\n\t\tfloat distance = _Mapping.Measure(_Point).y;\n\n\t\treturn _Arm.AtStart ? distance : _Arm.Length - distance;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The point of a line a distance out from the node, and the index of the line\u0027s next point after it.\n\t/// \u003C/summary\u003E\n\tprivate static Vector3 PointAt(List\u003CVector3\u003E _Points, float[] _At, float _Distance, out int _Next)\n\t{\n\t\tfor (int i = 1; i \u003C _Points.Count; i\u002B\u002B)\n\t\t{\n\t\t\tif (_At[i] \u003C _Distance)\n\t\t\t\tcontinue;\n\n\t\t\tfloat span = _At[i] - _At[i - 1];\n\t\t\tfloat t = span \u003E 0.0001f ? (_Distance - _At[i - 1]) / span : 1.0f;\n\n\t\t\t_Next = i;\n\n\t\t\treturn Vector3.Lerp(_Points[i - 1], _Points[i], Math.Clamp(t, 0.0f, 1.0f));\n\t\t}\n\n\t\t_Next = _Points.Count;\n\n\t\treturn _Points[^1];\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// A point brought to the height the junction\u0027s plain fan has there: on the line from the node out through it to\n\t/// the outline, the node\u0027s height and the outline\u0027s in proportion.\n\t/// \u003C/summary\u003E\n\tprivate static Vector3 OnCone(RoadJunctionLayout _Layout, Vector3 _Point)\n\t{\n\t\tvar polygon = _Layout.Polygon;\n\t\tvar node = _Layout.Centre;\n\t\tVector2 ray = Flat(_Point - node);\n\t\tfloat nearest = float.MaxValue;\n\t\tfloat height = node.z;\n\n\t\tfor (int i = 0; i \u003C polygon.Count; i\u002B\u002B)\n\t\t{\n\t\t\tVector3 a = polygon[i];\n\t\t\tVector3 b = polygon[(i \u002B 1) % polygon.Count];\n\t\t\tVector2 edge = Flat(b - a);\n\t\t\tVector2 toA = Flat(a - node);\n\t\t\tfloat denominator = Cross(ray, edge);\n\n\t\t\tif (MathF.Abs(denominator) \u003C 0.0001f)\n\t\t\t\tcontinue;\n\n\t\t\tfloat along = Cross(toA, edge) / denominator;\n\t\t\tfloat on = Cross(toA, ray) / denominator;\n\n\t\t\tif (along \u003E 0.0001f \u0026\u0026 on \u003E= -0.0001f \u0026\u0026 on \u003C= 1.0001f \u0026\u0026 along \u003C nearest)\n\t\t\t{\n\t\t\t\tnearest = along;\n\t\t\t\theight = MathX.Lerp(a.z, b.z, Math.Clamp(on, 0.0f, 1.0f));\n\t\t\t}\n\t\t}\n\n\t\tif (nearest == float.MaxValue)\n\t\t\treturn _Point;\n\n\t\treturn new Vector3(_Point.x, _Point.y, node.z \u002B (height - node.z) / nearest);\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The outline\u0027s points from one index round to another, both included.\n\t/// \u003C/summary\u003E\n\tprivate static List\u003CVector3\u003E Walk(IReadOnlyList\u003CVector3\u003E _Polygon, int _From, int _To)\n\t{\n\t\tvar points = new List\u003CVector3\u003E();\n\t\tint count = _Polygon.Count;\n\n\t\tfor (int i = _From; ; i = (i \u002B 1) % count)\n\t\t{\n\t\t\tpoints.Add(_Polygon[i]);\n\n\t\t\tif (i == _To || points.Count \u003E count)\n\t\t\t\tbreak;\n\t\t}\n\n\t\treturn points;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The index of the outline\u0027s point nearest a position, strictly between two indices (going round); -1 when there\n\t/// is none between them.\n\t/// \u003C/summary\u003E\n\tprivate static int Nearest(IReadOnlyList\u003CVector3\u003E _Polygon, int _After, int _Before, Vector3 _Position)\n\t{\n\t\tint count = _Polygon.Count;\n\t\tint best = -1;\n\t\tfloat nearest = float.MaxValue;\n\n\t\tfor (int i = (_After \u002B 1) % count; i != _Before; i = (i \u002B 1) % count)\n\t\t{\n\t\t\tfloat distance = Flat(_Polygon[i] - _Position).Length;\n\n\t\t\tif (distance \u003C nearest)\n\t\t\t{\n\t\t\t\tnearest = distance;\n\t\t\t\tbest = i;\n\t\t\t}\n\t\t}\n\n\t\treturn best;\n\t}\n\n\n\n\tprivate static float RowWidth(RoadJunctionLayout.Arm _Arm)\n\t{\n\t\tfloat distance = _Arm.CurveDistance(_Arm.Trim);\n\n\t\treturn _Arm.Widths.WidthAt(distance);\n\t}\n\n\n\n\tprivate static int Wrap(int _Index, int _Count)\n\t{\n\t\treturn ((_Index % _Count) \u002B _Count) % _Count;\n\t}\n\n\n\n\tprivate static Vector2 Flat(Vector3 _Vector)\n\t{\n\t\treturn new Vector2(_Vector.x, _Vector.y);\n\t}\n\n\n\n\tprivate static float Cross(Vector2 _A, Vector2 _B)\n\t{\n\t\treturn _A.x * _B.y - _A.y * _B.x;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Twice the area (in plan, counter-clockwise positive) of the triangle from an origin to two points, worked out\n\t/// from the origin so far-out coordinates lose nothing.\n\t/// \u003C/summary\u003E\n\tprivate static double Cross(Vector3 _A, Vector3 _B, Vector3 _Origin)\n\t{\n\t\tdouble ax = (double)_A.x - _Origin.x;\n\t\tdouble ay = (double)_A.y - _Origin.y;\n\t\tdouble bx = (double)_B.x - _Origin.x;\n\t\tdouble by = (double)_B.y - _Origin.y;\n\n\t\treturn ax * by - ay * bx;\n\t}\n}\n"},{"Ident":"redsnail.roadtool2","Path":".obj/__compiler_extra.cs","FileName":"__compiler_extra.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":443665,"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, \u0022Road Tool\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022AddonIdent\u0022, \u0022roadtool2\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022OrgIdent\u0022, \u0022redsnail\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022Ident\u0022, \u0022redsnail.roadtool2\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-01T10:13:06.5741628Z\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyVersion(\u00220.0.148.0\u0022)]\r\n[assembly: global::System.Reflection.AssemblyFileVersion(\u00220.0.148.0\u0022)]"},{"Ident":"redsnail.roadtool2","Path":"Code/Geometry/RoadCurveTable.cs","FileName":"RoadCurveTable.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":443665,"IsPrivate":false,"Code":"using System;\r\nusing Sandbox;\r\n\r\nnamespace RedSnail.RoadTool2;\r\n\r\n/// \u003Csummary\u003E\r\n/// Arc-length table over a \u003Csee cref=\u0022RoadCurve\u0022/\u003E, so the road can be sampled at even distances (mesh rows, chunk\r\n/// boundaries) instead of at even parameter values, which bunch up around tight bends. The samples double as a\r\n/// polyline for picking.\r\n/// \u003C/summary\u003E\r\npublic sealed class RoadCurveTable\r\n{\r\n\tprivate readonly Vector3[] m_Positions;\r\n\tprivate readonly float[] m_Distances;\r\n\r\n\tpublic RoadCurve Curve { get; }\r\n\r\n\tpublic float Length =\u003E m_Distances[^1];\r\n\r\n\tpublic int SampleCount =\u003E m_Positions.Length;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The box the curve itself runs through. Picking widens it by the road\u0027s own reach and skips the road\r\n\t/// altogether when the cursor\u0027s ray misses it, which is most of them in a city.\r\n\t/// \u003C/summary\u003E\r\n\tpublic BBox Bounds { get; }\r\n\r\n\r\n\r\n\tpublic RoadCurveTable(RoadCurve _Curve, int _Samples)\r\n\t{\r\n\t\tCurve = _Curve;\r\n\r\n\t\tint count = Math.Max(1, _Samples);\r\n\t\tm_Positions = new Vector3[count \u002B 1];\r\n\t\tm_Distances = new float[count \u002B 1];\r\n\t\tm_Positions[0] = _Curve.P0;\r\n\r\n\t\tvar bounds = new BBox(_Curve.P0, _Curve.P0);\r\n\r\n\t\tfor (int i = 1; i \u003C= count; i\u002B\u002B)\r\n\t\t{\r\n\t\t\tm_Positions[i] = _Curve.Evaluate((float)i / count);\r\n\t\t\tm_Distances[i] = m_Distances[i - 1] \u002B Vector3.DistanceBetween(m_Positions[i - 1], m_Positions[i]);\r\n\t\t\tbounds = bounds.AddPoint(m_Positions[i]);\r\n\t\t}\r\n\r\n\t\tBounds = bounds;\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Builds a table with a sample density that suits the curve\u0027s length.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static RoadCurveTable Create(RoadCurve _Curve)\r\n\t{\r\n\t\tint samples = Math.Clamp((int)(_Curve.ApproximateLength() / 20.0f), 16, 1024);\r\n\r\n\t\treturn new RoadCurveTable(_Curve, samples);\r\n\t}\r\n\r\n\r\n\r\n\tpublic Vector3 SamplePosition(int _Index)\r\n\t{\r\n\t\treturn m_Positions[_Index];\r\n\t}\r\n\r\n\r\n\r\n\tpublic float SampleDistance(int _Index)\r\n\t{\r\n\t\treturn m_Distances[_Index];\r\n\t}\r\n\r\n\r\n\r\n\tpublic float DistanceToT(float _Distance)\r\n\t{\r\n\t\tif (_Distance \u003C= 0.0f)\r\n\t\t\treturn 0.0f;\r\n\r\n\t\tif (_Distance \u003E= Length)\r\n\t\t\treturn 1.0f;\r\n\r\n\t\tint low = 0;\r\n\t\tint high = m_Distances.Length - 1;\r\n\r\n\t\twhile (high - low \u003E 1)\r\n\t\t{\r\n\t\t\tint mid = (low \u002B high) / 2;\r\n\r\n\t\t\tif (m_Distances[mid] \u003C= _Distance)\r\n\t\t\t\tlow = mid;\r\n\t\t\telse\r\n\t\t\t\thigh = mid;\r\n\t\t}\r\n\r\n\t\tfloat span = m_Distances[high] - m_Distances[low];\r\n\t\tfloat fraction = span \u003E 0.0f ? (_Distance - m_Distances[low]) / span : 0.0f;\r\n\r\n\t\treturn (low \u002B fraction) / (m_Distances.Length - 1);\r\n\t}\r\n\r\n\r\n\r\n\tpublic Vector3 PositionAt(float _Distance)\r\n\t{\r\n\t\treturn Curve.Evaluate(DistanceToT(_Distance));\r\n\t}\r\n\r\n\r\n\r\n\tpublic Vector3 TangentAt(float _Distance)\r\n\t{\r\n\t\treturn Curve.Tangent(DistanceToT(_Distance));\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Where the road is at a distance and which way it runs there, in one go: everything that lays something\r\n\t/// across the road wants both, and asking for them separately searches the table twice.\r\n\t/// \u003C/summary\u003E\r\n\tpublic void Frame(float _Distance, out Vector3 _Position, out Vector3 _Tangent)\r\n\t{\r\n\t\tfloat t = DistanceToT(_Distance);\r\n\r\n\t\t_Position = Curve.Evaluate(t);\r\n\t\t_Tangent = Curve.Tangent(t);\r\n\t}\r\n}\r\n"},{"Ident":"redsnail.roadtool2","Path":"Code/Geometry/RoadWidth.cs","FileName":"RoadWidth.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":443665,"IsPrivate":false,"Code":"using System;\r\nusing Sandbox;\r\n\r\nnamespace RedSnail.RoadTool2;\r\n\r\n/// \u003Csummary\u003E\r\n/// How far a road\u0027s two edges sit from its centreline along a segment: half the road\u0027s width on each side, plus\r\n/// whatever extra each side has at the segment\u0027s start and end, blended smoothly between the two. That is what lets\r\n/// a lane appear on one side over a taper (a highway exit or entry), a ramp start as a point and grow, or a road\r\n/// flare out to a wider one.\r\n/// \u003C/summary\u003E\r\npublic readonly struct RoadWidth\r\n{\r\n\t/// \u003Csummary\u003E\r\n\t/// No road is built narrower than this: two edges on one point make faces with no area.\r\n\t/// \u003C/summary\u003E\r\n\tprivate const float MinWidth = 2.0f;\r\n\r\n\tpublic readonly float Base;\r\n\tpublic readonly float LeftStart;\r\n\tpublic readonly float LeftEnd;\r\n\tpublic readonly float RightStart;\r\n\tpublic readonly float RightEnd;\r\n\tpublic readonly float Length;\r\n\r\n\tpublic RoadWidth(float _Base, float _LeftStart, float _LeftEnd, float _RightStart, float _RightEnd, float _Length)\r\n\t{\r\n\t\tBase = _Base;\r\n\t\tLeftStart = _LeftStart;\r\n\t\tLeftEnd = _LeftEnd;\r\n\t\tRightStart = _RightStart;\r\n\t\tRightEnd = _RightEnd;\r\n\t\tLength = MathF.Max(0.001f, _Length);\r\n\t}\r\n\r\n\tpublic RoadWidth(RoadSegment _Segment, float _Length)\r\n\t\t: this(_Segment.Width, _Segment.LeftExtraStart, _Segment.LeftExtraEnd, _Segment.RightExtraStart, _Segment.RightExtraEnd, _Length)\r\n\t{\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// A plain road of one width all along.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static RoadWidth Uniform(float _Width)\r\n\t{\r\n\t\treturn new RoadWidth(_Width, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f);\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// True when both edges sit at half the width all along: the road every piece of the tool was first built for.\r\n\t/// \u003C/summary\u003E\r\n\tpublic bool IsUniform =\u003E LeftStart == 0.0f \u0026\u0026 LeftEnd == 0.0f \u0026\u0026 RightStart == 0.0f \u0026\u0026 RightEnd == 0.0f;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The furthest either edge gets from the centreline anywhere along the segment.\r\n\t/// \u003C/summary\u003E\r\n\tpublic float MaxHalf =\u003E MathF.Max(MathF.Max(Base * 0.5f \u002B LeftStart, Base * 0.5f \u002B LeftEnd), MathF.Max(Base * 0.5f \u002B RightStart, Base * 0.5f \u002B RightEnd));\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Distance of the left edge from the centreline at a curve distance, looking along the segment.\r\n\t/// \u003C/summary\u003E\r\n\tpublic float LeftAt(float _Distance)\r\n\t{\r\n\t\tfloat left = Base * 0.5f \u002B Blend(LeftStart, LeftEnd, _Distance);\r\n\t\tfloat right = Base * 0.5f \u002B Blend(RightStart, RightEnd, _Distance);\r\n\r\n\t\treturn left \u002B right \u003C MinWidth ? left \u002B (MinWidth - left - right) * 0.5f : left;\r\n\t}\r\n\r\n\tpublic float RightAt(float _Distance)\r\n\t{\r\n\t\tfloat left = Base * 0.5f \u002B Blend(LeftStart, LeftEnd, _Distance);\r\n\t\tfloat right = Base * 0.5f \u002B Blend(RightStart, RightEnd, _Distance);\r\n\r\n\t\treturn left \u002B right \u003C MinWidth ? right \u002B (MinWidth - left - right) * 0.5f : right;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The road\u0027s full width at a curve distance.\r\n\t/// \u003C/summary\u003E\r\n\tpublic float WidthAt(float _Distance)\r\n\t{\r\n\t\treturn LeftAt(_Distance) \u002B RightAt(_Distance);\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// How much wider than the base half width the left edge is at a curve distance (negative when narrower).\r\n\t/// \u003C/summary\u003E\r\n\tpublic float LeftExtraAt(float _Distance)\r\n\t{\r\n\t\treturn LeftAt(_Distance) - Base * 0.5f;\r\n\t}\r\n\r\n\tpublic float RightExtraAt(float _Distance)\r\n\t{\r\n\t\treturn RightAt(_Distance) - Base * 0.5f;\r\n\t}\r\n\r\n\r\n\r\n\tprivate float Blend(float _Start, float _End, float _Distance)\r\n\t{\r\n\t\tif (_Start == _End)\r\n\t\t\treturn _Start;\r\n\r\n\t\tfloat t = Math.Clamp(_Distance / Length, 0.0f, 1.0f);\r\n\r\n\t\t// Eased, so the edge leaves and arrives without a kink.\r\n\t\tt = t * t * (3.0f - 2.0f * t);\r\n\r\n\t\treturn _Start \u002B (_End - _Start) * t;\r\n\t}\r\n\r\n\r\n\r\n\tpublic void AddToHash(ref StableHash _Hash)\r\n\t{\r\n\t\t_Hash.Add(Base);\r\n\t\t_Hash.Add(LeftStart);\r\n\t\t_Hash.Add(LeftEnd);\r\n\t\t_Hash.Add(RightStart);\r\n\t\t_Hash.Add(RightEnd);\r\n\t}\r\n}\r\n"},{"Ident":"redsnail.roadtool2","Path":"Code/Network/RoadSplitBuilder.cs","FileName":"RoadSplitBuilder.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":443665,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\nusing Sandbox;\n\nnamespace RedSnail.RoadTool2;\n\n/// \u003Csummary\u003E\n/// The surface of a junction where one road splits in two around a nose (a highway exit or entry, a fork), for a road\n/// texture fitted to the road\u0027s width. Fanned out from the node like any junction, such a junction reaches its nose\n/// thousands of units out in slivers, and no mapping laid over those can wrap the texture\u0027s edge round the nose: it\n/// smears, and the branches\u0027 lane edges show as lines across the gore. Here only the trunk\u0027s share (the road the\n/// split comes from) is fanned. Each branch is laid like a road of its own, in rows across it from the node out to\n/// its row, between its outer kerb and a spine from the node through the apex (where the branches\u0027 inner edges\n/// cross) to the nose\u0027s tip; its texture is fitted across that, edge on the outer kerb and round the nose, and held\n/// just short of its edge along the spine, which is no kerb.\n/// \u003C/summary\u003E\ninternal static class RoadSplitBuilder\n{\n\t/// \u003Csummary\u003E\n\t/// How far short of its edge (in U) a branch\u0027s texture is held along the spine.\n\t/// \u003C/summary\u003E\n\tprivate const float SpineMargin = 0.05f;\n\n\t/// \u003Csummary\u003E\n\t/// A nose sharper than this (the sine of its corner\u0027s half angle) is what makes a split.\n\t/// \u003C/summary\u003E\n\tprivate const float MaxHalfAngleSin = 0.5f;\n\n\t/// \u003Csummary\u003E\n\t/// A nose nearer the node than this many times the wider branch\u0027s width is fanned like any other corner.\n\t/// \u003C/summary\u003E\n\tprivate const float MinReach = 2.0f;\n\n\t/// \u003Csummary\u003E\n\t/// The spine\u0027s points from the node to the apex are this share of the wider branch\u0027s width apart; from the apex\n\t/// to the tip, and along each row, this share of the branch\u0027s own. Close enough that the surface strays no more\n\t/// than a few units from the plain fan the ground under a junction is shaped to, even round a steep nose.\n\t/// \u003C/summary\u003E\n\tprivate const float RowStep = 0.25f;\n\tprivate const float PointStep = 0.0625f;\n\n\t/// \u003Csummary\u003E\n\t/// How far (as a share of the junction\u0027s area) the triangles may cover more or less than its outline before\n\t/// something is taken to have gone wrong and the junction is fanned instead.\n\t/// \u003C/summary\u003E\n\tprivate const double AreaTolerance = 0.001;\n\n\t/// \u003Csummary\u003E\n\t/// A point of a branch\u0027s strip and its texture coordinates.\n\t/// \u003C/summary\u003E\n\tprivate readonly record struct Mark(Vector3 Position, Vector2 Uv);\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Builds the junction\u0027s surface as a split, when it is one: three arms, two of which (the branches) meet at a\n\t/// sharp, filleted nose well out from the node, beyond the point their inner edges cross. Anything else, or\n\t/// anything the rows would not lay out cleanly, is left to the fan. \u003Cparamref name=\u0022_Mappings\u0022/\u003E are the arms\u0027 own\n\t/// mappings, in the layout\u0027s order.\n\t/// \u003C/summary\u003E\n\tpublic static bool TryBuild(RoadJunctionLayout _Layout, IReadOnlyList\u003CRoadArmMapping\u003E _Mappings, Material _Material, out PolygonMesh _Mesh)\n\t{\n\t\t_Mesh = null;\n\n\t\tvar polygon = _Layout.Polygon;\n\t\tvar rows = _Layout.RowStarts;\n\t\tint count = polygon.Count;\n\n\t\tif (_Layout.Arms.Count != 3 || rows is null || rows.Count != 3 || _Mappings.Count != 3 || count \u003C 3)\n\t\t\treturn false;\n\n\t\tforeach (int row in rows)\n\t\t{\n\t\t\tif (row \u003C 0 || row \u003E= count)\n\t\t\t\treturn false;\n\t\t}\n\n\t\tRoadJunctionLayout.CornerPath nose = null;\n\n\t\tforeach (var path in _Layout.CornerPaths)\n\t\t{\n\t\t\tif (path.Fold is null || path.Fold.HalfAngleSin \u003E= MaxHalfAngleSin)\n\t\t\t\tcontinue;\n\n\t\t\tif (nose is not null)\n\t\t\t\treturn false;\n\n\t\t\tnose = path;\n\t\t}\n\n\t\tif (nose is null)\n\t\t\treturn false;\n\n\t\t// Counter-clockwise: the trunk, then the branch whose left edge runs to the nose, then the other.\n\t\tint first = _Layout.Arms.IndexOf(nose.ArmA);\n\t\tint second = _Layout.Arms.IndexOf(nose.ArmB);\n\t\tint trunk = 3 - first - second;\n\n\t\tif (first \u003C 0 || second != (first \u002B 1) % 3 || trunk != (second \u002B 1) % 3)\n\t\t\treturn false;\n\n\t\t// The trunk comes in from the far side: a branch at a right angle to it is a corner, not a split.\n\t\tvar trunkDirection = _Layout.Arms[trunk].Direction;\n\n\t\tif (Vector2.Dot(trunkDirection, _Layout.Arms[first].Direction) \u003E -0.5f || Vector2.Dot(trunkDirection, _Layout.Arms[second].Direction) \u003E -0.5f)\n\t\t\treturn false;\n\n\t\t// The nose\u0027s points are the polygon\u0027s from the first branch\u0027s row on, its middle the tip.\n\t\tint noseStart = (rows[first] \u002B 1) % count;\n\n\t\tif (Wrap(rows[second] - noseStart, count) != nose.Points.Count - 1 || nose.MidIndex \u003C= 0 || nose.MidIndex \u003E= nose.Points.Count - 1)\n\t\t\treturn false;\n\n\t\tint tip = (noseStart \u002B nose.MidIndex) % count;\n\t\tvar node = _Layout.Centre;\n\t\tVector3 tipPoint = polygon[tip];\n\t\tvar apex = OnCone(_Layout, new Vector3(nose.Fold.Apex.x, nose.Fold.Apex.y, node.z));\n\t\tfloat reach = Flat(tipPoint - node).Length;\n\t\tfloat width = MathF.Max(RowWidth(_Layout.Arms[first]), RowWidth(_Layout.Arms[second]));\n\n\t\t// The apex has to lie between the node and the nose, the nose well out.\n\t\tif (reach \u003C MinReach * width || Vector2.Dot(Flat(apex - node), Flat(tipPoint - node)) \u003C= 0.0f || Flat(apex - node).Length \u003E= reach)\n\t\t\treturn false;\n\n\t\t// Where the trunk\u0027s share ends on its two kerbs: their points nearest the node.\n\t\tint outerFirst = Nearest(polygon, (rows[trunk] \u002B 1) % count, rows[first], node);\n\t\tint outerSecond = Nearest(polygon, (rows[second] \u002B 1) % count, rows[trunk], node);\n\n\t\tif (outerFirst \u003C 0 || outerSecond \u003C 0)\n\t\t\treturn false;\n\n\t\t// The spine, shared by both branches: from the node to the apex, and on down the gore to the tip.\n\t\tvar spine = new List\u003CVector3\u003E { node };\n\n\t\tAddSpan(spine, node, apex, width * RowStep, _Layout);\n\t\tAddSpan(spine, apex, tipPoint, width * PointStep, _Layout);\n\t\tspine.RemoveAt(spine.Count - 1);\n\n\t\t// Each branch\u0027s two sides, from the node\u0027s end out to its row: its outer kerb, and the spine and its half of\n\t\t// the nose.\n\t\tvar firstOuter = Walk(polygon, outerFirst, rows[first]);\n\t\tvar firstInner = Walk(polygon, noseStart, tip);\n\t\tvar secondOuter = Walk(polygon, (rows[second] \u002B 1) % count, outerSecond);\n\t\tvar secondInner = Walk(polygon, tip, rows[second]);\n\n\t\tfirstInner.Reverse();\n\t\tsecondOuter.Reverse();\n\t\tfirstInner.InsertRange(0, spine);\n\t\tsecondInner.InsertRange(0, spine);\n\n\t\t// Rows across a branch need both its sides to run steadily away from the node; anything else is fanned.\n\t\tif (!Outward(firstOuter, _Layout.Arms[first], _Mappings[first]) || !Outward(firstInner, _Layout.Arms[first], _Mappings[first])\n\t\t\t|| !Outward(secondOuter, _Layout.Arms[second], _Mappings[second]) || !Outward(secondInner, _Layout.Arms[second], _Mappings[second]))\n\t\t\treturn false;\n\n\t\tvar firstTriangles = BuildBranch(_Layout, _Layout.Arms[first], _Mappings[first], firstOuter, firstInner, spine.Count);\n\t\tvar secondTriangles = BuildBranch(_Layout, _Layout.Arms[second], _Mappings[second], secondOuter, secondInner, spine.Count);\n\n\t\tif (firstTriangles is null || secondTriangles is null)\n\t\t\treturn false;\n\n\t\t// The trunk\u0027s share fanned from the node, and both branches, have to cover the outline exactly: no more (two\n\t\t// triangles over one spot) and no less (a hole).\n\t\tvar share = Walk(polygon, outerSecond, outerFirst);\n\t\tdouble outline = 0.0;\n\t\tdouble covered = 0.0;\n\n\t\tfor (int i = 0; i \u003C count; i\u002B\u002B)\n\t\t\toutline \u002B= Cross(polygon[i], polygon[(i \u002B 1) % count], node);\n\n\t\tfor (int i = 0; i \u003C share.Count - 1; i\u002B\u002B)\n\t\t\tcovered \u002B= Cross(share[i], share[i \u002B 1], node);\n\n\t\tforeach (var triangle in firstTriangles)\n\t\t\tcovered \u002B= Cross(triangle[1].Position, triangle[2].Position, triangle[0].Position);\n\n\t\tforeach (var triangle in secondTriangles)\n\t\t\tcovered \u002B= Cross(triangle[1].Position, triangle[2].Position, triangle[0].Position);\n\n\t\tif (outline \u003C= 0.0 || Math.Abs(covered - outline) \u003E outline * AreaTolerance)\n\t\t\treturn false;\n\n\t\tvar mesh = new PolygonMesh();\n\t\tvar vertices = new Dictionary\u003CVector2, HalfEdgeMesh.VertexHandle\u003E();\n\n\t\tHalfEdgeMesh.VertexHandle Vertex(Vector3 _Position)\n\t\t{\n\t\t\tvar key = Flat(_Position);\n\n\t\t\tif (!vertices.TryGetValue(key, out var handle))\n\t\t\t{\n\t\t\t\thandle = mesh.AddVertices(_Position)[0];\n\t\t\t\tvertices[key] = handle;\n\t\t\t}\n\n\t\t\treturn handle;\n\t\t}\n\n\t\t// The trunk first, then each branch from the node out, so every face joins on to those before it.\n\t\tRoadFanBuilder.Build(mesh, _Material, node, share, new int[share.Count], new IFanMapping[] { _Mappings[trunk] }, new[] { true }, Vertex, false);\n\n\t\tforeach (var triangle in firstTriangles)\n\t\t\tMeshUtility.AddTexturedTriangle(mesh, _Material, Vertex(triangle[0].Position), Vertex(triangle[1].Position), Vertex(triangle[2].Position), triangle[0].Uv, triangle[1].Uv, triangle[2].Uv);\n\n\t\tforeach (var triangle in secondTriangles)\n\t\t\tMeshUtility.AddTexturedTriangle(mesh, _Material, Vertex(triangle[0].Position), Vertex(triangle[1].Position), Vertex(triangle[2].Position), triangle[0].Uv, triangle[1].Uv, triangle[2].Uv);\n\n\t\t_Mesh = mesh;\n\n\t\treturn true;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// One branch\u0027s triangles, facing up, in the order they join on to one another. \u003Cparamref name=\u0022_Outer\u0022/\u003E runs\n\t/// along its outer kerb from the trunk\u0027s share to its row; \u003Cparamref name=\u0022_Inner\u0022/\u003E along the spine and then, from\n\t/// \u003Cparamref name=\u0022_KerbFrom\u0022/\u003E on, round the nose\u0027s half from its tip to the row. A row crosses the branch from each\n\t/// point of the inner side to the point of the outer kerb as far along it (as a share of the way, so the first row is\n\t/// the trunk\u0027s fan\u0027s end spoke and the last the branch\u0027s own row); the band between two rows is zipped from the kerb\n\t/// in, with whatever of the kerb\u0027s own points lie between them fanned from the first row\u0027s first point in. Null when\n\t/// the rows would fold over one another anywhere.\n\t/// \u003C/summary\u003E\n\tprivate static List\u003CMark[]\u003E BuildBranch(RoadJunctionLayout _Layout, RoadJunctionLayout.Arm _Arm, RoadArmMapping _Mapping, List\u003CVector3\u003E _Outer, List\u003CVector3\u003E _Inner,\n\t\tint _KerbFrom)\n\t{\n\t\tif (_Outer.Count \u003C 2 || _Inner.Count - _KerbFrom \u003C 2)\n\t\t\treturn null;\n\n\t\t// The branch\u0027s texture runs from its edge on the outer kerb to its other edge round the nose.\n\t\tfloat outerU = _Mapping.KerbUv(_Outer[^1]).x;\n\t\tfloat innerEdgeU = _Mapping.KerbUv(_Inner[^1]).x;\n\t\tbool innerHigh = innerEdgeU \u003E outerU;\n\n\t\tfloat InnerU(int _Index)\n\t\t{\n\t\t\tif (_Index \u003E= _KerbFrom)\n\t\t\t\treturn innerEdgeU;\n\n\t\t\tfloat u = _Mapping.Uv(_Inner[_Index]).x;\n\n\t\t\treturn innerHigh ? MathF.Min(u, innerEdgeU - SpineMargin) : MathF.Max(u, innerEdgeU \u002B SpineMargin);\n\t\t}\n\n\t\tMark MarkAt(Vector3 _Point, float _U)\n\t\t{\n\t\t\treturn new Mark(_Point, new Vector2(_U, _Mapping.Uv(_Point).y));\n\t\t}\n\n\t\tfloat[] outerAt = Levels(_Outer, _Arm, _Mapping);\n\t\tfloat[] innerAt = Levels(_Inner, _Arm, _Mapping);\n\t\tfloat outerSpan = outerAt[^1] - outerAt[0];\n\t\tfloat innerSpan = innerAt[^1] - innerAt[0];\n\n\t\tif (outerSpan \u003C 1.0f || innerSpan \u003C 1.0f)\n\t\t\treturn null;\n\n\t\tfloat step = MathF.Max(1.0f, RowWidth(_Arm) * PointStep);\n\t\tvar rows = new List\u003C(Mark[] Points, int Next)\u003E(_Inner.Count);\n\n\t\tfor (int k = 0; k \u003C _Inner.Count; k\u002B\u002B)\n\t\t{\n\t\t\tbool last = k == _Inner.Count - 1;\n\t\t\tVector3 outerPoint;\n\t\t\tint next;\n\n\t\t\tif (k == 0)\n\t\t\t{\n\t\t\t\touterPoint = _Outer[0];\n\t\t\t\tnext = 1;\n\t\t\t}\n\t\t\telse if (last)\n\t\t\t{\n\t\t\t\touterPoint = _Outer[^1];\n\t\t\t\tnext = _Outer.Count;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\touterPoint = PointAt(_Outer, outerAt, outerAt[0] \u002B (innerAt[k] - innerAt[0]) / innerSpan * outerSpan, out next);\n\t\t\t}\n\n\t\t\tVector3 innerPoint = _Inner[k];\n\t\t\tfloat innerU = InnerU(k);\n\n\t\t\t// The first row is the trunk\u0027s fan\u0027s end spoke, whole.\n\t\t\tint pieces = k == 0 ? 1 : Math.Max(1, (int)MathF.Ceiling(Flat(innerPoint - outerPoint).Length / step));\n\t\t\tvar row = new Mark[pieces \u002B 1];\n\n\t\t\tfor (int j = 0; j \u003C= pieces; j\u002B\u002B)\n\t\t\t{\n\t\t\t\tfloat f = (float)j / pieces;\n\t\t\t\tVector3 point = j == 0 ? outerPoint : j == pieces ? innerPoint : Vector3.Lerp(outerPoint, innerPoint, f);\n\n\t\t\t\t// Inside, on the surface the plain fan would have; the branch\u0027s own row straight, as its road\u0027s is.\n\t\t\t\tif (j \u003E 0 \u0026\u0026 j \u003C pieces \u0026\u0026 !last)\n\t\t\t\t\tpoint = OnCone(_Layout, point);\n\n\t\t\t\trow[j] = MarkAt(point, MathX.Lerp(outerU, innerU, f));\n\t\t\t}\n\n\t\t\trows.Add((row, next));\n\t\t}\n\n\t\tvar triangles = new List\u003CMark[]\u003E();\n\n\t\tfor (int k = 0; k \u003C rows.Count - 1; k\u002B\u002B)\n\t\t{\n\t\t\tvar (a, aNext) = rows[k];\n\t\t\tvar (b, bNext) = rows[k \u002B 1];\n\n\t\t\t// The kerb\u0027s own points between the two rows, fanned from the first row\u0027s first point in.\n\t\t\tvar kerb = new List\u003CMark\u003E { a[0] };\n\n\t\t\tfor (int i = aNext; i \u003C bNext \u0026\u0026 i \u003C _Outer.Count; i\u002B\u002B)\n\t\t\t{\n\t\t\t\tif (Flat(_Outer[i] - a[0].Position).Length \u003E 0.01f \u0026\u0026 Flat(_Outer[i] - b[0].Position).Length \u003E 0.01f)\n\t\t\t\t\tkerb.Add(MarkAt(_Outer[i], outerU));\n\t\t\t}\n\n\t\t\tif (kerb.Count \u003E 1)\n\t\t\t{\n\t\t\t\tkerb.Add(b[0]);\n\n\t\t\t\tfor (int j = 0; j \u003C kerb.Count - 1; j\u002B\u002B)\n\t\t\t\t\tAdd(triangles, kerb[j \u002B 1], kerb[j], a[1]);\n\n\t\t\t\tZip(triangles, a, 1, b);\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tZip(triangles, a, 0, b);\n\t\t\t}\n\t\t}\n\n\t\t// One winding for the whole branch, facing up; a triangle against it means the rows fold over somewhere.\n\t\tdouble area = 0.0;\n\n\t\tforeach (var triangle in triangles)\n\t\t\tarea \u002B= Cross(triangle[1].Position, triangle[2].Position, triangle[0].Position);\n\n\t\tif (area \u003C 0.0)\n\t\t{\n\t\t\tforeach (var triangle in triangles)\n\t\t\t\t(triangle[1], triangle[2]) = (triangle[2], triangle[1]);\n\t\t}\n\n\t\tforeach (var triangle in triangles)\n\t\t{\n\t\t\tif (Cross(triangle[1].Position, triangle[2].Position, triangle[0].Position) \u003C= 0.0)\n\t\t\t\treturn null;\n\t\t}\n\n\t\treturn triangles;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Triangles between two rows of a band (\u003Cparamref name=\u0022_A\u0022/\u003E from \u003Cparamref name=\u0022_From\u0022/\u003E on, and\n\t/// \u003Cparamref name=\u0022_B\u0022/\u003E), both running from the kerb in, in the order their points come along them.\n\t/// \u003C/summary\u003E\n\tprivate static void Zip(List\u003CMark[]\u003E _Triangles, Mark[] _A, int _From, Mark[] _B)\n\t{\n\t\tfloat[] atA = Fractions(_A, _From);\n\t\tfloat[] atB = Fractions(_B, 0);\n\t\tint a = _From;\n\t\tint b = 0;\n\n\t\twhile (a \u003C _A.Length - 1 || b \u003C _B.Length - 1)\n\t\t{\n\t\t\tif (b == _B.Length - 1 || (a \u003C _A.Length - 1 \u0026\u0026 atA[a \u002B 1] \u003C= atB[b \u002B 1]))\n\t\t\t{\n\t\t\t\tAdd(_Triangles, _A[a], _A[a \u002B 1], _B[b]);\n\t\t\t\ta\u002B\u002B;\n\t\t\t}\n\t\t\telse\n\t\t\t{\n\t\t\t\tAdd(_Triangles, _A[a], _B[b \u002B 1], _B[b]);\n\t\t\t\tb\u002B\u002B;\n\t\t\t}\n\t\t}\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Adds a triangle unless its points are in a line (rows that share a point on the kerb, points along a straight\n\t/// kerb), which would make no face.\n\t/// \u003C/summary\u003E\n\tprivate static void Add(List\u003CMark[]\u003E _Triangles, Mark _A, Mark _B, Mark _C)\n\t{\n\t\tif (Math.Abs(Cross(_B.Position, _C.Position, _A.Position)) \u003C 0.002)\n\t\t\treturn;\n\n\t\t_Triangles.Add(new[] { _A, _B, _C });\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// How far along a row each of its points is from \u003Cparamref name=\u0022_From\u0022/\u003E, as a share of the rest of its length.\n\t/// \u003C/summary\u003E\n\tprivate static float[] Fractions(Mark[] _Row, int _From)\n\t{\n\t\tvar at = new float[_Row.Length];\n\n\t\tfor (int i = _From \u002B 1; i \u003C _Row.Length; i\u002B\u002B)\n\t\t\tat[i] = at[i - 1] \u002B Flat(_Row[i].Position - _Row[i - 1].Position).Length;\n\n\t\tfloat length = at[^1];\n\n\t\tfor (int i = _From; i \u003C at.Length; i\u002B\u002B)\n\t\t\tat[i] = length \u003E 0.0f ? at[i] / length : 0.0f;\n\n\t\treturn at;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Points from \u003Cparamref name=\u0022_From\u0022/\u003E to \u003Cparamref name=\u0022_To\u0022/\u003E along a straight line, the first left out (it is\n\t/// already there) and the rest on the junction\u0027s surface.\n\t/// \u003C/summary\u003E\n\tprivate static void AddSpan(List\u003CVector3\u003E _Points, Vector3 _From, Vector3 _To, float _Step, RoadJunctionLayout _Layout)\n\t{\n\t\tint pieces = Math.Max(1, (int)MathF.Ceiling(Flat(_To - _From).Length / MathF.Max(1.0f, _Step)));\n\n\t\tfor (int j = 1; j \u003C= pieces; j\u002B\u002B)\n\t\t\t_Points.Add(j == pieces ? _To : OnCone(_Layout, Vector3.Lerp(_From, _To, (float)j / pieces)));\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Whether a line runs steadily out from the node along an arm: no point of it more than a unit back from the\n\t/// furthest out before it.\n\t/// \u003C/summary\u003E\n\tprivate static bool Outward(List\u003CVector3\u003E _Points, RoadJunctionLayout.Arm _Arm, RoadArmMapping _Mapping)\n\t{\n\t\tfloat furthest = float.MinValue;\n\n\t\tforeach (var point in _Points)\n\t\t{\n\t\t\tfloat fromNode = FromNode(point, _Arm, _Mapping);\n\n\t\t\tif (fromNode \u003C furthest - 1.0f)\n\t\t\t\treturn false;\n\n\t\t\tfurthest = MathF.Max(furthest, fromNode);\n\t\t}\n\n\t\treturn true;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// How far out from the node along the arm each point of a line is, never less than the point before\u0027s.\n\t/// \u003C/summary\u003E\n\tprivate static float[] Levels(List\u003CVector3\u003E _Points, RoadJunctionLayout.Arm _Arm, RoadArmMapping _Mapping)\n\t{\n\t\tvar at = new float[_Points.Count];\n\n\t\tfor (int i = 0; i \u003C _Points.Count; i\u002B\u002B)\n\t\t{\n\t\t\tfloat fromNode = FromNode(_Points[i], _Arm, _Mapping);\n\n\t\t\tat[i] = i == 0 ? fromNode : MathF.Max(fromNode, at[i - 1]);\n\t\t}\n\n\t\treturn at;\n\t}\n\n\n\n\tprivate static float FromNode(Vector3 _Point, RoadJunctionLayout.Arm _Arm, RoadArmMapping _Mapping)\n\t{\n\t\tfloat distance = _Mapping.Measure(_Point).y;\n\n\t\treturn _Arm.AtStart ? distance : _Arm.Length - distance;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The point of a line a distance out from the node, and the index of the line\u0027s next point after it.\n\t/// \u003C/summary\u003E\n\tprivate static Vector3 PointAt(List\u003CVector3\u003E _Points, float[] _At, float _Distance, out int _Next)\n\t{\n\t\tfor (int i = 1; i \u003C _Points.Count; i\u002B\u002B)\n\t\t{\n\t\t\tif (_At[i] \u003C _Distance)\n\t\t\t\tcontinue;\n\n\t\t\tfloat span = _At[i] - _At[i - 1];\n\t\t\tfloat t = span \u003E 0.0001f ? (_Distance - _At[i - 1]) / span : 1.0f;\n\n\t\t\t_Next = i;\n\n\t\t\treturn Vector3.Lerp(_Points[i - 1], _Points[i], Math.Clamp(t, 0.0f, 1.0f));\n\t\t}\n\n\t\t_Next = _Points.Count;\n\n\t\treturn _Points[^1];\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// A point brought to the height the junction\u0027s plain fan has there: on the line from the node out through it to\n\t/// the outline, the node\u0027s height and the outline\u0027s in proportion.\n\t/// \u003C/summary\u003E\n\tprivate static Vector3 OnCone(RoadJunctionLayout _Layout, Vector3 _Point)\n\t{\n\t\tvar polygon = _Layout.Polygon;\n\t\tvar node = _Layout.Centre;\n\t\tVector2 ray = Flat(_Point - node);\n\t\tfloat nearest = float.MaxValue;\n\t\tfloat height = node.z;\n\n\t\tfor (int i = 0; i \u003C polygon.Count; i\u002B\u002B)\n\t\t{\n\t\t\tVector3 a = polygon[i];\n\t\t\tVector3 b = polygon[(i \u002B 1) % polygon.Count];\n\t\t\tVector2 edge = Flat(b - a);\n\t\t\tVector2 toA = Flat(a - node);\n\t\t\tfloat denominator = Cross(ray, edge);\n\n\t\t\tif (MathF.Abs(denominator) \u003C 0.0001f)\n\t\t\t\tcontinue;\n\n\t\t\tfloat along = Cross(toA, edge) / denominator;\n\t\t\tfloat on = Cross(toA, ray) / denominator;\n\n\t\t\tif (along \u003E 0.0001f \u0026\u0026 on \u003E= -0.0001f \u0026\u0026 on \u003C= 1.0001f \u0026\u0026 along \u003C nearest)\n\t\t\t{\n\t\t\t\tnearest = along;\n\t\t\t\theight = MathX.Lerp(a.z, b.z, Math.Clamp(on, 0.0f, 1.0f));\n\t\t\t}\n\t\t}\n\n\t\tif (nearest == float.MaxValue)\n\t\t\treturn _Point;\n\n\t\treturn new Vector3(_Point.x, _Point.y, node.z \u002B (height - node.z) / nearest);\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The outline\u0027s points from one index round to another, both included.\n\t/// \u003C/summary\u003E\n\tprivate static List\u003CVector3\u003E Walk(IReadOnlyList\u003CVector3\u003E _Polygon, int _From, int _To)\n\t{\n\t\tvar points = new List\u003CVector3\u003E();\n\t\tint count = _Polygon.Count;\n\n\t\tfor (int i = _From; ; i = (i \u002B 1) % count)\n\t\t{\n\t\t\tpoints.Add(_Polygon[i]);\n\n\t\t\tif (i == _To || points.Count \u003E count)\n\t\t\t\tbreak;\n\t\t}\n\n\t\treturn points;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The index of the outline\u0027s point nearest a position, strictly between two indices (going round); -1 when there\n\t/// is none between them.\n\t/// \u003C/summary\u003E\n\tprivate static int Nearest(IReadOnlyList\u003CVector3\u003E _Polygon, int _After, int _Before, Vector3 _Position)\n\t{\n\t\tint count = _Polygon.Count;\n\t\tint best = -1;\n\t\tfloat nearest = float.MaxValue;\n\n\t\tfor (int i = (_After \u002B 1) % count; i != _Before; i = (i \u002B 1) % count)\n\t\t{\n\t\t\tfloat distance = Flat(_Polygon[i] - _Position).Length;\n\n\t\t\tif (distance \u003C nearest)\n\t\t\t{\n\t\t\t\tnearest = distance;\n\t\t\t\tbest = i;\n\t\t\t}\n\t\t}\n\n\t\treturn best;\n\t}\n\n\n\n\tprivate static float RowWidth(RoadJunctionLayout.Arm _Arm)\n\t{\n\t\tfloat distance = _Arm.CurveDistance(_Arm.Trim);\n\n\t\treturn _Arm.Widths.WidthAt(distance);\n\t}\n\n\n\n\tprivate static int Wrap(int _Index, int _Count)\n\t{\n\t\treturn ((_Index % _Count) \u002B _Count) % _Count;\n\t}\n\n\n\n\tprivate static Vector2 Flat(Vector3 _Vector)\n\t{\n\t\treturn new Vector2(_Vector.x, _Vector.y);\n\t}\n\n\n\n\tprivate static float Cross(Vector2 _A, Vector2 _B)\n\t{\n\t\treturn _A.x * _B.y - _A.y * _B.x;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// Twice the area (in plan, counter-clockwise positive) of the triangle from an origin to two points, worked out\n\t/// from the origin so far-out coordinates lose nothing.\n\t/// \u003C/summary\u003E\n\tprivate static double Cross(Vector3 _A, Vector3 _B, Vector3 _Origin)\n\t{\n\t\tdouble ax = (double)_A.x - _Origin.x;\n\t\tdouble ay = (double)_A.y - _Origin.y;\n\t\tdouble bx = (double)_B.x - _Origin.x;\n\t\tdouble by = (double)_B.y - _Origin.y;\n\n\t\treturn ax * by - ay * bx;\n\t}\n}\n"},{"Ident":"redsnail.roadtool2","Path":"Code/Network/RoadTerrainLayer.cs","FileName":"RoadTerrainLayer.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":443665,"IsPrivate":false,"Code":"using System.Collections.Generic;\nusing Sandbox;\n\nnamespace RedSnail.RoadTool2;\n\n/// \u003Csummary\u003E\n/// What the roads have done to the terrain on this GameObject, kept apart from it the way a layer would be: for\n/// every height sample the roads shaped and every control map texel they painted, the ground under it (with any\n/// sculpting or painting done there since) and what the roads wrote over it. The Terrain tool\u0027s Conform and Paint\n/// start from that ground every time, so they can be repeated, follow the roads when they move (by hand, or by\n/// themselves with Live Update), and be taken back out with Remove Road Layer, leaving the rest of the terrain as\n/// it is. Added by the tool\u0027s Start Road Layer.\n/// \u003C/summary\u003E\n[Icon(\u0022layers\u0022)]\npublic sealed class RoadTerrainLayer : Component\n{\n\t/// \u003Csummary\u003E\n\t/// The terrain\u0027s resolution when the layer was started: its samples are numbered on that grid, so a terrain\n\t/// resized since can no longer take them. Zero while the layer has not been started.\n\t/// \u003C/summary\u003E\n\t[Property, ReadOnly] public int Resolution { get; set; }\n\n\t/// \u003Csummary\u003E\n\t/// How many height samples the roads hold away from the ground.\n\t/// \u003C/summary\u003E\n\t[Property(Title = \u0022Shaped Samples\u0022), ReadOnly] public int HeightSamples { get; set; }\n\n\t/// \u003Csummary\u003E\n\t/// How many control map texels the roads have painted.\n\t/// \u003C/summary\u003E\n\t[Property(Title = \u0022Painted Texels\u0022), ReadOnly] public int PaintTexels { get; set; }\n\n\t/// \u003Csummary\u003E\n\t/// Bumped each time the layer is started again, so whatever keeps track of what it holds knows that is gone.\n\t/// \u003C/summary\u003E\n\t[Property, Hide] public int Generation { get; set; }\n\n\t/// \u003Csummary\u003E\n\t/// The shaped height samples, packed by the Terrain tool a square of the grid at a time.\n\t/// \u003C/summary\u003E\n\t[Property, Hide] public List\u003CRoadTerrainLayerTile\u003E HeightTiles { get; set; } = [];\n\n\t/// \u003Csummary\u003E\n\t/// The painted texels, packed the same way.\n\t/// \u003C/summary\u003E\n\t[Property, Hide] public List\u003CRoadTerrainLayerTile\u003E PaintTiles { get; set; } = [];\n\n\t/// \u003Csummary\u003E\n\t/// The shaped samples as the first version of the layer packed them, all in one; moved into tiles the first\n\t/// time the layer is used.\n\t/// \u003C/summary\u003E\n\t[Property, Hide] public string Heights { get; set; } = \u0022\u0022;\n\n\t/// \u003Csummary\u003E\n\t/// The painted texels in that first format.\n\t/// \u003C/summary\u003E\n\t[Property, Hide] public string Paint { get; set; } = \u0022\u0022;\n\n\tpublic bool IsStarted =\u003E Resolution \u003E 0;\n}\n\n/// \u003Csummary\u003E\n/// One square of a terrain\u0027s grid in a \u003Csee cref=\u0022RoadTerrainLayer\u0022/\u003E: the samples the roads hold in it, packed on\n/// their own so a change to the roads only repacks the squares it reaches.\n/// \u003C/summary\u003E\npublic sealed class RoadTerrainLayerTile\n{\n\t/// \u003Csummary\u003E\n\t/// Which square: counted across the grid, then down it.\n\t/// \u003C/summary\u003E\n\tpublic int Index { get; set; }\n\n\t/// \u003Csummary\u003E\n\t/// How many samples the roads hold in it.\n\t/// \u003C/summary\u003E\n\tpublic int Count { get; set; }\n\n\tpublic string Data { get; set; } = \u0022\u0022;\n}\n"},{"Ident":"redsnail.roadtool2","Path":"Code/Utility/StableHash.cs","FileName":"StableHash.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":443665,"IsPrivate":false,"Code":"using System;\r\nusing Sandbox;\r\n\r\nnamespace RedSnail.RoadTool2;\r\n\r\n/// \u003Csummary\u003E\r\n/// 64-bit FNV-1a hash that is stable across editor sessions, unlike \u003Csee cref=\u0022HashCode\u0022/\u003E which is seeded per\r\n/// process. Used to stamp generated meshes with the inputs they were built from, so a scene reopened days later\r\n/// still knows which chunks are current.\r\n/// \u003C/summary\u003E\r\npublic struct StableHash\r\n{\r\n\tprivate const ulong OffsetBasis = 14695981039346656037UL;\r\n\tprivate const ulong Prime = 1099511628211UL;\r\n\r\n\tprivate ulong m_Hash;\r\n\r\n\tpublic long Value =\u003E unchecked((long)m_Hash);\r\n\r\n\r\n\r\n\tpublic static StableHash Create()\r\n\t{\r\n\t\treturn new StableHash { m_Hash = OffsetBasis };\r\n\t}\r\n\r\n\r\n\r\n\tpublic void Add(int _Value)\r\n\t{\r\n\t\tunchecked\r\n\t\t{\r\n\t\t\tfor (int i = 0; i \u003C 4; i\u002B\u002B)\r\n\t\t\t{\r\n\t\t\t\tm_Hash ^= (byte)(_Value \u003E\u003E (i * 8));\r\n\t\t\t\tm_Hash *= Prime;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\r\n\r\n\tpublic void Add(long _Value)\r\n\t{\r\n\t\tAdd(unchecked((int)_Value));\r\n\t\tAdd(unchecked((int)(_Value \u003E\u003E 32)));\r\n\t}\r\n\r\n\r\n\r\n\tpublic void Add(float _Value)\r\n\t{\r\n\t\tAdd(BitConverter.SingleToInt32Bits(_Value));\r\n\t}\r\n\r\n\r\n\r\n\tpublic void Add(Vector3 _Value)\r\n\t{\r\n\t\tAdd(_Value.x);\r\n\t\tAdd(_Value.y);\r\n\t\tAdd(_Value.z);\r\n\t}\r\n\r\n\r\n\r\n\tpublic void Add(string _Value)\r\n\t{\r\n\t\tif (_Value is not null)\r\n\t\t{\r\n\t\t\tforeach (char c in _Value)\r\n\t\t\t\tAdd((int)c);\r\n\t\t}\r\n\r\n\t\t// Terminator, so \u0022ab\u0022 \u002B \u0022c\u0022 never collides with \u0022a\u0022 \u002B \u0022bc\u0022.\r\n\t\tAdd(-1);\r\n\t}\r\n}\r\n"},{"Ident":"redsnail.roadtool2","Path":"Network/RoadChunk.cs","FileName":"RoadChunk.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":443665,"IsPrivate":false,"Code":"using Sandbox;\r\n\r\nnamespace RedSnail.RoadTool2;\r\n\r\npublic enum RoadChunkKind\r\n{\r\n\t/// \u003Csummary\u003E\r\n\t/// The road surface itself.\r\n\t/// \u003C/summary\u003E\r\n\tSurface,\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// What runs along the road\u0027s sides: sidewalks, verges.\r\n\t/// \u003C/summary\u003E\r\n\tBorder,\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The painted lines on the surface: lane lines, centre line, edge lines.\r\n\t/// \u003C/summary\u003E\r\n\tMarking,\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The bridge under a road: deck, sides, supports.\r\n\t/// \u003C/summary\u003E\r\n\tBridge,\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The prefabs standing along a road and before its junctions.\r\n\t/// \u003C/summary\u003E\r\n\tProps,\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The rounded end of a road that stops: surface and border together, in one piece per end.\r\n\t/// \u003C/summary\u003E\r\n\tCap\r\n}\r\n\r\n/// \u003Csummary\u003E\r\n/// Marks a generated mesh child of a \u003Csee cref=\u0022RoadNetwork\u0022/\u003E and remembers what it covers: a stretch of a segment,\r\n/// or the junction at a node, and whether it is the surface or the border of it. The network uses it to replace\r\n/// exactly the pieces that went stale and leave the rest alone.\r\n/// \u003C/summary\u003E\r\n[Icon(\u0022view_week\u0022)]\r\npublic sealed class RoadChunk : Component\r\n{\r\n\t/// \u003Csummary\u003E\r\n\t/// The segment this chunk is a stretch of, or -1 for a junction piece.\r\n\t/// \u003C/summary\u003E\r\n\t[Property, ReadOnly] public int SegmentId { get; set; } = -1;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The node this chunk is the junction of, or -1 for a road stretch.\r\n\t/// \u003C/summary\u003E\r\n\t[Property, ReadOnly] public int NodeId { get; set; } = -1;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The parking lot this chunk is a piece of, or -1 for anything else.\r\n\t/// \u003C/summary\u003E\r\n\t[Property, ReadOnly] public int LotId { get; set; } = -1;\r\n\r\n\t[Property, ReadOnly] public RoadChunkKind Kind { get; set; } = RoadChunkKind.Surface;\r\n\r\n\t[Property, ReadOnly] public int ChunkIndex { get; set; }\r\n\r\n\t[Property, ReadOnly] public int ChunkCount { get; set; }\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// A locked chunk is never regenerated, so its mesh can be edited by hand. It keeps its geometry even if the road\r\n\t/// under it changes; unlock it to have it rebuilt.\r\n\t/// \u003C/summary\u003E\r\n\t[Property]\r\n\tpublic bool Locked\r\n\t{\r\n\t\tget;\r\n\t\tset\r\n\t\t{\r\n\t\t\tfield = value;\r\n\r\n\t\t\t// Unlocking is a request to catch up with the graph.\r\n\t\t\tGameObject?.Parent?.Components.Get\u003CRoadNetwork\u003E()?.MarkDirty();\r\n\t\t}\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Hash of everything this chunk was generated from. When it no longer matches what the graph says it should be\r\n\t/// the chunk is stale.\r\n\t/// \u003C/summary\u003E\r\n\t[Property, Hide] public long Signature { get; set; }\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The rows a border piece was built from, when the network\u0027s debug overlay is on. Not saved.\r\n\t/// \u003C/summary\u003E\r\n\tpublic BorderDebug Debug { get; set; }\r\n\r\n\tpublic bool IsJunction =\u003E NodeId \u003E= 0;\r\n\r\n\tpublic bool IsLot =\u003E LotId \u003E= 0;\r\n\r\n\r\n\r\n\tprotected override void DrawGizmos()\r\n\t{\r\n\t\tif (Debug is null)\r\n\t\t\treturn;\r\n\r\n\t\tvar network = GameObject?.Parent?.Components.Get\u003CRoadNetwork\u003E();\r\n\r\n\t\tif (network is null || !network.DebugBorders)\r\n\t\t\treturn;\r\n\r\n\t\tGizmo.Draw.IgnoreDepth = true;\r\n\t\tGizmo.Draw.LineThickness = 2.0f;\r\n\r\n\t\tforeach (var line in Debug.Lines)\r\n\t\t{\r\n\t\t\tGizmo.Draw.Color = line.Color;\r\n\t\t\tGizmo.Draw.Line(line.From, line.To);\r\n\t\t}\r\n\r\n\t\tforeach (var marker in Debug.Markers)\r\n\t\t{\r\n\t\t\tGizmo.Draw.Color = marker.Color;\r\n\t\t\tGizmo.Draw.SolidSphere(marker.Position, 2.0f);\r\n\t\t}\r\n\t}\r\n}\r\n"},{"Ident":"redsnail.roadtool2","Path":"Network/RoadNetwork.Rebuild.cs","FileName":"RoadNetwork.Rebuild.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":443665,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing System.Linq;\r\nusing Sandbox;\r\n\r\nnamespace RedSnail.RoadTool2;\r\n\r\npublic sealed partial class RoadNetwork\r\n{\r\n\t/// \u003Csummary\u003E\r\n\t/// Bump whenever the generated geometry changes (UV layout, sampling, profile...), so pieces built by an older\r\n\t/// generator are replaced on the next reconcile instead of lingering until their road is edited.\r\n\t/// \u003C/summary\u003E\r\n\tprivate const int GeneratorVersion = 76;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// A stretch of road shorter than this is not worth a chunk (it happens when a junction swallows a whole chunk).\r\n\t/// \u003C/summary\u003E\r\n\tprivate const float MinChunkLength = 1.0f;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Where a segment\u0027s painted lines may run: between \u003Csee cref=\u0022Start\u0022/\u003E and \u003Csee cref=\u0022End\u0022/\u003E, skipping the\r\n\t/// gap between \u003Csee cref=\u0022GapStart\u0022/\u003E and \u003Csee cref=\u0022GapEnd\u0022/\u003E when there is one (a crossing in the middle of\r\n\t/// a short road between two junctions).\r\n\t/// \u003C/summary\u003E\r\n\tprivate readonly record struct LineRange(float Start, float End, float GapStart, float GapEnd)\r\n\t{\r\n\t\tpublic bool HasGap =\u003E GapEnd \u003E GapStart;\r\n\r\n\t\tpublic void AddToHash(ref StableHash _Hash)\r\n\t\t{\r\n\t\t\t_Hash.Add(Start);\r\n\t\t\t_Hash.Add(End);\r\n\t\t\t_Hash.Add(GapStart);\r\n\t\t\t_Hash.Add(GapEnd);\r\n\t\t}\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// A segment\u0027s pedestrian crossings: at either end, or one shared crossing halfway along a short road between\r\n\t/// two junctions (recorded on the start end). Centres are curve distances from the segment\u0027s start.\r\n\t/// \u003C/summary\u003E\r\n\tprivate readonly record struct SegmentCrossings(bool AtStart, float StartCentre, bool AtEnd, float EndCentre);\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// One piece of a segment to build. \u003Csee cref=\u0022Lines\u0022/\u003E bounds the painted lines; \u003Csee cref=\u0022Taper\u0022/\u003E is the\r\n\t/// border\u0027s run-out into a different road type at either end; \u003Csee cref=\u0022Bridge\u0022/\u003E is the whole built range\r\n\t/// and the ends of a bridge piece; \u003Csee cref=\u0022Trails\u0022/\u003E is where a surface\u0027s trails rise out at its ends, and\r\n\t/// \u003Csee cref=\u0022Blend\u0022/\u003E where another surface runs on into it; the other kinds ignore them.\r\n\t/// \u003C/summary\u003E\r\n\tprivate readonly record struct ChunkPlan(int Index, int Count, float Start, float End, RoadChunkKind Kind, BorderCaps Caps, RoadBorderBuilder.SegmentBorderBlends Blends, long Signature, LineRange Lines = default, SegmentBorderTapers Taper = default, RoadBridgeBuilder.BridgeSpan Bridge = default, RoadPropBuilder.PropSpan Props = default, RoadMarkingBuilder.DashPhase Dash = default, SegmentCrossings Crossings = default, RoadTrailFade Trails = default, RoadSurfaceBlend Blend = default);\r\n\r\n\tprivate readonly record struct PendingGroup(long Signature, int Remaining);\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// One piece to (re)build: a chunk of a segment, or, when \u003Csee cref=\u0022NodeId\u0022/\u003E is set, a piece of a junction.\r\n\t/// \u003Csee cref=\u0022ArmBlends\u0022/\u003E and \u003Csee cref=\u0022ArmTapers\u0022/\u003E carry, for a junction\u0027s border piece, what each arm\u0027s\r\n\t/// chunks were built with, keyed by segment; \u003Csee cref=\u0022ArmSurfaces\u0022/\u003E, for its surface, each arm\u0027s road\u0027s blend.\r\n\t/// \u003C/summary\u003E\r\n\tprivate readonly record struct RebuildJob(int SegmentId, int NodeId, RoadChunkKind Kind, long GroupSignature, ChunkPlan Plan, RoadCurveTable Table, RoadWidth Width, RoadProfile Profile, RoadJunctionLayout Junction, Dictionary\u003Cint, RoadBorderBuilder.SegmentBorderBlends\u003E ArmBlends, Dictionary\u003Cint, SegmentBorderTapers\u003E ArmTapers, RoadLot Lot,\r\n\t\tDictionary\u003Cint, RoadSurfaceBlend\u003E ArmSurfaces = null);\r\n\r\n\tprivate bool m_IsDirty;\r\n\tprivate readonly Queue\u003CRebuildJob\u003E m_Jobs = new();\r\n\tprivate readonly Dictionary\u003Cint, PendingGroup\u003E m_PendingSegments = new();\r\n\tprivate readonly Dictionary\u003C(int NodeId, RoadChunkKind Kind), PendingGroup\u003E m_PendingJunctions = new();\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Junction layouts keyed by node, each with a hash of what it was computed from. Finding corners on curved\r\n\t/// edges is the one expensive step of a reconcile, and while a node is dragged only its own junction and its\r\n\t/// neighbours\u0027 change.\r\n\t/// \u003C/summary\u003E\r\n\tprivate readonly Dictionary\u003Cint, (long Key, RoadJunctionLayout Layout)\u003E m_JunctionCache = new();\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// True while pieces are still queued for (re)generation.\r\n\t/// \u003C/summary\u003E\r\n\tpublic bool IsRebuilding =\u003E m_Jobs.Count \u003E 0;\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Asks for a reconcile pass on the next editor frame: the graph is compared against the pieces that exist and\r\n\t/// only what differs gets queued for regeneration.\r\n\t/// \u003C/summary\u003E\r\n\tpublic void MarkDirty()\r\n\t{\r\n\t\tm_IsDirty = true;\r\n\r\n\t\t// Undo, reloads and the inspector all land here with a graph nobody told us about piece by piece.\r\n\t\tInvalidateIndex();\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Asks the network in the editor\u0027s scene for a reconcile. Editing a road type, a bridge, a prop set or a\r\n\t/// parking layout changes roads that hold no copy of it, so the asset tells the network rather than the other\r\n\t/// way round.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static void Editor_MarkDirty()\r\n\t{\r\n\t\tvar scene = Application.Editor?.Scene;\r\n\r\n\t\tif (!scene.IsValid())\r\n\t\t\treturn;\r\n\r\n\t\tvar network = scene.Get\u003CRoadNetwork\u003E();\r\n\r\n\t\tif (!network.IsValid())\r\n\t\t\treturn;\r\n\r\n\t\tnetwork.MarkDirty();\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// One reconcile pass, then as much of the queued work as this frame\u0027s budget allows. Driven from the\r\n\t/// component\u0027s own update in RoadNetwork.cs.\r\n\t/// \u003C/summary\u003E\r\n\tprivate void Tick()\r\n\t{\r\n\t\tif (m_IsDirty)\r\n\t\t{\r\n\t\t\tm_IsDirty = false;\r\n\t\t\tReconcile();\r\n\t\t}\r\n\r\n\t\tProcessJobs();\r\n\t}\r\n\r\n\r\n\r\n\tpublic IEnumerable\u003CRoadChunk\u003E GetChunks()\r\n\t{\r\n\t\tforeach (var child in GameObject.Children)\r\n\t\t{\r\n\t\t\tif (!child.IsValid() || child.IsDestroyed)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tvar chunk = child.Components.Get\u003CRoadChunk\u003E();\r\n\r\n\t\t\tif (chunk is not null)\r\n\t\t\t\tyield return chunk;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\r\n\tprivate RoadChunk FindChunk(int _SegmentId, int _ChunkIndex, RoadChunkKind _Kind)\r\n\t{\r\n\t\treturn GetChunks().FirstOrDefault(chunk =\u003E !chunk.IsJunction \u0026\u0026 chunk.SegmentId == _SegmentId \u0026\u0026 chunk.ChunkIndex == _ChunkIndex \u0026\u0026 chunk.Kind == _Kind);\r\n\t}\r\n\r\n\r\n\r\n\tprivate RoadChunk FindJunctionChunk(int _NodeId, RoadChunkKind _Kind)\r\n\t{\r\n\t\treturn GetChunks().FirstOrDefault(chunk =\u003E chunk.IsJunction \u0026\u0026 chunk.NodeId == _NodeId \u0026\u0026 chunk.Kind == _Kind);\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Compares the graph with the pieces under this GameObject and queues work for everything that is missing,\r\n\t/// stale or built from different settings. Stateless on purpose: it copes with undo, reloads, hand deleted\r\n\t/// pieces and hot reloads alike, because the pieces themselves carry what they were built from.\r\n\t/// \u003C/summary\u003E\r\n\tprivate void Reconcile()\r\n\t{\r\n\t\tPruneCurveTables();\r\n\r\n\t\t// A lot\u0027s entrances belong to its edge, wherever the lot has been moved to since.\r\n\t\tSnapAllOpenings();\r\n\r\n\t\tvar segmentChunks = new Dictionary\u003Cint, List\u003CRoadChunk\u003E\u003E();\r\n\t\tvar junctionChunks = new Dictionary\u003C(int NodeId, RoadChunkKind Kind), RoadChunk\u003E();\r\n\t\tvar lotChunks = new Dictionary\u003C(int LotId, RoadChunkKind Kind), RoadChunk\u003E();\r\n\r\n\t\tforeach (var chunk in GetChunks())\r\n\t\t{\r\n\t\t\tif (chunk.IsLot)\r\n\t\t\t{\r\n\t\t\t\tif (lotChunks.TryGetValue((chunk.LotId, chunk.Kind), out var duplicate))\r\n\t\t\t\t\tduplicate.GameObject.Destroy();\r\n\r\n\t\t\t\tlotChunks[(chunk.LotId, chunk.Kind)] = chunk;\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\r\n\t\t\tif (chunk.IsJunction)\r\n\t\t\t{\r\n\t\t\t\t// Two pieces for one junction can only be leftovers; keep one, the reconcile sorts out whether it is current.\r\n\t\t\t\tif (junctionChunks.TryGetValue((chunk.NodeId, chunk.Kind), out var duplicate))\r\n\t\t\t\t\tduplicate.GameObject.Destroy();\r\n\r\n\t\t\t\tjunctionChunks[(chunk.NodeId, chunk.Kind)] = chunk;\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\r\n\t\t\tif (!segmentChunks.TryGetValue(chunk.SegmentId, out var list))\r\n\t\t\t{\r\n\t\t\t\tlist = new List\u003CRoadChunk\u003E();\r\n\t\t\t\tsegmentChunks[chunk.SegmentId] = list;\r\n\t\t\t}\r\n\r\n\t\t\tlist.Add(chunk);\r\n\t\t}\r\n\r\n\t\tvar layouts = ComputeJunctionLayouts();\r\n\t\tvar dashPhases = ComputeDashPhases();\r\n\t\tvar liveSegments = new HashSet\u003Cint\u003E();\r\n\t\tvar segmentBlends = new Dictionary\u003Cint, RoadBorderBuilder.SegmentBorderBlends\u003E();\r\n\t\tvar segmentTapers = new Dictionary\u003Cint, SegmentBorderTapers\u003E();\r\n\t\tvar segmentSurfaces = new Dictionary\u003Cint, RoadSurfaceBlend\u003E();\r\n\r\n\t\tforeach (var segment in Segments)\r\n\t\t{\r\n\t\t\tvar table = GetCurveTable(segment);\r\n\r\n\t\t\tif (table is null)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tliveSegments.Add(segment.Id);\r\n\r\n\t\t\tvar profile = ProfileOf(segment);\r\n\t\t\t// A road opening into a parking lot starts where the lot\u0027s surface stops covering it.\r\n\t\t\tfloat trimStart = MathF.Max(layouts.GetValueOrDefault(segment.StartNodeId)?.FindArm(segment.Id)?.Trim ?? 0.0f, LotTrimAt(segment.StartNodeId));\r\n\t\t\tfloat trimEnd = MathF.Max(layouts.GetValueOrDefault(segment.EndNodeId)?.FindArm(segment.Id)?.Trim ?? 0.0f, LotTrimAt(segment.EndNodeId));\r\n\t\t\tvar caps = ComputeBorderCaps(segment, layouts);\r\n\t\t\tvar blends = ComputeBorderBlends(segment, table, layouts);\r\n\t\t\tvar taper = ComputeBorderTaper(segment, table, layouts, trimStart, trimEnd);\r\n\t\t\tvar crossings = ComputeCrossings(segment, table, layouts, trimStart, trimEnd);\r\n\t\t\tvar lines = ComputeLineRange(table, profile, trimStart, trimEnd, crossings);\r\n\t\t\tvar dash = dashPhases.GetValueOrDefault(segment.Id);\r\n\t\t\tvar trails = ComputeTrailFade(segment, table, profile, layouts, trimStart, trimEnd);\r\n\t\t\tvar surfaceBlend = ComputeSurfaceBlend(segment, table, profile, layouts, trimStart, trimEnd);\r\n\r\n\t\t\tvar plans = PlanChunks(segment, table, trimStart, trimEnd, profile, caps, blends, taper, ComputeSurfaceSignature(segment, table.Curve, profile), lines, dash, crossings, trails, surfaceBlend);\r\n\t\t\tlong groupSignature = CombineSignatures(plans);\r\n\r\n\t\t\tsegmentBlends[segment.Id] = blends;\r\n\t\t\tsegmentTapers[segment.Id] = taper;\r\n\t\t\tsegmentSurfaces[segment.Id] = surfaceBlend;\r\n\t\t\tsegmentChunks.TryGetValue(segment.Id, out var existing);\r\n\r\n\t\t\tif (IsSegmentUpToDate(existing, plans))\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\t// Already queued with these exact inputs: let those jobs finish rather than doubling them.\r\n\t\t\tif (m_PendingSegments.TryGetValue(segment.Id, out var pending) \u0026\u0026 pending.Signature == groupSignature)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tEnqueueSegment(segment, table, profile, plans, groupSignature, existing);\r\n\t\t}\r\n\r\n\t\tforeach (var (nodeId, layout) in layouts)\r\n\t\t{\r\n\t\t\t// A road blending the junction\u0027s surface into its own starts doing so across its mouth, inside the junction.\r\n\t\t\tvar armSurfaces = new Dictionary\u003Cint, RoadSurfaceBlend\u003E();\r\n\r\n\t\t\tforeach (var arm in layout.Arms)\r\n\t\t\t\tarmSurfaces[arm.Segment.Id] = segmentSurfaces.GetValueOrDefault(arm.Segment.Id);\r\n\r\n\t\t\tReconcileJunctionPiece(nodeId, layout, RoadChunkKind.Surface, ComputeJunctionSurfaceSignature(layout, armSurfaces), junctionChunks, null, null, armSurfaces);\r\n\r\n\t\t\tbool anyBorder = layout.Arms.Any(arm =\u003E ProfileOf(arm.Segment).HasBorder);\r\n\r\n\t\t\tif (anyBorder)\r\n\t\t\t{\r\n\t\t\t\t// The junction\u0027s border runs continue the arms\u0027 chunks, so they take the same lifts and tapers those\r\n\t\t\t\t// were built with.\r\n\t\t\t\tvar armBlends = new Dictionary\u003Cint, RoadBorderBuilder.SegmentBorderBlends\u003E();\r\n\t\t\t\tvar armTapers = new Dictionary\u003Cint, SegmentBorderTapers\u003E();\r\n\r\n\t\t\t\tforeach (var arm in layout.Arms)\r\n\t\t\t\t{\r\n\t\t\t\t\tarmBlends[arm.Segment.Id] = segmentBlends.GetValueOrDefault(arm.Segment.Id);\r\n\t\t\t\t\tarmTapers[arm.Segment.Id] = segmentTapers.GetValueOrDefault(arm.Segment.Id);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tReconcileJunctionPiece(nodeId, layout, RoadChunkKind.Border, ComputeJunctionBorderSignature(layout, armBlends, armTapers), junctionChunks, armBlends, armTapers);\r\n\t\t\t}\r\n\t\t\telse if (junctionChunks.TryGetValue((nodeId, RoadChunkKind.Border), out var border))\r\n\t\t\t{\r\n\t\t\t\tborder.GameObject.Destroy();\r\n\t\t\t}\r\n\r\n\t\t\t// Crossings used to be decals hung on the junction; the roads paint their own now, so anything left\r\n\t\t\t// here from then goes.\r\n\t\t\tif (junctionChunks.TryGetValue((nodeId, RoadChunkKind.Marking), out var marking))\r\n\t\t\t\tmarking.GameObject.Destroy();\r\n\t\t}\r\n\r\n\t\tReconcileLots(lotChunks);\r\n\r\n\t\t// Whatever no longer belongs to anything in the graph goes, locked or not.\r\n\t\tforeach (var (segmentId, chunks) in segmentChunks)\r\n\t\t{\r\n\t\t\tif (liveSegments.Contains(segmentId))\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tforeach (var chunk in chunks)\r\n\t\t\t\tchunk.GameObject.Destroy();\r\n\r\n\t\t\tm_PendingSegments.Remove(segmentId);\r\n\t\t}\r\n\r\n\t\tforeach (var (key, chunk) in junctionChunks)\r\n\t\t{\r\n\t\t\tif (layouts.ContainsKey(key.NodeId))\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tchunk.GameObject.Destroy();\r\n\t\t\tm_PendingJunctions.Remove(key);\r\n\t\t}\r\n\t}\r\n\r\n\r\n\r\n\tprivate void ReconcileJunctionPiece(int _NodeId, RoadJunctionLayout _Layout, RoadChunkKind _Kind, long _Signature, Dictionary\u003C(int NodeId, RoadChunkKind Kind), RoadChunk\u003E _Existing, Dictionary\u003Cint, RoadBorderBuilder.SegmentBorderBlends\u003E _ArmBlends, Dictionary\u003Cint, SegmentBorderTapers\u003E _ArmTapers = null,\r\n\t\tDictionary\u003Cint, RoadSurfaceBlend\u003E _ArmSurfaces = null)\r\n\t{\r\n\t\tvar key = (_NodeId, _Kind);\r\n\r\n\t\tif (_Existing.TryGetValue(key, out var existing) \u0026\u0026 (existing.Locked || (existing.Signature == _Signature \u0026\u0026 !LacksDebugRecord(existing))))\r\n\t\t\treturn;\r\n\r\n\t\tif (m_PendingJunctions.TryGetValue(key, out var pending) \u0026\u0026 pending.Signature == _Signature)\r\n\t\t\treturn;\r\n\r\n\t\tm_Jobs.Enqueue(new RebuildJob(-1, _NodeId, _Kind, _Signature, default, null, RoadWidth.Uniform(0.0f), null, _Layout, _ArmBlends, _ArmTapers, null, _ArmSurfaces));\r\n\t\tm_PendingJunctions[key] = new PendingGroup(_Signature, 1);\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Where every segment sits in its run: the stretch of road carried on through pass-through nodes until a\r\n\t/// junction, a road end or a loop. Each run is walked once, from the lowest-numbered segment in it backwards\r\n\t/// to its head and then forwards to its tail, in that segment\u0027s direction, so every segment of the run agrees\r\n\t/// on where the run\u0027s distance starts and the dashes carry across the nodes.\r\n\t/// \u003C/summary\u003E\r\n\tprivate Dictionary\u003Cint, RoadMarkingBuilder.DashPhase\u003E ComputeDashPhases()\r\n\t{\r\n\t\tvar phases = new Dictionary\u003Cint, RoadMarkingBuilder.DashPhase\u003E();\r\n\r\n\t\tforeach (var seed in Segments.OrderBy(segment =\u003E segment.Id))\r\n\t\t{\r\n\t\t\tif (phases.ContainsKey(seed.Id))\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tvar seen = new HashSet\u003Cint\u003E { seed.Id };\r\n\t\t\tvar run = new List\u003C(RoadSegment Segment, bool Forward)\u003E();\r\n\r\n\t\t\t// Back to the head: a road carrying on through the node runs with the run when it ends at that node.\r\n\t\t\tvar segment = seed;\r\n\t\t\tint nodeId = seed.StartNodeId;\r\n\r\n\t\t\twhile (RunContinuation(segment, nodeId) is { } previous \u0026\u0026 seen.Add(previous.Id))\r\n\t\t\t{\r\n\t\t\t\tbool forward = previous.EndNodeId == nodeId;\r\n\r\n\t\t\t\trun.Add((previous, forward));\r\n\t\t\t\tsegment = previous;\r\n\t\t\t\tnodeId = forward ? previous.StartNodeId : previous.EndNodeId;\r\n\t\t\t}\r\n\r\n\t\t\trun.Reverse();\r\n\t\t\trun.Add((seed, true));\r\n\r\n\t\t\t// On to the tail.\r\n\t\t\tsegment = seed;\r\n\t\t\tnodeId = seed.EndNodeId;\r\n\r\n\t\t\twhile (RunContinuation(segment, nodeId) is { } next \u0026\u0026 seen.Add(next.Id))\r\n\t\t\t{\r\n\t\t\t\tbool forward = next.StartNodeId == nodeId;\r\n\r\n\t\t\t\trun.Add((next, forward));\r\n\t\t\t\tsegment = next;\r\n\t\t\t\tnodeId = forward ? next.EndNodeId : next.StartNodeId;\r\n\t\t\t}\r\n\r\n\t\t\tfloat offset = 0.0f;\r\n\r\n\t\t\tforeach (var (member, forward) in run)\r\n\t\t\t{\r\n\t\t\t\tphases[member.Id] = new RoadMarkingBuilder.DashPhase(offset, !forward);\r\n\t\t\t\toffset \u002B= GetCurveTable(member)?.Length ?? 0.0f;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn phases;\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The road a segment carries straight on into at a pass-through node, or null at anything else.\r\n\t/// \u003C/summary\u003E\r\n\tprivate RoadSegment RunContinuation(RoadSegment _Segment, int _NodeId)\r\n\t{\r\n\t\tif (GetDegree(_NodeId) != 2)\r\n\t\t\treturn null;\r\n\r\n\t\treturn GetSegmentsAt(_NodeId).FirstOrDefault(candidate =\u003E candidate.Id != _Segment.Id);\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Where a segment\u0027s trails rise out of it: flat at each end where its surface stops (a junction, a bend sharp\r\n\t/// enough to be one, a parking lot, a rounded end, another road type, a bridge), at full depth the profile\u0027s fade\r\n\t/// length in from there, never more than half the stretch between the two. A road of the same type and width\r\n\t/// running on the same way through a plain pass-through node lays its trails exactly where these leave off, so\r\n\t/// they carry straight on across it. A bridge\u0027s deck takes no trails.\r\n\t/// \u003C/summary\u003E\r\n\tprivate RoadTrailFade ComputeTrailFade(RoadSegment _Segment, RoadCurveTable _Table, RoadProfile _Profile, Dictionary\u003Cint, RoadJunctionLayout\u003E _Layouts, float _TrimStart, float _TrimEnd)\r\n\t{\r\n\t\tif (_Segment.Bridge is not null || !_Profile.IsShaped)\r\n\t\t\treturn default;\r\n\r\n\t\tfloat start = _TrimStart;\r\n\t\tfloat end = _Table.Length - _TrimEnd;\r\n\r\n\t\tif (end - start \u003C= 0.01f)\r\n\t\t\treturn default;\r\n\r\n\t\tfloat length = MathF.Min(_Profile.TrailFade, (end - start) * 0.5f);\r\n\t\tbool startCarries = TrailsCarryOn(_Segment, _Table, _Profile, _Segment.StartNodeId, true, _Layouts);\r\n\t\tbool endCarries = TrailsCarryOn(_Segment, _Table, _Profile, _Segment.EndNodeId, false, _Layouts);\r\n\r\n\t\treturn new RoadTrailFade(startCarries, start, endCarries, end, length);\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Whether a segment\u0027s trails carry straight on across one of its ends: a plain pass-through node (no junction\r\n\t/// there, no lot), into a road with the same trails, no deck, the same way round (a trail lies to one side of the\r\n\t/// way the road runs, and wanders to that side) and the same width each side (trails are kept inside the road, so a\r\n\t/// narrower one could hold them elsewhere).\r\n\t/// \u003C/summary\u003E\r\n\tprivate bool TrailsCarryOn(RoadSegment _Segment, RoadCurveTable _Table, RoadProfile _Profile, int _NodeId, bool _AtStart, Dictionary\u003Cint, RoadJunctionLayout\u003E _Layouts)\r\n\t{\r\n\t\tif (_Layouts is not null \u0026\u0026 _Layouts.GetValueOrDefault(_NodeId) is not null)\r\n\t\t\treturn false;\r\n\r\n\t\tif (LotAtOpening(_NodeId) is not null)\r\n\t\t\treturn false;\r\n\r\n\t\tvar other = RunContinuation(_Segment, _NodeId);\r\n\r\n\t\tif (other is null || other.Bridge is not null)\r\n\t\t\treturn false;\r\n\r\n\t\t// Running the same way: into this segment\u0027s start comes the other\u0027s end, out of its end goes the other\u0027s start.\r\n\t\tbool otherStarts = other.StartNodeId == _NodeId;\r\n\r\n\t\tif (otherStarts == _AtStart)\r\n\t\t\treturn false;\r\n\r\n\t\tif (ProfileOf(other).TrailsSignature != _Profile.TrailsSignature)\r\n\t\t\treturn false;\r\n\r\n\t\tvar otherTable = GetCurveTable(other);\r\n\r\n\t\tif (otherTable is null)\r\n\t\t\treturn false;\r\n\r\n\t\tvar width = new RoadWidth(_Segment, _Table.Length);\r\n\t\tvar otherWidth = new RoadWidth(other, otherTable.Length);\r\n\t\tfloat distance = _AtStart ? 0.0f : _Table.Length;\r\n\t\tfloat otherDistance = otherStarts ? 0.0f : otherTable.Length;\r\n\r\n\t\treturn MathF.Abs(width.LeftAt(distance) - otherWidth.LeftAt(otherDistance)) \u003C 0.5f \u0026\u0026 MathF.Abs(width.RightAt(distance) - otherWidth.RightAt(otherDistance)) \u003C 0.5f;\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Where every segment\u0027s trails are cut into it, by segment id, exactly as its surface is built: for the tools that\r\n\t/// shape the ground to the roads, which keep it below the trails only where they are.\r\n\t/// \u003C/summary\u003E\r\n\tpublic Dictionary\u003Cint, RoadTrailFade\u003E GetTrailFades()\r\n\t{\r\n\t\tvar layouts = ComputeJunctionLayouts();\r\n\t\tvar fades = new Dictionary\u003Cint, RoadTrailFade\u003E();\r\n\r\n\t\tforeach (var segment in Segments)\r\n\t\t{\r\n\t\t\tvar table = GetCurveTable(segment);\r\n\r\n\t\t\tif (table is null)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tfloat trimStart = MathF.Max(layouts.GetValueOrDefault(segment.StartNodeId)?.FindArm(segment.Id)?.Trim ?? 0.0f, LotTrimAt(segment.StartNodeId));\r\n\t\t\tfloat trimEnd = MathF.Max(layouts.GetValueOrDefault(segment.EndNodeId)?.FindArm(segment.Id)?.Trim ?? 0.0f, LotTrimAt(segment.EndNodeId));\r\n\t\t\tvar profile = ProfileOf(segment);\r\n\r\n\t\t\tfades[segment.Id] = profile.HasTrails ? ComputeTrailFade(segment, table, profile, layouts, trimStart, trimEnd) : default;\r\n\t\t}\r\n\r\n\t\treturn fades;\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Where another surface runs on into a segment\u0027s own: from each end where its surface stops against another\r\n\t/// material (a junction laid in another road type\u0027s surface, a parking lot\u0027s, or another road type carrying on\r\n\t/// from a plain pass-through node), over the profile\u0027s blend length, never more than half the stretch between the\r\n\t/// two ends. At a junction the blend starts back across the road\u0027s mouth, where its share of the corners starts and\r\n\t/// its skirt and banks with it (see \u003Csee cref=\u0022RoadMouthBlend\u0022/\u003E), so the junction\u0027s surface is already giving way\r\n\t/// where the road\u0027s edges begin. Nothing without a blend material, or on a bridge\u0027s deck.\r\n\t/// \u003C/summary\u003E\r\n\tprivate RoadSurfaceBlend ComputeSurfaceBlend(RoadSegment _Segment, RoadCurveTable _Table, RoadProfile _Profile, Dictionary\u003Cint, RoadJunctionLayout\u003E _Layouts, float _TrimStart, float _TrimEnd)\r\n\t{\r\n\t\tif (_Profile.RoadBlendMaterial is null || _Segment.Bridge is not null)\r\n\t\t\treturn default;\r\n\r\n\t\tif (_Table.Length - _TrimEnd - _TrimStart \u003C= 0.01f)\r\n\t\t\treturn default;\r\n\r\n\t\tfloat start = MouthAt(true) ?? _TrimStart;\r\n\t\tfloat end = MouthAt(false) ?? _Table.Length - _TrimEnd;\r\n\t\tfloat length = MathF.Min(_Profile.RoadBlendLength, (end - start) * 0.5f);\r\n\t\tvar width = new RoadWidth(_Segment, _Table.Length);\r\n\t\tvar (scale, offset) = RoadProfile.TextureTransform(_Profile.ResolvedRoadMaterial);\r\n\t\tVector2 second = RoadProfile.SecondLayerScale(_Profile.RoadBlendMaterial);\r\n\t\tfloat repeat = MathF.Max(1.0f, _Profile.RoadTextureRepeat);\r\n\t\tvar startSource = SourceAt(true, start);\r\n\t\tvar endSource = SourceAt(false, end);\r\n\r\n\t\treturn new RoadSurfaceBlend(startSource is not null, start, endSource is not null, end, length, startSource ?? default, endSource ?? default);\r\n\r\n\t\tRoadBlendSource? SourceAt(bool _AtStart, float _Stop)\r\n\t\t{\r\n\t\t\tif (SurfaceMet(_Segment, _Table, _Profile, _AtStart, _Layouts) is not { } met)\r\n\t\t\t\treturn null;\r\n\r\n\t\t\t// Taken round by whole repeats to start out as near as it can to where the road\u0027s own texture is at the\r\n\t\t\t// stop, on its centreline (as the blend\u0027s second layer would take it), so the blend has as little to make\r\n\t\t\t// up as it moves from one to the other.\r\n\t\t\tfloat left = width.LeftAt(_Stop);\r\n\t\t\tfloat right = width.RightAt(_Stop);\r\n\t\t\tfloat centreU = _Profile.RoadTextureFitsWidth ? (left \u002B right \u003E 0.001f ? left / (left \u002B right) : 0.5f) : 0.0f;\r\n\t\t\tvar own = new Vector2((centreU * scale.x \u002B offset.x) * second.x, (_Stop / repeat * scale.y \u002B offset.y) * second.y);\r\n\t\t\tVector2 theirs = met.SampleAt(_Stop, 0.0f, left, right, _Table.PositionAt(_Stop));\r\n\r\n\t\t\treturn met with { Shift = new Vector2(MathF.Round(own.x - theirs.x), MathF.Round(own.y - theirs.y)) };\r\n\t\t}\r\n\r\n\t\t// Where the line across the road\u0027s mouth crosses its centreline, for an end at a junction.\r\n\t\tfloat? MouthAt(bool _AtStart)\r\n\t\t{\r\n\t\t\tint nodeId = _AtStart ? _Segment.StartNodeId : _Segment.EndNodeId;\r\n\r\n\t\t\tif (_Layouts?.GetValueOrDefault(nodeId) is not { } layout)\r\n\t\t\t\treturn null;\r\n\r\n\t\t\tvar arm = layout.Arms.FirstOrDefault(candidate =\u003E candidate.Segment.Id == _Segment.Id \u0026\u0026 candidate.AtStart == _AtStart);\r\n\r\n\t\t\tif (arm is null || !RoadJunctionBuilder.Mouth(layout, arm, JunctionMainArm(layout), out float centre, out _))\r\n\t\t\t\treturn null;\r\n\r\n\t\t\treturn arm.CurveDistance(centre);\r\n\t\t}\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The surface a segment\u0027s own stops against at one of its ends, when it is another material, as it is laid there:\r\n\t/// a junction\u0027s (laid in its widest road\u0027s surface, carried on into each arm along the arm\u0027s own curve), the\r\n\t/// parking lot\u0027s it opens into (fitted to the road through its mouth, or flat from above), or the road\u0027s carrying\r\n\t/// on from a plain pass-through node (its own mapping, run on past its end). Null for none.\r\n\t/// \u003C/summary\u003E\r\n\tprivate RoadBlendSource? SurfaceMet(RoadSegment _Segment, RoadCurveTable _Table, RoadProfile _Profile, bool _AtStart, Dictionary\u003Cint, RoadJunctionLayout\u003E _Layouts)\r\n\t{\r\n\t\tint nodeId = _AtStart ? _Segment.StartNodeId : _Segment.EndNodeId;\r\n\t\tstring own = _Profile.ResolvedRoadMaterial?.ResourcePath;\r\n\r\n\t\tif (_Layouts is not null \u0026\u0026 _Layouts.GetValueOrDefault(nodeId) is { } layout)\r\n\t\t{\r\n\t\t\tvar main = JunctionMainArm(layout);\r\n\r\n\t\t\tif (main is null || main.Segment.Id == _Segment.Id)\r\n\t\t\t\treturn null;\r\n\r\n\t\t\tvar junction = ProfileOf(main.Segment);\r\n\r\n\t\t\treturn junction.ResolvedRoadMaterial?.ResourcePath == own ? null : RoadBlendSource.Along(junction, 0.0f, false);\r\n\t\t}\r\n\r\n\t\tif (LotAtOpening(nodeId) is { } lot)\r\n\t\t{\r\n\t\t\tvar surface = ProfileOf(lot);\r\n\r\n\t\t\tif (surface.ResolvedRoadMaterial?.ResourcePath == own)\r\n\t\t\t\treturn null;\r\n\r\n\t\t\treturn surface.RoadTextureFitsWidth ? RoadBlendSource.Along(surface, 0.0f, false) : RoadBlendSource.Flat(surface);\r\n\t\t}\r\n\r\n\t\tvar other = RunContinuation(_Segment, nodeId);\r\n\t\tvar otherTable = other is null ? null : GetCurveTable(other);\r\n\r\n\t\tif (otherTable is null || ProfileOf(other).ResolvedRoadMaterial?.ResourcePath == own)\r\n\t\t\treturn null;\r\n\r\n\t\t// The other road\u0027s distance along its own curve, from this one\u0027s: the same way on from the node, or back the\r\n\t\t// other way when the two run away from (or into) it together.\r\n\t\tbool otherStarts = other.StartNodeId == nodeId;\r\n\t\tbool reversed = otherStarts == _AtStart;\r\n\t\tfloat at = _AtStart ? 0.0f : _Table.Length;\r\n\t\tfloat otherAt = otherStarts ? 0.0f : otherTable.Length;\r\n\r\n\t\treturn RoadBlendSource.Along(ProfileOf(other), otherAt - (reversed ? -at : at), reversed);\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// How a segment\u0027s border runs out at each end where it meets another road type\u0027s: over the profile\u0027s transition\r\n\t/// length, towards the cross-section the two share. Without the junction layouts only pass-through nodes are\r\n\t/// known; the reconcile passes them, so junction corners taper too.\r\n\t/// \u003C/summary\u003E\r\n\tpublic SegmentBorderTapers GetBorderTaper(RoadSegment _Segment)\r\n\t{\r\n\t\tvar table = GetCurveTable(_Segment);\r\n\r\n\t\treturn table is null ? default : ComputeBorderTaper(_Segment, table);\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// One end of a border\u0027s taper: how long it is, the width and share of relief it runs to, whether a country road\u0027s\r\n\t/// gravel spills over it, and how far from the node it ends.\r\n\t/// \u003C/summary\u003E\r\n\tprivate readonly record struct EndTaper(float Length, float Width, float Relief, bool Spill, float Offset);\r\n\r\n\r\n\r\n\tprivate SegmentBorderTapers ComputeBorderTaper(RoadSegment _Segment, RoadCurveTable _Table, Dictionary\u003Cint, RoadJunctionLayout\u003E _Layouts = null, float _TrimStart = 0.0f, float _TrimEnd = 0.0f)\r\n\t{\r\n\t\tvar profile = ProfileOf(_Segment);\r\n\r\n\t\tif (!profile.HasBorder)\r\n\t\t\treturn default;\r\n\r\n\t\tfloat limit = _Table.Length * 0.5f;\r\n\t\tRoadBorderTaper left = default;\r\n\t\tRoadBorderTaper right = default;\r\n\r\n\t\t// A transition ends at its trim, so the two ends share the stretch BETWEEN the trims and each gets half of\r\n\t\t// it; however far a junction reaches along the road (a ramp meeting a highway can trim most of it), the two\r\n\t\t// never run into each other and neither is squeezed out.\r\n\t\tfloat transitionLimit = MathF.Max(0.0f, _Table.Length - _TrimStart - _TrimEnd) * 0.5f;\r\n\r\n\t\tif (profile.TransitionLength \u003E 0.0f)\r\n\t\t{\r\n\t\t\tSideTapers(_Segment, profile, _Segment.StartNodeId, true, transitionLimit, _Layouts, ref left, ref right);\r\n\t\t\tSideTapers(_Segment, profile, _Segment.EndNodeId, false, transitionLimit, _Layouts, ref left, ref right);\r\n\t\t}\r\n\r\n\t\t// At a nose, the border on the side facing the road this one parts from grows out of nothing instead.\r\n\t\tif (GoreLength(_Segment, _Table, _Segment.StartNodeId, true, limit) is { } startLeft)\r\n\t\t\tleft = left with { StartLength = startLeft, StartWidth = 0.0f, StartRelief = 0.0f, StartSpill = false, StartGore = true, StartOffset = 0.0f };\r\n\r\n\t\tif (GoreLength(_Segment, _Table, _Segment.StartNodeId, false, limit) is { } startRight)\r\n\t\t\tright = right with { StartLength = startRight, StartWidth = 0.0f, StartRelief = 0.0f, StartSpill = false, StartGore = true, StartOffset = 0.0f };\r\n\r\n\t\tif (GoreLength(_Segment, _Table, _Segment.EndNodeId, true, limit) is { } endLeft)\r\n\t\t\tleft = left with { EndLength = endLeft, EndWidth = 0.0f, EndRelief = 0.0f, EndSpill = false, EndGore = true, EndOffset = 0.0f };\r\n\r\n\t\tif (GoreLength(_Segment, _Table, _Segment.EndNodeId, false, limit) is { } endRight)\r\n\t\t\tright = right with { EndLength = endRight, EndWidth = 0.0f, EndRelief = 0.0f, EndSpill = false, EndGore = true, EndOffset = 0.0f };\r\n\r\n\t\treturn new SegmentBorderTapers(left, right);\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The tapers at one end of a segment, one per side, each towards the border across from it there. At a plain\r\n\t/// pass-through node that is the other road on both sides. At a junction it is the road on the far side of each\r\n\t/// corner, and the taper ends at the arm\u0027s trim, where the corner starts: the corner itself is then built in the\r\n\t/// one cross-section both its roads have run to, so it is a clean curve rather than one border turning into\r\n\t/// the other round the arc.\r\n\t/// \u003C/summary\u003E\r\n\tprivate void SideTapers(RoadSegment _Segment, RoadProfile _Profile, int _NodeId, bool _AtStart, float _Limit, Dictionary\u003Cint, RoadJunctionLayout\u003E _Layouts, ref RoadBorderTaper _Left, ref RoadBorderTaper _Right)\r\n\t{\r\n\t\tint degree = GetDegree(_NodeId);\r\n\r\n\t\tif (degree \u003C 2)\r\n\t\t\treturn;\r\n\r\n\t\tRoadSegment leftNeighbour = null;\r\n\t\tRoadSegment rightNeighbour = null;\r\n\t\tfloat trim = 0.0f;\r\n\r\n\t\tif (_Layouts is not null \u0026\u0026 _Layouts.TryGetValue(_NodeId, out var layout) \u0026\u0026 layout.FindArm(_Segment.Id) is { } arm)\r\n\t\t{\r\n\t\t\ttrim = arm.Trim;\r\n\r\n\t\t\t// A corner starting on this arm runs on its left looking out of the node, one ending on it on its right;\r\n\t\t\t// looking along a segment that ends at the node swaps the two.\r\n\t\t\tforeach (var path in layout.CornerPaths)\r\n\t\t\t{\r\n\t\t\t\tif (path.ArmA.Segment.Id == _Segment.Id)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (_AtStart)\r\n\t\t\t\t\t\tleftNeighbour = path.ArmB.Segment;\r\n\t\t\t\t\telse\r\n\t\t\t\t\t\trightNeighbour = path.ArmB.Segment;\r\n\t\t\t\t}\r\n\t\t\t\telse if (path.ArmB.Segment.Id == _Segment.Id)\r\n\t\t\t\t{\r\n\t\t\t\t\tif (_AtStart)\r\n\t\t\t\t\t\trightNeighbour = path.ArmA.Segment;\r\n\t\t\t\t\telse\r\n\t\t\t\t\t\tleftNeighbour = path.ArmA.Segment;\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t}\r\n\t\telse if (degree == 2)\r\n\t\t{\r\n\t\t\tleftNeighbour = GetSegmentsAt(_NodeId).FirstOrDefault(candidate =\u003E candidate.Id != _Segment.Id);\r\n\t\t\trightNeighbour = leftNeighbour;\r\n\t\t}\r\n\r\n\t\tif (SideTaper(_Profile, leftNeighbour, degree, trim, _Limit, out var leftEnd))\r\n\t\t\t_Left = WithEnd(_Left, _AtStart, leftEnd);\r\n\r\n\t\tif (SideTaper(_Profile, rightNeighbour, degree, trim, _Limit, out var rightEnd))\r\n\t\t\t_Right = WithEnd(_Right, _AtStart, rightEnd);\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The taper one side of a border takes towards the border across from it at a node, or false when it takes none:\r\n\t/// nothing across, a border that is already the same size, or \u2014 at a junction \u2014 a border of another kind, which\r\n\t/// a junction still closes off against this one.\r\n\t/// \u003C/summary\u003E\r\n\tprivate bool SideTaper(RoadProfile _Profile, RoadSegment _Neighbour, int _Degree, float _Trim, float _Limit, out EndTaper _Taper)\r\n\t{\r\n\t\t_Taper = default;\r\n\r\n\t\tif (_Neighbour is null)\r\n\t\t\treturn false;\r\n\r\n\t\tvar other = ProfileOf(_Neighbour);\r\n\t\tbool sameKind = other.Border == _Profile.Border;\r\n\r\n\t\tif (_Degree \u003E 2 \u0026\u0026 !sameKind)\r\n\t\t\treturn false;\r\n\r\n\t\tif (sameKind \u0026\u0026 MathF.Abs(other.FlatBorderWidth - _Profile.FlatBorderWidth) \u003C 0.01f \u0026\u0026 MathF.Abs(other.ReliefHeight - _Profile.ReliefHeight) \u003C 0.01f)\r\n\t\t\treturn false;\r\n\r\n\t\t// Held to its half of the stretch between the trims, so it never runs into the taper at the far end.\r\n\t\tfloat length = MathF.Min(_Profile.TransitionLength, _Limit);\r\n\r\n\t\tif (length \u003C= 0.01f)\r\n\t\t\treturn false;\r\n\r\n\t\t_Taper = new EndTaper(length, RoadProfile.MeetingWidth(_Profile, other), RoadProfile.MeetingRelief(_Profile, other), !sameKind \u0026\u0026 other.Border == RoadBorderStyle.CountrySide, _Trim);\r\n\r\n\t\treturn true;\r\n\t}\r\n\r\n\r\n\r\n\tprivate static RoadBorderTaper WithEnd(in RoadBorderTaper _Taper, bool _AtStart, in EndTaper _End)\r\n\t{\r\n\t\treturn _AtStart\r\n\t\t\t? _Taper with { StartLength = _End.Length, StartWidth = _End.Width, StartRelief = _End.Relief, StartSpill = _End.Spill, StartOffset = _End.Offset }\r\n\t\t\t: _Taper with { EndLength = _End.Length, EndWidth = _End.Width, EndRelief = _End.Relief, EndSpill = _End.Spill, EndOffset = _End.Offset };\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// How far from a node the gap between this segment\u0027s edge on one side (its own left or right) and the edge of\r\n\t/// another road parting from the same point has opened enough for both roads\u0027 borders to fit side by side; null\r\n\t/// when no road parts from that edge there. Sampled along both roads at equal distances from the node, which\r\n\t/// is how two roads leaving a common tangent separate.\r\n\t/// \u003C/summary\u003E\r\n\tprivate float? GoreLength(RoadSegment _Segment, RoadCurveTable _Table, int _NodeId, bool _Left, float _Limit)\r\n\t{\r\n\t\tconst float step = 25.0f;\r\n\r\n\t\tif (GetDegree(_NodeId) \u003C 3)\r\n\t\t\treturn null;\r\n\r\n\t\tbool atStart = _Segment.StartNodeId == _NodeId;\r\n\t\tfloat own = ProfileOf(_Segment).FlatBorderWidth;\r\n\t\tvar width = new RoadWidth(_Segment, _Table.Length);\r\n\r\n\t\t// This segment\u0027s edge point at a distance from the node, on the side asked for.\r\n\t\tVector3 OwnEdge(float _FromNode)\r\n\t\t{\r\n\t\t\tfloat distance = atStart ? _FromNode : _Table.Length - _FromNode;\r\n\r\n\t\t\tRoadSurfaceBuilder.CrossSection(_Table, distance, width, 0.0f, out Vector3 leftEdge, out Vector3 rightEdge);\r\n\r\n\t\t\treturn _Left ? leftEdge : rightEdge;\r\n\t\t}\r\n\r\n\t\tVector3 start = OwnEdge(0.0f);\r\n\r\n\t\tforeach (var other in GetSegmentsAt(_NodeId))\r\n\t\t{\r\n\t\t\tif (other.Id == _Segment.Id)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tvar otherTable = GetCurveTable(other);\r\n\r\n\t\t\tif (otherTable is null)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tbool otherAtStart = other.StartNodeId == _NodeId;\r\n\t\t\tvar otherWidth = new RoadWidth(other, otherTable.Length);\r\n\r\n\t\t\tVector3 OtherEdge(float _FromNode, bool _OtherLeft)\r\n\t\t\t{\r\n\t\t\t\tfloat distance = otherAtStart ? _FromNode : otherTable.Length - _FromNode;\r\n\r\n\t\t\t\tRoadSurfaceBuilder.CrossSection(otherTable, distance, otherWidth, 0.0f, out Vector3 leftEdge, out Vector3 rightEdge);\r\n\r\n\t\t\t\treturn _OtherLeft ? leftEdge : rightEdge;\r\n\t\t\t}\r\n\r\n\t\t\t// The other road\u0027s edge that starts on ours, if either does.\r\n\t\t\tbool otherLeft;\r\n\r\n\t\t\tif (OtherEdge(0.0f, true).Distance(start) \u003C 1.0f)\r\n\t\t\t\totherLeft = true;\r\n\t\t\telse if (OtherEdge(0.0f, false).Distance(start) \u003C 1.0f)\r\n\t\t\t\totherLeft = false;\r\n\t\t\telse\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\t// Parting means leaving the node the same way; a road turning off at an angle is a corner, not a gore.\r\n\t\t\tVector3 ownWay = OwnEdge(step) - start;\r\n\t\t\tVector3 otherWay = OtherEdge(step, otherLeft) - start;\r\n\r\n\t\t\tif (ownWay.IsNearZeroLength || otherWay.IsNearZeroLength || Vector3.Dot(ownWay.Normal, otherWay.Normal) \u003C 0.7f)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tfloat needed = own \u002B ProfileOf(other).FlatBorderWidth;\r\n\t\t\tfloat reach = MathF.Min(_Limit, MathF.Min(_Table.Length, otherTable.Length));\r\n\r\n\t\t\tfor (float fromNode = step; fromNode \u003C= reach; fromNode \u002B= step)\r\n\t\t\t{\r\n\t\t\t\tif (OwnEdge(fromNode).Distance(OtherEdge(fromNode, otherLeft)) \u003E= needed)\r\n\t\t\t\t\treturn MathF.Max(step, fromNode);\r\n\t\t\t}\r\n\r\n\t\t\treturn MathF.Max(step, reach);\r\n\t\t}\r\n\r\n\t\treturn null;\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Whether two road types\u0027 borders come to one cross-section where they meet, so nothing needs closing off\r\n\t/// between them: of a kind, and both tapering into the width and height they share.\r\n\t/// \u003C/summary\u003E\r\n\tprivate static bool MeetsFlush(RoadProfile _A, RoadProfile _B)\r\n\t{\r\n\t\treturn _A.HasBorder \u0026\u0026 _A.Border == _B.Border \u0026\u0026 _A.TransitionLength \u003E 0.0f \u0026\u0026 _B.TransitionLength \u003E 0.0f;\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The filled area of every junction, in network space (lifted to the road surface): its centre and its\r\n\t/// outline, which the junction surface fans between, plus how far a pavement reaches out from the outline\r\n\t/// round it, how far above the outline that pavement\u0027s top sits (nothing when no arm has a sidewalk), and the\r\n\t/// roads it belongs to (a rounded end its own road, a junction its arms, a parking lot none). For tools that need\r\n\t/// to know where road is, and whose: the terrain conformer leaves alone an area whose roads all leave the ground\r\n\t/// alone.\r\n\t/// \u003C/summary\u003E\r\n\tpublic IEnumerable\u003C(Vector3 Centre, IReadOnlyList\u003CVector3\u003E Polygon, float PavementReach, float PavementTop, IReadOnlyList\u003CRoadSegment\u003E Roads)\u003E GetJunctionPolygons()\r\n\t{\r\n\t\treturn GetGroundAreas().Select(area =\u003E (area.Centre, area.Polygon, area.PavementReach, area.PavementTop, area.Roads));\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The same, with the banks the ground rises in round a banked road\u0027s rounded end (see \u003Csee cref=\u0022RoadGroundArea\u0022/\u003E).\r\n\t/// \u003C/summary\u003E\r\n\tpublic IEnumerable\u003CRoadGroundArea\u003E GetGroundAreas()\r\n\t{\r\n\t\t// A parking lot is a junction as far as the ground under it is concerned.\r\n\t\tforeach (var lot in Lots)\r\n\t\t{\r\n\t\t\tvar profile = ProfileOf(lot);\r\n\t\t\tbool pavement = profile.Border == RoadBorderStyle.Sidewalk;\r\n\r\n\t\t\tyield return new RoadGroundArea(lot.Centre, RoadLotOutline.Build(lot, OpeningsOf(lot)).Points, pavement ? profile.BorderWidth : 0.0f, pavement ? profile.CurbHeight : 0.0f, 0.0f, 0.0f, s_NoSegments);\r\n\t\t}\r\n\r\n\t\t// A rounded dead end reaches past its node, where no road piece covers the ground.\r\n\t\tforeach (var segment in Segments)\r\n\t\t{\r\n\t\t\tvar table = GetCurveTable(segment);\r\n\r\n\t\t\tif (table is null || segment.Bridge is not null)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tvar profile = ProfileOf(segment);\r\n\t\t\tbool pavement = profile.Border == RoadBorderStyle.Sidewalk;\r\n\t\t\tvar width = new RoadWidth(segment, table.Length);\r\n\r\n\t\t\tforeach (bool atStart in new[] { true, false })\r\n\t\t\t{\r\n\t\t\t\tint nodeId = atStart ? segment.StartNodeId : segment.EndNodeId;\r\n\r\n\t\t\t\tif (GetDegree(nodeId) != 1 || LotAtOpening(nodeId) is not null)\r\n\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\tvar outline = RoadCapBuilder.Outline(table, atStart ? 0.0f : table.Length, atStart, width, profile, SurfaceOffset, out Vector3 centre);\r\n\r\n\t\t\t\tif (outline.Count \u003E= 3)\r\n\t\t\t\t\tyield return new RoadGroundArea(centre, outline, pavement ? profile.BorderWidth : 0.0f, pavement ? profile.CurbHeight : 0.0f,\r\n\t\t\t\t\t\tprofile.HasBanks ? profile.BankHeight : 0.0f, profile.HasBanks ? profile.BankWidth : 0.0f, new[] { segment });\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tforeach (var layout in ComputeJunctionLayouts().Values)\r\n\t\t{\r\n\t\t\tif (layout.Polygon.Count \u003C 3)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tfloat reach = 0.0f;\r\n\t\t\tfloat top = 0.0f;\r\n\r\n\t\t\tforeach (var arm in layout.Arms)\r\n\t\t\t{\r\n\t\t\t\tvar profile = ProfileOf(arm.Segment);\r\n\r\n\t\t\t\tif (profile.Border != RoadBorderStyle.Sidewalk)\r\n\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\treach = MathF.Max(reach, profile.BorderWidth);\r\n\t\t\t\ttop = MathF.Max(top, profile.CurbHeight);\r\n\t\t\t}\r\n\r\n\t\t\tvar banks = JunctionBanks(layout, out float bankHeight, out float bankWidth);\r\n\r\n\t\t\tyield return new RoadGroundArea(layout.Centre, layout.Polygon, reach, top, bankHeight, bankWidth, layout.Arms.Select(arm =\u003E arm.Segment).ToList(), banks);\r\n\t\t}\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The banks round a junction, for each point of its outline: a banked road\u0027s (see \u003Csee cref=\u0022RoadProfile.BankHeight\u0022/\u003E)\r\n\t/// carry on along every stretch of the outline it owns (its row, and its half of the corner either side, which\r\n\t/// its skirt runs under), so the ground comes over the junction\u0027s kerb there as it does over the road\u0027s, up to\r\n\t/// where the corner hands over to the next road. A point between a banked stretch and another takes the bank, so\r\n\t/// the banked stretch is banked all the way along. Null when no road at the junction has banks.\r\n\t/// \u003C/summary\u003E\r\n\tprivate List\u003CVector2\u003E JunctionBanks(RoadJunctionLayout _Layout, out float _Height, out float _Width)\r\n\t{\r\n\t\t_Height = 0.0f;\r\n\t\t_Width = 0.0f;\r\n\r\n\t\tvar polygon = _Layout.Polygon;\r\n\t\tvar owners = _Layout.PolygonArms;\r\n\r\n\t\tif (owners is null || owners.Count != polygon.Count)\r\n\t\t\treturn null;\r\n\r\n\t\tvar edges = new Vector2[polygon.Count];\r\n\r\n\t\tfor (int i = 0; i \u003C polygon.Count; i\u002B\u002B)\r\n\t\t{\r\n\t\t\tif (owners[i] \u003C 0)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tvar arm = _Layout.Arms[owners[i]];\r\n\t\t\tvar profile = ProfileOf(arm.Segment);\r\n\r\n\t\t\tif (arm.Segment.Bridge is not null || !profile.HasBanks)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tedges[i] = new Vector2(profile.BankHeight, profile.BankWidth);\r\n\t\t\t_Height = MathF.Max(_Height, profile.BankHeight);\r\n\t\t\t_Width = MathF.Max(_Width, profile.BankWidth);\r\n\t\t}\r\n\r\n\t\tif (_Height \u003C= 0.0f)\r\n\t\t\treturn null;\r\n\r\n\t\t// Each point takes the edge leaving it or the one coming into it, whichever is banked more.\r\n\t\tvar banks = new List\u003CVector2\u003E(polygon.Count);\r\n\r\n\t\tfor (int i = 0; i \u003C polygon.Count; i\u002B\u002B)\r\n\t\t{\r\n\t\t\tVector2 leaving = edges[i];\r\n\t\t\tVector2 coming = edges[(i \u002B polygon.Count - 1) % polygon.Count];\r\n\r\n\t\t\tbanks.Add(leaving.x \u003E= coming.x ? leaving : coming);\r\n\t\t}\r\n\r\n\t\treturn banks;\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Lays out every junction. A road too short for the fillets at both its ends gets those fillets shrunk until\r\n\t/// their tangent points fit on it (a trim past the tangent point would send the corner geometry back over the\r\n\t/// road); only corners that cannot fit even sharp are clamped. Then the junction polygons are built.\r\n\t/// \u003C/summary\u003E\r\n\tprivate Dictionary\u003Cint, RoadJunctionLayout\u003E ComputeJunctionLayouts()\r\n\t{\r\n\t\tvar radii = Nodes.ToDictionary(node =\u003E node.Id, node =\u003E MathF.Max(0.0f, node.CornerRadius));\r\n\t\tvar layouts = BuildJunctionLayouts(radii);\r\n\t\tvar shrink = new Dictionary\u003Cint, float\u003E();\r\n\r\n\t\tforeach (var segment in Segments)\r\n\t\t{\r\n\t\t\tvar table = GetCurveTable(segment);\r\n\r\n\t\t\tif (table is null)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tvar startArm = layouts.GetValueOrDefault(segment.StartNodeId)?.FindArm(segment.Id);\r\n\t\t\tvar endArm = layouts.GetValueOrDefault(segment.EndNodeId)?.FindArm(segment.Id);\r\n\t\t\tfloat sharp = (startArm?.SharpTrim ?? 0.0f) \u002B (endArm?.SharpTrim ?? 0.0f);\r\n\t\t\tfloat fillet = (startArm is null ? 0.0f : startArm.RawTrim - startArm.SharpTrim) \u002B (endArm is null ? 0.0f : endArm.RawTrim - endArm.SharpTrim);\r\n\t\t\tfloat available = MathF.Max(0.0f, table.Length - MinChunkLength);\r\n\r\n\t\t\tif (fillet \u003C= 0.0f || sharp \u002B fillet \u003C= available)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\t// The fillet\u0027s share of a trim is proportional to the radius, so this factor makes it fit exactly.\r\n\t\t\tfloat factor = Math.Clamp((available - sharp) / fillet, 0.0f, 1.0f);\r\n\r\n\t\t\tforeach (int nodeId in new[] { segment.StartNodeId, segment.EndNodeId })\r\n\t\t\t{\r\n\t\t\t\tif (layouts.ContainsKey(nodeId))\r\n\t\t\t\t\tshrink[nodeId] = MathF.Min(shrink.GetValueOrDefault(nodeId, 1.0f), factor);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (shrink.Count \u003E 0)\r\n\t\t{\r\n\t\t\tforeach (var (nodeId, factor) in shrink)\r\n\t\t\t\tradii[nodeId] *= factor;\r\n\r\n\t\t\tlayouts = BuildJunctionLayouts(radii);\r\n\t\t}\r\n\r\n\t\t// Last resort, for corners that do not fit even when sharp: share what road there is.\r\n\t\tforeach (var segment in Segments)\r\n\t\t{\r\n\t\t\tvar table = GetCurveTable(segment);\r\n\r\n\t\t\tif (table is null)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tvar startArm = layouts.GetValueOrDefault(segment.StartNodeId)?.FindArm(segment.Id);\r\n\t\t\tvar endArm = layouts.GetValueOrDefault(segment.EndNodeId)?.FindArm(segment.Id);\r\n\t\t\tfloat total = (startArm?.Trim ?? 0.0f) \u002B (endArm?.Trim ?? 0.0f);\r\n\t\t\tfloat available = MathF.Max(0.0f, table.Length - MinChunkLength);\r\n\r\n\t\t\tif (total \u003C= available || total \u003C= 0.0f)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tfloat scale = available / total;\r\n\r\n\t\t\tif (startArm is not null)\r\n\t\t\t\tstartArm.Trim *= scale;\r\n\r\n\t\t\tif (endArm is not null)\r\n\t\t\t\tendArm.Trim *= scale;\r\n\t\t}\r\n\r\n\t\tforeach (var layout in layouts.Values)\r\n\t\t\tlayout.BuildPolygon();\r\n\r\n\t\treturn layouts;\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The corner fold on one side of a segment at one of its nodes, and whether the segment is that fold\u0027s first\r\n\t/// arm (its left edge) or second (its right edge). Looking out of the node, a segment starting there has its\r\n\t/// left on the arm\u0027s left; one ending there has it on the arm\u0027s right.\r\n\t/// \u003C/summary\u003E\r\n\tprivate static RoadJunctionLayout.CornerFold FindFold(RoadSegment _Segment, int _NodeId, bool _AtStart, bool _Left, Dictionary\u003Cint, RoadJunctionLayout\u003E _Layouts, out bool _SideA)\r\n\t{\r\n\t\t_SideA = _AtStart == _Left;\r\n\r\n\t\tif (!_Layouts.TryGetValue(_NodeId, out var layout))\r\n\t\t\treturn null;\r\n\r\n\t\tvar path = _SideA\r\n\t\t\t? layout.CornerPaths.FirstOrDefault(candidate =\u003E candidate.ArmA.Segment.Id == _Segment.Id)\r\n\t\t\t: layout.CornerPaths.FirstOrDefault(candidate =\u003E candidate.ArmB.Segment.Id == _Segment.Id);\r\n\r\n\t\treturn path?.Fold;\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The junction layout of every node for the given fillet radii, from the cache where the inputs match.\r\n\t/// \u003C/summary\u003E\r\n\tprivate Dictionary\u003Cint, RoadJunctionLayout\u003E BuildJunctionLayouts(Dictionary\u003Cint, float\u003E _Radii)\r\n\t{\r\n\t\tvar layouts = new Dictionary\u003Cint, RoadJunctionLayout\u003E();\r\n\t\tvar liveNodes = new HashSet\u003Cint\u003E();\r\n\r\n\t\tforeach (var node in Nodes)\r\n\t\t{\r\n\t\t\tliveNodes.Add(node.Id);\r\n\r\n\t\t\tfloat radius = _Radii[node.Id];\r\n\t\t\tlong key = ComputeJunctionKey(node, radius);\r\n\t\t\tRoadJunctionLayout layout;\r\n\r\n\t\t\t// A cached layout is only as good as its references: undo and reloads swap the graph\u0027s objects.\r\n\t\t\tif (m_JunctionCache.TryGetValue(node.Id, out var cached) \u0026\u0026 cached.Key == key \u0026\u0026 (cached.Layout is null || cached.Layout.Refresh(this)))\r\n\t\t\t{\r\n\t\t\t\tlayout = cached.Layout;\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tlayout = RoadJunctionLayout.Create(this, node, SurfaceOffset, radius);\r\n\t\t\t\tm_JunctionCache[node.Id] = (key, layout);\r\n\t\t\t}\r\n\r\n\t\t\tif (layout is null)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tlayout.ResetTrims();\r\n\t\t\tlayouts[node.Id] = layout;\r\n\t\t}\r\n\r\n\t\tforeach (int nodeId in m_JunctionCache.Keys.Where(id =\u003E !liveNodes.Contains(id)).ToList())\r\n\t\t\tm_JunctionCache.Remove(nodeId);\r\n\r\n\t\treturn layouts;\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Whether an end of a road asks for a pedestrian crossing: the road type has them, the road has not turned\r\n\t/// this end\u0027s off, and the end is a real junction (three roads or more; a bend has a layout too, but nobody\r\n\t/// crosses at a bend) that trims the road.\r\n\t/// \u003C/summary\u003E\r\n\tprivate bool WantsCrossing(RoadSegment _Segment, int _NodeId, Dictionary\u003Cint, RoadJunctionLayout\u003E _Layouts, float _Trim)\r\n\t{\r\n\t\tif (!ProfileOf(_Segment).Crossings || !_Segment.CrossingAt(_NodeId))\r\n\t\t\treturn false;\r\n\r\n\t\treturn _Layouts.TryGetValue(_NodeId, out var layout) \u0026\u0026 layout.Arms.Count \u003E= 3 \u0026\u0026 _Trim \u003E 0.01f;\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Places a road\u0027s crossings on the stretch left between its junctions. Two crossings need room for both and\r\n\t/// a gap between; a shorter road between two junctions gets one crossing shared by both, halfway along; a road\r\n\t/// shorter than a crossing gets none.\r\n\t/// \u003C/summary\u003E\r\n\tprivate SegmentCrossings ComputeCrossings(RoadSegment _Segment, RoadCurveTable _Table, Dictionary\u003Cint, RoadJunctionLayout\u003E _Layouts, float _TrimStart, float _TrimEnd)\r\n\t{\r\n\t\tvar profile = ProfileOf(_Segment);\r\n\t\tfloat depth = profile.CrossingDepth;\r\n\t\tfloat clear = _Table.Length - _TrimStart - _TrimEnd;\r\n\t\tbool wantStart = WantsCrossing(_Segment, _Segment.StartNodeId, _Layouts, _TrimStart);\r\n\t\tbool wantEnd = WantsCrossing(_Segment, _Segment.EndNodeId, _Layouts, _TrimEnd);\r\n\r\n\t\tif (clear \u003C depth || (!wantStart \u0026\u0026 !wantEnd))\r\n\t\t\treturn default;\r\n\r\n\t\t// A ladder of stripes is laid on the road outside the junction; two lines mark the walk across the\r\n\t\t// junction\u0027s own mouth, so that kind is pulled in far enough to put its outer line on the pavement\u0027s\r\n\t\t// corner instead of a crossing\u0027s depth short of it.\r\n\t\tbool inside = profile.CrossingStyle == RoadCrossingStyle.Lines;\r\n\t\tfloat startCentre = inside\r\n\t\t\t? MathF.Max(depth * 0.5f, _TrimStart - depth * 0.5f)\r\n\t\t\t: _TrimStart \u002B depth * 0.5f;\r\n\r\n\t\tfloat endCentre = inside\r\n\t\t\t? MathF.Min(_Table.Length - depth * 0.5f, _Table.Length - _TrimEnd \u002B depth * 0.5f)\r\n\t\t\t: _Table.Length - _TrimEnd - depth * 0.5f;\r\n\r\n\t\tif (wantStart \u0026\u0026 wantEnd)\r\n\t\t{\r\n\t\t\tif (clear \u003E= 2.0f * depth \u002B profile.CrossingClearance)\r\n\t\t\t\treturn new SegmentCrossings(true, startCentre, true, endCentre);\r\n\r\n\t\t\treturn new SegmentCrossings(true, _TrimStart \u002B clear * 0.5f, false, 0.0f);\r\n\t\t}\r\n\r\n\t\treturn wantStart\r\n\t\t\t? new SegmentCrossings(true, startCentre, false, 0.0f)\r\n\t\t\t: new SegmentCrossings(false, 0.0f, true, endCentre);\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Where the painted lines run: the stretch between the junctions, kept clear of the crossings.\r\n\t/// \u003C/summary\u003E\r\n\tprivate static LineRange ComputeLineRange(RoadCurveTable _Table, RoadProfile _Profile, float _TrimStart, float _TrimEnd, in SegmentCrossings _Crossings)\r\n\t{\r\n\t\tfloat reach = _Profile.CrossingDepth * 0.5f \u002B _Profile.CrossingClearance;\r\n\t\tfloat start = _TrimStart;\r\n\t\tfloat end = _Table.Length - _TrimEnd;\r\n\t\tfloat gapStart = 0.0f;\r\n\t\tfloat gapEnd = 0.0f;\r\n\r\n\t\tif (_Crossings.AtEnd)\r\n\t\t\tend = MathF.Min(end, _Crossings.EndCentre - reach);\r\n\r\n\t\tif (_Crossings.AtStart)\r\n\t\t{\r\n\t\t\tfloat before = _Crossings.StartCentre - reach;\r\n\t\t\tfloat after = _Crossings.StartCentre \u002B reach;\r\n\r\n\t\t\t// A crossing at the very start just pushes the lines back; one further along cuts a gap in them.\r\n\t\t\tif (before \u003C= start \u002B 1.0f)\r\n\t\t\t{\r\n\t\t\t\tstart = MathF.Max(start, after);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tgapStart = before;\r\n\t\t\t\tgapEnd = after;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\treturn new LineRange(start, end, gapStart, gapEnd);\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Which ends of a segment\u0027s borders nothing continues: a road end, a side of a junction with no corner on it,\r\n\t/// or a pass-through node where the road changes type or width.\r\n\t/// \u003C/summary\u003E\r\n\tprivate BorderCaps ComputeBorderCaps(RoadSegment _Segment, Dictionary\u003Cint, RoadJunctionLayout\u003E _Layouts)\r\n\t{\r\n\t\tvar caps = BorderCaps.None;\r\n\r\n\t\tif (IsBorderOpen(_Segment, _Segment.StartNodeId, true, _Layouts, out bool startLeft, out bool startRight))\r\n\t\t{\r\n\t\t\tcaps |= startLeft ? BorderCaps.StartLeft : BorderCaps.None;\r\n\t\t\tcaps |= startRight ? BorderCaps.StartRight : BorderCaps.None;\r\n\t\t}\r\n\r\n\t\tif (IsBorderOpen(_Segment, _Segment.EndNodeId, false, _Layouts, out bool endLeft, out bool endRight))\r\n\t\t{\r\n\t\t\tcaps |= endLeft ? BorderCaps.EndLeft : BorderCaps.None;\r\n\t\t\tcaps |= endRight ? BorderCaps.EndRight : BorderCaps.None;\r\n\t\t}\r\n\r\n\t\treturn caps;\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// A bridge segment\u0027s built range and ends. An end is closed off unless it is a pass-through node onto\r\n\t/// another bridge of the same style, width and border, where the two decks meet flush; there, only one of the\r\n\t/// two segments provides the node\u0027s railing post: the one leaving the node, or the lower id when both leave\r\n\t/// or both arrive.\r\n\t/// \u003C/summary\u003E\r\n\tprivate RoadBridgeBuilder.BridgeSpan ComputeBridgeSpan(RoadSegment _Segment, float _RangeStart, float _RangeEnd)\r\n\t{\r\n\t\tvar startNeighbour = DeckContinuation(_Segment, _Segment.StartNodeId);\r\n\t\tvar endNeighbour = DeckContinuation(_Segment, _Segment.EndNodeId);\r\n\r\n\t\tbool postStart = startNeighbour is null || startNeighbour.EndNodeId == _Segment.StartNodeId || _Segment.Id \u003C startNeighbour.Id;\r\n\t\tbool postEnd = endNeighbour is null || (endNeighbour.EndNodeId == _Segment.EndNodeId \u0026\u0026 _Segment.Id \u003C endNeighbour.Id);\r\n\r\n\t\treturn new RoadBridgeBuilder.BridgeSpan(_RangeStart, _RangeEnd, startNeighbour is null, postStart, endNeighbour is null, postEnd);\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The bridge segment the deck carries straight on to at a node, or null where the deck ends.\r\n\t/// \u003C/summary\u003E\r\n\tprivate RoadSegment DeckContinuation(RoadSegment _Segment, int _NodeId)\r\n\t{\r\n\t\tif (GetDegree(_NodeId) != 2)\r\n\t\t\treturn null;\r\n\r\n\t\tvar other = GetSegmentsAt(_NodeId).FirstOrDefault(candidate =\u003E candidate.Id != _Segment.Id);\r\n\r\n\t\tif (other?.Bridge is null || other.Bridge.ResourcePath != _Segment.Bridge.ResourcePath || !SameEdgesAt(_Segment, other, _NodeId))\r\n\t\t\treturn null;\r\n\r\n\t\tbool sameExtent = MathF.Abs(RoadBridgeBuilder.DeckExtent(ProfileOf(other), other.Bridge) - RoadBridgeBuilder.DeckExtent(ProfileOf(_Segment), _Segment.Bridge)) \u003C 0.01f;\r\n\r\n\t\treturn sameExtent ? other : null;\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The lift lines of a segment\u0027s two borders: at each end, the corner\u0027s height difference on that side (or\r\n\t/// nothing), run linearly along the road between the two.\r\n\t/// \u003C/summary\u003E\r\n\tprivate RoadBorderBuilder.SegmentBorderBlends ComputeBorderBlends(RoadSegment _Segment, RoadCurveTable _Table, Dictionary\u003Cint, RoadJunctionLayout\u003E _Layouts)\r\n\t{\r\n\t\treturn new RoadBorderBuilder.SegmentBorderBlends(SideBlendFor(_Segment, _Table, true, _Layouts), SideBlendFor(_Segment, _Table, false, _Layouts));\r\n\t}\r\n\r\n\r\n\r\n\tprivate RoadBorderBuilder.SideBlend SideBlendFor(RoadSegment _Segment, RoadCurveTable _Table, bool _Left, Dictionary\u003Cint, RoadJunctionLayout\u003E _Layouts)\r\n\t{\r\n\t\tbool hasStart = CornerLift(_Segment, _Segment.StartNodeId, true, _Left, _Layouts, out float startDistance, out float startDelta);\r\n\t\tbool hasEnd = CornerLift(_Segment, _Segment.EndNodeId, false, _Left, _Layouts, out float endDistance, out float endDelta);\r\n\r\n\t\tif (!hasStart \u0026\u0026 !hasEnd)\r\n\t\t\treturn default;\r\n\r\n\t\t// An end with no corner on this side holds the border at road height from where the border actually starts,\r\n\t\t// which is past the trim: a road opening into a lot stops at the lot\u0027s flares, and a blend still running\r\n\t\t// there hands the lot a pavement tilted by whatever it had left to shed while the lot\u0027s own is flat.\r\n\t\tif (!hasStart)\r\n\t\t{\r\n\t\t\tstartDistance = LotTrimAt(_Segment.StartNodeId);\r\n\t\t\tstartDelta = 0.0f;\r\n\t\t}\r\n\r\n\t\tif (!hasEnd)\r\n\t\t{\r\n\t\t\tendDistance = _Table.Length - LotTrimAt(_Segment.EndNodeId);\r\n\t\t\tendDelta = 0.0f;\r\n\t\t}\r\n\r\n\t\treturn new RoadBorderBuilder.SideBlend(true, startDistance, startDelta, endDistance, endDelta);\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Where along the segment the corner\u0027s tangent point on this side is, and how much higher the corner sits\r\n\t/// than the road edge there; false when there is no inside corner on that side at that end.\r\n\t/// \u003C/summary\u003E\r\n\tprivate static bool CornerLift(RoadSegment _Segment, int _NodeId, bool _AtStart, bool _Left, Dictionary\u003Cint, RoadJunctionLayout\u003E _Layouts, out float _Distance, out float _Delta)\r\n\t{\r\n\t\t_Distance = 0.0f;\r\n\t\t_Delta = 0.0f;\r\n\r\n\t\tvar fold = FindFold(_Segment, _NodeId, _AtStart, _Left, _Layouts, out bool sideA);\r\n\r\n\t\tif (fold is null || !_Layouts.TryGetValue(_NodeId, out var layout))\r\n\t\t\treturn false;\r\n\r\n\t\tvar arm = layout.FindArm(_Segment.Id);\r\n\r\n\t\tif (arm is null)\r\n\t\t\treturn false;\r\n\r\n\t\t_Distance = arm.CurveDistance(sideA ? fold.TangentParamA : fold.TangentParamB);\r\n\t\t_Delta = fold.ApexHeight - (sideA ? fold.TangentHeightA : fold.TangentHeightB);\r\n\r\n\t\treturn true;\r\n\t}\r\n\r\n\r\n\r\n\tprivate bool IsBorderOpen(RoadSegment _Segment, int _NodeId, bool _AtStart, Dictionary\u003Cint, RoadJunctionLayout\u003E _Layouts, out bool _Left, out bool _Right)\r\n\t{\r\n\t\tint degree = GetDegree(_NodeId);\r\n\r\n\t\t// A road opening into a lot runs into the lot\u0027s own kerb, which closes it off; two caps in one place\r\n\t\t// would only fight each other.\r\n\t\tif (LotAtOpening(_NodeId) is { } lot \u0026\u0026 ProfileOf(lot).Border == ProfileOf(_Segment).Border)\r\n\t\t{\r\n\t\t\t_Left = false;\r\n\t\t\t_Right = false;\r\n\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\tif (degree \u003C= 1)\r\n\t\t{\r\n\t\t\t// A road rounded off where it stops carries its border round the end; a cap across the road as well\r\n\t\t\t// would sit inside that.\r\n\t\t\tbool rounded = _Segment.Bridge is null \u0026\u0026 ProfileOf(_Segment).RoundedEnds;\r\n\r\n\t\t\t_Left = !rounded;\r\n\t\t\t_Right = !rounded;\r\n\t\t\treturn !rounded;\r\n\t\t}\r\n\r\n\t\tif (_Layouts.TryGetValue(_NodeId, out var layout))\r\n\t\t{\r\n\t\t\t// A corner path starting on this arm continues its left border (looking out of the node); one ending on\r\n\t\t\t// it continues its right. Looking out of the node along a segment that ends there swaps the sides.\r\n\t\t\tbool armLeftContinued = layout.CornerPaths.Any(path =\u003E path.ArmA.Segment.Id == _Segment.Id);\r\n\t\t\tbool armRightContinued = layout.CornerPaths.Any(path =\u003E path.ArmB.Segment.Id == _Segment.Id);\r\n\r\n\t\t\t_Left = !(_AtStart ? armLeftContinued : armRightContinued);\r\n\t\t\t_Right = !(_AtStart ? armRightContinued : armLeftContinued);\r\n\t\t\treturn _Left || _Right;\r\n\t\t}\r\n\r\n\t\tif (degree == 2)\r\n\t\t{\r\n\t\t\tvar other = GetSegmentsAt(_NodeId).FirstOrDefault(candidate =\u003E candidate.Id != _Segment.Id);\r\n\t\t\tbool continuous = other is not null \u0026\u0026 SameEdgesAt(_Segment, other, _NodeId)\r\n\t\t\t\t\u0026\u0026 (RoadBorderBuilder.SameProfile(ProfileOf(other), ProfileOf(_Segment)) || MeetsFlush(ProfileOf(other), ProfileOf(_Segment)));\r\n\r\n\t\t\t_Left = !continuous;\r\n\t\t\t_Right = !continuous;\r\n\t\t\treturn !continuous;\r\n\t\t}\r\n\r\n\t\t_Left = true;\r\n\t\t_Right = true;\r\n\t\treturn true;\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Splits a segment into chunks at fixed distances from its start, clipped by the junction trims at each end,\r\n\t/// with a border chunk over each stretch when the road type has borders. Anchoring the boundaries to the\r\n\t/// segment rather than to the trimmed length means a junction change at one end only touches the chunk next\r\n\t/// to it.\r\n\t/// \u003C/summary\u003E\r\n\tprivate List\u003CChunkPlan\u003E PlanChunks(RoadSegment _Segment, RoadCurveTable _Table, float _TrimStart, float _TrimEnd, RoadProfile _Profile, BorderCaps _Caps, in RoadBorderBuilder.SegmentBorderBlends _Blends, in SegmentBorderTapers _Taper, long _SurfaceSignature, in LineRange _Lines, in RoadMarkingBuilder.DashPhase _Dash, in SegmentCrossings _Crossings, in RoadTrailFade _Trails, in RoadSurfaceBlend _SurfaceBlend)\r\n\t{\r\n\t\tfloat length = _Table.Length;\r\n\t\tint count = Math.Max(1, (int)MathF.Ceiling(length / ChunkLength));\r\n\t\tfloat usableEnd = length - _TrimEnd;\r\n\t\tvar ranges = new List\u003C(int Index, float Start, float End)\u003E(count);\r\n\r\n\t\tfor (int i = 0; i \u003C count; i\u002B\u002B)\r\n\t\t{\r\n\t\t\tfloat start = MathF.Max(length * i / count, _TrimStart);\r\n\t\t\tfloat end = MathF.Min(length * (i \u002B 1) / count, usableEnd);\r\n\r\n\t\t\tif (end - start \u003E= MinChunkLength)\r\n\t\t\t\tranges.Add((i, start, end));\r\n\t\t}\r\n\r\n\t\tvar plans = new List\u003CChunkPlan\u003E(ranges.Count * 4);\r\n\t\tvar borderHash = StableHash.Create();\r\n\t\tborderHash.Add(_SurfaceSignature);\r\n\t\t_Profile.AddBorderToHash(ref borderHash);\r\n\t\t_Blends.AddToHash(ref borderHash);\r\n\t\t_Taper.AddToHash(ref borderHash);\r\n\t\tborderHash.Add(DebugBorders ? 1 : 0);\r\n\t\tlong borderSignature = borderHash.Value;\r\n\r\n\t\t// The deck follows the road and stands off its border, so it is stale when either changes; its posts and\r\n\t\t// supports are spread over the whole built range, so every piece is stale when an end moves.\r\n\t\tvar bridge = _Segment.Bridge;\r\n\t\tvar bridgeSpan = bridge is null ? default : ComputeBridgeSpan(_Segment, _TrimStart, usableEnd);\r\n\t\tlong bridgeSignature = 0;\r\n\r\n\t\tif (bridge is not null)\r\n\t\t{\r\n\t\t\tvar bridgeHash = StableHash.Create();\r\n\t\t\tbridgeHash.Add(_SurfaceSignature);\r\n\t\t\tbridgeHash.Add(bridge.ResourcePath);\r\n\t\t\t_Profile.AddBorderToHash(ref bridgeHash);\r\n\t\t\tbridge.AddToHash(ref bridgeHash);\r\n\t\t\tbridgeSpan.AddToHash(ref bridgeHash);\r\n\t\t\tbridgeSignature = bridgeHash.Value;\r\n\t\t}\r\n\r\n\t\t// Props are spread over the whole built range too, and stand on the border, so they follow its shape.\r\n\t\tvar props = _Segment.Props;\r\n\t\tvar propSpan = props is null ? default : new RoadPropBuilder.PropSpan(_TrimStart, usableEnd, GetDegree(_Segment.StartNodeId) \u003E= 3, GetDegree(_Segment.EndNodeId) \u003E= 3);\r\n\t\tlong propSignature = 0;\r\n\r\n\t\tif (props is not null \u0026\u0026 !props.IsEmpty)\r\n\t\t{\r\n\t\t\tvar propHash = StableHash.Create();\r\n\t\t\tpropHash.Add(_SurfaceSignature);\r\n\t\t\tpropHash.Add(props.ResourcePath);\r\n\t\t\tpropHash.Add(bridge is null ? 0 : 1);\r\n\t\t\t_Profile.AddBorderToHash(ref propHash);\r\n\t\t\tprops.AddToHash(ref propHash);\r\n\t\t\tpropSpan.AddToHash(ref propHash);\r\n\t\t\tpropSignature = propHash.Value;\r\n\t\t}\r\n\r\n\t\t// A road with no lines of its own still needs the piece when it has a crossing to paint.\r\n\t\tbool markings = RoadMarkingBuilder.HasMarkings(_Segment, _Profile) || _Crossings.AtStart || _Crossings.AtEnd;\r\n\t\tvar markingHash = StableHash.Create();\r\n\t\tmarkingHash.Add(_SurfaceSignature);\r\n\t\tmarkingHash.Add(_Segment.LaneCount);\r\n\t\tmarkingHash.Add(_Segment.ForwardLanes);\r\n\t\t_Lines.AddToHash(ref markingHash);\r\n\t\t_Dash.AddToHash(ref markingHash);\r\n\t\t_Profile.AddMarkingsToHash(ref markingHash);\r\n\t\t_Profile.AddCrossingsToHash(ref markingHash);\r\n\t\tmarkingHash.Add(_Crossings.AtStart ? _Crossings.StartCentre : -1.0f);\r\n\t\tmarkingHash.Add(_Crossings.AtEnd ? _Crossings.EndCentre : -1.0f);\r\n\t\tlong markingSignature = markingHash.Value;\r\n\r\n\t\tfor (int r = 0; r \u003C ranges.Count; r\u002B\u002B)\r\n\t\t{\r\n\t\t\tvar (index, start, end) = ranges[r];\r\n\r\n\t\t\tvar hash = StableHash.Create();\r\n\t\t\thash.Add(_SurfaceSignature);\r\n\t\t\thash.Add(index);\r\n\t\t\thash.Add(count);\r\n\t\t\thash.Add(start);\r\n\t\t\thash.Add(end);\r\n\t\t\t// Where the road climbs as it turns, its cells are cut into a column per lane (or more).\r\n\t\t\thash.Add(_Segment.LaneCount);\r\n\t\t\t// Its trails rise out, and another surface blends into it, wherever the road stops, which moves with the\r\n\t\t\t// junctions at its ends.\r\n\t\t\t_Trails.AddToHash(ref hash);\r\n\t\t\t_SurfaceBlend.AddToHash(ref hash);\r\n\r\n\t\t\tplans.Add(new ChunkPlan(index, count, start, end, RoadChunkKind.Surface, BorderCaps.None, default, hash.Value, Trails: _Trails, Blend: _SurfaceBlend));\r\n\r\n\t\t\tif (markings)\r\n\t\t\t{\r\n\t\t\t\thash = StableHash.Create();\r\n\t\t\t\t// A crossing belongs to one piece: the outermost, since its band may lie clear of every piece\u0027s\r\n\t\t\t\t// own stretch of road.\r\n\t\t\t\tvar owned = new SegmentCrossings(_Crossings.AtStart \u0026\u0026 r == 0, _Crossings.StartCentre,\r\n\t\t\t\t\t_Crossings.AtEnd \u0026\u0026 r == ranges.Count - 1, _Crossings.EndCentre);\r\n\r\n\t\t\t\thash.Add(markingSignature);\r\n\t\t\t\thash.Add(index);\r\n\t\t\t\thash.Add(count);\r\n\t\t\t\thash.Add(start);\r\n\t\t\t\thash.Add(end);\r\n\t\t\t\thash.Add(owned.AtStart ? 1 : 0);\r\n\t\t\t\thash.Add(owned.AtEnd ? 1 : 0);\r\n\r\n\t\t\t\tplans.Add(new ChunkPlan(index, count, start, end, RoadChunkKind.Marking, BorderCaps.None, default, hash.Value, _Lines, Dash: _Dash, Crossings: owned));\r\n\t\t\t}\r\n\r\n\t\t\tif (bridge is not null)\r\n\t\t\t{\r\n\t\t\t\t// The piece works out for itself whether it is an outermost one, from its stretch against the span.\r\n\t\t\t\thash = StableHash.Create();\r\n\t\t\t\thash.Add(bridgeSignature);\r\n\t\t\t\thash.Add(index);\r\n\t\t\t\thash.Add(count);\r\n\t\t\t\thash.Add(start);\r\n\t\t\t\thash.Add(end);\r\n\r\n\t\t\t\tplans.Add(new ChunkPlan(index, count, start, end, RoadChunkKind.Bridge, BorderCaps.None, default, hash.Value, Bridge: bridgeSpan));\r\n\t\t\t}\r\n\r\n\t\t\tif (propSignature != 0)\r\n\t\t\t{\r\n\t\t\t\thash = StableHash.Create();\r\n\t\t\t\thash.Add(propSignature);\r\n\t\t\t\thash.Add(index);\r\n\t\t\t\thash.Add(count);\r\n\t\t\t\thash.Add(start);\r\n\t\t\t\thash.Add(end);\r\n\r\n\t\t\t\tplans.Add(new ChunkPlan(index, count, start, end, RoadChunkKind.Props, BorderCaps.None, default, hash.Value, Props: propSpan));\r\n\t\t\t}\r\n\r\n\t\t\tif (!_Profile.HasBorder)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\t// Only the outermost stretches have open ends to close.\r\n\t\t\tvar caps = BorderCaps.None;\r\n\r\n\t\t\tif (r == 0)\r\n\t\t\t\tcaps |= _Caps \u0026 (BorderCaps.StartLeft | BorderCaps.StartRight);\r\n\r\n\t\t\tif (r == ranges.Count - 1)\r\n\t\t\t\tcaps |= _Caps \u0026 (BorderCaps.EndLeft | BorderCaps.EndRight);\r\n\r\n\t\t\thash = StableHash.Create();\r\n\t\t\thash.Add(borderSignature);\r\n\t\t\thash.Add(index);\r\n\t\t\thash.Add(count);\r\n\t\t\thash.Add(start);\r\n\t\t\thash.Add(end);\r\n\t\t\thash.Add((int)caps);\r\n\r\n\t\t\tplans.Add(new ChunkPlan(index, count, start, end, RoadChunkKind.Border, caps, _Blends, hash.Value, default, _Taper));\r\n\t\t}\r\n\r\n\t\t// A road that simply stops is rounded off there, in a piece of its own beyond the node.\r\n\t\tAddCapPlan(plans, _Segment, _Table, _Profile, _SurfaceSignature, true);\r\n\t\tAddCapPlan(plans, _Segment, _Table, _Profile, _SurfaceSignature, false);\r\n\r\n\t\treturn plans;\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The rounded end of a road, where it has one: at a node with nothing else at it, which is not a way into a\r\n\t/// parking lot (the lot\u0027s own kerb closes that), and on a road no bridge carries (a deck ends where it ends).\r\n\t/// The plan\u0027s start is the end\u0027s own distance along the curve and its end the depth the cap reaches past it.\r\n\t/// \u003C/summary\u003E\r\n\tprivate void AddCapPlan(List\u003CChunkPlan\u003E _Plans, RoadSegment _Segment, RoadCurveTable _Table, RoadProfile _Profile, long _SurfaceSignature, bool _AtStart)\r\n\t{\r\n\t\tint nodeId = _AtStart ? _Segment.StartNodeId : _Segment.EndNodeId;\r\n\r\n\t\tif (_Segment.Bridge is not null || GetDegree(nodeId) != 1 || LotAtOpening(nodeId) is not null)\r\n\t\t\treturn;\r\n\r\n\t\tfloat distance = _AtStart ? 0.0f : _Table.Length;\r\n\t\tfloat depth = RoadCapBuilder.Depth(_Profile, new RoadWidth(_Segment, _Table.Length), distance);\r\n\r\n\t\tif (depth \u003C= 0.01f)\r\n\t\t\treturn;\r\n\r\n\t\tvar hash = StableHash.Create();\r\n\r\n\t\thash.Add(_SurfaceSignature);\r\n\t\thash.Add(_AtStart ? 1 : 0);\r\n\t\thash.Add(depth);\r\n\t\t_Profile.AddBorderToHash(ref hash);\r\n\r\n\t\t_Plans.Add(new ChunkPlan(_AtStart ? 0 : 1, 2, distance, depth, RoadChunkKind.Cap, BorderCaps.None, default, hash.Value));\r\n\t}\r\n\r\n\r\n\r\n\tprivate static long CombineSignatures(List\u003CChunkPlan\u003E _Plans)\r\n\t{\r\n\t\tvar hash = StableHash.Create();\r\n\t\thash.Add(_Plans.Count);\r\n\r\n\t\tforeach (var plan in _Plans)\r\n\t\t\thash.Add(plan.Signature);\r\n\r\n\t\treturn hash.Value;\r\n\t}\r\n\r\n\r\n\r\n\tprivate bool IsSegmentUpToDate(List\u003CRoadChunk\u003E _Existing, List\u003CChunkPlan\u003E _Plans)\r\n\t{\r\n\t\tint have = _Existing?.Count ?? 0;\r\n\r\n\t\tif (have != _Plans.Count)\r\n\t\t\treturn false;\r\n\r\n\t\tforeach (var plan in _Plans)\r\n\t\t{\r\n\t\t\tvar chunk = _Existing.FirstOrDefault(candidate =\u003E candidate.ChunkIndex == plan.Index \u0026\u0026 candidate.Kind == plan.Kind);\r\n\r\n\t\t\tif (chunk is null)\r\n\t\t\t\treturn false;\r\n\r\n\t\t\t// A locked chunk is exempt: it is deliberately stale.\r\n\t\t\tif (!chunk.Locked \u0026\u0026 (chunk.Signature != plan.Signature || LacksDebugRecord(chunk)))\r\n\t\t\t\treturn false;\r\n\t\t}\r\n\r\n\t\treturn true;\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// While the border debug overlay is on, a border piece without its record (built before the flag went on, or\r\n\t/// before a hot reload, which drops the records) is rebuilt to get one.\r\n\t/// \u003C/summary\u003E\r\n\tprivate bool LacksDebugRecord(RoadChunk _Chunk)\r\n\t{\r\n\t\treturn DebugBorders \u0026\u0026 _Chunk.Kind == RoadChunkKind.Border \u0026\u0026 (_Chunk.Debug is null || _Chunk.Debug.Text.Length == 0);\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Throws away every unlocked piece\u0027s signature so the next reconcile rebuilds all of them, junction layouts\r\n\t/// included. Toggling the GameObject does not do this: pieces whose inputs have not changed are kept as they\r\n\t/// are, so after a generator change this is the way to see it everywhere.\r\n\t/// \u003C/summary\u003E\r\n\t[Button(\u0022Regenerate All\u0022, \u0022refresh\u0022)]\r\n\tpublic void RegenerateAll()\r\n\t{\r\n\t\tforeach (var chunk in GetChunks())\r\n\t\t{\r\n\t\t\tif (!chunk.Locked)\r\n\t\t\t\tchunk.Signature = 0;\r\n\t\t}\r\n\r\n\t\tm_JunctionCache.Clear();\r\n\t\tMarkDirty();\r\n\t}\r\n\r\n\r\n\r\n\tprivate long ComputeSurfaceSignature(RoadSegment _Segment, in RoadCurve _Curve, RoadProfile _Profile)\r\n\t{\r\n\t\tvar hash = StableHash.Create();\r\n\r\n\t\thash.Add(GeneratorVersion);\r\n\t\thash.Add(_Curve.P0);\r\n\t\thash.Add(_Curve.P1);\r\n\t\thash.Add(_Curve.P2);\r\n\t\thash.Add(_Curve.P3);\r\n\t\tnew RoadWidth(_Segment, 1.0f).AddToHash(ref hash);\r\n\t\thash.Add(SampleSpacing);\r\n\t\thash.Add(ChunkLength);\r\n\t\thash.Add(SurfaceOffset);\r\n\t\t_Profile.AddSurfaceToHash(ref hash);\r\n\r\n\t\treturn hash.Value;\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Everything a node\u0027s junction layout depends on: the node itself and the curve and width of each road at it.\r\n\t/// \u003C/summary\u003E\r\n\tprivate long ComputeJunctionKey(RoadNode _Node, float _Radius)\r\n\t{\r\n\t\tvar hash = StableHash.Create();\r\n\r\n\t\thash.Add(GeneratorVersion);\r\n\t\thash.Add(_Node.Position);\r\n\t\thash.Add(_Radius);\r\n\t\thash.Add(SurfaceOffset);\r\n\r\n\t\tforeach (var segment in GetSegmentsAt(_Node.Id).OrderBy(segment =\u003E segment.Id))\r\n\t\t{\r\n\t\t\thash.Add(segment.Id);\r\n\t\t\tnew RoadWidth(segment, 1.0f).AddToHash(ref hash);\r\n\t\t\thash.Add(segment.Ramp ? 1 : 0);\r\n\t\t\thash.Add(segment.StartNodeId == _Node.Id ? 1 : 0);\r\n\r\n\t\t\tif (!TryGetCurve(segment, out var curve))\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\thash.Add(curve.P0);\r\n\t\t\thash.Add(curve.P1);\r\n\t\t\thash.Add(curve.P2);\r\n\t\t\thash.Add(curve.P3);\r\n\t\t}\r\n\r\n\t\treturn hash.Value;\r\n\t}\r\n\r\n\r\n\r\n\tprivate static void AddPolygonToHash(RoadJunctionLayout _Layout, ref StableHash _Hash)\r\n\t{\r\n\t\t_Hash.Add(GeneratorVersion);\r\n\t\t_Hash.Add(_Layout.Centre);\r\n\t\t_Hash.Add(_Layout.Polygon.Count);\r\n\r\n\t\tforeach (var vertex in _Layout.Polygon)\r\n\t\t\t_Hash.Add(vertex);\r\n\t}\r\n\r\n\r\n\r\n\tprivate long ComputeJunctionSurfaceSignature(RoadJunctionLayout _Layout, Dictionary\u003Cint, RoadSurfaceBlend\u003E _ArmSurfaces)\r\n\t{\r\n\t\tvar hash = StableHash.Create();\r\n\r\n\t\tAddPolygonToHash(_Layout, ref hash);\r\n\t\tJunctionSurfaceProfile(_Layout).AddSurfaceToHash(ref hash);\r\n\r\n\t\t// Each arm\u0027s texture runs on into the junction along the arm\u0027s own curve from the row it stops at, so the\r\n\t\t// junction moves with the curve, where along it that row is and which way it runs, and with whether the\r\n\t\t// road is surfaced the same; a road blending the junction\u0027s surface into its own starts doing so in its mouth.\r\n\t\tforeach (var arm in _Layout.Arms)\r\n\t\t{\r\n\t\t\tvar curve = arm.Table.Curve;\r\n\r\n\t\t\thash.Add(arm.Segment.Id);\r\n\t\t\thash.Add(arm.AtStart ? 1 : 0);\r\n\t\t\thash.Add(arm.CurveDistance(arm.Trim));\r\n\t\t\thash.Add(curve.P0);\r\n\t\t\thash.Add(curve.P1);\r\n\t\t\thash.Add(curve.P2);\r\n\t\t\thash.Add(curve.P3);\r\n\t\t\tProfileOf(arm.Segment).AddSurfaceToHash(ref hash);\r\n\t\t\t_ArmSurfaces.GetValueOrDefault(arm.Segment.Id).AddToHash(ref hash);\r\n\t\t}\r\n\r\n\t\treturn hash.Value;\r\n\t}\r\n\r\n\r\n\r\n\tprivate long ComputeJunctionBorderSignature(RoadJunctionLayout _Layout, Dictionary\u003Cint, RoadBorderBuilder.SegmentBorderBlends\u003E _ArmBlends, Dictionary\u003Cint, SegmentBorderTapers\u003E _ArmTapers)\r\n\t{\r\n\t\tvar hash = StableHash.Create();\r\n\r\n\t\tAddPolygonToHash(_Layout, ref hash);\r\n\t\thash.Add(DebugBorders ? 1 : 0);\r\n\r\n\t\tforeach (var arm in _Layout.Arms)\r\n\t\t{\r\n\t\t\tvar profile = ProfileOf(arm.Segment);\r\n\r\n\t\t\thash.Add(arm.Segment.Id);\r\n\t\t\thash.Add(arm.AtStart ? 1 : 0);\r\n\t\t\thash.Add(arm.Length);\r\n\t\t\tprofile.AddSurfaceToHash(ref hash);\r\n\t\t\tprofile.AddBorderToHash(ref hash);\r\n\t\t\t_ArmBlends.GetValueOrDefault(arm.Segment.Id).AddToHash(ref hash);\r\n\t\t\t_ArmTapers.GetValueOrDefault(arm.Segment.Id).AddToHash(ref hash);\r\n\t\t}\r\n\r\n\t\treturn hash.Value;\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// A junction\u0027s surface takes after its main road: the widest arm.\r\n\t/// \u003C/summary\u003E\r\n\tprivate RoadProfile JunctionSurfaceProfile(RoadJunctionLayout _Layout)\r\n\t{\r\n\t\treturn ProfileOf(JunctionMainArm(_Layout)?.Segment);\r\n\t}\r\n\r\n\r\n\r\n\tprivate static RoadJunctionLayout.Arm JunctionMainArm(RoadJunctionLayout _Layout)\r\n\t{\r\n\t\treturn _Layout.Arms.OrderByDescending(arm =\u003E arm.Widths.Base).ThenBy(arm =\u003E arm.Segment.Id).FirstOrDefault();\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Whether an arm\u0027s road is surfaced like the junction it runs into (same material, laid the same way at the\r\n\t/// same scale), so the junction can carry the arm\u0027s texture on.\r\n\t/// \u003C/summary\u003E\r\n\tprivate bool SameSurface(RoadJunctionLayout.Arm _Arm, RoadProfile _Surface)\r\n\t{\r\n\t\treturn SameSurface(ProfileOf(_Arm.Segment), _Surface);\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Whether two road types lay the same road surface: the same material, laid the same way at the same scale.\r\n\t/// \u003C/summary\u003E\r\n\tprivate static bool SameSurface(RoadProfile _Profile, RoadProfile _Surface)\r\n\t{\r\n\t\treturn _Profile == _Surface || (_Profile.ResolvedRoadMaterial?.ResourcePath == _Surface.ResolvedRoadMaterial?.ResourcePath\r\n\t\t\t\u0026\u0026 _Profile.RoadTextureRepeat == _Surface.RoadTextureRepeat \u0026\u0026 _Profile.RoadTextureAcross == _Surface.RoadTextureAcross);\r\n\t}\r\n\r\n\r\n\r\n\tprivate void EnqueueSegment(RoadSegment _Segment, RoadCurveTable _Table, RoadProfile _Profile, List\u003CChunkPlan\u003E _Plans, long _GroupSignature, List\u003CRoadChunk\u003E _Existing)\r\n\t{\r\n\t\t// Chunks with no plan (swallowed by a junction, past a shorter road\u0027s end, or a border the road no longer\r\n\t\t// has) have no job coming to replace them.\r\n\t\tif (_Existing is not null)\r\n\t\t{\r\n\t\t\tforeach (var chunk in _Existing)\r\n\t\t\t{\r\n\t\t\t\tif (!chunk.Locked \u0026\u0026 _Plans.All(plan =\u003E plan.Index != chunk.ChunkIndex || plan.Kind != chunk.Kind))\r\n\t\t\t\t\tchunk.GameObject.Destroy();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (_Plans.Count == 0)\r\n\t\t{\r\n\t\t\tm_PendingSegments.Remove(_Segment.Id);\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tforeach (var plan in _Plans)\r\n\t\t\tm_Jobs.Enqueue(new RebuildJob(_Segment.Id, -1, plan.Kind, _GroupSignature, plan, _Table, new RoadWidth(_Segment, _Table.Length), _Profile, null, null, null, null));\r\n\r\n\t\tm_PendingSegments[_Segment.Id] = new PendingGroup(_GroupSignature, _Plans.Count);\r\n\t}\r\n\r\n\r\n\r\n\tprivate void ProcessJobs()\r\n\t{\r\n\t\tint budget = Math.Max(1, RebuildBudget);\r\n\r\n\t\twhile (budget \u003E 0 \u0026\u0026 m_Jobs.Count \u003E 0)\r\n\t\t{\r\n\t\t\tvar job = m_Jobs.Dequeue();\r\n\r\n\t\t\tif (job.Lot is not null)\r\n\t\t\t{\r\n\t\t\t\tvar lotKey = (job.Lot.Id, job.Kind);\r\n\r\n\t\t\t\t// Superseded by a newer version of the same lot, or the lot is gone.\r\n\t\t\t\tif (!m_PendingLots.TryGetValue(lotKey, out var pendingLot) || pendingLot.Signature != job.GroupSignature)\r\n\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\tBuildLotPiece(job);\r\n\t\t\t\tbudget--;\r\n\r\n\t\t\t\tm_PendingLots.Remove(lotKey);\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\r\n\t\t\tif (job.NodeId \u003E= 0)\r\n\t\t\t{\r\n\t\t\t\tvar key = (job.NodeId, job.Kind);\r\n\r\n\t\t\t\t// Superseded by a newer layout of the same junction, or the junction is gone.\r\n\t\t\t\tif (!m_PendingJunctions.TryGetValue(key, out var pending) || pending.Signature != job.GroupSignature)\r\n\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\tBuildJunctionPiece(job);\r\n\t\t\t\tbudget--;\r\n\r\n\t\t\t\tm_PendingJunctions.Remove(key);\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\r\n\t\t\t// Superseded by a newer rebuild of the same segment, or the segment is gone.\r\n\t\t\tif (!m_PendingSegments.TryGetValue(job.SegmentId, out var pendingSegment) || pendingSegment.Signature != job.GroupSignature)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tif (BuildChunk(job))\r\n\t\t\t\tbudget--;\r\n\r\n\t\t\tif (pendingSegment.Remaining \u003C= 1)\r\n\t\t\t\tm_PendingSegments.Remove(job.SegmentId);\r\n\t\t\telse\r\n\t\t\t\tm_PendingSegments[job.SegmentId] = pendingSegment with { Remaining = pendingSegment.Remaining - 1 };\r\n\t\t}\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Returns false when there was nothing to do: the chunk in place was already built from these inputs (a\r\n\t/// junction change at the far end of the road requeues the whole road, but only the chunk next to it differs).\r\n\t/// \u003C/summary\u003E\r\n\tprivate bool BuildChunk(in RebuildJob _Job)\r\n\t{\r\n\t\tvar plan = _Job.Plan;\r\n\t\tvar existing = FindChunk(_Job.SegmentId, plan.Index, plan.Kind);\r\n\r\n\t\tif (existing is not null \u0026\u0026 (existing.Locked || (existing.Signature == plan.Signature \u0026\u0026 !LacksDebugRecord(existing))))\r\n\t\t\treturn false;\r\n\r\n\t\tPolygonMesh mesh;\r\n\t\tstring name;\r\n\t\tBorderDebug debug = null;\r\n\t\tvar placements = new List\u003C(GameObject Prefab, Transform Transform)\u003E();\r\n\r\n\t\tif (plan.Kind == RoadChunkKind.Border)\r\n\t\t{\r\n\t\t\tdebug = DebugBorders ? new BorderDebug() : null;\r\n\t\t\tmesh = RoadBorderBuilder.BuildSegment(_Job.Table, plan.Start, plan.End, _Job.Width, _Job.Profile, SampleSpacing, SurfaceOffset, plan.Caps, plan.Blends, plan.Taper, debug);\r\n\t\t\tname = $\u0022Road {_Job.SegmentId} border [{plan.Index \u002B 1}/{plan.Count}]\u0022;\r\n\t\t}\r\n\t\telse if (plan.Kind == RoadChunkKind.Bridge)\r\n\t\t{\r\n\t\t\tvar segment = FindSegment(_Job.SegmentId);\r\n\r\n\t\t\tif (segment?.Bridge is null)\r\n\t\t\t\treturn false;\r\n\r\n\t\t\tvar parts = new List\u003CRoadBridgeBuilder.Placement\u003E();\r\n\t\t\tmesh = RoadBridgeBuilder.Build(_Job.Table, plan.Start, plan.End, plan.Bridge, _Job.Width, _Job.Profile, segment.Bridge, SampleSpacing, SurfaceOffset, GroundBelow, parts);\r\n\t\t\tname = $\u0022Road {_Job.SegmentId} bridge [{plan.Index \u002B 1}/{plan.Count}]\u0022;\r\n\r\n\t\t\tforeach (var part in parts)\r\n\t\t\t\tplacements.Add((part.Prefab, new Transform(part.Position, part.Rotation)));\r\n\t\t}\r\n\t\telse if (plan.Kind == RoadChunkKind.Props)\r\n\t\t{\r\n\t\t\tvar segment = FindSegment(_Job.SegmentId);\r\n\r\n\t\t\tif (segment?.Props is null)\r\n\t\t\t\treturn false;\r\n\r\n\t\t\t// Nothing to mesh: the piece is only the parent of its prefabs.\r\n\t\t\tvar props = new List\u003CRoadPropBuilder.Placement\u003E();\r\n\t\t\tvar context = new RoadPropBuilder.Context(_Job.Table, plan.Start, plan.End, plan.Props, _Job.SegmentId, _Job.Width, _Job.Profile, segment.Bridge is not null, SurfaceOffset, GroundAround);\r\n\r\n\t\t\tRoadPropBuilder.Build(context, segment.Props, props);\r\n\t\t\tmesh = null;\r\n\t\t\tname = $\u0022Road {_Job.SegmentId} props [{plan.Index \u002B 1}/{plan.Count}]\u0022;\r\n\r\n\t\t\tforeach (var prop in props)\r\n\t\t\t\tplacements.Add((prop.Prefab, new Transform(prop.Position, prop.Rotation, prop.Scale)));\r\n\t\t}\r\n\t\telse if (plan.Kind == RoadChunkKind.Cap)\r\n\t\t{\r\n\t\t\t// Surface and border in one piece: the whole end is small, and nothing else shares it.\r\n\t\t\tmesh = RoadCapBuilder.Build(_Job.Table, plan.Start, plan.Index == 0, _Job.Width, _Job.Profile, SurfaceOffset, plan.End);\r\n\t\t\tname = $\u0022Road {_Job.SegmentId} {(plan.Index == 0 ? \u0022start\u0022 : \u0022end\u0022)} cap\u0022;\r\n\t\t}\r\n\t\telse if (plan.Kind == RoadChunkKind.Marking)\r\n\t\t{\r\n\t\t\tvar segment = FindSegment(_Job.SegmentId);\r\n\r\n\t\t\tif (segment is null)\r\n\t\t\t\treturn false;\r\n\r\n\t\t\t// Lines only where the chunk overlaps the stretches left clear by the crossings, laid on the rows the\r\n\t\t\t// road surface itself was built on.\r\n\t\t\tmesh = new PolygonMesh();\r\n\r\n\t\t\tvar roadRows = RoadRows.Build(_Job.Table, plan.Start, plan.End, SampleSpacing, _Job.Width, _Job.Profile.Simplification);\r\n\t\t\tint columns = RoadSurfaceBuilder.Columns(_Job.Table, roadRows, _Job.Width, segment.LaneCount);\r\n\r\n\t\t\tif (plan.Lines.HasGap)\r\n\t\t\t{\r\n\t\t\t\tRoadMarkingBuilder.Build(mesh, _Job.Table, roadRows, columns, MathF.Max(plan.Start, plan.Lines.Start), MathF.Min(plan.End, plan.Lines.GapStart), segment, _Job.Width, _Job.Profile, SurfaceOffset, plan.Dash);\r\n\t\t\t\tRoadMarkingBuilder.Build(mesh, _Job.Table, roadRows, columns, MathF.Max(plan.Start, plan.Lines.GapEnd), MathF.Min(plan.End, plan.Lines.End), segment, _Job.Width, _Job.Profile, SurfaceOffset, plan.Dash);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tRoadMarkingBuilder.Build(mesh, _Job.Table, roadRows, columns, MathF.Max(plan.Start, plan.Lines.Start), MathF.Min(plan.End, plan.Lines.End), segment, _Job.Width, _Job.Profile, SurfaceOffset, plan.Dash);\r\n\t\t\t}\r\n\r\n\t\t\t// The crossings this piece owns, laid on the same rows as the lines and the road itself.\r\n\t\t\tif (plan.Crossings.AtStart)\r\n\t\t\t\tRoadMarkingBuilder.BuildCrossing(mesh, _Job.Table, roadRows, columns, plan.Crossings.StartCentre, _Job.Width, _Job.Profile, SurfaceOffset);\r\n\r\n\t\t\tif (plan.Crossings.AtEnd)\r\n\t\t\t\tRoadMarkingBuilder.BuildCrossing(mesh, _Job.Table, roadRows, columns, plan.Crossings.EndCentre, _Job.Width, _Job.Profile, SurfaceOffset);\r\n\r\n\t\t\tname = $\u0022Road {_Job.SegmentId} markings [{plan.Index \u002B 1}/{plan.Count}]\u0022;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tvar segment = FindSegment(_Job.SegmentId);\r\n\r\n\t\t\tif (segment is null)\r\n\t\t\t\treturn false;\r\n\r\n\t\t\tmesh = RoadSurfaceBuilder.Build(_Job.Table, plan.Start, plan.End, _Job.Width, SampleSpacing, _Job.Profile.Simplification, segment.LaneCount, _Job.Profile.RoadTextureRepeat, _Job.Profile.RoadTextureFitsWidth, SurfaceOffset, _Job.Profile.ResolvedRoadMaterial, _Job.Profile, plan.Trails, plan.Blend);\r\n\t\t\tname = $\u0022Road {_Job.SegmentId} [{plan.Index \u002B 1}/{plan.Count}]\u0022;\r\n\t\t}\r\n\r\n\t\tvar piece = CreateChunkObject(name, _Job.SegmentId, -1, plan.Kind, plan.Index, plan.Count, plan.Signature, mesh, debug);\r\n\r\n\t\tforeach (var (prefab, transform) in placements)\r\n\t\t\tprefab.Clone(transform, piece);\r\n\r\n\t\t// The new piece is in place before the old one goes, so the road never flickers.\r\n\t\texisting?.GameObject.Destroy();\r\n\r\n\t\treturn true;\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The height of whatever lies under a point of the network (its own pieces excepted), in network space, for\r\n\t/// bridge supports to land on: the search starts just below the point, so the deck itself is never it. Null\r\n\t/// over nothing.\r\n\t/// \u003C/summary\u003E\r\n\tprivate float? GroundBelow(Vector3 _Local)\r\n\t{\r\n\t\treturn TraceGround(_Local, -1.0f);\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The height of the ground at a point of the network, for props to stand on: the search starts well above\r\n\t/// the point, so ground rising beside a road is found as well as ground falling away from it.\r\n\t/// \u003C/summary\u003E\r\n\tprivate float? GroundAround(Vector3 _Local)\r\n\t{\r\n\t\treturn TraceGround(_Local, 3000.0f);\r\n\t}\r\n\r\n\r\n\r\n\tprivate float? TraceGround(Vector3 _Local, float _StartAbove)\r\n\t{\r\n\t\tconst float reach = 50000.0f;\r\n\r\n\t\tvar transform = WorldTransform;\r\n\t\tVector3 from = transform.PointToWorld(_Local) \u002B Vector3.Up * _StartAbove;\r\n\t\tvar trace = Scene.Trace.Ray(from, from \u002B Vector3.Down * reach).WithoutTags(ChunkTag).Run();\r\n\r\n\t\tif (!trace.Hit)\r\n\t\t\treturn null;\r\n\r\n\t\treturn transform.PointToLocal(trace.EndPosition).z;\r\n\t}\r\n\r\n\r\n\r\n\tprivate void BuildJunctionPiece(in RebuildJob _Job)\r\n\t{\r\n\t\tvar existing = FindJunctionChunk(_Job.NodeId, _Job.Kind);\r\n\r\n\t\tif (existing is not null \u0026\u0026 existing.Locked)\r\n\t\t\treturn;\r\n\r\n\t\tPolygonMesh mesh;\r\n\t\tstring name;\r\n\t\tBorderDebug debug = null;\r\n\r\n\t\tif (_Job.Kind == RoadChunkKind.Border)\r\n\t\t{\r\n\t\t\tvar armBlends = _Job.ArmBlends;\r\n\t\t\tvar armTapers = _Job.ArmTapers;\r\n\r\n\t\t\tdebug = DebugBorders ? new BorderDebug() : null;\r\n\t\t\tmesh = RoadBorderBuilder.BuildJunction(_Job.Junction, ProfileOf,\r\n\t\t\t\tsegment =\u003E armBlends is not null ? armBlends.GetValueOrDefault(segment.Id) : default,\r\n\t\t\t\tsegment =\u003E armTapers is not null ? armTapers.GetValueOrDefault(segment.Id) : default,\r\n\t\t\t\tdebug);\r\n\t\t\tname = $\u0022Junction {_Job.NodeId} border\u0022;\r\n\t\t}\r\n\t\telse\r\n\t\t{\r\n\t\t\tvar profile = JunctionSurfaceProfile(_Job.Junction);\r\n\t\t\tvar surfaces = _Job.ArmSurfaces;\r\n\r\n\t\t\tmesh = RoadJunctionBuilder.Build(_Job.Junction, JunctionMainArm(_Job.Junction), arm =\u003E SameSurface(arm, profile), profile.RoadTextureRepeat, profile.RoadTextureFitsWidth, profile.ResolvedRoadMaterial, arm =\u003E ProfileOf(arm.Segment),\r\n\t\t\t\tarm =\u003E surfaces is not null ? surfaces.GetValueOrDefault(arm.Segment.Id) : default);\r\n\t\t\tname = $\u0022Junction {_Job.NodeId}\u0022;\r\n\t\t}\r\n\r\n\t\tCreateChunkObject(name, -1, _Job.NodeId, _Job.Kind, 0, 1, _Job.GroupSignature, mesh, debug);\r\n\r\n\t\texisting?.GameObject.Destroy();\r\n\t}\r\n\r\n\r\n\r\n\tprivate GameObject CreateChunkObject(string _Name, int _SegmentId, int _NodeId, RoadChunkKind _Kind, int _Index, int _Count, long _Signature, PolygonMesh _Mesh, BorderDebug _Debug, int _LotId = -1)\r\n\t{\r\n\t\tvar child = new GameObject(GameObject, true, _Name);\r\n\t\tchild.Tags.Add(ChunkTag);\r\n\r\n\t\tvar chunk = child.AddComponent\u003CRoadChunk\u003E();\r\n\t\tchunk.SegmentId = _SegmentId;\r\n\t\tchunk.NodeId = _NodeId;\r\n\t\tchunk.LotId = _LotId;\r\n\t\tchunk.Kind = _Kind;\r\n\t\tchunk.ChunkIndex = _Index;\r\n\t\tchunk.ChunkCount = _Count;\r\n\t\tchunk.Signature = _Signature;\r\n\t\tchunk.Debug = _Debug;\r\n\r\n\t\tif (_Debug is not null)\r\n\t\t\tDebugRevision\u002B\u002B;\r\n\r\n\t\t// A piece of props has no geometry of its own; it is the parent of its prefabs.\r\n\t\tif (_Mesh is null)\r\n\t\t\treturn child;\r\n\r\n\t\tvar meshComponent = child.AddComponent\u003CMeshComponent\u003E();\r\n\t\tmeshComponent.Mesh = _Mesh;\r\n\t\tmeshComponent.SmoothingAngle = 40.0f;\r\n\r\n\t\t// Paint lies flat on the road: nothing to collide with, and its shadow would be a sliver hidden under it,\r\n\t\t// at the cost of a shadow pass.\r\n\t\tif (_Kind == RoadChunkKind.Marking)\r\n\t\t{\r\n\t\t\tmeshComponent.Collision = MeshComponent.CollisionType.None;\r\n\t\t\tmeshComponent.RenderType = ModelRenderer.ShadowRenderType.Off;\r\n\t\t}\r\n\r\n\t\treturn child;\r\n\t}\r\n}\r\n"},{"Ident":"redsnail.roadtool2","Path":"Network/RoadTrailFade.cs","FileName":"RoadTrailFade.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":443665,"IsPrivate":false,"Code":"using System;\nusing System.Collections.Generic;\nusing Sandbox;\n\nnamespace RedSnail.RoadTool2;\n\n/// \u003Csummary\u003E\n/// Where a segment\u0027s trails rise out of the road: flat at \u003Csee cref=\u0022StartFlat\u0022/\u003E and \u003Csee cref=\u0022EndFlat\u0022/\u003E (distances\n/// along the segment\u0027s curve, where its surface stops at a junction, a parking lot or a rounded end), at full depth\n/// \u003Csee cref=\u0022Length\u0022/\u003E in from each. An end the trails carry straight on across (into the same road type, at a plain\n/// pass-through node) has no fade. The default is a segment with no trails at all.\n/// \u003C/summary\u003E\npublic readonly record struct RoadTrailFade(bool StartCarries, float StartFlat, bool EndCarries, float EndFlat, float Length)\n{\n\t/// \u003Csummary\u003E\n\t/// The steps a fade is laid in, between where the trails are flat and where they are at full depth.\n\t/// \u003C/summary\u003E\n\tprivate const int Steps = 4;\n\n\t/// \u003Csummary\u003E\n\t/// True when the trails reach nowhere along the segment: none at all, or no room between the two flat ends.\n\t/// \u003C/summary\u003E\n\tpublic bool IsNone =\u003E !StartCarries \u0026\u0026 !EndCarries \u0026\u0026 EndFlat - StartFlat \u003C= 0.01f;\n\n\n\n\t/// \u003Csummary\u003E\n\t/// How much of their depth the trails have at a distance along the segment, easing in and out of each fade.\n\t/// \u003C/summary\u003E\n\tpublic float StrengthAt(float _Distance)\n\t{\n\t\tif (IsNone)\n\t\t\treturn 0.0f;\n\n\t\tfloat strength = 1.0f;\n\n\t\tif (!StartCarries)\n\t\t\tstrength *= Rise(_Distance - StartFlat);\n\n\t\tif (!EndCarries)\n\t\t\tstrength *= Rise(EndFlat - _Distance);\n\n\t\treturn strength;\n\t}\n\n\n\n\t/// \u003Csummary\u003E\n\t/// The distances a surface needs rows at for the fades to be laid smoothly: each fade\u0027s two ends and the steps\n\t/// between them.\n\t/// \u003C/summary\u003E\n\tpublic IEnumerable\u003Cfloat\u003E Knots()\n\t{\n\t\tif (IsNone)\n\t\t\tyield break;\n\n\t\tfor (int step = 0; step \u003C= Steps; step\u002B\u002B)\n\t\t{\n\t\t\tfloat into = Length * step / Steps;\n\n\t\t\tif (!StartCarries)\n\t\t\t\tyield return StartFlat \u002B into;\n\n\t\t\tif (!EndCarries)\n\t\t\t\tyield return EndFlat - into;\n\t\t}\n\t}\n\n\n\n\tpublic void AddToHash(ref StableHash _Hash)\n\t{\n\t\t_Hash.Add(StartCarries ? 1 : 0);\n\t\t_Hash.Add(StartCarries ? 0.0f : StartFlat);\n\t\t_Hash.Add(EndCarries ? 1 : 0);\n\t\t_Hash.Add(EndCarries ? 0.0f : EndFlat);\n\t\t_Hash.Add(Length);\n\t}\n\n\n\n\tprivate float Rise(float _Into)\n\t{\n\t\tif (Length \u003C= 0.01f)\n\t\t\treturn _Into \u003E 0.0f ? 1.0f : 0.0f;\n\n\t\tfloat t = Math.Clamp(_Into / Length, 0.0f, 1.0f);\n\n\t\treturn t * t * (3.0f - 2.0f * t);\n\t}\n}\n"},{"Ident":"redsnail.roadtool2","Path":"Editor/RoadGizmos.cs","FileName":"RoadGizmos.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":443665,"IsPrivate":false,"Code":"using Sandbox;\r\n\r\nnamespace RedSnail.RoadTool2.Editor;\r\n\r\n/// \u003Csummary\u003E\r\n/// Gizmo drawing shared by the road tools. Curves are in network-local space and drawn through the network\u0027s\r\n/// transform, in whatever colour and thickness the caller set up.\r\n/// \u003C/summary\u003E\r\ninternal static class RoadGizmos\r\n{\r\n\tpublic static void DrawCurve(in RoadCurve _Curve, in Transform _Transform, int _Steps = 24)\r\n\t{\r\n\t\tVector3 previous = _Transform.PointToWorld(_Curve.P0);\r\n\r\n\t\tfor (int i = 1; i \u003C= _Steps; i\u002B\u002B)\r\n\t\t{\r\n\t\t\tVector3 point = _Transform.PointToWorld(_Curve.Evaluate((float)i / _Steps));\r\n\r\n\t\t\tGizmo.Draw.Line(previous, point);\r\n\t\t\tprevious = point;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Draws the two edges of a road of the given width along the curve, capped at both ends.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static void DrawRoadOutline(in RoadCurve _Curve, float _Width, in Transform _Transform, int _Steps = 24)\r\n\t{\r\n\t\tDrawRoadOutline(_Curve, RoadWidth.Uniform(_Width), _Transform, _Steps);\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Draws the two edges of a road along the curve, each its own distance out (the curve\u0027s parameter standing in\r\n\t/// for its distance), capped at both ends.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static void DrawRoadOutline(in RoadCurve _Curve, in RoadWidth _Width, in Transform _Transform, int _Steps = 24)\r\n\t{\r\n\t\tVector3 previousLeft = default;\r\n\t\tVector3 previousRight = default;\r\n\r\n\t\tfor (int i = 0; i \u003C= _Steps; i\u002B\u002B)\r\n\t\t{\r\n\t\t\tfloat t = (float)i / _Steps;\r\n\t\t\tfloat distance = t * _Width.Length;\r\n\t\t\tVector3 point = _Curve.Evaluate(t);\r\n\t\t\tVector3 right = RoadCurve.RightOf(_Curve.Tangent(t));\r\n\r\n\t\t\tVector3 left = _Transform.PointToWorld(point - right * _Width.LeftAt(distance));\r\n\t\t\tVector3 rightEdge = _Transform.PointToWorld(point \u002B right * _Width.RightAt(distance));\r\n\r\n\t\t\tif (i == 0 || i == _Steps)\r\n\t\t\t\tGizmo.Draw.Line(left, rightEdge);\r\n\r\n\t\t\tif (i \u003E 0)\r\n\t\t\t{\r\n\t\t\t\tGizmo.Draw.Line(previousLeft, left);\r\n\t\t\t\tGizmo.Draw.Line(previousRight, rightEdge);\r\n\t\t\t}\r\n\r\n\t\t\tpreviousLeft = left;\r\n\t\t\tpreviousRight = rightEdge;\r\n\t\t}\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// A node marker: a flat ring on the ground, filled when it is the one being worked on.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static void DrawNode(Vector3 _WorldPosition, bool _Filled)\r\n\t{\r\n\t\tfloat radius = RoadPicker.NodeRadius(_WorldPosition);\r\n\r\n\t\tif (_Filled)\r\n\t\t\tGizmo.Draw.SolidSphere(_WorldPosition, radius * 0.6f);\r\n\r\n\t\tGizmo.Draw.LineCircle(_WorldPosition, Vector3.Up, radius);\r\n\t}\r\n}\r\n"},{"Ident":"redsnail.roadtool2","Path":"Code/Geometry/RoadCurve.cs","FileName":"RoadCurve.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":443665,"IsPrivate":false,"Code":"using System;\r\nusing Sandbox;\r\n\r\nnamespace RedSnail.RoadTool2;\r\n\r\n/// \u003Csummary\u003E\r\n/// The cubic Bezier of one road segment, in network-local space. P1 and P2 are the tangent handles hanging off the\r\n/// two end nodes.\r\n/// \u003C/summary\u003E\r\npublic readonly struct RoadCurve : IEquatable\u003CRoadCurve\u003E\r\n{\r\n\tpublic readonly Vector3 P0;\r\n\tpublic readonly Vector3 P1;\r\n\tpublic readonly Vector3 P2;\r\n\tpublic readonly Vector3 P3;\r\n\r\n\r\n\r\n\tpublic RoadCurve(Vector3 _P0, Vector3 _P1, Vector3 _P2, Vector3 _P3)\r\n\t{\r\n\t\tP0 = _P0;\r\n\t\tP1 = _P1;\r\n\t\tP2 = _P2;\r\n\t\tP3 = _P3;\r\n\t}\r\n\r\n\r\n\r\n\tpublic Vector3 Evaluate(float _T)\r\n\t{\r\n\t\tfloat u = 1.0f - _T;\r\n\t\tfloat uu = u * u;\r\n\t\tfloat tt = _T * _T;\r\n\r\n\t\treturn P0 * (uu * u) \u002B P1 * (3.0f * uu * _T) \u002B P2 * (3.0f * u * tt) \u002B P3 * (tt * _T);\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Unit direction of travel at \u003Cparamref name=\u0022_T\u0022/\u003E. Falls back to the chord when the derivative vanishes (a\r\n\t/// handle sitting on its node) so callers always get a usable frame.\r\n\t/// \u003C/summary\u003E\r\n\tpublic Vector3 Tangent(float _T)\r\n\t{\r\n\t\tfloat u = 1.0f - _T;\r\n\t\tVector3 derivative = (P1 - P0) * (3.0f * u * u) \u002B (P2 - P1) * (6.0f * u * _T) \u002B (P3 - P2) * (3.0f * _T * _T);\r\n\r\n\t\tif (derivative.IsNearZeroLength)\r\n\t\t\tderivative = P3 - P0;\r\n\r\n\t\tif (derivative.IsNearZeroLength)\r\n\t\t\treturn Vector3.Forward;\r\n\r\n\t\treturn derivative.Normal;\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Chord-summed length, good enough to size sampling tables and count chunks.\r\n\t/// \u003C/summary\u003E\r\n\tpublic float ApproximateLength(int _Steps = 32)\r\n\t{\r\n\t\tfloat length = 0.0f;\r\n\t\tVector3 previous = P0;\r\n\r\n\t\tfor (int i = 1; i \u003C= _Steps; i\u002B\u002B)\r\n\t\t{\r\n\t\t\tVector3 point = Evaluate((float)i / _Steps);\r\n\t\t\tlength \u002B= Vector3.DistanceBetween(previous, point);\r\n\t\t\tprevious = point;\r\n\t\t}\r\n\r\n\t\treturn length;\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// De Casteljau subdivision: the two halves trace exactly the same path as the whole, so a road can be split\r\n\t/// without moving.\r\n\t/// \u003C/summary\u003E\r\n\tpublic void Split(float _T, out RoadCurve _Left, out RoadCurve _Right)\r\n\t{\r\n\t\tVector3 q0 = Vector3.Lerp(P0, P1, _T);\r\n\t\tVector3 q1 = Vector3.Lerp(P1, P2, _T);\r\n\t\tVector3 q2 = Vector3.Lerp(P2, P3, _T);\r\n\t\tVector3 r0 = Vector3.Lerp(q0, q1, _T);\r\n\t\tVector3 r1 = Vector3.Lerp(q1, q2, _T);\r\n\t\tVector3 s = Vector3.Lerp(r0, r1, _T);\r\n\r\n\t\t_Left = new RoadCurve(P0, q0, r0, s);\r\n\t\t_Right = new RoadCurve(s, r1, q2, P3);\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The road\u0027s right-hand direction for a direction of travel: flat, perpendicular to the tangent, and\r\n\t/// consistent with \u003Csee cref=\u0022Rotation.Right\u0022/\u003E for a rotation looking down the tangent with world up.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static Vector3 RightOf(Vector3 _Tangent)\r\n\t{\r\n\t\tVector3 right = Vector3.Cross(_Tangent, Vector3.Up);\r\n\r\n\t\t// Vertical tangent (a ramp seen from nowhere useful): any horizontal axis will do.\r\n\t\tif (right.IsNearZeroLength)\r\n\t\t\treturn Vector3.Right;\r\n\r\n\t\treturn right.Normal;\r\n\t}\r\n\r\n\r\n\r\n\tpublic bool Equals(RoadCurve _Other)\r\n\t{\r\n\t\treturn P0 == _Other.P0 \u0026\u0026 P1 == _Other.P1 \u0026\u0026 P2 == _Other.P2 \u0026\u0026 P3 == _Other.P3;\r\n\t}\r\n\r\n\r\n\r\n\tpublic override bool Equals(object _Obj)\r\n\t{\r\n\t\treturn _Obj is RoadCurve other \u0026\u0026 Equals(other);\r\n\t}\r\n\r\n\r\n\r\n\tpublic override int GetHashCode()\r\n\t{\r\n\t\treturn HashCode.Combine(P0, P1, P2, P3);\r\n\t}\r\n}\r\n"},{"Ident":"redsnail.roadtool2","Path":"Code/Network/RoadCapBuilder.cs","FileName":"RoadCapBuilder.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":443665,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing Sandbox;\r\n\r\nnamespace RedSnail.RoadTool2;\r\n\r\n/// \u003Csummary\u003E\r\n/// Generates the rounded end of a road that stops: a half disc of surface carried on past the last row, with the\r\n/// border swept round it, so a dead end reads as a turning head rather than a road sliced through. The piece is\r\n/// built beyond the road\u0027s own end, on the end row itself, so its seam with the last chunk is exact and nothing\r\n/// about the road\u0027s length changes.\r\n/// \u003C/summary\u003E\r\ninternal static class RoadCapBuilder\r\n{\r\n\t/// \u003Csummary\u003E\r\n\t/// The arc is drawn in steps of about this many degrees.\r\n\t/// \u003C/summary\u003E\r\n\tprivate const float ArcStepDegrees = 9.0f;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// How deep a road\u0027s rounded end reaches past it, as a share of the road\u0027s half width. 1 is a half circle.\r\n\t/// \u003C/summary\u003E\r\n\tpublic const float DepthFactor = 1.0f;\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// How far the rounded end of a road reaches past the node, or 0 where the road type does not round its ends.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static float Depth(RoadProfile _Profile, in RoadWidth _Width, float _Distance)\r\n\t{\r\n\t\tif (_Profile is null || !_Profile.RoundedEnds)\r\n\t\t\treturn 0.0f;\r\n\r\n\t\treturn (_Width.LeftAt(_Distance) \u002B _Width.RightAt(_Distance)) * 0.5f * DepthFactor;\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The rounded end at one end of a road. \u003Cparamref name=\u0022_Distance\u0022/\u003E is the end\u0027s own distance along the curve\r\n\t/// (0 or the table\u0027s length) and \u003Cparamref name=\u0022_AtStart\u0022/\u003E which end it is; the cap reaches out from there.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static PolygonMesh Build(RoadCurveTable _Table, float _Distance, bool _AtStart, in RoadWidth _Width, RoadProfile _Profile, float _Lift, float _Depth)\r\n\t{\r\n\t\tvar mesh = new PolygonMesh();\r\n\r\n\t\tif (_Depth \u003C= 0.01f)\r\n\t\t\treturn mesh;\r\n\r\n\t\t_Table.Frame(_Distance, out Vector3 centre, out Vector3 tangent);\r\n\r\n\t\tcentre \u002B= Vector3.Up * _Lift;\r\n\r\n\t\t// Out of the road, and the road\u0027s own right at that end. The arc keeps the road\u0027s grade because the\r\n\t\t// direction it reaches along carries the curve\u0027s climb with it.\r\n\t\tVector3 forward = (_AtStart ? -tangent : tangent).Normal;\r\n\t\tVector3 right = RoadCurve.RightOf(tangent);\r\n\t\tfloat leftHalf = _Width.LeftAt(_Distance);\r\n\t\tfloat rightHalf = _Width.RightAt(_Distance);\r\n\r\n\t\tif (leftHalf \u002B rightHalf \u003C= 0.01f)\r\n\t\t\treturn mesh;\r\n\r\n\t\tint steps = ArcSteps();\r\n\t\tvar outline = new List\u003CVector3\u003E(steps \u002B 1);\r\n\t\tvar outwards = new List\u003CVector3\u003E(steps \u002B 1);\r\n\r\n\t\tArc(centre, forward, right, leftHalf, rightHalf, _Depth, steps, outline, outwards, null, null);\r\n\r\n\t\tAddSurface(mesh, centre, outline, outwards, leftHalf, rightHalf, _Distance, _AtStart, _Profile);\r\n\t\tAddBorder(mesh, outline, outwards, _Profile);\r\n\r\n\t\treturn mesh;\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// How many steps the arc is drawn in: an even number, so its tip, where the road\u0027s two sides meet, is a point\r\n\t/// of it.\r\n\t/// \u003C/summary\u003E\r\n\tprivate static int ArcSteps()\r\n\t{\r\n\t\tint steps = Math.Max(4, (int)MathF.Ceiling(180.0f / ArcStepDegrees));\r\n\r\n\t\treturn steps \u002B steps % 2;\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The outline of a road\u0027s rounded end in network space, lifted onto the road surface, for the tools that need\r\n\t/// to know where road is (the ground under it is held down and brought up to its kerb like a junction\u0027s).\r\n\t/// Empty where the road does not round that end.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static List\u003CVector3\u003E Outline(RoadCurveTable _Table, float _Distance, bool _AtStart, in RoadWidth _Width, RoadProfile _Profile, float _Lift, out Vector3 _Centre)\r\n\t{\r\n\t\tvar outline = new List\u003CVector3\u003E();\r\n\t\tfloat depth = Depth(_Profile, _Width, _Distance);\r\n\r\n\t\t_Table.Frame(_Distance, out _Centre, out Vector3 tangent);\r\n\r\n\t\t_Centre \u002B= Vector3.Up * _Lift;\r\n\r\n\t\tfloat leftHalf = _Width.LeftAt(_Distance);\r\n\t\tfloat rightHalf = _Width.RightAt(_Distance);\r\n\r\n\t\tif (depth \u003C= 0.01f || leftHalf \u002B rightHalf \u003C= 0.01f)\r\n\t\t\treturn outline;\r\n\r\n\t\tArc(_Centre, (_AtStart ? -tangent : tangent).Normal, RoadCurve.RightOf(tangent), leftHalf, rightHalf, depth, ArcSteps(), outline, null, null, null);\r\n\r\n\t\treturn outline;\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The half ellipse from the road\u0027s left edge, round the tip, to its right edge: where each point is, which way\r\n\t/// is out of the road there, and how far across and ahead of the end row it sits.\r\n\t/// \u003C/summary\u003E\r\n\tprivate static void Arc(Vector3 _Centre, Vector3 _Forward, Vector3 _Right, float _LeftHalf, float _RightHalf, float _Depth, int _Steps,\r\n\t\tList\u003CVector3\u003E _Points, List\u003CVector3\u003E _Outwards, List\u003Cfloat\u003E _Offsets, List\u003Cfloat\u003E _Aheads)\r\n\t{\r\n\t\tfor (int i = 0; i \u003C= _Steps; i\u002B\u002B)\r\n\t\t{\r\n\t\t\tfloat angle = MathF.PI * (i / (float)_Steps - 0.5f);\r\n\t\t\tfloat sin = MathF.Sin(angle);\r\n\t\t\tfloat cos = MathF.Cos(angle);\r\n\t\t\tfloat offset = sin * (sin \u003E= 0.0f ? _RightHalf : _LeftHalf);\r\n\t\t\tfloat ahead = _Depth * cos;\r\n\r\n\t\t\t_Points.Add(_Centre \u002B _Right * offset \u002B _Forward * ahead);\r\n\t\t\t_Outwards?.Add((_Right * sin \u002B _Forward * cos).Normal);\r\n\t\t\t_Offsets?.Add(offset);\r\n\t\t\t_Aheads?.Add(ahead);\r\n\t\t}\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The half disc of road surface: a fan from the middle of the end row out to the arc, so every triangle is\r\n\t/// planar and the row itself is the fan\u0027s own base. The texture turns round the end with the kerb, the way the\r\n\t/// road\u0027s lanes would in a U-turn: U is held at the road\u0027s edge all round the arc, so whatever runs along the edge\r\n\t/// of the road in the texture (dark edges, a gutter) follows it round, and V is measured round the arc from the\r\n\t/// end row, up each side to the tip, where the two sides meet. Carried straight on instead, the road\u0027s edge would\r\n\t/// run off the arc, and its middle run on to the tip. Under banks the surface carries on past the arc as a skirt,\r\n\t/// down under the ground, the way the road\u0027s own does past its edges (see \u003Csee cref=\u0022RoadProfile.SkirtWidth\u0022/\u003E).\r\n\t/// \u003C/summary\u003E\r\n\tprivate static void AddSurface(PolygonMesh _Mesh, Vector3 _Centre, List\u003CVector3\u003E _Outline, List\u003CVector3\u003E _Outwards, float _LeftHalf, float _RightHalf,\r\n\t\tfloat _Distance, bool _AtStart, RoadProfile _Profile)\r\n\t{\r\n\t\tfloat repeat = MathF.Max(1.0f, _Profile.RoadTextureRepeat);\r\n\t\tvar material = _Profile.ResolvedRoadMaterial;\r\n\t\tvar centre = _Mesh.AddVertices(_Centre)[0];\r\n\t\tvar ring = new HalfEdgeMesh.VertexHandle[_Outline.Count];\r\n\r\n\t\tfor (int i = 0; i \u003C _Outline.Count; i\u002B\u002B)\r\n\t\t\tring[i] = _Mesh.AddVertices(_Outline[i])[0];\r\n\r\n\t\t// How far round the arc each point is from the row\u0027s left end, and the tip halfway round. Both sides reach\r\n\t\t// the tip at the same V, the mean of their lengths: a road wider one side than the other stretches the\r\n\t\t// shorter side to meet the longer.\r\n\t\tvar round = new float[_Outline.Count];\r\n\r\n\t\tfor (int i = 1; i \u003C _Outline.Count; i\u002B\u002B)\r\n\t\t\tround[i] = round[i - 1] \u002B _Outline[i].Distance(_Outline[i - 1]);\r\n\r\n\t\tint tip = (_Outline.Count - 1) / 2;\r\n\t\tfloat leftQuarter = MathF.Max(0.001f, round[tip]);\r\n\t\tfloat rightQuarter = MathF.Max(0.001f, round[^1] - round[tip]);\r\n\t\tfloat quarter = (leftQuarter \u002B rightQuarter) * 0.5f;\r\n\t\tfloat sign = _AtStart ? -1.0f : 1.0f;\r\n\r\n\t\t// Across, U is the road\u0027s own: out from the centre line at the texture\u0027s size, or fitted edge to edge.\r\n\t\tbool fit = _Profile.RoadTextureFitsWidth;\r\n\t\tfloat leftU = fit ? 0.0f : -_LeftHalf / repeat;\r\n\t\tfloat rightU = fit ? 1.0f : _RightHalf / repeat;\r\n\t\tfloat centreU = fit ? _LeftHalf / MathF.Max(0.001f, _LeftHalf \u002B _RightHalf) : 0.0f;\r\n\t\tvar leftUvs = new Vector2[_Outline.Count];\r\n\t\tvar rightUvs = new Vector2[_Outline.Count];\r\n\r\n\t\tfor (int i = 0; i \u003C _Outline.Count; i\u002B\u002B)\r\n\t\t{\r\n\t\t\tleftUvs[i] = new Vector2(leftU, (_Distance \u002B sign * round[i] * quarter / leftQuarter) / repeat);\r\n\t\t\trightUvs[i] = new Vector2(rightU, (_Distance \u002B sign * (round[^1] - round[i]) * quarter / rightQuarter) / repeat);\r\n\t\t}\r\n\r\n\t\t// The middle of the row is where the road\u0027s own mapping has it, so the asphalt carries on through the seam.\r\n\t\tVector2 centreUv = new(centreU, _Distance / repeat);\r\n\r\n\t\t// Which way round the fan closes, so it faces up like the road it carries on from.\r\n\t\tVector3 first = _Outline[0] - _Centre;\r\n\t\tVector3 second = _Outline[1] - _Centre;\r\n\t\tbool flip = Vector3.Cross(first, second).z \u003C 0.0f;\r\n\r\n\t\tfor (int i = 0; i \u003C _Outline.Count - 1; i\u002B\u002B)\r\n\t\t{\r\n\t\t\t// Each side\u0027s own mapping, the tip taking whichever side the triangle is on.\r\n\t\t\tvar uvs = i \u003C tip ? leftUvs : rightUvs;\r\n\t\t\tVector2 uvA = uvs[i];\r\n\t\t\tVector2 uvB = uvs[i \u002B 1];\r\n\r\n\t\t\tif (flip)\r\n\t\t\t\tMeshUtility.AddTexturedTriangle(_Mesh, material, centre, ring[i \u002B 1], ring[i], centreUv, uvB, uvA);\r\n\t\t\telse\r\n\t\t\t\tMeshUtility.AddTexturedTriangle(_Mesh, material, centre, ring[i], ring[i \u002B 1], centreUv, uvA, uvB);\r\n\t\t}\r\n\r\n\t\tif (!_Profile.HasSkirt)\r\n\t\t\treturn;\r\n\r\n\t\t// The skirt: out level from the arc and down (whatever the road\u0027s grade, as the road\u0027s own goes out level from\r\n\t\t// its edges), each side carrying on its own mapping (out across at the texture\u0027s size, or a texture fitted to\r\n\t\t// the width turned back on itself at the edge). A strip of its own, so the mesh never has to join it to the\r\n\t\t// fan\u0027s rim.\r\n\t\tfloat width = _Profile.SkirtWidth;\r\n\t\tfloat across = fit ? -width / MathF.Max(0.001f, _LeftHalf \u002B _RightHalf) : width / repeat;\r\n\t\tvar top = new HalfEdgeMesh.VertexHandle[_Outline.Count];\r\n\t\tvar bottom = new HalfEdgeMesh.VertexHandle[_Outline.Count];\r\n\r\n\t\tfor (int i = 0; i \u003C _Outline.Count; i\u002B\u002B)\r\n\t\t{\r\n\t\t\ttop[i] = _Mesh.AddVertices(_Outline[i])[0];\r\n\t\t\tbottom[i] = _Mesh.AddVertices(_Outline[i] \u002B _Outwards[i].WithZ(0.0f).Normal * width - Vector3.Up * _Profile.SkirtDepth)[0];\r\n\t\t}\r\n\r\n\t\tfor (int i = 0; i \u003C _Outline.Count - 1; i\u002B\u002B)\r\n\t\t{\r\n\t\t\tbool leftSide = i \u003C tip;\r\n\t\t\tvar uvs = leftSide ? leftUvs : rightUvs;\r\n\t\t\tvar outward = new Vector2(leftSide ? -across : across, 0.0f);\r\n\t\t\tVector2 uvA = uvs[i];\r\n\t\t\tVector2 uvB = uvs[i \u002B 1];\r\n\r\n\t\t\t// Wound like the fan, so it faces up and out.\r\n\t\t\tif (flip)\r\n\t\t\t{\r\n\t\t\t\tMeshUtility.AddTexturedTriangle(_Mesh, material, top[i], top[i \u002B 1], bottom[i \u002B 1], uvA, uvB, uvB \u002B outward);\r\n\t\t\t\tMeshUtility.AddTexturedTriangle(_Mesh, material, top[i], bottom[i \u002B 1], bottom[i], uvA, uvB \u002B outward, uvA \u002B outward);\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tMeshUtility.AddTexturedTriangle(_Mesh, material, top[i], bottom[i \u002B 1], top[i \u002B 1], uvA, uvB \u002B outward, uvB);\r\n\t\t\t\tMeshUtility.AddTexturedTriangle(_Mesh, material, top[i], bottom[i], bottom[i \u002B 1], uvA, uvA \u002B outward, uvB \u002B outward);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The border round the arc, open at both ends: what closes it off is the road\u0027s own border, which runs into\r\n\t/// it at the end row.\r\n\t/// \u003C/summary\u003E\r\n\tprivate static void AddBorder(PolygonMesh _Mesh, List\u003CVector3\u003E _Outline, List\u003CVector3\u003E _Outwards, RoadProfile _Profile)\r\n\t{\r\n\t\tif (!_Profile.HasBorder)\r\n\t\t\treturn;\r\n\r\n\t\tvar path = new List\u003CRoadBorderBuilder.PathPoint\u003E(_Outline.Count);\r\n\t\tfloat along = 0.0f;\r\n\r\n\t\tfor (int i = 0; i \u003C _Outline.Count; i\u002B\u002B)\r\n\t\t{\r\n\t\t\tif (i \u003E 0)\r\n\t\t\t\talong \u002B= _Outline[i].Distance(_Outline[i - 1]);\r\n\r\n\t\t\tpath.Add(new RoadBorderBuilder.PathPoint(_Outline[i], _Outwards[i], along));\r\n\t\t}\r\n\r\n\t\tRoadBorderBuilder.BuildPath(_Mesh, _Profile, path, false, false);\r\n\t}\r\n}\r\n"}]}