Skip to content

Game.Simulation.WorkProviderSystem

Assembly: Game (inferred from namespace; runtime assembly typically Assembly-CSharp/Game)
Namespace: Game.Simulation

Type: class

Base: GameSystemBase

Summary:
WorkProviderSystem is a simulation system responsible for updating workplace-related data for buildings and companies each simulation tick slice. It: - Iterates work providers (companies, buildings, outside connections, and schools), updates their available and occupied workplaces, - Refreshes employee buffers (removes dead/moving away workers, lays off excess workers), - Updates notifications for understaffed/uneducated worker shortages, - Computes and writes building efficiency factors according to employee availability, sickness and happiness, - Enqueues layoff reasons for later aggregation, - Uses Unity ECS Jobs (Burst-compiled) to parallelize work and writes commands through an EndFrameBarrier command buffer.


Fields

  • private SimulationSystem m_SimulationSystem
    Reference to the global SimulationSystem used to compute update frames.

  • private EndFrameBarrier m_EndFrameBarrier
    Barrier system used to create a command buffer (parallel writer) for structural changes performed by jobs.

  • private IconCommandSystem m_IconCommandSystem
    System used to add/remove notification icons via an IconCommandBuffer.

  • private EntityQuery m_WorkProviderGroup
    EntityQuery used to match all WorkProvider entities (companies, buildings, schools, outside connections).

  • private NativeQueue<LayOffReason> m_LayOffQueue
    Thread-safe queue used by worker jobs to enqueue layoff reasons. Processed afterwards by LayOffCountJob.

  • [DebugWatchValue] private NativeArray<int> m_LayOffs
    NativeArray sized to the LayOffReason enum count used to aggregate layoff counts (populated by LayOffCountJob).

  • private TypeHandle __TypeHandle
    Internal container holding the component/handle type references used when scheduling jobs.

  • private EntityQuery __query_543653706_0
    Internal query used to fetch WorkProviderParameterData singleton.

  • private EntityQuery __query_543653706_1
    Internal query used to fetch BuildingEfficiencyParameterData singleton.

  • private const int kUpdatesPerDay = 512
    Constant used when computing the update frame index (the system updates subsets of entities per frame).

  • private enum LayOffReason { Unknown, MovingAway, TooMany, NoBuilding, Count }
    Reasons enqueued when an employee is removed from a workplace. Used for aggregating layoff statistics.


Properties

  • (none exposed by this class)

Constructors

  • public WorkProviderSystem()
    Default constructor. The system's initialization logic is implemented in OnCreate.

Methods

  • public override int GetUpdateInterval(SystemUpdatePhase phase)
    Returns the update interval for this system. In code it returns 32 (the system runs every 32 simulation ticks).

  • protected override void OnCreate()
    Initializes system references and allocations:

  • Gets SimulationSystem, EndFrameBarrier and IconCommandSystem references from the World.
  • Builds the m_WorkProviderGroup EntityQuery matching WorkProvider + PrefabRef + Employee buffer, and entities that are companies OR buildings OR outside connections, excluding Deleted and Temp.
  • Allocates m_LayOffQueue and m_LayOffs.
  • Requires WorkProviderParameterData and BuildingEfficiencyParameterData for updates.

  • protected override void OnDestroy()
    Disposes native allocations (m_LayOffs and m_LayOffQueue) and calls base.OnDestroy().

  • protected override void OnUpdate()
    Main scheduling method:

  • Calculates an updateFrame index using SimulationUtils.GetUpdateFrame with kUpdatesPerDay=512.
  • Configures and schedules the Burst-compiled WorkProviderTickJob (IJobChunk) in parallel over m_WorkProviderGroup.
  • Adds the produced JobHandle to the EndFrameBarrier and IconCommandSystem.
  • Schedules LayOffCountJob (IJob) to aggregate layoff reasons from m_LayOffQueue into m_LayOffs.

  • private void __AssignQueries(ref SystemState state)
    Internal helper to build the queries used to retrieve the WorkProviderParameterData and BuildingEfficiencyParameterData singletons (used by jobs).

  • protected override void OnCreateForCompiler()
    Internal method called by generated/compiled code to assign type handles and queries used by the system.

