Skip to content

Game.Simulation.BuyingCompanySystem

Assembly:
Assembly-CSharp (game assembly)

Namespace:
Game.Simulation

Type:
class BuyingCompanySystem

Base:
GameSystemBase

Summary:
System responsible for evaluating companies that buy resources each update interval and creating purchase requests (ResourceBuyer components) when stocks are low. It runs a parallel IJobChunk (CompanyBuyJob) over entities with BuyingCompany and related buffers/components, computes resource needs based on storage, owned vehicles, pending trips and trade costs, selects an appropriate delivery truck capacity, and enqueues commands (via an EndFrameBarrier command buffer) to create ResourceBuyer components. The system also manages company "no-inputs" icon notifications when buying is considered too expensive. It integrates with ResourceSystem, VehicleCapacitySystem, IconCommandSystem and uses shared UpdateFrame batching to only run on certain update frames.


Fields

  • private static readonly float kNotificationCostLimit
    Threshold buy cost above which an input is considered "expensive" and triggers a "no input" notification. Value: 5f.

  • private static readonly int kResourceLowStockAmount
    Minimum stock level considered "low" for input resources. Value: 4000.

  • private static readonly int kResourceMinimumRequestAmount
    Minimum amount requested when creating a resource purchase. Value: 2000.

  • private SimulationSystem m_SimulationSystem
    Reference to the world SimulationSystem used to query the current frame index and timing utilities.

  • private ResourceSystem m_ResourceSystem
    Reference to ResourceSystem used to get resource prefab mappings and to register a reader dependency.

  • private VehicleCapacitySystem m_VehicleCapacitySystem
    Reference to VehicleCapacitySystem used to choose delivery truck capacity for purchase requests.

  • private EndFrameBarrier m_EndFrameBarrier
    Barrier used to create an EntityCommandBuffer (parallel writer) for safely adding components at end of frame.

  • private IconCommandSystem m_IconCommandSystem
    System that provides an IconCommandBuffer to add/remove UI icon notifications on entities.

  • private EntityQuery m_CompanyNotificationParameterQuery
    Query used to obtain CompanyNotificationParameterData singleton (contains prefabs used for notifications).

  • private EntityQuery m_CompanyGroup
    Query describing the set of company entities processed by this system (BuyingCompany + Resources + OwnedVehicle + PrefabRef + TradeCost + CompanyNotifications + TripNeeded + PropertyRenter, excludes ResourceBuyer and Deleted).

  • private TypeHandle __TypeHandle
    Internal cached collection of type/buffer/component lookups and handles used for jobs (generated helper).

Properties

  • (none)

Constructors

  • public BuyingCompanySystem()
    Default constructor. The system initializes via OnCreate; constructor itself contains no custom logic beyond base initialization.

Methods

  • public override int GetUpdateInterval(SystemUpdatePhase phase)
    Returns the update interval in frames for when this system should run. This implementation returns 256, meaning the system's effective update uses a spaced interval across simulation frames (the system internally uses SimulationUtils.GetUpdateFrameWithInterval to pick frames).

  • protected override void OnCreate()
    Initializes the system: acquires references to SimulationSystem, ResourceSystem, VehicleCapacitySystem, EndFrameBarrier and IconCommandSystem; constructs the entity queries (m_CompanyGroup and m_CompanyNotificationParameterQuery); and sets the queries as required for update (RequireForUpdate). Marked with [Preserve].

  • protected override void OnUpdate()
    Main update logic. Builds and schedules the CompanyBuyJob (IJobChunk) as a parallel job using the stored type handles and lookups. It:

  • Computes the updateFrame index to run on using SimulationUtils.GetUpdateFrameWithInterval.
  • Fills CompanyBuyJob fields including component lookups, buffer lookups, resource prefabs/data, notification parameters, command buffers, delivery truck selection data, and a random seed.
  • Schedules the job over m_CompanyGroup with JobChunkExtensions.ScheduleParallel.
  • Registers dependencies with ResourceSystem, EndFrameBarrier and IconCommandSystem.

  • private void __AssignQueries(ref SystemState state)
    Internal compiler helper used to assign queries at compile-time; no runtime behavior beyond generated boilerplate.

  • protected override void OnCreateForCompiler()
    Compiler-time initialization: calls __AssignQueries and assigns type handles in __TypeHandle. Used by generated code paths.

