Game.SelectionToolSystem
Assembly:
Game
Namespace:
Game.Tools
Type:
class
Base:
ToolBaseSystem
Summary:
SelectionToolSystem implements the in-game selection tool used to select and deselect area-based objects (currently Map Tiles and Service Districts). It integrates with the DOTS/ECS world, scheduling Burst-compiled jobs to find entities inside a marquee, create temporary "creation/definition" entities, and copy/update selection buffers. The system tracks a simple state machine (Default, Selecting, Deselecting), handles input actions and UI sound cues, and coordinates with systems such as SearchSystem (area quadtree), MapTileSystem, MapTilePurchaseSystem, TerrainSystem and WaterSystem to compute selection geometry (a 3D marquee quad) and valid targets.
Fields
-
private SearchSystem m_AreaSearchSystem
Holds a reference to the SearchSystem used to query area spatial structures (native quadtrees) for area entities intersecting the selection quad. -
private MapTileSystem m_MapTileSystem
Reference to the MapTileSystem used to get the game's start tiles and other map-tile related information. -
private MapTilePurchaseSystem m_MapTilePurchaseSystem
Used to query how many map tiles are available for purchase when selectionType == MapTiles (game-mode restrictions). -
private ToolOutputBarrier m_ToolOutputBarrier
Command buffer barrier used when jobs produce ECS structural changes (CreateDefinition entities, buffer writes, etc). -
private AudioManager m_AudioManager
Used to play UI sounds for marquee start/end/clear events. -
private TerrainSystem m_TerrainSystem
Used when computing marquee geometry (sample terrain height). -
private WaterSystem m_WaterSystem
Used to sample water surface heights for marquee geometry so the selection quad follows water/terrain. -
private EntityQuery m_DefinitionGroup
EntityQuery used to find and destroy previous "definition" entities created by this tool. -
private EntityQuery m_TempGroup
EntityQuery that selects temporary entities that can be toggled during marquee selection. -
private EntityQuery m_SoundQuery
Query used to read tool sound settings. -
private Entity m_SelectionEntity
An ECS entity created per-active tool instance to hold selection info (SelectionInfo) and selected elements (SelectionElement buffer). -
private Entity m_LastOwner
Tracks last selectionOwner to detect changes and recreate the selection entity. -
private SelectionType m_LastType
Tracks last selectionType to detect changes and recreate the selection entity. -
private EntityArchetype m_SelectionArchetype
Archetype used when creating the per-tool selection entity (SelectionInfo + SelectionElement buffer). -
private State m_State
Current tool state (Default / Selecting / Deselecting). Controls behavior and input handling. -
private ControlPoint m_StartPoint
Start point of the marquee (set on press when entering Selecting/Deselecting). -
private ControlPoint m_RaycastPoint
Current raycast point (mouse/cursor hit) used as marquee end or hover. -
private IProxyAction m_SelectArea
Proxy action mapping for the primary (apply) action for area selection. -
private IProxyAction m_DeselectArea
Proxy action mapping for the secondary (apply) action for area deselection. -
private IProxyAction m_DiscardSelect
Proxy action mapping for canceling a select marquee. -
private IProxyAction m_DiscardDeselect
Proxy action mapping for canceling a deselect marquee. -
private bool m_ApplyBlocked
Internal flag used to temporarily block apply inputs (used when canceling mid-marquee). -
private TypeHandle __TypeHandle
Struct that stores pre-fetched Component/Buffer lookup handles used by jobs. Assigned in OnCreateForCompiler to optimize access. -
private const string kToolID = "Selection Tool"
Identifier string for the tool.
Properties
-
public override string toolID => "Selection Tool"
Tool identifier. Overrides ToolBaseSystem.toolID. -
public SelectionType selectionType { get; set; }
Gets/sets the current selection type (MapTiles, ServiceDistrict, etc). Changing this triggers recreation of the selection entity and resets configuration used by the tool. -
public Entity selectionOwner { get; set; }
Gets/sets the owner entity context for the selection (used for service-district copying and ownership association). -
public State state => m_State
Read-only property exposing the current state of the selection tool (Default / Selecting / Deselecting). -
private protected override IEnumerable<IProxyAction> toolActions
Enumerable exposing the actions used by the tool (select, deselect, discard select/deselect). Used by UI to show/enable action bindings.
Constructors
public SelectionToolSystem()
Default constructor (marks class for preservation with [Preserve] attribute elsewhere). Initialization of many subsystems occurs in OnCreate, not here.
Methods
-
protected override void OnCreate()
Initializes references to required systems (SearchSystem, MapTileSystem, MapTilePurchaseSystem, ToolOutputBarrier, AudioManager, TerrainSystem, WaterSystem), creates entity archetype for selection, fetches input actions from InputManager, and prepares EntityQueries. Marked [Preserve]. -
protected override void OnStartRunning()
Initializes per-run state: sets m_State = Default, clears m_StartPoint and m_ApplyBlocked. -
protected override void OnStopRunning()
Destroys the selection entity if present and performs base shutdown logic. -
private protected override void UpdateActions()
Updates the enabled/disabled state and overrides for the tool's proxy actions depending on selectionType, current m_State, whether there are editable temp entities, map-tile purchase availability and actionsEnabled. Controls which action triggers map tile select/deselect/discard. -
public override PrefabBase GetPrefab()
Tool-level prefab accessor, returns null — the selection tool does not expose a current prefab. -
public override bool TrySetPrefab(PrefabBase prefab)
Selection tool does not set a prefab for placement; always returns false. -
public override void InitializeRaycast()
Configures the tool raycast type mask and areaTypeMask based on selectionType (for MapTiles/ServiceDistrict uses terrain/areas/water raycasting and appropriate area masks). -
private AreaType GetAreaType(SelectionType selectionType)
Maps SelectionType enum to underlying AreaType used by area quadtrees (ServiceDistrict -> District, MapTiles -> MapTile, otherwise None). -
protected override JobHandle OnUpdate(JobHandle inputDeps)
Main update driver. Ensures selection entity exists and is configured for current selectionType/selectionOwner (creates and sets SelectionInfo and Owner). Updates actions and then handles state-specific input flows: reacting to apply/secondary/cancel proxy inputs to call Apply/Cancel/Update/Clear flows. Coordinates whether raycasts are allowed (disables when UI/debug flags present). -
private JobHandle Cancel(JobHandle inputDeps, bool singleFrameOnly = false)
Handles cancel behavior depending on m_State: - If Selecting: aborts select marquee, clears start point, sets state Default, plays end sound and calls UpdateDefinitions to refresh selection definitions.
- If Deselecting: toggles temp entities off (if allowed), updates selection, checks movement distance to play clear-end sound, clears state and updates definitions.
-
If Default: if a raycast point exists, enters Deselecting (unless singleFrameOnly) and plays clear-start sound, or toggles selection if singleFrameOnly and allowed.
-
private JobHandle Apply(JobHandle inputDeps, bool singleFrameOnly = false)
Handles apply behavior depending on m_State: - If Selecting: toggles temp entities on and updates selection, plays end sound if marquee moved, clears state and updates definitions.
- If Deselecting: finishes clear marquee, resets start point/state and updates definitions.
-
If Default: if raycast point exists, enters Selecting (unless singleFrameOnly), plays marquee start sound, or toggles selection immediately if singleFrameOnly and allowed.
-
private JobHandle Update(JobHandle inputDeps)
Updates current raycast point and marquee: - In Selecting/Deselecting: only re-schedules definition updates if the raycast point changed or forceUpdate occurs.
-
In Default: updates hover state and only re-generates definitions when underlying entity changed or forceUpdate.
-
private JobHandle Clear(JobHandle inputDeps)
Sets applyMode = Clear and returns inputDeps; clears visual apply hints. -
private JobHandle UpdateDefinitions(JobHandle inputDeps)
Destroys previously created definition entities and (if in a marquee/hover) schedules jobs to find area entities intersecting the marquee and create CreationDefinition entities for those areas. Uses FindEntitiesJob + CreateDefinitionsJob. Coordinates dependencies with SearchSystem (quad-tree reader) and ToolOutputBarrier. -
protected override bool GetRaycastResult(out ControlPoint controlPoint)
Overrides to disallow raycasting when selectionType is MapTiles and in game mode with zero available purchase tiles. Otherwise delegates to base.GetRaycastResult. -
protected override bool GetRaycastResult(out ControlPoint controlPoint, out bool forceUpdate)
Same as above but returns forceUpdate flag from base. -
private JobHandle ToggleTempEntity(JobHandle inputDeps, bool select)
Schedules ToggleEntityJob across temp entities (m_TempGroup) to either add or remove entries in the selection buffer on the selection entity. Respects editor/game mode and map tile/native flags. -
private JobHandle CopySelection(JobHandle inputDeps)
Copies an initial selection into the selection entity when the tool is created or selection type/owner changes: - For ServiceDistrict: copies existing owner's service districts into the selection buffer.
- For MapTiles in editor mode: copies start tiles.
-
Otherwise returns inputDeps unchanged.
-
private JobHandle UpdateSelection(JobHandle inputDeps)
Writes selection back to world buffers when applying: - For ServiceDistrict: writes selection buffer back to the owner's ServiceDistrict buffer.
-
For MapTiles in editor mode: updates the MapTile start tiles and marks Updated on affected tiles.
-
private JobHandle CopyStartTiles(JobHandle inputDeps)
Schedules CopyStartTilesJob to copy start tiles from MapTileSystem into the selection buffer on the selection entity (editor only). -
private JobHandle UpdateStartTiles(JobHandle inputDeps)
Schedules UpdateStartTilesJob to update Updated components on start tiles and replace the MapTileSystem start tiles list with the selection buffer contents; uses ToolOutputBarrier for structural changes. -
private JobHandle CopyServiceDistricts(JobHandle inputDeps)
Schedules CopyServiceDistrictsJob to copy a service owner's service districts into the selection buffer and mark owner Updated. -
private JobHandle UpdateServiceDistricts(JobHandle inputDeps)
Schedules UpdateServiceDistrictsJob to copy the selection buffer back into the owner's ServiceDistrict buffer and mark owner Updated. -
public bool GetSelectionQuad(out Quad3 quad)
Computes the 3D marquee quad (Quad3) from m_StartPoint and m_RaycastPoint using the main Camera orientation. It projects the marquee corners on terrain/water heights (uses TerrainSystem.GetHeightData and WaterSystem.GetSurfaceData). Returns false if camera is missing or start/end points are not valid. -
private void __AssignQueries(ref SystemState state)
Compiler-time method to assign EntityQuery builders. In this file it constructs an empty builder and disposes; present for the generated ECS system pipeline. -
protected override void OnCreateForCompiler()
Called by the generated ECS bootstrap; assigns queries and component handles by calling __AssignQueries and __TypeHandle.__AssignHandles. -
Nested/burst jobs and helper structs:
- FindEntitiesJob (IJob): Burst job that, given start/end ControlPoints, area search tree and other lookups, finds unique area entities intersecting the selection quad. Uses an AreaIterator to iterate quad-tree items and verify triangle/quad intersection. Results are sorted and deduplicated.
- CreateDefinitionsJob (IJobParallelForDefer): For each found entity, creates a CreationDefinition entity (with CreationFlags.Select) and copies node buffers into the created entity so the marquis can preview selection geometry.
- ToggleEntityJob (IJobChunk): Toggles entries in the SelectionElement buffer on the selection entity based on Temp buffer entries for temp entities; used to add/remove temporary selections during marquee operations.
- CopyStartTilesJob / UpdateStartTilesJob / CopyServiceDistrictsJob / UpdateServiceDistrictsJob: utility burst jobs to copy buffers between selection entity and world entities and to mark Updated components.
Usage Example
// Typical minimal usage inside a custom derived tool system or when inspecting behavior:
[Preserve]
protected override void OnCreate()
{
base.OnCreate();
// Set the selection type (MapTiles or ServiceDistrict) and optionally an owner entity
this.selectionType = SelectionType.MapTiles;
// selectionOwner = someOwnerEntity; // optional for ServiceDistrict mode
// Initialize raycasting (this is normally handled by the base tool lifecycle)
InitializeRaycast();
}
// During runtime, the system handles input and will create a per-tool selection entity
// which contains SelectionInfo and a SelectionElement buffer. Use SelectionElement buffer
// on the selection entity to query/set currently selected entities.