{"TotalCount":12,"Files":[{"Ident":"redsnail.floratool","Path":"Code/FloraDefinition.cs","FileName":"FloraDefinition.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":421873,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing Sandbox;\r\n\r\nnamespace RedSnail.FloraTool;\r\n\r\n/// \u003Csummary\u003E\r\n/// One kind of flora the brush can plant. Weight decides how often it comes up relative to the\r\n/// other entries in the definition.\r\n/// \u003C/summary\u003E\r\npublic sealed class FloraEntry\r\n{\r\n\t[Property]\r\n\tpublic Model Model { get; set; }\r\n\r\n\t/// \u003Csummary\u003ERelative chance of this entry being picked. Zero excludes it without deleting it.\u003C/summary\u003E\r\n\t[Property, Range(0, 10)]\r\n\tpublic float Weight { get; set; } = 1.0f;\r\n\r\n\t[Property]\r\n\tpublic RangedFloat Scale { get; set; } = new(0.85f, 1.25f);\r\n\r\n\t/// \u003Csummary\u003ERandom spin about the vertical axis, so repeated instances don\u0027t read as clones.\u003C/summary\u003E\r\n\t[Property]\r\n\tpublic bool RandomYaw { get; set; } = true;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Tilts the instance toward the surface normal. Right for rocks and bushes, usually wrong for\r\n\t/// trees - a trunk growing perpendicular to a hillside looks broken.\r\n\t/// \u003C/summary\u003E\r\n\t[Property, Range(0, 1)]\r\n\tpublic float AlignToNormal { get; set; } = 0.0f;\r\n\r\n\t/// \u003Csummary\u003ERandom lean away from vertical, in degrees. A little goes a long way on trees.\u003C/summary\u003E\r\n\t[Property, Range(0, 45)]\r\n\tpublic float RandomTilt { get; set; } = 0.0f;\r\n\r\n\t/// \u003Csummary\u003ESinks the instance into the ground, hiding the seam where the base meets the surface.\u003C/summary\u003E\r\n\t[Property, Range(0, 64)]\r\n\tpublic float SinkDepth { get; set; } = 0.0f;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Gives this entry real collision. Colliders are only created near the player, so this is about\r\n\t/// whether the flora is solid at all - not about paying for every painted instance at once.\r\n\t/// \u003C/summary\u003E\r\n\t[Property, Group(\u0022Physics\u0022)]\r\n\tpublic bool EnablePhysics { get; set; } = true;\r\n\r\n\t[Property, Group(\u0022Rendering\u0022)]\r\n\tpublic bool CastShadows { get; set; } = true;\r\n\r\n\tpublic bool HasModel =\u003E Model is not null \u0026\u0026 !string.IsNullOrEmpty(Model.ResourcePath);\r\n}\r\n\r\n/// \u003Csummary\u003E\r\n/// A palette of flora plus the rules used when painting it. Shared by every\r\n/// \u003Csee cref=\u0022FloraRenderer\u0022/\u003E that references it, so a whole world can be retuned from one asset.\r\n/// \u003C/summary\u003E\r\n[AssetType(Name = \u0022Flora Definition\u0022, Extension = \u0022floradef\u0022, Category = \u0022Flora\u0022)]\r\npublic sealed class FloraDefinition : GameResource\r\n{\r\n\t[Property]\r\n\tpublic List\u003CFloraEntry\u003E Entries { get; set; } = [];\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Instances a fully painted cell can hold. Coverage scales this, so it sets the ceiling on how\r\n\t/// tightly flora can pack - raise it for undergrowth, leave it low for trees.\r\n\t/// \u003C/summary\u003E\r\n\t[Property, Group(\u0022Painting\u0022), Range(1, 16)]\r\n\tpublic int MaxPerCell { get; set; } = 2;\r\n\r\n\t/// \u003Csummary\u003EMinimum ground normal Z. Steeper than this and nothing plants, so cliffs stay bare.\u003C/summary\u003E\r\n\t[Property, Group(\u0022Painting\u0022), Range(0, 1)]\r\n\tpublic float SlopeLimit { get; set; } = 0.6f;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Radius around the viewer within which chunks are turned into scene objects. Chunks beyond it\r\n\t/// keep their painted coverage but cost nothing to render.\r\n\t/// \u003C/summary\u003E\r\n\t[Property, Group(\u0022Streaming\u0022), Range(2000, 100000)]\r\n\tpublic float StreamRadius { get; set; } = 25000.0f;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Distance past which flora stops casting shadows. Shadow cascades ignore the view frustum, so\r\n\t/// distant trees are rendered into them whichever way the camera faces - dropping them is one of\r\n\t/// the few savings that applies even when you are looking away.\r\n\t///\r\n\t/// Set it too low and you will see shadows wink out as chunks cross the boundary, most obviously\r\n\t/// under a low sun where far geometry casts long shadows into view. Zero disables the cutoff.\r\n\t/// \u003C/summary\u003E\r\n\t[Property, Group(\u0022Streaming\u0022), Range(0, 50000)]\r\n\tpublic float ShadowDistance { get; set; } = 10000.0f;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Radius around the viewer within which entries flagged \u003Csee cref=\u0022FloraEntry.EnablePhysics\u0022/\u003E\r\n\t/// get real colliders. Keep it just past where the player can reach.\r\n\t/// \u003C/summary\u003E\r\n\t[Property, Group(\u0022Physics\u0022), Range(256, 20000)]\r\n\tpublic float CollisionRadius { get; set; } = 4000.0f;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The entry at an index, or null when the index no longer resolves - entries can be removed\r\n\t/// after coverage has already been painted naming them.\r\n\t/// \u003C/summary\u003E\r\n\tpublic FloraEntry GetEntry(int index)\r\n\t{\r\n\t\tif (Entries is null || index \u003C 0 || index \u003E= Entries.Count)\r\n\t\t\treturn null;\r\n\r\n\t\tvar entry = Entries[index];\r\n\t\treturn entry?.HasModel is true ? entry : null;\r\n\t}\r\n}\r\n"},{"Ident":"redsnail.floratool","Path":"Code/FloraStorage.cs","FileName":"FloraStorage.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":421873,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing Sandbox;\r\n\r\nnamespace RedSnail.FloraTool;\r\n\r\n/// \u003Csummary\u003E\r\n/// Painted flora coverage, stored as a sparse chunked grid of density samples rather than one\r\n/// transform per tree. Instances are regenerated from this plus a seed, so a forest of a hundred\r\n/// thousand trees costs a few megabytes instead of tens - which matters because the scene sidecar\r\n/// has to survive being committed to a repository.\r\n///\r\n/// The trade is that positions are derived, not authored: painting decides where flora *can* grow\r\n/// and how densely, and the seed decides exactly where each trunk lands.\r\n/// \u003C/summary\u003E\r\npublic sealed class FloraStorage : BlobData\r\n{\r\n\tpublic override int Version =\u003E 1;\r\n\r\n\t/// \u003Csummary\u003ECells along one edge of a chunk.\u003C/summary\u003E\r\n\tpublic const int ChunkResolution = 32;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// World size of one density cell. Roughly a tree\u0027s footprint - each cell holds at most a\r\n\t/// handful of instances, so this is what bounds how tightly flora can pack.\r\n\t/// Changing it invalidates every painted scene, so it is a constant rather than a setting.\r\n\t/// \u003C/summary\u003E\r\n\tpublic const float CellSize = 256.0f;\r\n\r\n\tpublic const float ChunkSize = ChunkResolution * CellSize;\r\n\r\n\tpublic const int CellsPerChunk = ChunkResolution * ChunkResolution;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// One coverage sample. Height and normal are baked at paint time so flora sits on whatever\r\n\t/// geometry was there, without the renderer having to trace anything at load.\r\n\t/// \u003C/summary\u003E\r\n\tpublic struct Cell\r\n\t{\r\n\t\tpublic float Height;\r\n\r\n\t\t/// \u003Csummary\u003Edensity (0-7) | normal.x (8-15) | normal.y (16-23) | entry index (24-31)\u003C/summary\u003E\r\n\t\tpublic uint Packed;\r\n\r\n\t\tpublic readonly float Density =\u003E (Packed \u0026 0xFF) / 255.0f;\r\n\r\n\t\t/// \u003Csummary\u003EIndex into the definition\u0027s entry list. 0xFF means \u0022pick one by weight\u0022.\u003C/summary\u003E\r\n\t\tpublic readonly int EntryIndex =\u003E (int)((Packed \u003E\u003E 24) \u0026 0xFF);\r\n\r\n\t\tpublic readonly Vector3 Normal\r\n\t\t{\r\n\t\t\tget\r\n\t\t\t{\r\n\t\t\t\tvar x = ((Packed \u003E\u003E 8) \u0026 0xFF) / 127.5f - 1.0f;\r\n\t\t\t\tvar y = ((Packed \u003E\u003E 16) \u0026 0xFF) / 127.5f - 1.0f;\r\n\t\t\t\tvar z = MathF.Sqrt(Math.Clamp(1.0f - x * x - y * y, 0.0f, 1.0f));\r\n\t\t\t\treturn new Vector3(x, y, z);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic static uint Pack(float density, Vector3 normal, int entryIndex)\r\n\t\t{\r\n\t\t\tvar d = (uint)Math.Clamp(density * 255.0f \u002B 0.5f, 0.0f, 255.0f);\r\n\t\t\tvar nx = (uint)Math.Clamp((normal.x \u002B 1.0f) * 127.5f \u002B 0.5f, 0.0f, 255.0f);\r\n\t\t\tvar ny = (uint)Math.Clamp((normal.y \u002B 1.0f) * 127.5f \u002B 0.5f, 0.0f, 255.0f);\r\n\t\t\tvar e = (uint)Math.Clamp(entryIndex, 0, 255);\r\n\r\n\t\t\treturn d | (nx \u003C\u003C 8) | (ny \u003C\u003C 16) | (e \u003C\u003C 24);\r\n\t\t}\r\n\t}\r\n\r\n\tpublic readonly record struct ChunkCoord(int X, int Y);\r\n\r\n\tprivate readonly Dictionary\u003CChunkCoord, Cell[]\u003E _chunks = [];\r\n\r\n\t/// \u003Csummary\u003EBumped on every mutation so the renderer knows to regenerate.\u003C/summary\u003E\r\n\tpublic int Revision { get; private set; }\r\n\r\n\tpublic int ChunkCount =\u003E _chunks.Count;\r\n\r\n\tpublic IReadOnlyDictionary\u003CChunkCoord, Cell[]\u003E Chunks =\u003E _chunks;\r\n\r\n\tpublic static ChunkCoord WorldToChunk(Vector3 world) =\u003E new(\r\n\t\t(int)MathF.Floor(world.x / ChunkSize),\r\n\t\t(int)MathF.Floor(world.y / ChunkSize));\r\n\r\n\tpublic static Vector2 ChunkOrigin(ChunkCoord coord) =\u003E new(coord.X * ChunkSize, coord.Y * ChunkSize);\r\n\r\n\tpublic static Vector3 ChunkCenter(ChunkCoord coord, float height = 0.0f)\r\n\t{\r\n\t\tvar origin = ChunkOrigin(coord);\r\n\t\treturn new Vector3(origin.x \u002B ChunkSize * 0.5f, origin.y \u002B ChunkSize * 0.5f, height);\r\n\t}\r\n\r\n\tprivate static int WorldToCell(float world) =\u003E (int)MathF.Floor(world / CellSize);\r\n\r\n\tprivate static int FloorDiv(int a, int b) =\u003E a \u003E= 0 ? a / b : ~(~a / b);\r\n\r\n\tprivate static int Mod(int a, int b)\r\n\t{\r\n\t\tvar r = a % b;\r\n\t\treturn r \u003C 0 ? r \u002B b : r;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Writes a coverage sample, baking the surface height and normal alongside it. Density of zero\r\n\t/// frees the sample.\r\n\t/// \u003C/summary\u003E\r\n\tpublic void SetCell(float worldX, float worldY, float density, float height, Vector3 normal, int entryIndex)\r\n\t{\r\n\t\tvar cellX = WorldToCell(worldX);\r\n\t\tvar cellY = WorldToCell(worldY);\r\n\t\tvar coord = new ChunkCoord(FloorDiv(cellX, ChunkResolution), FloorDiv(cellY, ChunkResolution));\r\n\r\n\t\tif (!_chunks.TryGetValue(coord, out var cells))\r\n\t\t{\r\n\t\t\tif (density \u003C= 0.0f) return;\r\n\r\n\t\t\tcells = new Cell[CellsPerChunk];\r\n\t\t\t_chunks[coord] = cells;\r\n\t\t}\r\n\r\n\t\tvar index = Mod(cellY, ChunkResolution) * ChunkResolution \u002B Mod(cellX, ChunkResolution);\r\n\t\tcells[index] = new Cell { Height = height, Packed = Cell.Pack(density, normal, entryIndex) };\r\n\r\n\t\tRevision\u002B\u002B;\r\n\t}\r\n\r\n\tpublic Cell GetCell(float worldX, float worldY)\r\n\t{\r\n\t\tvar cellX = WorldToCell(worldX);\r\n\t\tvar cellY = WorldToCell(worldY);\r\n\t\tvar coord = new ChunkCoord(FloorDiv(cellX, ChunkResolution), FloorDiv(cellY, ChunkResolution));\r\n\r\n\t\tif (!_chunks.TryGetValue(coord, out var cells))\r\n\t\t\treturn default;\r\n\r\n\t\treturn cells[Mod(cellY, ChunkResolution) * ChunkResolution \u002B Mod(cellX, ChunkResolution)];\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EReduces coverage in a radius, removing samples that reach zero.\u003C/summary\u003E\r\n\tpublic void Erase(Vector3 center, float radius, float strength)\r\n\t{\r\n\t\tvar radiusSquared = radius * radius;\r\n\r\n\t\tvar minCellX = WorldToCell(center.x - radius);\r\n\t\tvar maxCellX = WorldToCell(center.x \u002B radius);\r\n\t\tvar minCellY = WorldToCell(center.y - radius);\r\n\t\tvar maxCellY = WorldToCell(center.y \u002B radius);\r\n\r\n\t\tvar changed = false;\r\n\r\n\t\tfor (var cy = minCellY; cy \u003C= maxCellY; cy\u002B\u002B)\r\n\t\t{\r\n\t\t\tfor (var cx = minCellX; cx \u003C= maxCellX; cx\u002B\u002B)\r\n\t\t\t{\r\n\t\t\t\tvar coord = new ChunkCoord(FloorDiv(cx, ChunkResolution), FloorDiv(cy, ChunkResolution));\r\n\t\t\t\tif (!_chunks.TryGetValue(coord, out var cells))\r\n\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\tvar wx = (cx \u002B 0.5f) * CellSize;\r\n\t\t\t\tvar wy = (cy \u002B 0.5f) * CellSize;\r\n\t\t\t\tvar dx = wx - center.x;\r\n\t\t\t\tvar dy = wy - center.y;\r\n\r\n\t\t\t\tif (dx * dx \u002B dy * dy \u003E radiusSquared)\r\n\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\tvar index = Mod(cy, ChunkResolution) * ChunkResolution \u002B Mod(cx, ChunkResolution);\r\n\t\t\t\tref var cell = ref cells[index];\r\n\r\n\t\t\t\tif ((cell.Packed \u0026 0xFF) == 0)\r\n\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\tvar density = Math.Max(cell.Density - strength, 0.0f);\r\n\t\t\t\tcell.Packed = density \u003C= 0.0f\r\n\t\t\t\t\t? 0u\r\n\t\t\t\t\t: Cell.Pack(density, cell.Normal, cell.EntryIndex);\r\n\r\n\t\t\t\tchanged = true;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (!changed)\r\n\t\t\treturn;\r\n\r\n\t\tPruneEmptyChunks();\r\n\t\tRevision\u002B\u002B;\r\n\t}\r\n\r\n\tpublic void ClearAll()\r\n\t{\r\n\t\tif (_chunks.Count == 0) return;\r\n\r\n\t\t_chunks.Clear();\r\n\t\tRevision\u002B\u002B;\r\n\t}\r\n\r\n\tprivate void PruneEmptyChunks()\r\n\t{\r\n\t\tList\u003CChunkCoord\u003E empty = null;\r\n\r\n\t\tforeach (var (coord, cells) in _chunks)\r\n\t\t{\r\n\t\t\tvar used = false;\r\n\t\t\tfor (var i = 0; i \u003C cells.Length; i\u002B\u002B)\r\n\t\t\t{\r\n\t\t\t\tif ((cells[i].Packed \u0026 0xFF) != 0) { used = true; break; }\r\n\t\t\t}\r\n\r\n\t\t\tif (!used)\r\n\t\t\t{\r\n\t\t\t\tempty ??= [];\r\n\t\t\t\tempty.Add(coord);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (empty is null) return;\r\n\r\n\t\tforeach (var coord in empty)\r\n\t\t\t_chunks.Remove(coord);\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Writes only the painted cells. Storing them densely cost 8KB per chunk however little of it\r\n\t/// was painted, and a brush stroke across a landscape touches a lot of chunks.\r\n\t///\r\n\t/// Each painted cell costs 2 bytes more than it did dense (its index), so a chunk past about 80%\r\n\t/// coverage is cheaper stored densely. Both layouts are written and each chunk says which it used.\r\n\t/// \u003C/summary\u003E\r\n\tpublic override void Serialize(ref Writer writer)\r\n\t{\r\n\t\twriter.Stream.Write(_chunks.Count);\r\n\r\n\t\tforeach (var (coord, cells) in _chunks)\r\n\t\t{\r\n\t\t\twriter.Stream.Write(coord.X);\r\n\t\t\twriter.Stream.Write(coord.Y);\r\n\r\n\t\t\tvar painted = 0;\r\n\t\t\tfor (var i = 0; i \u003C CellsPerChunk; i\u002B\u002B)\r\n\t\t\t{\r\n\t\t\t\tif ((cells[i].Packed \u0026 0xFF) != 0) painted\u002B\u002B;\r\n\t\t\t}\r\n\r\n\t\t\tvar sparse = painted * 10 \u003C CellsPerChunk * 8;\r\n\t\t\twriter.Stream.Write(sparse);\r\n\r\n\t\t\tif (!sparse)\r\n\t\t\t{\r\n\t\t\t\tfor (var i = 0; i \u003C CellsPerChunk; i\u002B\u002B)\r\n\t\t\t\t{\r\n\t\t\t\t\twriter.Stream.Write(cells[i].Height);\r\n\t\t\t\t\twriter.Stream.Write(cells[i].Packed);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\r\n\t\t\twriter.Stream.Write(painted);\r\n\r\n\t\t\tfor (var i = 0; i \u003C CellsPerChunk; i\u002B\u002B)\r\n\t\t\t{\r\n\t\t\t\tif ((cells[i].Packed \u0026 0xFF) == 0)\r\n\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\twriter.Stream.Write((ushort)i);\r\n\t\t\t\twriter.Stream.Write(cells[i].Height);\r\n\t\t\t\twriter.Stream.Write(cells[i].Packed);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tpublic override void Deserialize(ref Reader reader)\r\n\t{\r\n\t\t_chunks.Clear();\r\n\r\n\t\tvar chunkCount = reader.Stream.Read\u003Cint\u003E();\r\n\r\n\t\tfor (var c = 0; c \u003C chunkCount; c\u002B\u002B)\r\n\t\t{\r\n\t\t\tvar coord = new ChunkCoord(reader.Stream.Read\u003Cint\u003E(), reader.Stream.Read\u003Cint\u003E());\r\n\t\t\tvar cells = new Cell[CellsPerChunk];\r\n\r\n\t\t\tif (reader.Stream.Read\u003Cbool\u003E())\r\n\t\t\t{\r\n\t\t\t\tvar painted = reader.Stream.Read\u003Cint\u003E();\r\n\r\n\t\t\t\tfor (var p = 0; p \u003C painted; p\u002B\u002B)\r\n\t\t\t\t{\r\n\t\t\t\t\tvar index = reader.Stream.Read\u003Cushort\u003E();\r\n\t\t\t\t\tvar height = reader.Stream.Read\u003Cfloat\u003E();\r\n\t\t\t\t\tvar packed = reader.Stream.Read\u003Cuint\u003E();\r\n\r\n\t\t\t\t\tif (index \u003C CellsPerChunk)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tcells[index].Height = height;\r\n\t\t\t\t\t\tcells[index].Packed = packed;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tfor (var i = 0; i \u003C CellsPerChunk; i\u002B\u002B)\r\n\t\t\t\t{\r\n\t\t\t\t\tcells[i].Height = reader.Stream.Read\u003Cfloat\u003E();\r\n\t\t\t\t\tcells[i].Packed = reader.Stream.Read\u003Cuint\u003E();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t_chunks[coord] = cells;\r\n\t\t}\r\n\r\n\t\tRevision\u002B\u002B;\r\n\t}\r\n}\r\n"},{"Ident":"redsnail.floratool","Path":"FloraRenderer.cs","FileName":"FloraRenderer.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":421873,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing Sandbox;\r\n\r\nnamespace RedSnail.FloraTool;\r\n\r\n/// \u003Csummary\u003E\r\n/// Renders painted flora. Coverage is stored per chunk and instances are regenerated from it plus\r\n/// \u003Csee cref=\u0022Seed\u0022/\u003E, so the scene file holds a density map rather than a transform per tree - the\r\n/// difference between a few megabytes and something a repository will refuse.\r\n///\r\n/// Chunks become scene objects only within the definition\u0027s stream radius. Scene objects rather than\r\n/// a hand-rolled instanced draw because they take part in every pass the engine runs: the depth\r\n/// prepass, the shadow cascades, and per-object LOD using the model\u0027s own compiled distances.\r\n/// Standard instancing still batches them into few draw calls.\r\n/// \u003C/summary\u003E\r\n[Icon(\u0022park\u0022), Group(\u0022Flora\u0022), Title(\u0022Flora Renderer\u0022)]\r\npublic sealed partial class FloraRenderer : Component, Component.ExecuteInEditor, Component.DontExecuteOnServer\r\n{\r\n\t/// \u003Csummary\u003EA chunk\u0027s generated instances and the scene objects currently standing for them.\u003C/summary\u003E\r\n\tprivate sealed class LiveChunk\r\n\t{\r\n\t\tpublic List\u003CFloraGenerator.Instance\u003E Instances = [];\r\n\t\tpublic List\u003CSceneObject\u003E SceneObjects = [];\r\n\r\n\t\t/// \u003Csummary\u003E\r\n\t\t/// Whether this chunk is currently allowed to cast. Tracked so the flags are only touched\r\n\t\t/// when a chunk crosses the shadow boundary, rather than every object every frame.\r\n\t\t/// \u003C/summary\u003E\r\n\t\tpublic bool ShadowsEnabled = true;\r\n\t}\r\n\r\n\t[Property, Group(\u0022General\u0022)]\r\n\tpublic FloraDefinition Definition { get; set; }\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Decides exactly where each instance lands within the painted coverage. Change it to reshuffle\r\n\t/// a whole forest without repainting; keep it fixed and the same trees stand in the same places\r\n\t/// every run, on every machine.\r\n\t/// \u003C/summary\u003E\r\n\t[Property, Group(\u0022General\u0022)]\r\n\tpublic int Seed\r\n\t{\r\n\t\tget =\u003E field;\r\n\t\tset\r\n\t\t{\r\n\t\t\tif (field == value) return;\r\n\t\t\tfield = value;\r\n\t\t\tMarkDirty();\r\n\t\t}\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EPainted coverage. Serialized as a binary blob, not JSON.\u003C/summary\u003E\r\n\t[Property, Hide]\r\n\tpublic FloraStorage Storage { get; set; } = new();\r\n\r\n\tprivate readonly Dictionary\u003CFloraStorage.ChunkCoord, LiveChunk\u003E _live = [];\r\n\tprivate readonly List\u003CFloraStorage.ChunkCoord\u003E _wantedChunks = [];\r\n\tprivate readonly List\u003CFloraStorage.ChunkCoord\u003E _staleChunks = [];\r\n\r\n\t// Reused across chunk builds so streaming doesn\u0027t allocate a fresh list per chunk.\r\n\tprivate readonly List\u003CFloraGenerator.Instance\u003E _scratchInstances = [];\r\n\r\n\tprivate int _builtRevision = -1;\r\n\tprivate Vector3 _lastStreamOrigin;\r\n\tprivate bool _hasStreamOrigin;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Restreaming walks every painted chunk, so it only happens once the viewer has moved far enough\r\n\t/// for the answer to have changed. A fraction of a chunk keeps the boundary from thrashing.\r\n\t/// \u003C/summary\u003E\r\n\tprivate const float StreamRefreshDistance = FloraStorage.ChunkSize * 0.25f;\r\n\r\n\tprotected override void OnEnabled()\r\n\t{\r\n\t\tStorage ??= new FloraStorage();\r\n\r\n\t\t// Scene objects were deleted on disable, so a matching revision would leave us thinking the\r\n\t\t// world is already built when nothing is in it.\r\n\t\t_builtRevision = -1;\r\n\t\t_hasStreamOrigin = false;\r\n\t}\r\n\r\n\tprotected override void OnDisabled()\r\n\t{\r\n\t\tReleaseAllChunks();\r\n\t\tReleaseCollision();\r\n\r\n\t\t_builtRevision = -1;\r\n\t\t_hasStreamOrigin = false;\r\n\t}\r\n\r\n\tprotected override void OnUpdate()\r\n\t{\r\n\t\tvar viewer = GetViewerPosition();\r\n\t\tif (!viewer.HasValue)\r\n\t\t\treturn;\r\n\r\n\t\tUpdateStreaming(viewer.Value);\r\n\t\tUpdateCollision(viewer.Value);\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// What streaming follows. While editing that is the viewport camera, so flora appears around\r\n\t/// what you are looking at rather than wherever the game camera is parked.\r\n\t/// \u003C/summary\u003E\r\n\tprivate Vector3? GetViewerPosition()\r\n\t{\r\n\t\tif (Scene.IsEditor)\r\n\t\t{\r\n\t\t\tvar editorCamera = Application.Editor?.Camera;\r\n\t\t\tif (editorCamera.IsValid())\r\n\t\t\t\treturn editorCamera.WorldPosition;\r\n\t\t}\r\n\r\n\t\treturn Scene.Camera.IsValid() ? Scene.Camera.WorldPosition : null;\r\n\t}\r\n\r\n\tprivate void UpdateStreaming(Vector3 origin)\r\n\t{\r\n\t\tif (Storage is null || !Definition.IsValid())\r\n\t\t{\r\n\t\t\tReleaseAllChunks();\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\t// Painting or reseeding invalidates everything regardless of whether the viewer moved.\r\n\t\tvar dirty = _builtRevision != Storage.Revision;\r\n\r\n\t\tif (!dirty \u0026\u0026 _hasStreamOrigin \u0026\u0026 origin.Distance(_lastStreamOrigin) \u003C StreamRefreshDistance)\r\n\t\t\treturn;\r\n\r\n\t\tif (dirty)\r\n\t\t{\r\n\t\t\tReleaseAllChunks();\r\n\t\t\t_builtRevision = Storage.Revision;\r\n\t\t}\r\n\r\n\t\t_lastStreamOrigin = origin;\r\n\t\t_hasStreamOrigin = true;\r\n\r\n\t\tGatherWantedChunks(origin);\r\n\t\tSyncChunks(origin);\r\n\t}\r\n\r\n\tprivate void GatherWantedChunks(Vector3 origin)\r\n\t{\r\n\t\t_wantedChunks.Clear();\r\n\r\n\t\t// A chunk\u0027s near corner can be in range while its centre is not, hence the circumradius.\r\n\t\tvar radius = Definition.StreamRadius \u002B FloraStorage.ChunkSize * 0.7072f;\r\n\t\tvar radiusSquared = radius * radius;\r\n\r\n\t\tforeach (var (coord, _) in Storage.Chunks)\r\n\t\t{\r\n\t\t\tvar center = FloraStorage.ChunkCenter(coord);\r\n\r\n\t\t\tvar dx = center.x - origin.x;\r\n\t\t\tvar dy = center.y - origin.y;\r\n\r\n\t\t\tif (dx * dx \u002B dy * dy \u003E radiusSquared)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\t_wantedChunks.Add(coord);\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void SyncChunks(Vector3 origin)\r\n\t{\r\n\t\t_staleChunks.Clear();\r\n\r\n\t\tforeach (var (coord, _) in _live)\r\n\t\t{\r\n\t\t\tif (!_wantedChunks.Contains(coord))\r\n\t\t\t\t_staleChunks.Add(coord);\r\n\t\t}\r\n\r\n\t\tforeach (var coord in _staleChunks)\r\n\t\t\tReleaseChunk(coord);\r\n\r\n\t\tforeach (var coord in _wantedChunks)\r\n\t\t{\r\n\t\t\tif (_live.ContainsKey(coord))\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tBuildChunk(coord, origin);\r\n\t\t}\r\n\r\n\t\tUpdateChunkShadows(origin);\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Turns shadow casting off for chunks past the shadow distance. Evaluated per chunk rather than\r\n\t/// per instance, and only written when a chunk actually crosses the boundary, so a stationary\r\n\t/// camera costs nothing here.\r\n\t/// \u003C/summary\u003E\r\n\tprivate void UpdateChunkShadows(Vector3 origin)\r\n\t{\r\n\t\tforeach (var (coord, chunk) in _live)\r\n\t\t{\r\n\t\t\tvar wanted = ChunkCastsShadows(coord, origin);\r\n\t\t\tif (wanted == chunk.ShadowsEnabled)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tchunk.ShadowsEnabled = wanted;\r\n\t\t\tApplyChunkShadows(chunk);\r\n\t\t}\r\n\t}\r\n\r\n\tprivate bool ChunkCastsShadows(FloraStorage.ChunkCoord coord, Vector3 origin)\r\n\t{\r\n\t\tvar distance = Definition.ShadowDistance;\r\n\t\tif (distance \u003C= 0.0f)\r\n\t\t\treturn true;\r\n\r\n\t\t// Measured to the chunk\u0027s near edge via its circumradius, so a chunk is only cut off once all\r\n\t\t// of it is beyond the limit.\r\n\t\tvar limit = distance \u002B FloraStorage.ChunkSize * 0.7072f;\r\n\r\n\t\tvar center = FloraStorage.ChunkCenter(coord);\r\n\t\tvar dx = center.x - origin.x;\r\n\t\tvar dy = center.y - origin.y;\r\n\r\n\t\treturn dx * dx \u002B dy * dy \u003C= limit * limit;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The per-entry CastShadows setting is the ceiling - distance can only ever take shadows away,\r\n\t/// never grant them to an entry the artist turned them off for.\r\n\t/// \u003C/summary\u003E\r\n\tprivate void ApplyChunkShadows(LiveChunk chunk)\r\n\t{\r\n\t\tfor (var i = 0; i \u003C chunk.SceneObjects.Count \u0026\u0026 i \u003C chunk.Instances.Count; i\u002B\u002B)\r\n\t\t{\r\n\t\t\tvar sceneObject = chunk.SceneObjects[i];\r\n\t\t\tif (!sceneObject.IsValid())\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tvar entry = Definition.GetEntry(chunk.Instances[i].EntryIndex);\r\n\t\t\tsceneObject.Flags.CastShadows = chunk.ShadowsEnabled \u0026\u0026 entry?.CastShadows is true;\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void BuildChunk(FloraStorage.ChunkCoord coord, Vector3 origin)\r\n\t{\r\n\t\tif (!Storage.Chunks.TryGetValue(coord, out var cells))\r\n\t\t\treturn;\r\n\r\n\t\tvar world = Scene.SceneWorld;\r\n\t\tif (!world.IsValid())\r\n\t\t\treturn;\r\n\r\n\t\tvar chunk = new LiveChunk();\r\n\t\tchunk.ShadowsEnabled = ChunkCastsShadows(coord, origin);\r\n\r\n\t\t_scratchInstances.Clear();\r\n\t\tFloraGenerator.GenerateChunk(coord, cells, Definition, Seed, _scratchInstances);\r\n\r\n\t\t// Instances and scene objects are kept strictly parallel - anything whose entry no longer\r\n\t\t// resolves is dropped from both. Skipping only the scene object would slide the two lists out\r\n\t\t// of step, and the shadow and collision paths index one by the other.\r\n\t\tfor (var i = 0; i \u003C _scratchInstances.Count; i\u002B\u002B)\r\n\t\t{\r\n\t\t\tvar instance = _scratchInstances[i];\r\n\r\n\t\t\tvar entry = Definition.GetEntry(instance.EntryIndex);\r\n\t\t\tif (entry is null)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tvar sceneObject = new SceneObject(world, entry.Model, instance.ToTransform());\r\n\t\t\tsceneObject.Flags.CastShadows = chunk.ShadowsEnabled \u0026\u0026 entry.CastShadows;\r\n\r\n\t\t\tchunk.Instances.Add(instance);\r\n\t\t\tchunk.SceneObjects.Add(sceneObject);\r\n\t\t}\r\n\r\n\t\t_live[coord] = chunk;\r\n\t}\r\n\r\n\tprivate void ReleaseChunk(FloraStorage.ChunkCoord coord)\r\n\t{\r\n\t\tif (!_live.Remove(coord, out var chunk))\r\n\t\t\treturn;\r\n\r\n\t\tforeach (var sceneObject in chunk.SceneObjects)\r\n\t\t{\r\n\t\t\tif (sceneObject.IsValid())\r\n\t\t\t\tsceneObject.Delete();\r\n\t\t}\r\n\r\n\t\tchunk.SceneObjects.Clear();\r\n\t\tchunk.Instances.Clear();\r\n\t}\r\n\r\n\tprivate void ReleaseAllChunks()\r\n\t{\r\n\t\tforeach (var (_, chunk) in _live)\r\n\t\t{\r\n\t\t\tforeach (var sceneObject in chunk.SceneObjects)\r\n\t\t\t{\r\n\t\t\t\tif (sceneObject.IsValid())\r\n\t\t\t\t\tsceneObject.Delete();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t_live.Clear();\r\n\t\t_wantedChunks.Clear();\r\n\t\t_staleChunks.Clear();\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Called by the editor tool after painting, so the next frame regenerates. Also fires when the\r\n\t/// seed changes.\r\n\t/// \u003C/summary\u003E\r\n\tpublic void MarkDirty()\r\n\t{\r\n\t\t_builtRevision = -1;\r\n\t\t_hasStreamOrigin = false;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003ETotal instances currently streamed in. Useful when tuning density and stream radius.\u003C/summary\u003E\r\n\tpublic int LiveInstanceCount\r\n\t{\r\n\t\tget\r\n\t\t{\r\n\t\t\tvar count = 0;\r\n\t\t\tforeach (var (_, chunk) in _live)\r\n\t\t\t\tcount \u002B= chunk.SceneObjects.Count;\r\n\t\t\treturn count;\r\n\t\t}\r\n\t}\r\n\r\n\tprotected override void DrawGizmos()\r\n\t{\r\n\t\tif (!Gizmo.IsSelected || Storage is null || Storage.ChunkCount == 0)\r\n\t\t\treturn;\r\n\r\n\t\tGizmo.Draw.Color = Color.Green.WithAlpha(0.25f);\r\n\r\n\t\tforeach (var (coord, _) in Storage.Chunks)\r\n\t\t{\r\n\t\t\tvar origin = FloraStorage.ChunkOrigin(coord);\r\n\r\n\t\t\tvar mins = WorldTransform.PointToLocal(new Vector3(origin.x, origin.y, 0));\r\n\t\t\tvar maxs = WorldTransform.PointToLocal(new Vector3(\r\n\t\t\t\torigin.x \u002B FloraStorage.ChunkSize, origin.y \u002B FloraStorage.ChunkSize, 0));\r\n\r\n\t\t\tGizmo.Draw.LineBBox(new BBox(mins, maxs));\r\n\t\t}\r\n\t}\r\n}\r\n"},{"Ident":"redsnail.floratool","Path":"Code/FloraRenderer.Collision.cs","FileName":"FloraRenderer.Collision.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":421873,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing Sandbox;\r\n\r\nnamespace RedSnail.FloraTool;\r\n\r\n/// \u003Csummary\u003E\r\n/// Collision for painted flora. Instances only exist as scene objects, so nothing is solid until a\r\n/// collider is made for it - and those are made only for instances near the viewer and recycled as\r\n/// it moves, keeping physics cost tied to what is reachable rather than to the whole forest.\r\n/// \u003C/summary\u003E\r\npublic sealed partial class FloraRenderer\r\n{\r\n\tprivate readonly record struct CollisionKey(FloraStorage.ChunkCoord Chunk, int Index);\r\n\r\n\tprivate readonly Dictionary\u003CCollisionKey, GameObject\u003E _colliders = [];\r\n\r\n\t// A set rather than a list: SyncColliders tests every live collider against it, so a linear scan\r\n\t// there would be quadratic once a few hundred are in range.\r\n\tprivate readonly HashSet\u003CCollisionKey\u003E _wantedColliders = [];\r\n\tprivate readonly List\u003CCollisionKey\u003E _staleColliders = [];\r\n\r\n\tprivate GameObject _collisionRoot;\r\n\tprivate Vector3 _lastCollisionOrigin;\r\n\tprivate bool _hasCollisionOrigin;\r\n\tprivate int _collisionRevision = -1;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Rebuilding walks every streamed instance, so it only happens once the viewer has moved far\r\n\t/// enough for the answer to have changed.\r\n\t/// \u003C/summary\u003E\r\n\tprivate const float CollisionRefreshDistance = 256.0f;\r\n\r\n\tprivate void UpdateCollision(Vector3 origin)\r\n\t{\r\n\t\tif (!Definition.IsValid() || Definition.CollisionRadius \u003C= 0.0f)\r\n\t\t{\r\n\t\t\tReleaseCollision();\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tvar storageChanged = Storage is null || _collisionRevision != Storage.Revision;\r\n\r\n\t\tif (!storageChanged \u0026\u0026 _hasCollisionOrigin \u0026\u0026\r\n\t\t\t origin.Distance(_lastCollisionOrigin) \u003C CollisionRefreshDistance)\r\n\t\t\treturn;\r\n\r\n\t\t_collisionRevision = Storage?.Revision ?? -1;\r\n\t\t_lastCollisionOrigin = origin;\r\n\t\t_hasCollisionOrigin = true;\r\n\r\n\t\tGatherWantedColliders(origin);\r\n\t\tSyncColliders();\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Only streamed chunks are considered. Collision radius should sit well inside the stream radius\r\n\t/// anyway, so anything outside it has no business being solid.\r\n\t/// \u003C/summary\u003E\r\n\tprivate void GatherWantedColliders(Vector3 origin)\r\n\t{\r\n\t\t_wantedColliders.Clear();\r\n\r\n\t\tvar radiusSquared = Definition.CollisionRadius * Definition.CollisionRadius;\r\n\r\n\t\tforeach (var (coord, chunk) in _live)\r\n\t\t{\r\n\t\t\tfor (var i = 0; i \u003C chunk.Instances.Count; i\u002B\u002B)\r\n\t\t\t{\r\n\t\t\t\tvar instance = chunk.Instances[i];\r\n\r\n\t\t\t\tif (instance.Position.DistanceSquared(origin) \u003E radiusSquared)\r\n\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\tvar entry = Definition.GetEntry(instance.EntryIndex);\r\n\t\t\t\tif (entry?.EnablePhysics is not true)\r\n\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t_wantedColliders.Add(new CollisionKey(coord, i));\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void SyncColliders()\r\n\t{\r\n\t\t// Drop what fell out of range first, so those objects are free to be reused this same frame.\r\n\t\t_staleColliders.Clear();\r\n\r\n\t\tforeach (var (key, gameObject) in _colliders)\r\n\t\t{\r\n\t\t\tif (gameObject.IsValid() \u0026\u0026 _wantedColliders.Contains(key))\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\t_staleColliders.Add(key);\r\n\t\t}\r\n\r\n\t\tforeach (var key in _staleColliders)\r\n\t\t{\r\n\t\t\tif (_colliders.Remove(key, out var gameObject) \u0026\u0026 gameObject.IsValid())\r\n\t\t\t\tgameObject.Destroy();\r\n\t\t}\r\n\r\n\t\tforeach (var key in _wantedColliders)\r\n\t\t{\r\n\t\t\tif (_colliders.ContainsKey(key))\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tvar gameObject = CreateCollider(key);\r\n\t\t\tif (gameObject.IsValid())\r\n\t\t\t\t_colliders[key] = gameObject;\r\n\t\t}\r\n\t}\r\n\r\n\tprivate GameObject CreateCollider(CollisionKey key)\r\n\t{\r\n\t\tif (!_live.TryGetValue(key.Chunk, out var chunk))\r\n\t\t\treturn null;\r\n\r\n\t\tif (key.Index \u003C 0 || key.Index \u003E= chunk.Instances.Count)\r\n\t\t\treturn null;\r\n\r\n\t\tvar instance = chunk.Instances[key.Index];\r\n\r\n\t\tvar entry = Definition.GetEntry(instance.EntryIndex);\r\n\t\tif (entry is null)\r\n\t\t\treturn null;\r\n\r\n\t\tEnsureCollisionRoot();\r\n\r\n\t\tvar gameObject = new GameObject(true, \u0022FloraCollider\u0022)\r\n\t\t{\r\n\t\t\tParent = _collisionRoot,\r\n\t\t\tWorldTransform = instance.ToTransform(),\r\n\t\t};\r\n\r\n\t\t// Not saved with the scene and not shown in the hierarchy - these are transient physics\r\n\t\t// proxies for geometry that is regenerated from the seed anyway.\r\n\t\tgameObject.Flags |= GameObjectFlags.NotSaved | GameObjectFlags.Hidden;\r\n\r\n\t\tvar collider = gameObject.Components.Create\u003CModelCollider\u003E();\r\n\t\tcollider.Model = entry.Model;\r\n\t\tcollider.Static = true;\r\n\r\n\t\treturn gameObject;\r\n\t}\r\n\r\n\tprivate void EnsureCollisionRoot()\r\n\t{\r\n\t\tif (_collisionRoot.IsValid())\r\n\t\t\treturn;\r\n\r\n\t\t_collisionRoot = new GameObject(true, \u0022Flora Colliders\u0022) { Parent = GameObject };\r\n\t\t_collisionRoot.Flags |= GameObjectFlags.NotSaved | GameObjectFlags.Hidden;\r\n\t}\r\n\r\n\tprivate void ReleaseCollision()\r\n\t{\r\n\t\tforeach (var (_, gameObject) in _colliders)\r\n\t\t{\r\n\t\t\tif (gameObject.IsValid())\r\n\t\t\t\tgameObject.Destroy();\r\n\t\t}\r\n\r\n\t\t_colliders.Clear();\r\n\t\t_wantedColliders.Clear();\r\n\t\t_staleColliders.Clear();\r\n\r\n\t\tif (_collisionRoot.IsValid())\r\n\t\t\t_collisionRoot.Destroy();\r\n\r\n\t\t_collisionRoot = null;\r\n\t\t_hasCollisionOrigin = false;\r\n\t\t_collisionRevision = -1;\r\n\t}\r\n}\r\n"},{"Ident":"redsnail.floratool","Path":"FloraGenerator.cs","FileName":"FloraGenerator.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":421873,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing Sandbox;\r\n\r\nnamespace RedSnail.FloraTool;\r\n\r\n/// \u003Csummary\u003E\r\n/// Turns painted coverage into concrete instances. Everything here is a pure function of the chunk\r\n/// coordinate, the cell contents and the seed - no state, no RNG object - so a chunk regenerates\r\n/// identically every run, on every machine, however many times it is streamed in and out.\r\n/// \u003C/summary\u003E\r\npublic static class FloraGenerator\r\n{\r\n\tpublic readonly record struct Instance(int EntryIndex, Vector3 Position, Rotation Rotation, float Scale)\r\n\t{\r\n\t\tpublic readonly Transform ToTransform() =\u003E new(Position, Rotation, Scale);\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Integer avalanche hash. Deterministic across runs and platforms, which the framework RNG is\r\n\t/// not guaranteed to be, and cheap enough to call several times per instance.\r\n\t/// \u003C/summary\u003E\r\n\tprivate static uint Hash(uint x)\r\n\t{\r\n\t\tx ^= x \u003E\u003E 16;\r\n\t\tx *= 0x7feb352du;\r\n\t\tx ^= x \u003E\u003E 15;\r\n\t\tx *= 0x846ca68bu;\r\n\t\tx ^= x \u003E\u003E 16;\r\n\t\treturn x;\r\n\t}\r\n\r\n\tprivate static float HashFloat(uint x) =\u003E Hash(x) * (1.0f / 4294967296.0f);\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Generates every instance for one chunk, appending into \u003Cparamref name=\u0022results\u0022/\u003E.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static void GenerateChunk(FloraStorage.ChunkCoord coord, FloraStorage.Cell[] cells,\r\n\t\tFloraDefinition definition, int seed, List\u003CInstance\u003E results)\r\n\t{\r\n\t\tif (cells is null || definition is null)\r\n\t\t\treturn;\r\n\r\n\t\tvar origin = FloraStorage.ChunkOrigin(coord);\r\n\t\tvar maxPerCell = Math.Max(definition.MaxPerCell, 1);\r\n\r\n\t\t// Mixing the chunk coordinate into the seed keeps neighbouring chunks from sharing a\r\n\t\t// sequence, which would otherwise show up as a visible repeating pattern across the world.\r\n\t\tvar chunkSeed = Hash((uint)seed\r\n\t\t\t^ Hash((uint)coord.X * 73856093u)\r\n\t\t\t^ Hash((uint)coord.Y * 19349663u));\r\n\r\n\t\tfor (var cellIndex = 0; cellIndex \u003C cells.Length; cellIndex\u002B\u002B)\r\n\t\t{\r\n\t\t\tvar cell = cells[cellIndex];\r\n\r\n\t\t\tvar density = cell.Density;\r\n\t\t\tif (density \u003C= 0.0f)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tif (cell.Normal.z \u003C definition.SlopeLimit)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tvar cellSeed = Hash(chunkSeed ^ Hash((uint)cellIndex * 0x9e3779b9u));\r\n\r\n\t\t\tvar cx = cellIndex % FloraStorage.ChunkResolution;\r\n\t\t\tvar cy = cellIndex / FloraStorage.ChunkResolution;\r\n\r\n\t\t\tvar cellMinX = origin.x \u002B cx * FloraStorage.CellSize;\r\n\t\t\tvar cellMinY = origin.y \u002B cy * FloraStorage.CellSize;\r\n\r\n\t\t\t// Fractional counts are resolved by a hash rather than rounding, so density reads as a\r\n\t\t\t// smooth thinning across a field instead of stepping between whole numbers per cell.\r\n\t\t\tvar exact = density * maxPerCell;\r\n\t\t\tvar count = (int)exact;\r\n\t\t\tif (HashFloat(cellSeed ^ 0x1b56c4e9u) \u003C exact - count)\r\n\t\t\t\tcount\u002B\u002B;\r\n\r\n\t\t\tfor (var i = 0; i \u003C count; i\u002B\u002B)\r\n\t\t\t{\r\n\t\t\t\tvar s = Hash(cellSeed \u002B (uint)i * 0x85ebca6bu);\r\n\r\n\t\t\t\tvar entry = ResolveEntry(definition, cell.EntryIndex, s);\r\n\t\t\t\tif (entry.Index \u003C 0)\r\n\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\tresults.Add(BuildInstance(entry.Index, entry.Entry, cell, s, cellMinX, cellMinY));\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// A cell either names its entry - painted deliberately with one species selected - or defers to\r\n\t/// the definition\u0027s weights.\r\n\t/// \u003C/summary\u003E\r\n\tprivate static (int Index, FloraEntry Entry) ResolveEntry(FloraDefinition definition, int cellEntryIndex, uint seed)\r\n\t{\r\n\t\tvar entries = definition.Entries;\r\n\t\tif (entries is null || entries.Count == 0)\r\n\t\t\treturn (-1, null);\r\n\r\n\t\tif (cellEntryIndex \u003C entries.Count)\r\n\t\t{\r\n\t\t\tvar named = entries[cellEntryIndex];\r\n\t\t\treturn named?.HasModel is true ? (cellEntryIndex, named) : (-1, null);\r\n\t\t}\r\n\r\n\t\tvar total = 0.0f;\r\n\t\tfor (var i = 0; i \u003C entries.Count; i\u002B\u002B)\r\n\t\t{\r\n\t\t\tif (entries[i]?.HasModel is true \u0026\u0026 entries[i].Weight \u003E 0.0f)\r\n\t\t\t\ttotal \u002B= entries[i].Weight;\r\n\t\t}\r\n\r\n\t\tif (total \u003C= 0.0f)\r\n\t\t\treturn (-1, null);\r\n\r\n\t\tvar pick = HashFloat(seed ^ 0x3c6ef372u) * total;\r\n\r\n\t\tfor (var i = 0; i \u003C entries.Count; i\u002B\u002B)\r\n\t\t{\r\n\t\t\tvar entry = entries[i];\r\n\t\t\tif (entry?.HasModel is not true || entry.Weight \u003C= 0.0f)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tpick -= entry.Weight;\r\n\t\t\tif (pick \u003C= 0.0f)\r\n\t\t\t\treturn (i, entry);\r\n\t\t}\r\n\r\n\t\treturn (-1, null);\r\n\t}\r\n\r\n\tprivate static Instance BuildInstance(int entryIndex, FloraEntry entry, FloraStorage.Cell cell,\r\n\t\tuint seed, float cellMinX, float cellMinY)\r\n\t{\r\n\t\tvar jitterX = HashFloat(seed ^ 0x68bc21ebu);\r\n\t\tvar jitterY = HashFloat(seed ^ 0x02e5be93u);\r\n\r\n\t\tvar x = cellMinX \u002B jitterX * FloraStorage.CellSize;\r\n\t\tvar y = cellMinY \u002B jitterY * FloraStorage.CellSize;\r\n\r\n\t\tvar normal = cell.Normal;\r\n\r\n\t\t// The baked height is the cell centre\u0027s, so a slope needs the offset carried across to the\r\n\t\t// jittered position or trunks float on the uphill side and sink on the downhill one.\r\n\t\tvar offsetX = x - (cellMinX \u002B FloraStorage.CellSize * 0.5f);\r\n\t\tvar offsetY = y - (cellMinY \u002B FloraStorage.CellSize * 0.5f);\r\n\t\tvar z = cell.Height - (normal.x * offsetX \u002B normal.y * offsetY) / MathF.Max(normal.z, 0.1f);\r\n\r\n\t\tvar position = new Vector3(x, y, z);\r\n\t\tif (entry.SinkDepth \u003E 0.0f)\r\n\t\t\tposition -= normal * entry.SinkDepth;\r\n\r\n\t\tvar rotation = entry.RandomYaw\r\n\t\t\t? Rotation.FromYaw(HashFloat(seed ^ 0x7f4a7c15u) * 360.0f)\r\n\t\t\t: Rotation.Identity;\r\n\r\n\t\tif (entry.AlignToNormal \u003E 0.0f)\r\n\t\t{\r\n\t\t\tvar aligned = Rotation.LookAt(normal) * Rotation.FromPitch(90.0f);\r\n\t\t\trotation = Rotation.Slerp(rotation, aligned * rotation, entry.AlignToNormal);\r\n\t\t}\r\n\r\n\t\tif (entry.RandomTilt \u003E 0.0f)\r\n\t\t{\r\n\t\t\tvar tiltAngle = HashFloat(seed ^ 0x165667b1u) * entry.RandomTilt;\r\n\t\t\tvar tiltDirection = HashFloat(seed ^ 0x27d4eb2fu) * 360.0f;\r\n\t\t\trotation *= Rotation.FromAxis(Rotation.FromYaw(tiltDirection).Forward, tiltAngle);\r\n\t\t}\r\n\r\n\t\tvar scale = MathX.Lerp(entry.Scale.Min, entry.Scale.Max, HashFloat(seed ^ 0xd3a2646cu));\r\n\r\n\t\treturn new Instance(entryIndex, position, rotation, scale);\r\n\t}\r\n}\r\n"},{"Ident":"redsnail.floratool","Path":"Editor/FloraTool.cs","FileName":"FloraTool.cs","PackageType":"library","CodeKind":"Editor","AssetVersionId":421873,"IsPrivate":false,"Code":"using System;\r\nusing System.Linq;\r\nusing Editor;\r\nusing Editor.TerrainEditor;\r\nusing Sandbox;\r\n\r\nnamespace RedSnail.FloraTool.Editor;\r\n\r\n/// \u003Csummary\u003E\r\n/// Paints flora onto any surface. Each stroke scatters entries from the target renderer\u0027s\r\n/// definition, honouring its spacing and slope rules, and bakes the resulting transform into the\r\n/// renderer\u0027s storage. Hold Ctrl to erase.\r\n/// \u003C/summary\u003E\r\n[EditorTool(\u0022flora\u0022)]\r\n[Title(\u0022Flora\u0022)]\r\n[Icon(\u0022park\u0022)]\r\npublic sealed class FloraPaintTool : EditorTool\r\n{\r\n\tpublic BrushSettings BrushSettings { get; private set; } = new();\r\n\r\n\tprivate FloraRenderer _target;\r\n\tprivate bool _erasing;\r\n\tprivate bool _dragging;\r\n\tprivate bool _painted;\r\n\tprivate Vector3 _lastPaintPosition;\r\n\r\n\tprivate ComboBox _entryDropdown;\r\n\r\n\t/// \u003Csummary\u003EIndex into the definition\u0027s entries, or 255 for \u0022mix by weight\u0022.\u003C/summary\u003E\r\n\tprivate int _entryIndex = MixedEntryIndex;\r\n\r\n\tprivate const int MixedEntryIndex = 255;\r\n\r\n\t// The brush has to travel a fraction of its own radius before depositing again, or holding the\r\n\t// mouse still would keep hammering the same spot with traces.\r\n\tprivate float PaintStepDistance =\u003E BrushSettings.Size * 0.35f;\r\n\r\n\tpublic FloraPaintTool()\r\n\t{\r\n\t\tRebuildSidebarOnSelectionChange = false;\r\n\t}\r\n\r\n\tpublic override Widget CreateToolSidebar()\r\n\t{\r\n\t\tvar sidebar = new ToolSidebarWidget();\r\n\t\tsidebar.AddTitle(\u0022Flora Brush\u0022, \u0022brush\u0022);\r\n\t\tsidebar.MinimumWidth = 300;\r\n\r\n\t\t{\r\n\t\t\tvar group = sidebar.AddGroup(\u0022Brush\u0022);\r\n\t\t\tvar so = BrushSettings.GetSerialized();\r\n\t\t\tgroup.Add(ControlSheet.CreateRow(so.GetProperty(nameof(BrushSettings.Size))));\r\n\t\t\tgroup.Add(ControlSheet.CreateRow(so.GetProperty(nameof(BrushSettings.Opacity))));\r\n\t\t}\r\n\r\n\t\t{\r\n\t\t\t// Coverage names the entry it was painted with, so an artist can lay down pines here and\r\n\t\t\t// oaks there rather than getting one weighted mix everywhere.\r\n\t\t\tvar group = sidebar.AddGroup(\u0022Entry\u0022);\r\n\r\n\t\t\t_entryDropdown = new ComboBox(sidebar);\r\n\t\t\t_entryDropdown.ToolTip = \u0022Which flora entry this stroke paints. Mixed uses the definition\u0027s weights.\u0022;\r\n\t\t\tRebuildEntryOptions();\r\n\r\n\t\t\tgroup.Add(_entryDropdown);\r\n\t\t}\r\n\r\n\t\t{\r\n\t\t\tvar group = sidebar.AddGroup(\u0022Actions\u0022);\r\n\r\n\t\t\tvar clear = new Button(\u0022Clear All Flora\u0022, \u0022delete_sweep\u0022);\r\n\t\t\tclear.ToolTip = \u0022Remove every painted instance from the target Flora Renderer\u0022;\r\n\t\t\tclear.Clicked \u002B= () =\u003E\r\n\t\t\t{\r\n\t\t\t\tvar target = ResolveTarget();\r\n\t\t\t\tif (!target.IsValid() || target.Storage is null)\r\n\t\t\t\t\treturn;\r\n\r\n\t\t\t\t// Wiping the whole painted set has no undo, so this one asks first.\r\n\t\t\t\tDialog.AskConfirm(\r\n\t\t\t\t\t() =\u003E\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\ttarget.Storage.ClearAll();\r\n\t\t\t\t\t\ttarget.MarkDirty();\r\n\t\t\t\t\t},\r\n\t\t\t\t\t\u0022Are you sure you want to delete all flora? This action cannot be undone.\u0022,\r\n\t\t\t\t\t\u0022Delete All Flora\u0022,\r\n\t\t\t\t\t\u0022Delete\u0022,\r\n\t\t\t\t\t\u0022Cancel\u0022);\r\n\t\t\t};\r\n\t\t\tgroup.Add(clear);\r\n\t\t}\r\n\r\n\t\tsidebar.Layout.AddStretchCell();\r\n\r\n\t\treturn sidebar;\r\n\t}\r\n\r\n\tpublic override void OnUpdate()\r\n\t{\r\n\t\t_erasing = Gizmo.IsCtrlPressed;\r\n\r\n\t\tDrawBrushPreview();\r\n\r\n\t\tGizmo.Hitbox.BBox(BBox.FromPositionAndSize(Vector3.Zero, 999999));\r\n\r\n\t\tif (Gizmo.IsLeftMouseDown)\r\n\t\t{\r\n\t\t\tif (!_dragging)\r\n\t\t\t{\r\n\t\t\t\t_dragging = true;\r\n\t\t\t\t_lastPaintPosition = Vector3.Zero;\r\n\t\t\t}\r\n\r\n\t\t\tOnPaintUpdate();\r\n\t\t}\r\n\t\telse if (_dragging)\r\n\t\t{\r\n\t\t\t_dragging = false;\r\n\t\t\t_lastPaintPosition = Vector3.Zero;\r\n\r\n\t\t\tif (_painted)\r\n\t\t\t{\r\n\t\t\t\tResolveTarget()?.MarkDirty();\r\n\t\t\t\t_painted = false;\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Uses the selected renderer when there is one, otherwise the last used, otherwise the only one\r\n\t/// in the scene. Creating one implicitly would leave stray components behind every time someone\r\n\t/// opens the tool.\r\n\t/// \u003C/summary\u003E\r\n\tprivate FloraRenderer ResolveTarget()\r\n\t{\r\n\t\tvar selected = Selection\r\n\t\t\t.OfType\u003CGameObject\u003E()\r\n\t\t\t.Select(go =\u003E go.Components.Get\u003CFloraRenderer\u003E(FindMode.EnabledInSelfAndDescendants))\r\n\t\t\t.FirstOrDefault(r =\u003E r.IsValid());\r\n\r\n\t\tif (selected.IsValid())\r\n\t\t{\r\n\t\t\t_target = selected;\r\n\t\t\treturn _target;\r\n\t\t}\r\n\r\n\t\tif (_target.IsValid())\r\n\t\t\treturn _target;\r\n\r\n\t\t_target = Scene.GetAllComponents\u003CFloraRenderer\u003E().FirstOrDefault();\r\n\t\treturn _target;\r\n\t}\r\n\r\n\tprivate void OnPaintUpdate()\r\n\t{\r\n\t\tvar target = ResolveTarget();\r\n\t\tif (!target.IsValid() || target.Storage is null || !target.Definition.IsValid())\r\n\t\t\treturn;\r\n\r\n\t\tvar cursor = TraceCursor();\r\n\t\tif (!cursor.Hit)\r\n\t\t\treturn;\r\n\r\n\t\tif (_lastPaintPosition != Vector3.Zero \u0026\u0026\r\n\t\t\t Vector3.DistanceBetween(cursor.HitPosition, _lastPaintPosition) \u003C PaintStepDistance)\r\n\t\t\treturn;\r\n\r\n\t\t_lastPaintPosition = cursor.HitPosition;\r\n\r\n\t\tvar radius = (float)BrushSettings.Size;\r\n\t\tvar strength = BrushSettings.Opacity;\r\n\r\n\t\tif (_erasing)\r\n\t\t{\r\n\t\t\ttarget.Storage.Erase(cursor.HitPosition, radius, strength);\r\n\t\t\t_painted = true;\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tPaintCoverage(target, cursor.HitPosition, radius, strength);\r\n\t\t_painted = true;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Walks every coverage cell the brush touches and traces straight down onto the world, baking\r\n\t/// the surface height and normal so instances sit on whatever geometry is there. Nothing is\r\n\t/// placed here - the renderer derives the actual trunks from this coverage plus its seed.\r\n\t/// \u003C/summary\u003E\r\n\tprivate void PaintCoverage(FloraRenderer target, Vector3 center, float radius, float strength)\r\n\t{\r\n\t\tvar definition = target.Definition;\r\n\t\tvar storage = target.Storage;\r\n\r\n\t\tvar radiusSquared = radius * radius;\r\n\r\n\t\tvar minX = (int)MathF.Floor((center.x - radius) / FloraStorage.CellSize);\r\n\t\tvar maxX = (int)MathF.Floor((center.x \u002B radius) / FloraStorage.CellSize);\r\n\t\tvar minY = (int)MathF.Floor((center.y - radius) / FloraStorage.CellSize);\r\n\t\tvar maxY = (int)MathF.Floor((center.y \u002B radius) / FloraStorage.CellSize);\r\n\r\n\t\t// Enough headroom to find the surface from above without punching through overhangs the\r\n\t\t// brush was never aimed at.\r\n\t\tvar traceHeight = radius \u002B 2048.0f;\r\n\r\n\t\tfor (var cy = minY; cy \u003C= maxY; cy\u002B\u002B)\r\n\t\t{\r\n\t\t\tfor (var cx = minX; cx \u003C= maxX; cx\u002B\u002B)\r\n\t\t\t{\r\n\t\t\t\tvar wx = (cx \u002B 0.5f) * FloraStorage.CellSize;\r\n\t\t\t\tvar wy = (cy \u002B 0.5f) * FloraStorage.CellSize;\r\n\r\n\t\t\t\tvar dx = wx - center.x;\r\n\t\t\t\tvar dy = wy - center.y;\r\n\t\t\t\tvar distSq = dx * dx \u002B dy * dy;\r\n\r\n\t\t\t\tif (distSq \u003E radiusSquared)\r\n\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\tvar from = new Vector3(wx, wy, center.z \u002B traceHeight);\r\n\t\t\t\tvar to = new Vector3(wx, wy, center.z - traceHeight);\r\n\r\n\t\t\t\tvar tr = Scene.Trace.Ray(from, to)\r\n\t\t\t\t\t.UseRenderMeshes(true)\r\n\t\t\t\t\t.WithTag(\u0022solid\u0022)\r\n\t\t\t\t\t.Run();\r\n\r\n\t\t\t\tif (!tr.Hit)\r\n\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\tif (tr.Normal.z \u003C definition.SlopeLimit)\r\n\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t// Soft edge, so overlapping strokes build up smoothly instead of leaving a disc.\r\n\t\t\t\tvar falloff = 1.0f - MathF.Sqrt(distSq) / radius;\r\n\t\t\t\tvar added = strength * MathF.Pow(falloff, 0.5f);\r\n\r\n\t\t\t\tvar existing = storage.GetCell(wx, wy).Density;\r\n\t\t\t\tvar density = Math.Clamp(existing \u002B added, 0.0f, 1.0f);\r\n\r\n\t\t\t\tstorage.SetCell(wx, wy, density, tr.HitPosition.z, tr.Normal, _entryIndex);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Fills the entry dropdown from the target definition. Rebuilt on demand, since entries can be\r\n\t/// added or changed while the tool is open.\r\n\t/// \u003C/summary\u003E\r\n\tprivate void RebuildEntryOptions()\r\n\t{\r\n\t\tif (_entryDropdown is null)\r\n\t\t\treturn;\r\n\r\n\t\t_entryDropdown.Clear();\r\n\t\t_entryDropdown.AddItem(\u0022Mixed (by weight)\u0022, \u0022shuffle\u0022, () =\u003E _entryIndex = MixedEntryIndex);\r\n\r\n\t\tvar definition = ResolveTarget()?.Definition;\r\n\t\tif (!definition.IsValid() || definition.Entries is null)\r\n\t\t\treturn;\r\n\r\n\t\tfor (var i = 0; i \u003C definition.Entries.Count; i\u002B\u002B)\r\n\t\t{\r\n\t\t\tvar entry = definition.Entries[i];\r\n\t\t\tif (entry?.HasModel is not true)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tvar index = i;\r\n\t\t\tvar name = System.IO.Path.GetFileNameWithoutExtension(entry.Model.ResourcePath);\r\n\r\n\t\t\t_entryDropdown.AddItem(name, \u0022park\u0022, () =\u003E _entryIndex = index);\r\n\t\t}\r\n\t}\r\n\r\n\tprivate SceneTraceResult TraceCursor() =\u003E\r\n\t\tScene.Trace.Ray(Gizmo.CurrentRay, 100000)\r\n\t\t\t.UseRenderMeshes(true)\r\n\t\t\t.WithTag(\u0022solid\u0022)\r\n\t\t\t.Run();\r\n\r\n\tprivate void DrawBrushPreview()\r\n\t{\r\n\t\tvar tr = TraceCursor();\r\n\t\tif (!tr.Hit)\r\n\t\t\treturn;\r\n\r\n\t\tusing (Gizmo.Scope(\u0022FloraBrush\u0022))\r\n\t\t{\r\n\t\t\tGizmo.Draw.Color = _erasing\r\n\t\t\t\t? Color.FromBytes(250, 150, 150)\r\n\t\t\t\t: Color.FromBytes(160, 230, 150);\r\n\r\n\t\t\tGizmo.Draw.LineCircle(tr.HitPosition \u002B tr.Normal * 1.0f, tr.Normal, BrushSettings.Size);\r\n\t\t\tGizmo.Draw.LineCircle(tr.HitPosition \u002B tr.Normal * 1.0f, tr.Normal, BrushSettings.Size * 0.5f);\r\n\t\t}\r\n\t}\r\n}\r\n"},{"Ident":"redsnail.floratool","Path":"Code/FloraRenderer.cs","FileName":"FloraRenderer.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":421873,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing Sandbox;\r\n\r\nnamespace RedSnail.FloraTool;\r\n\r\n/// \u003Csummary\u003E\r\n/// Renders painted flora. Coverage is stored per chunk and instances are regenerated from it plus\r\n/// \u003Csee cref=\u0022Seed\u0022/\u003E, so the scene file holds a density map rather than a transform per tree - the\r\n/// difference between a few megabytes and something a repository will refuse.\r\n///\r\n/// Chunks become scene objects only within the definition\u0027s stream radius. Scene objects rather than\r\n/// a hand-rolled instanced draw because they take part in every pass the engine runs: the depth\r\n/// prepass, the shadow cascades, and per-object LOD using the model\u0027s own compiled distances.\r\n/// Standard instancing still batches them into few draw calls.\r\n/// \u003C/summary\u003E\r\n[Icon(\u0022park\u0022), Group(\u0022Flora\u0022), Title(\u0022Flora Renderer\u0022)]\r\npublic sealed partial class FloraRenderer : Component, Component.ExecuteInEditor, Component.DontExecuteOnServer\r\n{\r\n\t/// \u003Csummary\u003EA chunk\u0027s generated instances and the scene objects currently standing for them.\u003C/summary\u003E\r\n\tprivate sealed class LiveChunk\r\n\t{\r\n\t\tpublic List\u003CFloraGenerator.Instance\u003E Instances = [];\r\n\t\tpublic List\u003CSceneObject\u003E SceneObjects = [];\r\n\r\n\t\t/// \u003Csummary\u003E\r\n\t\t/// Whether this chunk is currently allowed to cast. Tracked so the flags are only touched\r\n\t\t/// when a chunk crosses the shadow boundary, rather than every object every frame.\r\n\t\t/// \u003C/summary\u003E\r\n\t\tpublic bool ShadowsEnabled = true;\r\n\t}\r\n\r\n\t[Property, Group(\u0022General\u0022)]\r\n\tpublic FloraDefinition Definition { get; set; }\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Decides exactly where each instance lands within the painted coverage. Change it to reshuffle\r\n\t/// a whole forest without repainting; keep it fixed and the same trees stand in the same places\r\n\t/// every run, on every machine.\r\n\t/// \u003C/summary\u003E\r\n\t[Property, Group(\u0022General\u0022)]\r\n\tpublic int Seed\r\n\t{\r\n\t\tget =\u003E field;\r\n\t\tset\r\n\t\t{\r\n\t\t\tif (field == value) return;\r\n\t\t\tfield = value;\r\n\t\t\tMarkDirty();\r\n\t\t}\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EPainted coverage. Serialized as a binary blob, not JSON.\u003C/summary\u003E\r\n\t[Property, Hide]\r\n\tpublic FloraStorage Storage { get; set; } = new();\r\n\r\n\tprivate readonly Dictionary\u003CFloraStorage.ChunkCoord, LiveChunk\u003E _live = [];\r\n\tprivate readonly List\u003CFloraStorage.ChunkCoord\u003E _wantedChunks = [];\r\n\tprivate readonly List\u003CFloraStorage.ChunkCoord\u003E _staleChunks = [];\r\n\r\n\t// Reused across chunk builds so streaming doesn\u0027t allocate a fresh list per chunk.\r\n\tprivate readonly List\u003CFloraGenerator.Instance\u003E _scratchInstances = [];\r\n\r\n\tprivate int _builtRevision = -1;\r\n\tprivate Vector3 _lastStreamOrigin;\r\n\tprivate bool _hasStreamOrigin;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Restreaming walks every painted chunk, so it only happens once the viewer has moved far enough\r\n\t/// for the answer to have changed. A fraction of a chunk keeps the boundary from thrashing.\r\n\t/// \u003C/summary\u003E\r\n\tprivate const float StreamRefreshDistance = FloraStorage.ChunkSize * 0.25f;\r\n\r\n\tprotected override void OnEnabled()\r\n\t{\r\n\t\tStorage ??= new FloraStorage();\r\n\r\n\t\t// Scene objects were deleted on disable, so a matching revision would leave us thinking the\r\n\t\t// world is already built when nothing is in it.\r\n\t\t_builtRevision = -1;\r\n\t\t_hasStreamOrigin = false;\r\n\t}\r\n\r\n\tprotected override void OnDisabled()\r\n\t{\r\n\t\tReleaseAllChunks();\r\n\t\tReleaseCollision();\r\n\r\n\t\t_builtRevision = -1;\r\n\t\t_hasStreamOrigin = false;\r\n\t}\r\n\r\n\tprotected override void OnUpdate()\r\n\t{\r\n\t\tvar viewer = GetViewerPosition();\r\n\t\tif (!viewer.HasValue)\r\n\t\t\treturn;\r\n\r\n\t\tUpdateStreaming(viewer.Value);\r\n\t\tUpdateCollision(viewer.Value);\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// What streaming follows. While editing that is the viewport camera, so flora appears around\r\n\t/// what you are looking at rather than wherever the game camera is parked.\r\n\t/// \u003C/summary\u003E\r\n\tprivate Vector3? GetViewerPosition()\r\n\t{\r\n\t\tif (Scene.IsEditor)\r\n\t\t{\r\n\t\t\tvar editorCamera = Application.Editor?.Camera;\r\n\t\t\tif (editorCamera.IsValid())\r\n\t\t\t\treturn editorCamera.WorldPosition;\r\n\t\t}\r\n\r\n\t\treturn Scene.Camera.IsValid() ? Scene.Camera.WorldPosition : null;\r\n\t}\r\n\r\n\tprivate void UpdateStreaming(Vector3 origin)\r\n\t{\r\n\t\tif (Storage is null || !Definition.IsValid())\r\n\t\t{\r\n\t\t\tReleaseAllChunks();\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\t// Painting or reseeding invalidates everything regardless of whether the viewer moved.\r\n\t\tvar dirty = _builtRevision != Storage.Revision;\r\n\r\n\t\tif (!dirty \u0026\u0026 _hasStreamOrigin \u0026\u0026 origin.Distance(_lastStreamOrigin) \u003C StreamRefreshDistance)\r\n\t\t\treturn;\r\n\r\n\t\tif (dirty)\r\n\t\t{\r\n\t\t\tReleaseAllChunks();\r\n\t\t\t_builtRevision = Storage.Revision;\r\n\t\t}\r\n\r\n\t\t_lastStreamOrigin = origin;\r\n\t\t_hasStreamOrigin = true;\r\n\r\n\t\tGatherWantedChunks(origin);\r\n\t\tSyncChunks(origin);\r\n\t}\r\n\r\n\tprivate void GatherWantedChunks(Vector3 origin)\r\n\t{\r\n\t\t_wantedChunks.Clear();\r\n\r\n\t\t// A chunk\u0027s near corner can be in range while its centre is not, hence the circumradius.\r\n\t\tvar radius = Definition.StreamRadius \u002B FloraStorage.ChunkSize * 0.7072f;\r\n\t\tvar radiusSquared = radius * radius;\r\n\r\n\t\tforeach (var (coord, _) in Storage.Chunks)\r\n\t\t{\r\n\t\t\tvar center = FloraStorage.ChunkCenter(coord);\r\n\r\n\t\t\tvar dx = center.x - origin.x;\r\n\t\t\tvar dy = center.y - origin.y;\r\n\r\n\t\t\tif (dx * dx \u002B dy * dy \u003E radiusSquared)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\t_wantedChunks.Add(coord);\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void SyncChunks(Vector3 origin)\r\n\t{\r\n\t\t_staleChunks.Clear();\r\n\r\n\t\tforeach (var (coord, _) in _live)\r\n\t\t{\r\n\t\t\tif (!_wantedChunks.Contains(coord))\r\n\t\t\t\t_staleChunks.Add(coord);\r\n\t\t}\r\n\r\n\t\tforeach (var coord in _staleChunks)\r\n\t\t\tReleaseChunk(coord);\r\n\r\n\t\tforeach (var coord in _wantedChunks)\r\n\t\t{\r\n\t\t\tif (_live.ContainsKey(coord))\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tBuildChunk(coord, origin);\r\n\t\t}\r\n\r\n\t\tUpdateChunkShadows(origin);\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Turns shadow casting off for chunks past the shadow distance. Evaluated per chunk rather than\r\n\t/// per instance, and only written when a chunk actually crosses the boundary, so a stationary\r\n\t/// camera costs nothing here.\r\n\t/// \u003C/summary\u003E\r\n\tprivate void UpdateChunkShadows(Vector3 origin)\r\n\t{\r\n\t\tforeach (var (coord, chunk) in _live)\r\n\t\t{\r\n\t\t\tvar wanted = ChunkCastsShadows(coord, origin);\r\n\t\t\tif (wanted == chunk.ShadowsEnabled)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tchunk.ShadowsEnabled = wanted;\r\n\t\t\tApplyChunkShadows(chunk);\r\n\t\t}\r\n\t}\r\n\r\n\tprivate bool ChunkCastsShadows(FloraStorage.ChunkCoord coord, Vector3 origin)\r\n\t{\r\n\t\tvar distance = Definition.ShadowDistance;\r\n\t\tif (distance \u003C= 0.0f)\r\n\t\t\treturn true;\r\n\r\n\t\t// Measured to the chunk\u0027s near edge via its circumradius, so a chunk is only cut off once all\r\n\t\t// of it is beyond the limit.\r\n\t\tvar limit = distance \u002B FloraStorage.ChunkSize * 0.7072f;\r\n\r\n\t\tvar center = FloraStorage.ChunkCenter(coord);\r\n\t\tvar dx = center.x - origin.x;\r\n\t\tvar dy = center.y - origin.y;\r\n\r\n\t\treturn dx * dx \u002B dy * dy \u003C= limit * limit;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The per-entry CastShadows setting is the ceiling - distance can only ever take shadows away,\r\n\t/// never grant them to an entry the artist turned them off for.\r\n\t/// \u003C/summary\u003E\r\n\tprivate void ApplyChunkShadows(LiveChunk chunk)\r\n\t{\r\n\t\tfor (var i = 0; i \u003C chunk.SceneObjects.Count \u0026\u0026 i \u003C chunk.Instances.Count; i\u002B\u002B)\r\n\t\t{\r\n\t\t\tvar sceneObject = chunk.SceneObjects[i];\r\n\t\t\tif (!sceneObject.IsValid())\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tvar entry = Definition.GetEntry(chunk.Instances[i].EntryIndex);\r\n\t\t\tsceneObject.Flags.CastShadows = chunk.ShadowsEnabled \u0026\u0026 entry?.CastShadows is true;\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void BuildChunk(FloraStorage.ChunkCoord coord, Vector3 origin)\r\n\t{\r\n\t\tif (!Storage.Chunks.TryGetValue(coord, out var cells))\r\n\t\t\treturn;\r\n\r\n\t\tvar world = Scene.SceneWorld;\r\n\t\tif (!world.IsValid())\r\n\t\t\treturn;\r\n\r\n\t\tvar chunk = new LiveChunk();\r\n\t\tchunk.ShadowsEnabled = ChunkCastsShadows(coord, origin);\r\n\r\n\t\t_scratchInstances.Clear();\r\n\t\tFloraGenerator.GenerateChunk(coord, cells, Definition, Seed, _scratchInstances);\r\n\r\n\t\t// Instances and scene objects are kept strictly parallel - anything whose entry no longer\r\n\t\t// resolves is dropped from both. Skipping only the scene object would slide the two lists out\r\n\t\t// of step, and the shadow and collision paths index one by the other.\r\n\t\tfor (var i = 0; i \u003C _scratchInstances.Count; i\u002B\u002B)\r\n\t\t{\r\n\t\t\tvar instance = _scratchInstances[i];\r\n\r\n\t\t\tvar entry = Definition.GetEntry(instance.EntryIndex);\r\n\t\t\tif (entry is null)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tvar sceneObject = new SceneObject(world, entry.Model, instance.ToTransform());\r\n\t\t\tsceneObject.Flags.CastShadows = chunk.ShadowsEnabled \u0026\u0026 entry.CastShadows;\r\n\r\n\t\t\tchunk.Instances.Add(instance);\r\n\t\t\tchunk.SceneObjects.Add(sceneObject);\r\n\t\t}\r\n\r\n\t\t_live[coord] = chunk;\r\n\t}\r\n\r\n\tprivate void ReleaseChunk(FloraStorage.ChunkCoord coord)\r\n\t{\r\n\t\tif (!_live.Remove(coord, out var chunk))\r\n\t\t\treturn;\r\n\r\n\t\tforeach (var sceneObject in chunk.SceneObjects)\r\n\t\t{\r\n\t\t\tif (sceneObject.IsValid())\r\n\t\t\t\tsceneObject.Delete();\r\n\t\t}\r\n\r\n\t\tchunk.SceneObjects.Clear();\r\n\t\tchunk.Instances.Clear();\r\n\t}\r\n\r\n\tprivate void ReleaseAllChunks()\r\n\t{\r\n\t\tforeach (var (_, chunk) in _live)\r\n\t\t{\r\n\t\t\tforeach (var sceneObject in chunk.SceneObjects)\r\n\t\t\t{\r\n\t\t\t\tif (sceneObject.IsValid())\r\n\t\t\t\t\tsceneObject.Delete();\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\t_live.Clear();\r\n\t\t_wantedChunks.Clear();\r\n\t\t_staleChunks.Clear();\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Called by the editor tool after painting, so the next frame regenerates. Also fires when the\r\n\t/// seed changes.\r\n\t/// \u003C/summary\u003E\r\n\tpublic void MarkDirty()\r\n\t{\r\n\t\t_builtRevision = -1;\r\n\t\t_hasStreamOrigin = false;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003ETotal instances currently streamed in. Useful when tuning density and stream radius.\u003C/summary\u003E\r\n\tpublic int LiveInstanceCount\r\n\t{\r\n\t\tget\r\n\t\t{\r\n\t\t\tvar count = 0;\r\n\t\t\tforeach (var (_, chunk) in _live)\r\n\t\t\t\tcount \u002B= chunk.SceneObjects.Count;\r\n\t\t\treturn count;\r\n\t\t}\r\n\t}\r\n\r\n\tprotected override void DrawGizmos()\r\n\t{\r\n\t\tif (!Gizmo.IsSelected || Storage is null || Storage.ChunkCount == 0)\r\n\t\t\treturn;\r\n\r\n\t\tGizmo.Draw.Color = Color.Green.WithAlpha(0.25f);\r\n\r\n\t\tforeach (var (coord, _) in Storage.Chunks)\r\n\t\t{\r\n\t\t\tvar origin = FloraStorage.ChunkOrigin(coord);\r\n\r\n\t\t\tvar mins = WorldTransform.PointToLocal(new Vector3(origin.x, origin.y, 0));\r\n\t\t\tvar maxs = WorldTransform.PointToLocal(new Vector3(\r\n\t\t\t\torigin.x \u002B FloraStorage.ChunkSize, origin.y \u002B FloraStorage.ChunkSize, 0));\r\n\r\n\t\t\tGizmo.Draw.LineBBox(new BBox(mins, maxs));\r\n\t\t}\r\n\t}\r\n}\r\n"},{"Ident":"redsnail.floratool","Path":"Code/FloraGenerator.cs","FileName":"FloraGenerator.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":421873,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing Sandbox;\r\n\r\nnamespace RedSnail.FloraTool;\r\n\r\n/// \u003Csummary\u003E\r\n/// Turns painted coverage into concrete instances. Everything here is a pure function of the chunk\r\n/// coordinate, the cell contents and the seed - no state, no RNG object - so a chunk regenerates\r\n/// identically every run, on every machine, however many times it is streamed in and out.\r\n/// \u003C/summary\u003E\r\npublic static class FloraGenerator\r\n{\r\n\tpublic readonly record struct Instance(int EntryIndex, Vector3 Position, Rotation Rotation, float Scale)\r\n\t{\r\n\t\tpublic readonly Transform ToTransform() =\u003E new(Position, Rotation, Scale);\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Integer avalanche hash. Deterministic across runs and platforms, which the framework RNG is\r\n\t/// not guaranteed to be, and cheap enough to call several times per instance.\r\n\t/// \u003C/summary\u003E\r\n\tprivate static uint Hash(uint x)\r\n\t{\r\n\t\tx ^= x \u003E\u003E 16;\r\n\t\tx *= 0x7feb352du;\r\n\t\tx ^= x \u003E\u003E 15;\r\n\t\tx *= 0x846ca68bu;\r\n\t\tx ^= x \u003E\u003E 16;\r\n\t\treturn x;\r\n\t}\r\n\r\n\tprivate static float HashFloat(uint x) =\u003E Hash(x) * (1.0f / 4294967296.0f);\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Generates every instance for one chunk, appending into \u003Cparamref name=\u0022results\u0022/\u003E.\r\n\t/// \u003C/summary\u003E\r\n\tpublic static void GenerateChunk(FloraStorage.ChunkCoord coord, FloraStorage.Cell[] cells,\r\n\t\tFloraDefinition definition, int seed, List\u003CInstance\u003E results)\r\n\t{\r\n\t\tif (cells is null || definition is null)\r\n\t\t\treturn;\r\n\r\n\t\tvar origin = FloraStorage.ChunkOrigin(coord);\r\n\t\tvar maxPerCell = Math.Max(definition.MaxPerCell, 1);\r\n\r\n\t\t// Mixing the chunk coordinate into the seed keeps neighbouring chunks from sharing a\r\n\t\t// sequence, which would otherwise show up as a visible repeating pattern across the world.\r\n\t\tvar chunkSeed = Hash((uint)seed\r\n\t\t\t^ Hash((uint)coord.X * 73856093u)\r\n\t\t\t^ Hash((uint)coord.Y * 19349663u));\r\n\r\n\t\tfor (var cellIndex = 0; cellIndex \u003C cells.Length; cellIndex\u002B\u002B)\r\n\t\t{\r\n\t\t\tvar cell = cells[cellIndex];\r\n\r\n\t\t\tvar density = cell.Density;\r\n\t\t\tif (density \u003C= 0.0f)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tif (cell.Normal.z \u003C definition.SlopeLimit)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tvar cellSeed = Hash(chunkSeed ^ Hash((uint)cellIndex * 0x9e3779b9u));\r\n\r\n\t\t\tvar cx = cellIndex % FloraStorage.ChunkResolution;\r\n\t\t\tvar cy = cellIndex / FloraStorage.ChunkResolution;\r\n\r\n\t\t\tvar cellMinX = origin.x \u002B cx * FloraStorage.CellSize;\r\n\t\t\tvar cellMinY = origin.y \u002B cy * FloraStorage.CellSize;\r\n\r\n\t\t\t// Fractional counts are resolved by a hash rather than rounding, so density reads as a\r\n\t\t\t// smooth thinning across a field instead of stepping between whole numbers per cell.\r\n\t\t\tvar exact = density * maxPerCell;\r\n\t\t\tvar count = (int)exact;\r\n\t\t\tif (HashFloat(cellSeed ^ 0x1b56c4e9u) \u003C exact - count)\r\n\t\t\t\tcount\u002B\u002B;\r\n\r\n\t\t\tfor (var i = 0; i \u003C count; i\u002B\u002B)\r\n\t\t\t{\r\n\t\t\t\tvar s = Hash(cellSeed \u002B (uint)i * 0x85ebca6bu);\r\n\r\n\t\t\t\tvar entry = ResolveEntry(definition, cell.EntryIndex, s);\r\n\t\t\t\tif (entry.Index \u003C 0)\r\n\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\tresults.Add(BuildInstance(entry.Index, entry.Entry, cell, s, cellMinX, cellMinY));\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// A cell either names its entry - painted deliberately with one species selected - or defers to\r\n\t/// the definition\u0027s weights.\r\n\t/// \u003C/summary\u003E\r\n\tprivate static (int Index, FloraEntry Entry) ResolveEntry(FloraDefinition definition, int cellEntryIndex, uint seed)\r\n\t{\r\n\t\tvar entries = definition.Entries;\r\n\t\tif (entries is null || entries.Count == 0)\r\n\t\t\treturn (-1, null);\r\n\r\n\t\tif (cellEntryIndex \u003C entries.Count)\r\n\t\t{\r\n\t\t\tvar named = entries[cellEntryIndex];\r\n\t\t\treturn named?.HasModel is true ? (cellEntryIndex, named) : (-1, null);\r\n\t\t}\r\n\r\n\t\tvar total = 0.0f;\r\n\t\tfor (var i = 0; i \u003C entries.Count; i\u002B\u002B)\r\n\t\t{\r\n\t\t\tif (entries[i]?.HasModel is true \u0026\u0026 entries[i].Weight \u003E 0.0f)\r\n\t\t\t\ttotal \u002B= entries[i].Weight;\r\n\t\t}\r\n\r\n\t\tif (total \u003C= 0.0f)\r\n\t\t\treturn (-1, null);\r\n\r\n\t\tvar pick = HashFloat(seed ^ 0x3c6ef372u) * total;\r\n\r\n\t\tfor (var i = 0; i \u003C entries.Count; i\u002B\u002B)\r\n\t\t{\r\n\t\t\tvar entry = entries[i];\r\n\t\t\tif (entry?.HasModel is not true || entry.Weight \u003C= 0.0f)\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tpick -= entry.Weight;\r\n\t\t\tif (pick \u003C= 0.0f)\r\n\t\t\t\treturn (i, entry);\r\n\t\t}\r\n\r\n\t\treturn (-1, null);\r\n\t}\r\n\r\n\tprivate static Instance BuildInstance(int entryIndex, FloraEntry entry, FloraStorage.Cell cell,\r\n\t\tuint seed, float cellMinX, float cellMinY)\r\n\t{\r\n\t\tvar jitterX = HashFloat(seed ^ 0x68bc21ebu);\r\n\t\tvar jitterY = HashFloat(seed ^ 0x02e5be93u);\r\n\r\n\t\tvar x = cellMinX \u002B jitterX * FloraStorage.CellSize;\r\n\t\tvar y = cellMinY \u002B jitterY * FloraStorage.CellSize;\r\n\r\n\t\tvar normal = cell.Normal;\r\n\r\n\t\t// The baked height is the cell centre\u0027s, so a slope needs the offset carried across to the\r\n\t\t// jittered position or trunks float on the uphill side and sink on the downhill one.\r\n\t\tvar offsetX = x - (cellMinX \u002B FloraStorage.CellSize * 0.5f);\r\n\t\tvar offsetY = y - (cellMinY \u002B FloraStorage.CellSize * 0.5f);\r\n\t\tvar z = cell.Height - (normal.x * offsetX \u002B normal.y * offsetY) / MathF.Max(normal.z, 0.1f);\r\n\r\n\t\tvar position = new Vector3(x, y, z);\r\n\t\tif (entry.SinkDepth \u003E 0.0f)\r\n\t\t\tposition -= normal * entry.SinkDepth;\r\n\r\n\t\tvar rotation = entry.RandomYaw\r\n\t\t\t? Rotation.FromYaw(HashFloat(seed ^ 0x7f4a7c15u) * 360.0f)\r\n\t\t\t: Rotation.Identity;\r\n\r\n\t\tif (entry.AlignToNormal \u003E 0.0f)\r\n\t\t{\r\n\t\t\tvar aligned = Rotation.LookAt(normal) * Rotation.FromPitch(90.0f);\r\n\t\t\trotation = Rotation.Slerp(rotation, aligned * rotation, entry.AlignToNormal);\r\n\t\t}\r\n\r\n\t\tif (entry.RandomTilt \u003E 0.0f)\r\n\t\t{\r\n\t\t\tvar tiltAngle = HashFloat(seed ^ 0x165667b1u) * entry.RandomTilt;\r\n\t\t\tvar tiltDirection = HashFloat(seed ^ 0x27d4eb2fu) * 360.0f;\r\n\t\t\trotation *= Rotation.FromAxis(Rotation.FromYaw(tiltDirection).Forward, tiltAngle);\r\n\t\t}\r\n\r\n\t\tvar scale = MathX.Lerp(entry.Scale.Min, entry.Scale.Max, HashFloat(seed ^ 0xd3a2646cu));\r\n\r\n\t\treturn new Instance(entryIndex, position, rotation, scale);\r\n\t}\r\n}\r\n"},{"Ident":"redsnail.floratool","Path":"FloraDefinition.cs","FileName":"FloraDefinition.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":421873,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing Sandbox;\r\n\r\nnamespace RedSnail.FloraTool;\r\n\r\n/// \u003Csummary\u003E\r\n/// One kind of flora the brush can plant. Weight decides how often it comes up relative to the\r\n/// other entries in the definition.\r\n/// \u003C/summary\u003E\r\npublic sealed class FloraEntry\r\n{\r\n\t[Property]\r\n\tpublic Model Model { get; set; }\r\n\r\n\t/// \u003Csummary\u003ERelative chance of this entry being picked. Zero excludes it without deleting it.\u003C/summary\u003E\r\n\t[Property, Range(0, 10)]\r\n\tpublic float Weight { get; set; } = 1.0f;\r\n\r\n\t[Property]\r\n\tpublic RangedFloat Scale { get; set; } = new(0.85f, 1.25f);\r\n\r\n\t/// \u003Csummary\u003ERandom spin about the vertical axis, so repeated instances don\u0027t read as clones.\u003C/summary\u003E\r\n\t[Property]\r\n\tpublic bool RandomYaw { get; set; } = true;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Tilts the instance toward the surface normal. Right for rocks and bushes, usually wrong for\r\n\t/// trees - a trunk growing perpendicular to a hillside looks broken.\r\n\t/// \u003C/summary\u003E\r\n\t[Property, Range(0, 1)]\r\n\tpublic float AlignToNormal { get; set; } = 0.0f;\r\n\r\n\t/// \u003Csummary\u003ERandom lean away from vertical, in degrees. A little goes a long way on trees.\u003C/summary\u003E\r\n\t[Property, Range(0, 45)]\r\n\tpublic float RandomTilt { get; set; } = 0.0f;\r\n\r\n\t/// \u003Csummary\u003ESinks the instance into the ground, hiding the seam where the base meets the surface.\u003C/summary\u003E\r\n\t[Property, Range(0, 64)]\r\n\tpublic float SinkDepth { get; set; } = 0.0f;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Gives this entry real collision. Colliders are only created near the player, so this is about\r\n\t/// whether the flora is solid at all - not about paying for every painted instance at once.\r\n\t/// \u003C/summary\u003E\r\n\t[Property, Group(\u0022Physics\u0022)]\r\n\tpublic bool EnablePhysics { get; set; } = true;\r\n\r\n\t[Property, Group(\u0022Rendering\u0022)]\r\n\tpublic bool CastShadows { get; set; } = true;\r\n\r\n\tpublic bool HasModel =\u003E Model is not null \u0026\u0026 !string.IsNullOrEmpty(Model.ResourcePath);\r\n}\r\n\r\n/// \u003Csummary\u003E\r\n/// A palette of flora plus the rules used when painting it. Shared by every\r\n/// \u003Csee cref=\u0022FloraRenderer\u0022/\u003E that references it, so a whole world can be retuned from one asset.\r\n/// \u003C/summary\u003E\r\n[AssetType(Name = \u0022Flora Definition\u0022, Extension = \u0022floradef\u0022, Category = \u0022Flora\u0022)]\r\npublic sealed class FloraDefinition : GameResource\r\n{\r\n\t[Property]\r\n\tpublic List\u003CFloraEntry\u003E Entries { get; set; } = [];\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Instances a fully painted cell can hold. Coverage scales this, so it sets the ceiling on how\r\n\t/// tightly flora can pack - raise it for undergrowth, leave it low for trees.\r\n\t/// \u003C/summary\u003E\r\n\t[Property, Group(\u0022Painting\u0022), Range(1, 16)]\r\n\tpublic int MaxPerCell { get; set; } = 2;\r\n\r\n\t/// \u003Csummary\u003EMinimum ground normal Z. Steeper than this and nothing plants, so cliffs stay bare.\u003C/summary\u003E\r\n\t[Property, Group(\u0022Painting\u0022), Range(0, 1)]\r\n\tpublic float SlopeLimit { get; set; } = 0.6f;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Radius around the viewer within which chunks are turned into scene objects. Chunks beyond it\r\n\t/// keep their painted coverage but cost nothing to render.\r\n\t/// \u003C/summary\u003E\r\n\t[Property, Group(\u0022Streaming\u0022), Range(2000, 100000)]\r\n\tpublic float StreamRadius { get; set; } = 25000.0f;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Distance past which flora stops casting shadows. Shadow cascades ignore the view frustum, so\r\n\t/// distant trees are rendered into them whichever way the camera faces - dropping them is one of\r\n\t/// the few savings that applies even when you are looking away.\r\n\t///\r\n\t/// Set it too low and you will see shadows wink out as chunks cross the boundary, most obviously\r\n\t/// under a low sun where far geometry casts long shadows into view. Zero disables the cutoff.\r\n\t/// \u003C/summary\u003E\r\n\t[Property, Group(\u0022Streaming\u0022), Range(0, 50000)]\r\n\tpublic float ShadowDistance { get; set; } = 10000.0f;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Radius around the viewer within which entries flagged \u003Csee cref=\u0022FloraEntry.EnablePhysics\u0022/\u003E\r\n\t/// get real colliders. Keep it just past where the player can reach.\r\n\t/// \u003C/summary\u003E\r\n\t[Property, Group(\u0022Physics\u0022), Range(256, 20000)]\r\n\tpublic float CollisionRadius { get; set; } = 4000.0f;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// The entry at an index, or null when the index no longer resolves - entries can be removed\r\n\t/// after coverage has already been painted naming them.\r\n\t/// \u003C/summary\u003E\r\n\tpublic FloraEntry GetEntry(int index)\r\n\t{\r\n\t\tif (Entries is null || index \u003C 0 || index \u003E= Entries.Count)\r\n\t\t\treturn null;\r\n\r\n\t\tvar entry = Entries[index];\r\n\t\treturn entry?.HasModel is true ? entry : null;\r\n\t}\r\n}\r\n"},{"Ident":"redsnail.floratool","Path":"FloraRenderer.Collision.cs","FileName":"FloraRenderer.Collision.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":421873,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing Sandbox;\r\n\r\nnamespace RedSnail.FloraTool;\r\n\r\n/// \u003Csummary\u003E\r\n/// Collision for painted flora. Instances only exist as scene objects, so nothing is solid until a\r\n/// collider is made for it - and those are made only for instances near the viewer and recycled as\r\n/// it moves, keeping physics cost tied to what is reachable rather than to the whole forest.\r\n/// \u003C/summary\u003E\r\npublic sealed partial class FloraRenderer\r\n{\r\n\tprivate readonly record struct CollisionKey(FloraStorage.ChunkCoord Chunk, int Index);\r\n\r\n\tprivate readonly Dictionary\u003CCollisionKey, GameObject\u003E _colliders = [];\r\n\r\n\t// A set rather than a list: SyncColliders tests every live collider against it, so a linear scan\r\n\t// there would be quadratic once a few hundred are in range.\r\n\tprivate readonly HashSet\u003CCollisionKey\u003E _wantedColliders = [];\r\n\tprivate readonly List\u003CCollisionKey\u003E _staleColliders = [];\r\n\r\n\tprivate GameObject _collisionRoot;\r\n\tprivate Vector3 _lastCollisionOrigin;\r\n\tprivate bool _hasCollisionOrigin;\r\n\tprivate int _collisionRevision = -1;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Rebuilding walks every streamed instance, so it only happens once the viewer has moved far\r\n\t/// enough for the answer to have changed.\r\n\t/// \u003C/summary\u003E\r\n\tprivate const float CollisionRefreshDistance = 256.0f;\r\n\r\n\tprivate void UpdateCollision(Vector3 origin)\r\n\t{\r\n\t\tif (!Definition.IsValid() || Definition.CollisionRadius \u003C= 0.0f)\r\n\t\t{\r\n\t\t\tReleaseCollision();\r\n\t\t\treturn;\r\n\t\t}\r\n\r\n\t\tvar storageChanged = Storage is null || _collisionRevision != Storage.Revision;\r\n\r\n\t\tif (!storageChanged \u0026\u0026 _hasCollisionOrigin \u0026\u0026\r\n\t\t\t origin.Distance(_lastCollisionOrigin) \u003C CollisionRefreshDistance)\r\n\t\t\treturn;\r\n\r\n\t\t_collisionRevision = Storage?.Revision ?? -1;\r\n\t\t_lastCollisionOrigin = origin;\r\n\t\t_hasCollisionOrigin = true;\r\n\r\n\t\tGatherWantedColliders(origin);\r\n\t\tSyncColliders();\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Only streamed chunks are considered. Collision radius should sit well inside the stream radius\r\n\t/// anyway, so anything outside it has no business being solid.\r\n\t/// \u003C/summary\u003E\r\n\tprivate void GatherWantedColliders(Vector3 origin)\r\n\t{\r\n\t\t_wantedColliders.Clear();\r\n\r\n\t\tvar radiusSquared = Definition.CollisionRadius * Definition.CollisionRadius;\r\n\r\n\t\tforeach (var (coord, chunk) in _live)\r\n\t\t{\r\n\t\t\tfor (var i = 0; i \u003C chunk.Instances.Count; i\u002B\u002B)\r\n\t\t\t{\r\n\t\t\t\tvar instance = chunk.Instances[i];\r\n\r\n\t\t\t\tif (instance.Position.DistanceSquared(origin) \u003E radiusSquared)\r\n\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\tvar entry = Definition.GetEntry(instance.EntryIndex);\r\n\t\t\t\tif (entry?.EnablePhysics is not true)\r\n\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\t_wantedColliders.Add(new CollisionKey(coord, i));\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tprivate void SyncColliders()\r\n\t{\r\n\t\t// Drop what fell out of range first, so those objects are free to be reused this same frame.\r\n\t\t_staleColliders.Clear();\r\n\r\n\t\tforeach (var (key, gameObject) in _colliders)\r\n\t\t{\r\n\t\t\tif (gameObject.IsValid() \u0026\u0026 _wantedColliders.Contains(key))\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\t_staleColliders.Add(key);\r\n\t\t}\r\n\r\n\t\tforeach (var key in _staleColliders)\r\n\t\t{\r\n\t\t\tif (_colliders.Remove(key, out var gameObject) \u0026\u0026 gameObject.IsValid())\r\n\t\t\t\tgameObject.Destroy();\r\n\t\t}\r\n\r\n\t\tforeach (var key in _wantedColliders)\r\n\t\t{\r\n\t\t\tif (_colliders.ContainsKey(key))\r\n\t\t\t\tcontinue;\r\n\r\n\t\t\tvar gameObject = CreateCollider(key);\r\n\t\t\tif (gameObject.IsValid())\r\n\t\t\t\t_colliders[key] = gameObject;\r\n\t\t}\r\n\t}\r\n\r\n\tprivate GameObject CreateCollider(CollisionKey key)\r\n\t{\r\n\t\tif (!_live.TryGetValue(key.Chunk, out var chunk))\r\n\t\t\treturn null;\r\n\r\n\t\tif (key.Index \u003C 0 || key.Index \u003E= chunk.Instances.Count)\r\n\t\t\treturn null;\r\n\r\n\t\tvar instance = chunk.Instances[key.Index];\r\n\r\n\t\tvar entry = Definition.GetEntry(instance.EntryIndex);\r\n\t\tif (entry is null)\r\n\t\t\treturn null;\r\n\r\n\t\tEnsureCollisionRoot();\r\n\r\n\t\tvar gameObject = new GameObject(true, \u0022FloraCollider\u0022)\r\n\t\t{\r\n\t\t\tParent = _collisionRoot,\r\n\t\t\tWorldTransform = instance.ToTransform(),\r\n\t\t};\r\n\r\n\t\t// Not saved with the scene and not shown in the hierarchy - these are transient physics\r\n\t\t// proxies for geometry that is regenerated from the seed anyway.\r\n\t\tgameObject.Flags |= GameObjectFlags.NotSaved | GameObjectFlags.Hidden;\r\n\r\n\t\tvar collider = gameObject.Components.Create\u003CModelCollider\u003E();\r\n\t\tcollider.Model = entry.Model;\r\n\t\tcollider.Static = true;\r\n\r\n\t\treturn gameObject;\r\n\t}\r\n\r\n\tprivate void EnsureCollisionRoot()\r\n\t{\r\n\t\tif (_collisionRoot.IsValid())\r\n\t\t\treturn;\r\n\r\n\t\t_collisionRoot = new GameObject(true, \u0022Flora Colliders\u0022) { Parent = GameObject };\r\n\t\t_collisionRoot.Flags |= GameObjectFlags.NotSaved | GameObjectFlags.Hidden;\r\n\t}\r\n\r\n\tprivate void ReleaseCollision()\r\n\t{\r\n\t\tforeach (var (_, gameObject) in _colliders)\r\n\t\t{\r\n\t\t\tif (gameObject.IsValid())\r\n\t\t\t\tgameObject.Destroy();\r\n\t\t}\r\n\r\n\t\t_colliders.Clear();\r\n\t\t_wantedColliders.Clear();\r\n\t\t_staleColliders.Clear();\r\n\r\n\t\tif (_collisionRoot.IsValid())\r\n\t\t\t_collisionRoot.Destroy();\r\n\r\n\t\t_collisionRoot = null;\r\n\t\t_hasCollisionOrigin = false;\r\n\t\t_collisionRevision = -1;\r\n\t}\r\n}\r\n"},{"Ident":"redsnail.floratool","Path":"FloraStorage.cs","FileName":"FloraStorage.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":421873,"IsPrivate":false,"Code":"using System;\r\nusing System.Collections.Generic;\r\nusing Sandbox;\r\n\r\nnamespace RedSnail.FloraTool;\r\n\r\n/// \u003Csummary\u003E\r\n/// Painted flora coverage, stored as a sparse chunked grid of density samples rather than one\r\n/// transform per tree. Instances are regenerated from this plus a seed, so a forest of a hundred\r\n/// thousand trees costs a few megabytes instead of tens - which matters because the scene sidecar\r\n/// has to survive being committed to a repository.\r\n///\r\n/// The trade is that positions are derived, not authored: painting decides where flora *can* grow\r\n/// and how densely, and the seed decides exactly where each trunk lands.\r\n/// \u003C/summary\u003E\r\npublic sealed class FloraStorage : BlobData\r\n{\r\n\tpublic override int Version =\u003E 1;\r\n\r\n\t/// \u003Csummary\u003ECells along one edge of a chunk.\u003C/summary\u003E\r\n\tpublic const int ChunkResolution = 32;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// World size of one density cell. Roughly a tree\u0027s footprint - each cell holds at most a\r\n\t/// handful of instances, so this is what bounds how tightly flora can pack.\r\n\t/// Changing it invalidates every painted scene, so it is a constant rather than a setting.\r\n\t/// \u003C/summary\u003E\r\n\tpublic const float CellSize = 256.0f;\r\n\r\n\tpublic const float ChunkSize = ChunkResolution * CellSize;\r\n\r\n\tpublic const int CellsPerChunk = ChunkResolution * ChunkResolution;\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// One coverage sample. Height and normal are baked at paint time so flora sits on whatever\r\n\t/// geometry was there, without the renderer having to trace anything at load.\r\n\t/// \u003C/summary\u003E\r\n\tpublic struct Cell\r\n\t{\r\n\t\tpublic float Height;\r\n\r\n\t\t/// \u003Csummary\u003Edensity (0-7) | normal.x (8-15) | normal.y (16-23) | entry index (24-31)\u003C/summary\u003E\r\n\t\tpublic uint Packed;\r\n\r\n\t\tpublic readonly float Density =\u003E (Packed \u0026 0xFF) / 255.0f;\r\n\r\n\t\t/// \u003Csummary\u003EIndex into the definition\u0027s entry list. 0xFF means \u0022pick one by weight\u0022.\u003C/summary\u003E\r\n\t\tpublic readonly int EntryIndex =\u003E (int)((Packed \u003E\u003E 24) \u0026 0xFF);\r\n\r\n\t\tpublic readonly Vector3 Normal\r\n\t\t{\r\n\t\t\tget\r\n\t\t\t{\r\n\t\t\t\tvar x = ((Packed \u003E\u003E 8) \u0026 0xFF) / 127.5f - 1.0f;\r\n\t\t\t\tvar y = ((Packed \u003E\u003E 16) \u0026 0xFF) / 127.5f - 1.0f;\r\n\t\t\t\tvar z = MathF.Sqrt(Math.Clamp(1.0f - x * x - y * y, 0.0f, 1.0f));\r\n\t\t\t\treturn new Vector3(x, y, z);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tpublic static uint Pack(float density, Vector3 normal, int entryIndex)\r\n\t\t{\r\n\t\t\tvar d = (uint)Math.Clamp(density * 255.0f \u002B 0.5f, 0.0f, 255.0f);\r\n\t\t\tvar nx = (uint)Math.Clamp((normal.x \u002B 1.0f) * 127.5f \u002B 0.5f, 0.0f, 255.0f);\r\n\t\t\tvar ny = (uint)Math.Clamp((normal.y \u002B 1.0f) * 127.5f \u002B 0.5f, 0.0f, 255.0f);\r\n\t\t\tvar e = (uint)Math.Clamp(entryIndex, 0, 255);\r\n\r\n\t\t\treturn d | (nx \u003C\u003C 8) | (ny \u003C\u003C 16) | (e \u003C\u003C 24);\r\n\t\t}\r\n\t}\r\n\r\n\tpublic readonly record struct ChunkCoord(int X, int Y);\r\n\r\n\tprivate readonly Dictionary\u003CChunkCoord, Cell[]\u003E _chunks = [];\r\n\r\n\t/// \u003Csummary\u003EBumped on every mutation so the renderer knows to regenerate.\u003C/summary\u003E\r\n\tpublic int Revision { get; private set; }\r\n\r\n\tpublic int ChunkCount =\u003E _chunks.Count;\r\n\r\n\tpublic IReadOnlyDictionary\u003CChunkCoord, Cell[]\u003E Chunks =\u003E _chunks;\r\n\r\n\tpublic static ChunkCoord WorldToChunk(Vector3 world) =\u003E new(\r\n\t\t(int)MathF.Floor(world.x / ChunkSize),\r\n\t\t(int)MathF.Floor(world.y / ChunkSize));\r\n\r\n\tpublic static Vector2 ChunkOrigin(ChunkCoord coord) =\u003E new(coord.X * ChunkSize, coord.Y * ChunkSize);\r\n\r\n\tpublic static Vector3 ChunkCenter(ChunkCoord coord, float height = 0.0f)\r\n\t{\r\n\t\tvar origin = ChunkOrigin(coord);\r\n\t\treturn new Vector3(origin.x \u002B ChunkSize * 0.5f, origin.y \u002B ChunkSize * 0.5f, height);\r\n\t}\r\n\r\n\tprivate static int WorldToCell(float world) =\u003E (int)MathF.Floor(world / CellSize);\r\n\r\n\tprivate static int FloorDiv(int a, int b) =\u003E a \u003E= 0 ? a / b : ~(~a / b);\r\n\r\n\tprivate static int Mod(int a, int b)\r\n\t{\r\n\t\tvar r = a % b;\r\n\t\treturn r \u003C 0 ? r \u002B b : r;\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Writes a coverage sample, baking the surface height and normal alongside it. Density of zero\r\n\t/// frees the sample.\r\n\t/// \u003C/summary\u003E\r\n\tpublic void SetCell(float worldX, float worldY, float density, float height, Vector3 normal, int entryIndex)\r\n\t{\r\n\t\tvar cellX = WorldToCell(worldX);\r\n\t\tvar cellY = WorldToCell(worldY);\r\n\t\tvar coord = new ChunkCoord(FloorDiv(cellX, ChunkResolution), FloorDiv(cellY, ChunkResolution));\r\n\r\n\t\tif (!_chunks.TryGetValue(coord, out var cells))\r\n\t\t{\r\n\t\t\tif (density \u003C= 0.0f) return;\r\n\r\n\t\t\tcells = new Cell[CellsPerChunk];\r\n\t\t\t_chunks[coord] = cells;\r\n\t\t}\r\n\r\n\t\tvar index = Mod(cellY, ChunkResolution) * ChunkResolution \u002B Mod(cellX, ChunkResolution);\r\n\t\tcells[index] = new Cell { Height = height, Packed = Cell.Pack(density, normal, entryIndex) };\r\n\r\n\t\tRevision\u002B\u002B;\r\n\t}\r\n\r\n\tpublic Cell GetCell(float worldX, float worldY)\r\n\t{\r\n\t\tvar cellX = WorldToCell(worldX);\r\n\t\tvar cellY = WorldToCell(worldY);\r\n\t\tvar coord = new ChunkCoord(FloorDiv(cellX, ChunkResolution), FloorDiv(cellY, ChunkResolution));\r\n\r\n\t\tif (!_chunks.TryGetValue(coord, out var cells))\r\n\t\t\treturn default;\r\n\r\n\t\treturn cells[Mod(cellY, ChunkResolution) * ChunkResolution \u002B Mod(cellX, ChunkResolution)];\r\n\t}\r\n\r\n\t/// \u003Csummary\u003EReduces coverage in a radius, removing samples that reach zero.\u003C/summary\u003E\r\n\tpublic void Erase(Vector3 center, float radius, float strength)\r\n\t{\r\n\t\tvar radiusSquared = radius * radius;\r\n\r\n\t\tvar minCellX = WorldToCell(center.x - radius);\r\n\t\tvar maxCellX = WorldToCell(center.x \u002B radius);\r\n\t\tvar minCellY = WorldToCell(center.y - radius);\r\n\t\tvar maxCellY = WorldToCell(center.y \u002B radius);\r\n\r\n\t\tvar changed = false;\r\n\r\n\t\tfor (var cy = minCellY; cy \u003C= maxCellY; cy\u002B\u002B)\r\n\t\t{\r\n\t\t\tfor (var cx = minCellX; cx \u003C= maxCellX; cx\u002B\u002B)\r\n\t\t\t{\r\n\t\t\t\tvar coord = new ChunkCoord(FloorDiv(cx, ChunkResolution), FloorDiv(cy, ChunkResolution));\r\n\t\t\t\tif (!_chunks.TryGetValue(coord, out var cells))\r\n\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\tvar wx = (cx \u002B 0.5f) * CellSize;\r\n\t\t\t\tvar wy = (cy \u002B 0.5f) * CellSize;\r\n\t\t\t\tvar dx = wx - center.x;\r\n\t\t\t\tvar dy = wy - center.y;\r\n\r\n\t\t\t\tif (dx * dx \u002B dy * dy \u003E radiusSquared)\r\n\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\tvar index = Mod(cy, ChunkResolution) * ChunkResolution \u002B Mod(cx, ChunkResolution);\r\n\t\t\t\tref var cell = ref cells[index];\r\n\r\n\t\t\t\tif ((cell.Packed \u0026 0xFF) == 0)\r\n\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\tvar density = Math.Max(cell.Density - strength, 0.0f);\r\n\t\t\t\tcell.Packed = density \u003C= 0.0f\r\n\t\t\t\t\t? 0u\r\n\t\t\t\t\t: Cell.Pack(density, cell.Normal, cell.EntryIndex);\r\n\r\n\t\t\t\tchanged = true;\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (!changed)\r\n\t\t\treturn;\r\n\r\n\t\tPruneEmptyChunks();\r\n\t\tRevision\u002B\u002B;\r\n\t}\r\n\r\n\tpublic void ClearAll()\r\n\t{\r\n\t\tif (_chunks.Count == 0) return;\r\n\r\n\t\t_chunks.Clear();\r\n\t\tRevision\u002B\u002B;\r\n\t}\r\n\r\n\tprivate void PruneEmptyChunks()\r\n\t{\r\n\t\tList\u003CChunkCoord\u003E empty = null;\r\n\r\n\t\tforeach (var (coord, cells) in _chunks)\r\n\t\t{\r\n\t\t\tvar used = false;\r\n\t\t\tfor (var i = 0; i \u003C cells.Length; i\u002B\u002B)\r\n\t\t\t{\r\n\t\t\t\tif ((cells[i].Packed \u0026 0xFF) != 0) { used = true; break; }\r\n\t\t\t}\r\n\r\n\t\t\tif (!used)\r\n\t\t\t{\r\n\t\t\t\tempty ??= [];\r\n\t\t\t\tempty.Add(coord);\r\n\t\t\t}\r\n\t\t}\r\n\r\n\t\tif (empty is null) return;\r\n\r\n\t\tforeach (var coord in empty)\r\n\t\t\t_chunks.Remove(coord);\r\n\t}\r\n\r\n\t/// \u003Csummary\u003E\r\n\t/// Writes only the painted cells. Storing them densely cost 8KB per chunk however little of it\r\n\t/// was painted, and a brush stroke across a landscape touches a lot of chunks.\r\n\t///\r\n\t/// Each painted cell costs 2 bytes more than it did dense (its index), so a chunk past about 80%\r\n\t/// coverage is cheaper stored densely. Both layouts are written and each chunk says which it used.\r\n\t/// \u003C/summary\u003E\r\n\tpublic override void Serialize(ref Writer writer)\r\n\t{\r\n\t\twriter.Stream.Write(_chunks.Count);\r\n\r\n\t\tforeach (var (coord, cells) in _chunks)\r\n\t\t{\r\n\t\t\twriter.Stream.Write(coord.X);\r\n\t\t\twriter.Stream.Write(coord.Y);\r\n\r\n\t\t\tvar painted = 0;\r\n\t\t\tfor (var i = 0; i \u003C CellsPerChunk; i\u002B\u002B)\r\n\t\t\t{\r\n\t\t\t\tif ((cells[i].Packed \u0026 0xFF) != 0) painted\u002B\u002B;\r\n\t\t\t}\r\n\r\n\t\t\tvar sparse = painted * 10 \u003C CellsPerChunk * 8;\r\n\t\t\twriter.Stream.Write(sparse);\r\n\r\n\t\t\tif (!sparse)\r\n\t\t\t{\r\n\t\t\t\tfor (var i = 0; i \u003C CellsPerChunk; i\u002B\u002B)\r\n\t\t\t\t{\r\n\t\t\t\t\twriter.Stream.Write(cells[i].Height);\r\n\t\t\t\t\twriter.Stream.Write(cells[i].Packed);\r\n\t\t\t\t}\r\n\r\n\t\t\t\tcontinue;\r\n\t\t\t}\r\n\r\n\t\t\twriter.Stream.Write(painted);\r\n\r\n\t\t\tfor (var i = 0; i \u003C CellsPerChunk; i\u002B\u002B)\r\n\t\t\t{\r\n\t\t\t\tif ((cells[i].Packed \u0026 0xFF) == 0)\r\n\t\t\t\t\tcontinue;\r\n\r\n\t\t\t\twriter.Stream.Write((ushort)i);\r\n\t\t\t\twriter.Stream.Write(cells[i].Height);\r\n\t\t\t\twriter.Stream.Write(cells[i].Packed);\r\n\t\t\t}\r\n\t\t}\r\n\t}\r\n\r\n\tpublic override void Deserialize(ref Reader reader)\r\n\t{\r\n\t\t_chunks.Clear();\r\n\r\n\t\tvar chunkCount = reader.Stream.Read\u003Cint\u003E();\r\n\r\n\t\tfor (var c = 0; c \u003C chunkCount; c\u002B\u002B)\r\n\t\t{\r\n\t\t\tvar coord = new ChunkCoord(reader.Stream.Read\u003Cint\u003E(), reader.Stream.Read\u003Cint\u003E());\r\n\t\t\tvar cells = new Cell[CellsPerChunk];\r\n\r\n\t\t\tif (reader.Stream.Read\u003Cbool\u003E())\r\n\t\t\t{\r\n\t\t\t\tvar painted = reader.Stream.Read\u003Cint\u003E();\r\n\r\n\t\t\t\tfor (var p = 0; p \u003C painted; p\u002B\u002B)\r\n\t\t\t\t{\r\n\t\t\t\t\tvar index = reader.Stream.Read\u003Cushort\u003E();\r\n\t\t\t\t\tvar height = reader.Stream.Read\u003Cfloat\u003E();\r\n\t\t\t\t\tvar packed = reader.Stream.Read\u003Cuint\u003E();\r\n\r\n\t\t\t\t\tif (index \u003C CellsPerChunk)\r\n\t\t\t\t\t{\r\n\t\t\t\t\t\tcells[index].Height = height;\r\n\t\t\t\t\t\tcells[index].Packed = packed;\r\n\t\t\t\t\t}\r\n\t\t\t\t}\r\n\t\t\t}\r\n\t\t\telse\r\n\t\t\t{\r\n\t\t\t\tfor (var i = 0; i \u003C CellsPerChunk; i\u002B\u002B)\r\n\t\t\t\t{\r\n\t\t\t\t\tcells[i].Height = reader.Stream.Read\u003Cfloat\u003E();\r\n\t\t\t\t\tcells[i].Packed = reader.Stream.Read\u003Cuint\u003E();\r\n\t\t\t\t}\r\n\t\t\t}\r\n\r\n\t\t\t_chunks[coord] = cells;\r\n\t\t}\r\n\r\n\t\tRevision\u002B\u002B;\r\n\t}\r\n}\r\n"},{"Ident":"redsnail.floratool","Path":".obj/__compiler_extra.cs","FileName":"__compiler_extra.cs","PackageType":"library","CodeKind":"Game","AssetVersionId":421873,"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, \u0022Flora Tool\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022AddonIdent\u0022, \u0022floratool\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022OrgIdent\u0022, \u0022redsnail\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022Ident\u0022, \u0022redsnail.floratool\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyMetadata( \u0022EngineVersion\u0022, \u002229\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-10-08T16:53:09.3035175Z\u0022 )]\r\n[assembly: global::System.Reflection.AssemblyVersion(\u00220.0.124.0\u0022)]\r\n[assembly: global::System.Reflection.AssemblyFileVersion(\u00220.0.124.0\u0022)]"}]}