Nested types (documented here because they contain the job logic executed by the system):

  • CompanyBuyJob (private struct)
  • Implements IJobChunk. Runs per archetype chunk for companies selected by the query.
  • Key fields:
    • various ReadOnly handles: UpdateFrame, EntityType, buffers (OwnedVehicle, Resources, TripNeeded, TradeCost), PrefabRef, PropertyRenter, ComponentLookup for StorageLimitData, IndustrialProcessData, DeliveryTruck, PropertyRenter, Transform, ResourceData, BufferLookup for LayoutElement, DeliveryTruckSelectData, ResourcePrefabs, CompanyNotificationParameterData, RandomSeed.
    • m_CommandBuffer: EntityCommandBuffer.ParallelWriter to add ResourceBuyer components.
    • m_IconCommandBuffer: IconCommandBuffer to add/remove in-game UI icons.
    • m_UpdateFrameIndex: used to only process entities whose UpdateFrame matches current frame.
  • Execute(...) logic (per chunk):
    • Skips chunk if its UpdateFrame shared component index doesn't match m_UpdateFrameIndex.
    • For each entity in chunk:
    • Reads CompanyNotifications, resources, vehicles, trips, trade costs and prefab.
    • Determines storage limit (via StorageLimitData) and industrial process inputs/outputs for prefab.
    • Calls CalculateResourceNeeded to compute needResource, needResourceLeft, storageLeft and whether inputs are expensive.
    • Updates "no input" notification icon state via m_IconCommandBuffer and CompanyNotifications component.
    • If a resource is needed, selects a desired request amount and chooses a delivery truck item (using VehicleCapacitySystem's DeliveryTruckSelectData) and then:
      • If company is a property renter and the property has a Transform, creates a ResourceBuyer component with payer, amount, flags (Industrial|Import), location and resource, and adds it to the entity via m_CommandBuffer.AddComponent (parallel).
  • CalculateResourceNeeded(...) (private helper inside the job):

    • Computes the current amount on-hand for a resource using EconomyUtils.GetResources.
    • If isInput, considers trade buy cost (if > kNotificationCostLimit marks expensive), owned vehicles' expected incoming loads, and pending shopping TripNeeded entries to augment the expected available amount; marks resource as needed when low (below kResourceLowStockAmount).
    • If resource is a material (EconomyUtils.IsMaterial), reduces storageLeft by current held amount.
  • TypeHandle (private struct)

  • Holds cached EntityTypeHandle, BufferTypeHandles, ComponentTypeHandles, SharedComponentTypeHandle and ComponentLookup/BufferLookup references used when scheduling the job.
  • __AssignHandles(ref SystemState state) fills handles from SystemState (used in OnCreateForCompiler).

Usage Example

[Preserve]
protected override void OnCreate()
{
    base.OnCreate();
    // Acquire dependent systems
    m_SimulationSystem = base.World.GetOrCreateSystemManaged<SimulationSystem>();
    m_ResourceSystem = base.World.GetOrCreateSystemManaged<ResourceSystem>();
    m_VehicleCapacitySystem = base.World.GetOrCreateSystemManaged<VehicleCapacitySystem>();
    m_EndFrameBarrier = base.World.GetOrCreateSystemManaged<EndFrameBarrier>();
    m_IconCommandSystem = base.World.GetOrCreateSystemManaged<IconCommandSystem>();

    // Create the entity queries used by this system
    m_CompanyGroup = GetEntityQuery(
        ComponentType.ReadOnly<BuyingCompany>(),
        ComponentType.ReadOnly<Resources>(),
        ComponentType.ReadWrite<OwnedVehicle>(),
        ComponentType.ReadOnly<PropertyRenter>(),
        ComponentType.ReadOnly<PrefabRef>(),
        ComponentType.ReadOnly<TradeCost>(),
        ComponentType.ReadWrite<CompanyNotifications>(),
        ComponentType.ReadWrite<TripNeeded>(),
        ComponentType.Exclude<ResourceBuyer>(),
        ComponentType.Exclude<Deleted>(),
        ComponentType.ReadOnly<UpdateFrame>());

    m_CompanyNotificationParameterQuery = GetEntityQuery(ComponentType.ReadOnly<CompanyNotificationParameterData>());

    RequireForUpdate(m_CompanyGroup);
    RequireForUpdate(m_CompanyNotificationParameterQuery);
}

Notes and tips for modders: - The system only processes companies on specific UpdateFrame indices (so companies are spread across frames). Use SimulationUtils.GetUpdateFrameWithInterval if creating compatible systems that should run in sync. - ResourceBuyer components are added via a parallel command buffer created from an EndFrameBarrier; if your mod consumes ResourceBuyer or depends on companies adding buyers, ensure proper ordering or register reader/writer dependencies with the involved systems. - The job uses several generated/internal handles (TypeHandle). If you adapt this system to a custom system, ensure you create and assign the appropriate EntityTypeHandle/BufferTypeHandle/etc. before scheduling jobs. - Costs and thresholds are controlled by three private constants: kNotificationCostLimit (5f), kResourceLowStockAmount (4000) and kResourceMinimumRequestAmount (2000). Modify with caution.