Inner/Burst Jobs and helpers (important behaviour)

  • WorkProviderTickJob : IJobChunk (BurstCompile)
  • Purpose: iterate matched archetype chunks of WorkProvider entities to update workplaces and employees in parallel.
  • Important fields passed into the job: component/handle lookups (Citizens, TravelPurpose, Worker, PrefabRef, WorkplaceData, SchoolData, HealthProblem, HouseholdMember, MovingAway, InstalledUpgrade, Deleted, Student buffers), buffer lookup for Efficiency, EndFrameBarrier command buffer (parallel writer), IconCommandBuffer, native queue for layoff reasons, and parameter singletons (WorkProviderParameterData, BuildingEfficiencyParameterData).
  • Main Execute behavior:
    • Skips chunks not scheduled for this updateFrame (except outside connections which update every frame).
    • For each work provider entity:
    • Determines the provider entity (the building, or the property owner for companies).
    • Computes building level and number of workplaces via EconomyUtils.CalculateNumberOfWorkplaces.
    • Calls RefreshFreeWorkplace to validate and prune Employee buffer: removes dead/moving away workers, removes workers if there are too many (enqueues appropriate LayOffReason).
    • Updates FreeWorkplaces component presence/value through command buffer.
    • Calls UpdateNotificationAndEfficiency to:
      • Update uneducated/educated shortage cooldowns and add/remove notification icons via IconCommandBuffer.
      • Compute employee-based efficiency factors (NotEnoughEmployees, SickEmployees, EmployeeHappiness) and write them into the building Efficiency buffer.
    • If workplace prefab data is missing, it liquidates the provider (removes employees and FreeWorkplaces component).
  • Notable private helpers inside the job:

    • UpdateSchoolMaxWorkers: sets max workers for school buildings using CityUtils and installed upgrades/student buffers.
    • RefreshFreeWorkplace: iterates Employee buffer to remove invalid or excess employees; decrements freeWorkplaces counters; writes FreeWorkplaces via command buffer or removes it.
    • UpdateNotificationAndEfficiency: updates notification cooldowns, uses IconCommandBuffer for notification icons, computes workforce metrics and maps them to efficiency factors using BuildingUtils.ApproximateEfficiencyFactors and BuildingUtils.SetEfficiencyFactor.
    • UpdateCooldown: increments or resets short cooldown counters.
    • UpdateNotification: add/remove icon using IconCommandBuffer when condition toggles.
    • CalculateCurrentWorkforce: sums current workforce, average workforce and sick workforce based on employee data and citizen states.
    • Liquidate: removes all employees and clears FreeWorkplaces on the provider.
    • RemoveWorker: removes TravelPurpose and Worker components from a citizen entity using the command buffer when they are being removed from the workplace.
  • LayOffCountJob : IJob (BurstCompile)

  • Purpose: dequeues LayOffReason entries from the NativeQueue and increments the corresponding counters in m_LayOffs. Runs after the parallel job to produce aggregated counts.

  • TypeHandle (struct)

  • Internal structure storing all necessary component/handle lookups for scheduling the job. __AssignHandles is called to initialize these handles from the SystemState.

Notes / Behavioural details - The system spreads updates across frames using SimulationUtils.GetUpdateFrame with kUpdatesPerDay to avoid processing all providers every frame. - OutsideConnection entities are treated specially: they have their own manually set MaxWorkers and bypass the updateFrame filtering. - Student/school handling adjusts school workplace capacity based on installed upgrades and students present. - Efficiency penalties are applied for missing employees and sick employees using BuildingEfficiencyParameterData settings; employee happiness influences an EmployeeHappiness factor. - Layoffs are enqueued with a reason so they can be counted and used for diagnostics or statistics later.


Usage Example

A minimal example showing how this system initializes its native allocations in OnCreate (extracted/simplified from the system):

[Preserve]
protected override void OnCreate()
{
    base.OnCreate();

    // Example of allocations performed by the system:
    m_LayOffQueue = new NativeQueue<WorkProviderSystem.LayOffReason>(Allocator.Persistent);
    m_LayOffs = new NativeArray<int>(4, Allocator.Persistent);

    // The system also builds an EntityQuery to match work providers and requires parameter singletons.
}

If you are modding, interact with the system at a higher level (e.g., provide WorkProviderParameterData or BuildingEfficiencyParameterData singletons, or add/remove Employee/Worker components through ECS command buffers). Inspecting layoff data requires exposing/reading m_LayOffs or hooking into aggregated statistics produced elsewhere in the game.