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