Game.Rendering.AreaBatchSystem
Assembly:
Game (runtime systems)
Namespace:
Game.Rendering
Type:
class
Base:
GameSystemBase, IPreDeserialize
Summary:
Manages GPU-visible batching, culling and upload of "area" geometry (areas are polygonal surfaces used by the game). AreaBatchSystem coordinates Unity ECS/Burst jobs to:
- perform spatial tree culling (two-stage: tree + explicit triangle/query culling),
- allocate and manage packed triangle buffers via a NativeHeapAllocator,
- generate per-triangle runtime data (AreaTriangleData / AreaColorData),
- maintain GPU resources (ComputeBuffers / GraphicsBuffer / Material) per prefab batch,
- expose APIs to fetch GPU buffers for rendering.
The system integrates with PrefabSystem, CameraUpdateSystem, RenderingSystem and BatchDataSystem and uses multiple Burst jobs (TreeCullingJob1/2, QueryCullingJob, CullingActionJob, BatchAllocationJob, TriangleUpdateJob, VisibleUpdateJob) to parallelize work and minimize main-thread overhead. It keeps both managed (ManagedBatchData) and native (NativeBatchData) representations for each area-prefab batch.
Fields
-
private PrefabSystem m_PrefabSystem
Reference to the PrefabSystem used to query prefab assets and components. -
private CameraUpdateSystem m_CameraUpdateSystem
Reference to the camera system to obtain LOD parameters and viewer info. -
private RenderingSystem m_RenderingSystem
Reference to the rendering system (used for shader enable checks, etc). -
private BatchDataSystem m_BatchDataSystem
Used to determine level-of-detail details and other batch related state. -
private Game.Areas.SearchSystem m_AreaSearchSystem
Provides the spatial search/tree used for coarse culling of area geometry. -
private ComputeBuffer m_AreaTriangleBuffer
GPU ComputeBuffer storing AreaTriangleData for all allocated triangles. -
private ComputeBuffer m_AreaColorBuffer
GPU ComputeBuffer storing AreaColorData (per-triangle colors / parameters). -
private List<ManagedBatchData> m_ManagedBatchData
Managed per-batch list holding Material, GraphicsBuffer for visible indices and renderer priority. -
private NativeHeapAllocator m_AreaBufferAllocator
Native allocator that packs per-area triangle allocations into a single native heap. -
private NativeReference<int> m_AllocationCount
Number of currently allocated areas (native reference updated inside allocation jobs). -
private NativeList<NativeBatchData> m_NativeBatchData
Native counterpart to m_ManagedBatchData. Holds UnsafeLists for area metadata and visible indices, bounds and flags. -
private NativeList<AreaTriangleData> m_AreaTriangleData
Native linear buffer of AreaTriangleData that backs m_AreaTriangleBuffer. -
private NativeList<TriangleMetaData> m_TriangleMetaData
Native metadata per triangle used for sorting, visibility flags and index remapping. -
private NativeList<AreaColorData> m_AreaColorData
Native linear buffer of per-triangle color/parameter data that backs m_AreaColorBuffer. -
private NativeList<NativeHeapBlock> m_UpdatedTriangles
List of heap blocks that were updated and need to be uploaded to the GPU buffers in GetAreaBatch. -
private EntityQuery m_UpdatedQuery
ECS query used to find updated area/prefab chunks during job scheduling. -
private EntityQuery m_PrefabQuery
Query used to detect added/removed/changed RenderedAreaData prefabs and update batch lists. -
private JobHandle m_DataDependencies
Tracks jobs that produce data used by renderers / other systems (used when callers want access to color data). -
private float3 m_PrevCameraPosition
Cached previous frame camera position (used to compute visibility deltas). -
private float3 m_PrevCameraDirection
Cached previous frame camera forward direction. -
private float4 m_PrevLodParameters
Cached previous LOD parameters. -
private int m_AreaParameters
Shader property ID for area parameters (set on created materials). -
private int m_DecalLayerMask
Shader property ID for decal layer mask. -
private bool m_Loaded
Internal flag set in PreDeserialize to indicate the system has just been loaded. -
private bool m_ColorsUpdated
Flag toggled when color data was requested/modified so GPU buffer can be updated on next GetAreaBatch. -
private TypeHandle __TypeHandle
Struct holding cached type handles used by UpdatePrefabs (compiler helper).
Properties
- (none public)
This system exposes functionality via methods rather than properties.
Constructors
public AreaBatchSystem()
Default constructor. Standard system initialization is performed in OnCreate; the constructor itself is empty (marked with [Preserve] on OnCreate).
Methods
-
protected override void OnCreate()
Initializes native lists, native allocator, GPU buffers, shader property IDs, and gets references to PrefabSystem, CameraUpdateSystem, RenderingSystem, BatchDataSystem and Game.Areas.SearchSystem. Creates entity queries for updates and prefabs and prepares managed/native per-batch containers. -
protected override void OnDestroy()
Releases ComputeBuffers and GraphicsBuffers, destroys created Materials, disposes native lists/allocator and completes outstanding job dependencies. -
public void PreDeserialize(Context context)
Called before deserialization/loading of world state. Completes data jobs, clears allocator and native structures and marks the system as loaded so the next update will treat previous camera/LOD as empty. -
public int GetBatchCount()
Returns number of area-prefab batches currently managed (m_ManagedBatchData.Count). -
public bool GetAreaBatch(int index, out ComputeBuffer buffer, out ComputeBuffer colors, out GraphicsBuffer indices, out Material material, out Bounds bounds, out int count, out int rendererPriority)
Main API used by the rendering code to obtain GPU resources for a given batch index: - Uploads any pending area triangle and color ranges to the GPU ComputeBuffers.
- Updates managed GraphicsBuffer for visible indices if its capacity changed.
-
Returns whether the batch currently has any visible indices (count != 0) and outputs buffer handles, bounds and material/priority.
-
public NativeList<AreaColorData> GetColorData(out JobHandle dependencies)
Marks colors as updated and returns the native list backing color data. Also returns m_DataDependencies so the caller can add a dependency on in-flight jobs before modifying colors. -
public void AddColorWriter(JobHandle jobHandle)
Adds a JobHandle dependency to m_DataDependencies. Used by code that writes into the color array from jobs. -
public void GetAreaStats(out uint allocatedSize, out uint bufferSize, out uint count)
Completes data dependencies and returns: - allocatedSize: used bytes in the area allocator (triangles * triangle size),
- bufferSize: total buffer capacity (allocator size * triangle size),
-
count: number of allocated areas (m_AllocationCount).
-
private static uint GetTriangleSize()
Returns size of triangle entry (AreaTriangleData + AreaColorData). Used to compute buffer sizes. -
protected override void OnUpdate()
Primary per-frame scheduler. Steps: - Complete any data dependencies required for safe prefab updates.
- Optionally call UpdatePrefabs when there are new/changed RenderedAreaData.
- Compute current LOD/camera parameters (via CameraUpdateSystem).
- Build native queues and buffers for culling.
- Schedule TreeCullingJob1/2, QueryCullingJob, CullingActionJob, BatchAllocationJob, TriangleUpdateJob and VisibleUpdateJob with appropriate dependencies.
-
Register tree reader with the search system and set m_DataDependencies and base.Dependency appropriately.
-
public void EnabledShadersUpdated()
Called when shader enable state might have changed. Completes data dependencies and sets per-batch m_IsEnabled flags; marks batches whose enabled state changed as needing visible index rebuild. -
private void UpdatePrefabs()
Handles created/removed/changed prefab batches: - Creates ManagedBatchData + NativeBatchData entries for newly created RenderedArea prefabs.
- When a prefab is deleted, cleans up its managed/native resources and compacts the arrays (swap-remove).
-
Sets up Materials copied from the RenderedArea component and initializes GPU buffers and shader properties.
-
private void __AssignQueries(ref SystemState state)
/protected override void OnCreateForCompiler()
Compiler-generated helpers used by the ECS code-gen to initialize type/query handles. Not typically used directly by modders. -
private void CompleteDependency()
(Internal helper used in UpdatePrefabs) Ensures job dependencies are completed before making structural/managed changes.
Usage of many nested private/Burst jobs (TreeCullingJob1/2, QueryCullingJob, CullingActionJob, BatchAllocationJob, TriangleUpdateJob, VisibleUpdateJob) implements the heavy-lifting: culling, allocation, triangle generation, sorting, and visible index building. See the source for full job semantics; modders extending or interfacing with this system typically call GetAreaBatch / GetColorData / AddColorWriter or hook into RenderedArea prefab assets.
Usage Example
[Preserve]
protected override void OnCreate()
{
base.OnCreate();
// Example of what AreaBatchSystem does: allocate native buffers and GPU buffers.
m_AreaBufferAllocator = new NativeHeapAllocator(4194304 / GetTriangleSize(), 1u, Allocator.Persistent);
m_AllocationCount = new NativeReference<int>(0, Allocator.Persistent);
m_NativeBatchData = new NativeList<NativeBatchData>(Allocator.Persistent);
m_AreaTriangleData = new NativeList<AreaTriangleData>(Allocator.Persistent);
m_TriangleMetaData = new NativeList<TriangleMetaData>(Allocator.Persistent);
m_AreaColorData = new NativeList<AreaColorData>(Allocator.Persistent);
m_UpdatedTriangles = new NativeList<NativeHeapBlock>(100, Allocator.Persistent);
m_AreaTriangleBuffer = new ComputeBuffer(m_AreaTriangleData.Capacity, sizeof(AreaTriangleData));
m_AreaColorBuffer = new ComputeBuffer(m_AreaColorData.Capacity, sizeof(AreaColorData));
}
Notes / Tips for modders: - Use GetAreaBatch from rendering code to fetch buffers for drawing; call GetColorData/AddColorWriter if you need to update per-triangle color/state from jobs and pass the returned JobHandle into AddColorWriter to ensure proper ordering. - The system tightly couples with RenderedArea prefab data. To add a new area-rendered prefab, set up RenderedArea on your prefab and the system will create a batch entry automatically. - The internal NativeHeapAllocator packs triangle data contiguously; avoid modifying internal native lists directly unless you fully understand the allocator and job dependencies. - Many methods / fields are internal/private and rely on job coordination; prefer the public APIs (GetAreaBatch, GetColorData, AddColorWriter, GetAreaStats, PreDeserialize) for safe interaction.