### C# System Setup for Functions and Job Scheduling Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/Functions.md Illustrates how to set up an example system in C# that utilizes the Functions system for managing instantiation logic. It shows the creation of a Functions collection, reflection of implementations, and scheduling a job that uses these functions. ```csharp public partial struct ExampleSystem : ISystem { private Functions instantiateFunctions; public void OnCreate(ref SystemState state) { instantiateFunctions = new FunctionsBuilder(Allocator.Temp) .ReflectAll(ref state) // Find all IFunction .Build(); } public void OnDestroy(ref SystemState state) { instantiateFunctions.OnDestroy(ref state); } public void OnUpdate(ref SystemState state) { instantiateFunctions.Update(ref state); new SpawnJob { InstantiateFunctions = instantiateFunctions }.Schedule(); } public struct InstantiateData { public Entity Prefab; public EntityCommandBuffer EntityCommandBuffer; public float3 Position; } } ``` -------------------------------- ### Spatial Map System Setup and Update Example Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/Spatial.md Illustrates how to set up and use the SpatialMap within an ECS system. It shows initializing a PositionBuilder, creating a SpatialMap, gathering entity positions, and building the spatial map. ```csharp public partial struct TestSystem : ISystem { private PositionBuilder positionBuilder; private SpatialMap spatialMap; public void OnCreate(ref SystemState state) { var query = SystemAPI.QueryBuilder().WithAll().Build(); this.positionBuilder = new PositionBuilder(ref state, query); const int size = 4096; const int quantizeStep = 16; this.spatialMap = new SpatialMap(quantizeStep, size); } public void OnDestroy(ref SystemState state) { this.spatialMap.Dispose(); } [BurstCompile] public void OnUpdate(ref SystemState state) { state.Dependency = this.positionBuilder.Gather(ref state, state.Dependency, out NativeArray positions); state.Dependency = this.spatialMap.Build(positions, state.Dependency); } } ``` -------------------------------- ### CameraAuthoring Setup - C# Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/Camera.md Illustrates the basic setup for ECS camera integration using the CameraAuthoring script. This script automatically adds necessary components during the baking process and allows configuration for the main camera. ```csharp // CameraAuthoring automatically adds required components during baking [SerializeField] private bool isMainCamera = true; ``` -------------------------------- ### C# Job Implementation Using Functions for Entity Instantiation Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/Functions.md Provides a C# example of an IJobEntity that leverages the Functions system to execute instantiation logic. It iterates through available functions, passing necessary data to find a matching instantiation method. ```csharp [BurstCompile] private partial struct SpawnJob : IJobEntity { public Functions InstantiateFunctions; private void Execute(Entity entity, in Spawner spawner, in LocalTransform localTransform) { var data = new InstantiateData { Prefab = spawner.Prefab, Position = localTransform.Position, EntityCommandBuffer = EntityCommandBuffer, }; for (var i = 0; i < InstantiateFunctions.Length; i++) { if (InstantiateFunctions.Execute(i, ref data) != Entity.Null) { return; // Found a match } } } } ``` -------------------------------- ### C# Function Implementation for Test Unit Instantiation Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/Functions.md Shows a concrete C# implementation of an IFunction for instantiating a 'TestUnit'. This example includes the necessary forwarding functions required by the Functions system, demonstrating how to access components and modify entities. ```csharp [BurstCompile] public unsafe struct InstantiateTestUnit : IFunction { private UnsafeComponentLookup testUnit; public UpdateFunction? UpdateFunction => Update; public DestroyFunction? DestroyFunction => null; public ExecuteFunction ExecuteFunction => Execute; public void OnCreate(ref SystemState state) { testUnit = state.GetUnsafeComponentLookup(true); } private Entity Execute(ref ExampleSystem.InstantiateData data) { if (!testUnit.HasComponent(data.Prefab)) return Entity.Null; var instance = data.EntityCommandBuffer.Instantiate(data.Prefab); var position = LocalTransform.FromPosition(data.Position + new float3(0, 1, 0)); data.EntityCommandBuffer.SetComponent(instance, position); return instance; } // Required forwarding functions [BurstCompile] [AOT.MonoPInvokeCallback(typeof(UpdateFunction))] private static void Update(void* target, ref SystemState state) { ((InstantiateTestUnit*)target)->testUnit.Update(ref state); } [BurstCompile] [AOT.MonoPInvokeCallback(typeof(ExecuteFunction))] private static void Execute(void* target, void* data, void* result) { *(Entity*)result = ((InstantiateTestUnit*)target)->Execute(ref UnsafeUtility.AsRef(data)); } } ``` -------------------------------- ### K Inspector Integration (C#) Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/K.md Provides examples of using the `KAttribute` in C# to integrate K settings into the Unity inspector. It shows how to display K values as a dropdown list or as a flags field for bitwise operations. ```csharp // Display as a dropdown with available values [K("ClientStates")] public int currentState; // Display as a flags field (for bitwise operations) [K("GameLayers", flags: true)] public int layerMask; ``` -------------------------------- ### Unified Entity Manipulation with IEntityCommands in Unity DOTS Source: https://context7.com/tertle/com.bovinelabs.core/llms.txt Demonstrates the IEntityCommands interface for unified entity manipulation across various Unity DOTS contexts like EntityManager, EntityCommandBuffer, and IBaker. The generic SetupCharacter method can be used with CommandBufferCommands and BakerCommands for entity setup. ```csharp // Generic entity setup method usable across all contexts public static void SetupCharacter(ref T commands, float3 position, int health) where T : unmanaged, IEntityCommands { commands.AddComponent(LocalTransform.FromPosition(position)); commands.AddComponent(new Health { Value = health, Max = health }); commands.AddComponent(); } // System usage with EntityCommandBuffer [BurstCompile] public partial struct SpawnSystem : ISystem { public void OnUpdate(ref SystemState state) { var ecb = new EntityCommandBuffer(state.WorldUpdateAllocator); foreach (var (request, entity) in SystemAPI.Query>() .WithEntityAccess()) { var newEntity = ecb.CreateEntity(); var commands = new CommandBufferCommands(ecb, newEntity); SetupCharacter(ref commands, request.ValueRO.Position, 100); ecb.DestroyEntity(entity); } ecb.Playback(state.EntityManager); } } // Baker usage public class CharacterBaker : Baker { public override void Bake(CharacterAuthoring authoring) { var entity = GetEntity(TransformUsageFlags.Dynamic); var commands = new BakerCommands(this, entity); SetupCharacter(ref commands, float3.zero, authoring.InitialHealth); } } ``` -------------------------------- ### Scene Loading Integration Example (C#) Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/Pause.md Demonstrates how to integrate the Pause extension with scene loading processes in Unity DOTS. It shows a system that automatically pauses the world in full-pause mode during subscene loading and unpauses upon completion. Requires a SystemState reference. ```csharp public partial struct SubSceneLoadingSystem : ISystem { public void OnUpdate(ref SystemState state) { if (loadingInProgress) { PauseGame.Pause(ref state, pauseAll: true); } else if (loadingComplete) { PauseGame.Unpause(ref state); } } } ``` -------------------------------- ### Generic Entity Setup Method in C# Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/EntityCommands.md This C# method demonstrates a generic approach to setting up an entity with movement-related components. It accepts any type implementing `IEntityCommands` and adds `LocalTransform`, `PhysicsVelocity`, and `MovementTag` components to the entity. This promotes code reuse across different command execution contexts. ```cs public static void SetupMovementEntity(ref T commands, float3 position, float3 velocity) where T : unmanaged, IEntityCommands { commands.AddComponent(LocalTransform.FromPosition(position)); commands.AddComponent(new PhysicsVelocity { Linear = velocity }); commands.AddComponent(); } ``` -------------------------------- ### Menu System Integration Example (C#) Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/Pause.md Illustrates integrating the Pause extension with a menu system in Unity DOTS. This example shows a menu system that uses a normal pause (where UI systems can continue updating) when the menu is opened and unpauses when closed. It implements IUpdateWhilePaused to ensure the menu system itself is not paused. ```csharp public partial struct MenuSystem : ISystem, IUpdateWhilePaused { public void OnUpdate(ref SystemState state) { if (menuOpened) { PauseGame.Pause(ref state); // Normal pause - UI continues } else if (menuClosed) { PauseGame.Unpause(ref state); } } } ``` -------------------------------- ### Frustum Culling Example - C# Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/Camera.md Demonstrates how to perform efficient visibility culling using frustum planes. This code iterates through entities with CameraFrustumPlanes and RenderBounds, performing intersection tests to determine visibility. ```csharp foreach (var (frustumPlanes, renderBounds) in SystemAPI.Query()) { var bounds = new AABB { Center = renderBounds.Value.Center, Extents = renderBounds.Value.Extents }; // Fast culling check if (!frustumPlanes.AnyIntersect(bounds)) continue; // Detailed intersection for partial objects var result = frustumPlanes.Intersect(bounds); switch (result) { case IntersectResult.In: // Fully visible break; case IntersectResult.Partial: // Partially visible break; case IntersectResult.Out: // Not visible continue; } } ``` -------------------------------- ### Track Destroyed Monsters Before Destruction (C#) Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/LifeCycle.md This C# example demonstrates how to perform actions on entities just before they are destroyed. It uses the DestroySystemGroup and a NativeHashMap to track destroyed monsters by their ObjectId. This system runs before the actual destruction occurs, allowing for pre-destruction logic. Requires Unity DOTS and Burst compiler. ```csharp using Unity.Entities; using Unity.Jobs; using Unity.Burst; using Unity.Collections; [UpdateInGroup(typeof(DestroySystemGroup))] public partial struct TrackDestroyedMonsterSystem : ISystem { public void OnUpdate(ref SystemState state) { new TrackJob { Tracking = SystemAPI.GetSingleton().Map }.Schedule(); } [BurstCompile] [WithAll(typeof(Monster), typeof(DestroyEntity))] private partial struct TrackJob : IJobEntity { public NativeHashMap Tracking; private void Execute(in ObjectId id) { Tracking.GetOrAddRef(id)++; } } } ``` -------------------------------- ### Parallel Job Processing with EntityCommandBuffer in C# Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/EntityCommands.md This C# `ProcessEntitiesJob` implements `IJobChunk` to process entities in parallel using `EntityCommandBuffer.ParallelWriter`. It demonstrates how to obtain a parallel command buffer and use it within the `Execute` method to add components to entities, leveraging the `SetupMovementEntity` for generic setup. ```cs [BurstCompile] public struct ProcessEntitiesJob : IJobChunk { public EntityCommandBuffer.ParallelWriter CommandBuffer; public void Execute(in ArchetypeChunk chunk, int unfilteredChunkIndex, bool useEnabledMask, in v128 chunkEnabledMask) { // Use parallel command buffer var commands = new CommandBufferParallelCommands(CommandBuffer, entity, unfilteredChunkIndex); SetupMovementEntity(ref commands, data.Position, data.Velocity); } } ``` -------------------------------- ### Access Blobs at Runtime - C# Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/EntityBlob.md Shows how to retrieve blob assets from an EntityBlob component at runtime using integer keys. It includes examples of safe access with TryGet and direct access with Get, along with Burst compilation attributes for performance. ```csharp [BurstCompile] public partial struct MySystem : ISystem { [BurstCompile] public void OnUpdate(ref SystemState state) { foreach (var entityBlob in SystemAPI.Query>()) { // Safe access with null checking if (entityBlob.ValueRO.TryGet(0, out var blobAsset)) { // Use the blob asset var data = blobAsset.Value.SomeField; } // Direct access (throws if key doesn't exist) var directBlob = entityBlob.ValueRO.Get(1); } } } ``` -------------------------------- ### Define K Settings Class (C#) Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/K.md Demonstrates how to define a settings class using K. It shows two approaches: automatic string-int pairing and custom authoring data with a base implementation. This is the first step in setting up K configurations. ```csharp public class ClientStates : KSettings { } public class ClientStates : KSettingsBase { [SerializeField] private KeyValues[] keys = Array.Empty(); public override IEnumerable> Keys => keys.Select(k => new NameValue(k.Name, k.Value)); [Serializable] public class KeyValues { public string Name = string.Empty; [Min(0)] public int Value = -1; } } ``` -------------------------------- ### Create Resource Settings (C#) Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/Settings.md Defines settings that can be loaded via Unity's Resources system. The 'ResourceSettings' attribute specifies the path for loading the ScriptableObject asset. ```csharp [ResourceSettings("MyGame")] public class ResourceGameSettings : ScriptableObject, ISettings { // Implementation } ``` -------------------------------- ### Create Basic Settings (C#) Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/Settings.md Defines a basic settings configuration using ScriptableObject for simple data management without direct ECS integration. It requires the 'SettingsGroupAttribute' for editor organization. ```csharp [SettingsGroup("Game")] public class GameConfiguration : ScriptableObject, ISettings { [SerializeField] private float musicVolume = 0.75f; [SerializeField] private bool enableTutorials = true; public float MusicVolume => musicVolume; public bool EnableTutorials => enableTutorials; } ``` -------------------------------- ### GlobalRandom - Usage Example in a Unity DOTS System Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/GlobalRandom.md Illustrates how to use GlobalRandom within a Burst-compiled Unity DOTS system. This example shows generating random positions, rotations, and scales for entities in parallel using a job. ```csharp [BurstCompile] public partial struct RandomMovementSystem : ISystem { [BurstCompile] public void OnUpdate(ref SystemState state) { new RandomMovementJob().ScheduleParallel(); } [BurstCompile] private partial struct RandomMovementJob : IJobEntity { private void Execute(ref LocalTransform transform, in RandomMovementComponent movement) { // Generate random position within bounds transform.Position = GlobalRandom.NextFloat3(movement.MinBounds, movement.MaxBounds); // Generate random rotation transform.Rotation = GlobalRandom.NextQuaternion(); // Generate random scale transform.Scale = GlobalRandom.NextFloat(movement.MinScale, movement.MaxScale); } } } ``` -------------------------------- ### Define Container Component with DynamicHashMap Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/DynamicHashMap.md Demonstrates how to define a custom container component implementing the IDynamicHashMap interface. This setup allows for key-value storage within entities, utilizing a specified initial buffer capacity. ```csharp [InternalBufferCapacity(0)] public struct PlayerInventory : IDynamicHashMap { byte IDynamicHashMap.Value { get; } } ``` -------------------------------- ### Runtime Object Spawning using ObjectDefinitionRegistry (C#) Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/ObjectManagement.md Illustrates how to spawn entities at runtime using the ObjectDefinitionRegistry. It queries for SpawnCommand components, uses the registry to retrieve the entity prefab based on ObjectId, instantiates it, and sets its position before destroying the command entity. ```csharp public void OnUpdate(ref SystemState state) { var ecb = new EntityCommandBuffer(state.WorldUpdateAllocator); var objectDefinitionRegistry = SystemAPI.GetSingleton(); foreach (var (command, commandEntity) in SystemAPI.Query>().WithEntityAccess()) { var entityPrefab = objectDefinitionRegistry[command.ValueRO.Prefab]; var entity = ecb.Instantiate(entityPrefab); ecb.SetComponent(entity, LocalTransform.FromPosition(command.ValueRO.Position)); ecb.DestroyEntity(commandEntity); } ecb.Playback(state.EntityManager); } ``` -------------------------------- ### Toggle Client States (C#) Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/States.md Demonstrates toggling client states. It shows how to set a specific state by creating a new `ClientState` singleton and how to enable a specific flag within the existing `ClientState` using a read-write singleton. ```csharp // Switch to state 4 SystemAPI.SetSingleton(new ClientState { Value = new BitArray256 { [4] = true } }); // Enable state 3 but keeping existing states var clientState = SystemAPI.GetSingletonRW(); clientState.ValueRW.Value[3] = true; ``` -------------------------------- ### Register Camera State using StateAPI (C#) Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/States.md Registers a specific camera state (`FreeCameraState`) with the `StateAPI` for use within the system. This example demonstrates registering a state identified by its enum value. ```csharp public enum CameraStates : byte { None = 0, TopDown = 250, ThirdPerson = 251, Follow = 252, Free = 254, } public partial struct FreeCameraSystem : ISystem { public void OnCreate(ref SystemState state) { StateAPI.Register(ref state, (byte)CameraStates.Free); } } ``` -------------------------------- ### Define Two-Column VariableMap Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/DynamicHashMap.md Illustrates the definition of a custom container implementing IDynamicVariableMap with two extra columns. This example stores Entity keys, RelationData values, and associated integer and float data using OrderedListColumns. ```csharp using BovineLabs.Core.Iterators.Columns; // Two column example public struct EntityRelations : IDynamicVariableMap, float, OrderedListColumn> { byte IDynamicVariableMap, float, OrderedListColumn>.Value { get; } } ``` -------------------------------- ### Define Single-Column VariableMap Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/DynamicHashMap.md Shows how to define a custom container implementing IDynamicVariableMap with a single extra column for associated data. This example uses an OrderedListColumn for storing a float value alongside the main key-value pair. ```csharp using BovineLabs.Core.Iterators.Columns; // Single column example public struct InventoryMap : IDynamicVariableMap> { byte IDynamicVariableMap>.Value { get; } } ``` -------------------------------- ### Implement Camera State System (C#) Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/States.md Implements a state system for managing camera states using `StateModel`. It handles system start/stop and updates, managing state transitions and component updates. ```csharp public partial struct CameraStateSystem : ISystem, ISystemStartStop { private StateModel impl; public void OnStartRunning(ref SystemState state) { impl = new StateModel(ref state, ComponentType.ReadWrite(), ComponentType.ReadWrite()); } public void OnStopRunning(ref SystemState state) { impl.Dispose(); } public void OnUpdate(ref SystemState state) { var ecb = new EntityCommandBuffer(state.WorldUpdateAllocator); impl.Run(ref state, ecb); ecb.Playback(state.EntityManager); } } ``` -------------------------------- ### Custom Job Types for Parallel Hash Map Processing in Unity DOTS Source: https://context7.com/tertle/com.bovinelabs.core/llms.txt Implements IJobParallelHashMapDefer for efficient parallel processing of NativeParallelHashMap. This example shows how to read from the hash map and conditionally destroy entities using EntityCommandBuffer.ParallelWriter. ```csharp // IJobParallelHashMapDefer for processing parallel hash maps [BurstCompile] private struct ProcessEntityDataJob : IJobParallelHashMapDefer { [ReadOnly] public NativeParallelHashMap DamageMap; [ReadOnly] public ComponentLookup HealthLookup; public EntityCommandBuffer.ParallelWriter ECB; public void ExecuteNext(int entryIndex, int jobIndex) { this.Read(DamageMap, entryIndex, out Entity entity, out DamageData damage); if (HealthLookup.HasComponent(entity)) { var health = HealthLookup[entity]; if (health.Value <= damage.Amount) { ECB.DestroyEntity(jobIndex, entity); } } } } // Schedule with appropriate batch size state.Dependency = new ProcessEntityDataJob { DamageMap = damageHashMap, HealthLookup = SystemAPI.GetComponentLookup(true), ECB = ecb.AsParallelWriter() }.ScheduleParallel(damageHashMap, 64, state.Dependency); ``` -------------------------------- ### Checking Group Membership with ObjectGroupMatcher (C#) Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/ObjectManagement.md Provides a C# example of using the ObjectGroupMatcher singleton buffer at runtime to check if a given ObjectId belongs to a specified group. This is useful for systems like spell targeting or AI behavior categorization. ```csharp public void OnUpdate(ref SystemState state) { var objectGroupMatcher = SystemAPI.GetSingletonBuffer(); foreach (var (dealDamage, target) in SystemAPI.Query()) { var targetId = SystemAPI.GetComponent(target.Entity); if (objectGroupMatcher.Matches(dealDamage.Group, targetId.Value)) { // Deal damage } } } ``` -------------------------------- ### C# Builder and Functions Methods for Extensible Jobs Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/Functions.md Demonstrates core C# methods for building and managing extensible functions within jobs. Includes reflection, manual addition, building function collections, and executing/updating/cleaning up functions. Assumes a 'state' object is available for context. ```csharp // Builder methods new FunctionsBuilder(Allocator.Temp) .ReflectAll(ref state) // Find all IFunction implementations .Add(ref state) // Manually add function .Build(); // Create Functions // Functions methods functions.Update(ref state); // Update all functions functions.Execute(index, ref data); // Execute specific function functions.OnDestroy(ref state); // Cleanup ``` -------------------------------- ### Access InputCommon Utilities (C#) Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/Input.md Demonstrates how to access and utilize the `InputCommon` singleton struct to retrieve common input-related data updated every frame. This includes cursor positions in different spaces, viewport status, UI interaction checks, camera rays, and general button press detection. Ensure the `BovineLabs.Core.Input` assembly is referenced. ```csharp var inputCommon = SystemAPI.GetSingleton(); // Common properties inputCommon.CursorScreenPoint; // Screen space cursor position inputCommon.CursorViewPoint; // Viewport space cursor position inputCommon.CursorInViewPort; // Is cursor in viewport inputCommon.InputOverUI; // Is cursor over UI inputCommon.CameraRay; // Ray from camera through cursor inputCommon.AnyButtonPress; // Any button pressed this frame ``` -------------------------------- ### Filtering Object Definitions with SearchContext (C#) Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/ObjectManagement.md Shows how to use the `SearchContext` attribute in C# to filter ObjectDefinitions within the Unity inspector. It demonstrates filtering by category and provides examples of available search filters like category type, ID, name, and description. ```csharp [SearchContext("ca=creature", ObjectDefinition.SearchProviderType)] public ObjectDefinition Definition; ``` -------------------------------- ### Custom Job Types for Fixed Thread Workload Splitting in Unity DOTS Source: https://context7.com/tertle/com.bovinelabs.core/llms.txt Implements IJobForThread for splitting workload across a fixed number of threads. This example demonstrates a parallel calculation job that computes the square root of modified input values. ```csharp // IJobForThread for splitting workload across fixed threads [BurstCompile] private struct ParallelCalculationJob : IJobForThread { public NativeArray InputValues; public NativeArray Results; public void Execute(int index) { Results[index] = math.sqrt(InputValues[index] * 2.0f + 10.0f); } } // Schedule across 4 worker threads state.Dependency = new ParallelCalculationJob { InputValues = values, Results = results }.ScheduleParallel(values.Length, 4, state.Dependency); ``` -------------------------------- ### Authoring Spawn Command with Object Definition (C#) Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/ObjectManagement.md Demonstrates how to author a SpawnCommand component, linking an ObjectDefinition prefab to an entity. It uses a Baker class to convert the authoring component to a runtime component, implicitly casting ObjectDefinition to ObjectId. ```csharp public struct SpawnCommand : IComponentData { public ObjectId Prefab; public float3 Position; } public class SpawnCommandAuthoring : MonoBehaviour { public ObjectDefinition Prefab; public Vector3 Position; public class Baker : Baker { public override void Bake(SpawnCommandAuthoring authoring) { AddComponent(GetEntity(TransformUsageFlags.None), new SpawnCommand { Prefab = authoring.Prefab, Position = authoring.Position, }); } } } ``` -------------------------------- ### Create ECS-Integrated Settings (C#) Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/Settings.md Implements ECS-integrated settings by inheriting from 'SettingsBase'. This allows settings to be baked into ECS worlds, enabling their use within systems. It uses 'SettingsGroupAttribute' and 'SettingsWorldAttribute' to define its scope and target worlds. ```csharp [SettingsGroup("Game")] [SettingsWorld("Client", "Server")] public class GameplaySettings : SettingsBase { [SerializeField] private float playerMoveSpeed = 5.0f; [SerializeField] private int maxHealth = 100; public override void Bake(Baker baker) { var entity = baker.GetEntity(TransformUsageFlags.None); baker.AddComponent(entity, new GameplayData { MoveSpeed = playerMoveSpeed, Health = maxHealth, }); } } ``` -------------------------------- ### Iterate All K Key-Value Pairs (C#) Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/K.md Shows how to iterate through all defined key-value pairs within a K settings configuration. This is useful for dynamically accessing and processing all available mappings. ```csharp // Get an enumerator for all key-value pairs var enumerator = ClientStates.Enumerator(); while (enumerator.MoveNext()) { var pair = enumerator.Current; Debug.Log($"Name: {pair.Name}, Value: {pair.Value}"); } ``` -------------------------------- ### System Control Interface: IUpdateWhilePaused (C#) Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/Pause.md A marker interface for Unity DOTS systems that should continue to update regardless of the current pause mode. Systems implementing this interface will always run, even during a full pause. Example shows a basic system structure. ```csharp public partial struct MySystem : ISystem, IUpdateWhilePaused { public void OnUpdate(ref SystemState state) { // This system always updates, even when paused } } ``` -------------------------------- ### Runtime Assertions and Logging with C# Source: https://context7.com/tertle/com.bovinelabs.core/llms.txt Demonstrates runtime assertions using Check.Assume and world-specific logging with BLLogger for ECS development. Also shows global static logging with BLGlobalLogger and unit testing with ECSTestsFixture. Ensure correct log levels are configured for desired output. ```csharp // Runtime assertions with Check.Assume [BurstCompile] public partial struct ValidationSystem : ISystem { [BurstCompile] public void OnUpdate(ref SystemState state) { foreach (var (transform, health) in SystemAPI.Query, RefRO>()) { Check.Assume(health.ValueRO.Value >= 0, "Health cannot be negative"); Check.Assume(!math.isnan(transform.ValueRO.Position.x)); } } } // World-specific logging with BLLogger [BurstCompile] public partial struct GameSystem : ISystem { [BurstCompile] public void OnUpdate(ref SystemState state) { var logger = SystemAPI.GetSingleton(); logger.LogInfo("Processing game tick"); logger.LogWarning("Entity count exceeding threshold"); logger.LogError512("Critical failure in system XYZ"); // Verbose logging (editor-only) logger.LogVerboseString("Detailed debug information"); } } // Global static logging public class GameBootstrap { public static void Initialize() { BLGlobalLogger.LogInfo("Game initializing"); try { // Game setup } catch (Exception ex) { BLGlobalLogger.LogFatal(ex); throw; } } } // Configure log level via BovineLabs → Settings // Or runtime: set debug.loglevel config variable (Disabled, Fatal, Error, Warning, Info, Debug, Verbose) // Unit testing with ECSTestsFixture [TestFixture] [TestLeakDetection] public class MovementTests : ECSTestsFixture { [Test] public void TestMovementSystem() { var entity = EntityManager.CreateEntity(typeof(LocalTransform), typeof(Velocity)); EntityManager.SetComponentData(entity, new Velocity { Value = new float3(1, 0, 0) }); World.GetOrCreateSystemManaged().Update(World.Unmanaged); var transform = EntityManager.GetComponentData(entity); AssertMath.AreApproximatelyEqual(new float3(1, 0, 0), transform.Position, 0.01f); } } ``` -------------------------------- ### Access Settings During Baking (C#) Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/Settings.md Shows how to access settings during the baking process in Unity's DOTS. 'AuthoringSettingsUtility' is used to retrieve settings data that can then be applied to ECS entities. ```csharp var gameSettings = AuthoringSettingsUtility.GetSettings(); ``` -------------------------------- ### Convert Names to Keys (C#) Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/K.md Shows how to convert human-readable string names into their corresponding integer keys using K. It includes both a direct conversion and a safe conversion method with error handling. ```csharp // Get a value by name var state = ClientStates.NameToKey("menu"); // Try to get a value with error handling if (ClientStates.TryNameToKey("menu", out var stateValue)) { // Use stateValue } ``` -------------------------------- ### Third-Party System Support with PauseUtility (C#) Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/Pause.md Provides static HashSets within PauseUtility for registering third-party Unity DOTS systems that cannot directly implement marker interfaces. Allows systems to be explicitly added to update or be disabled during pauses. Example demonstrates adding system types. ```csharp // Register a system to update during pause PauseUtility.UpdateWhilePaused.Add(typeof(ThirdPartySystem)); // Register a system to be disabled during pause PauseUtility.DisableWhilePaused.Add(typeof(ThirdPartyRootSystem)); ``` -------------------------------- ### Implement Client State System (C#) Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/States.md Implements a state system for managing client states using `StateFlagModel`. This system handles the lifecycle and updates for flag-based states, similar to the `CameraStateSystem` but for multiple active states. ```csharp public partial struct ClientStateSystem : ISystem, ISystemStartStop { private StateFlagModel impl; public void OnStartRunning(ref SystemState state) { impl = new StateFlagModel(ref state, ComponentType.ReadWrite(), ComponentType.ReadWrite()); } public void OnStopRunning(ref SystemState state) { impl.Dispose(); } public void OnUpdate(ref SystemState state) { var ecb = new EntityCommandBuffer(state.WorldUpdateAllocator); impl.Run(ref state, ecb); ecb.Playback(state.EntityManager); } } ``` -------------------------------- ### System Control Interface: IDisableWhilePaused (C#) Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/Pause.md A marker interface for root Unity DOTS systems that should be disabled during a normal pause mode (when PauseAll is false). Systems implementing this interface will stop updating unless a full pause is active. Example shows a system group implementing the interface. ```csharp public partial struct MySimulationGroup : ISystem, IDisableWhilePaused { // This system group stops during normal pause } ``` -------------------------------- ### Initialize Player on Entity Initialization (C#) Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/LifeCycle.md This C# code demonstrates how to create a system that runs during the entity initialization phase. It uses the InitializeSystemGroup and targets entities with the InitializeEntity component to set initial player properties like Health and Score. Requires Unity DOTS and Burst compiler. ```csharp using Unity.Entities; using Unity.Jobs; using Unity.Burst; [UpdateInGroup(typeof(InitializeSystemGroup))] public partial struct InitializePlayerSystem : ISystem { public void OnUpdate(ref SystemState state) { new InitializeJob().ScheduleParallel(); } [BurstCompile] [WithAll(typeof(InitializeEntity))] private partial struct InitializeJob : IJobEntity { private void Execute(Entity entity, ref Player player) { player.Health = 100; player.Score = 0; } } } ``` -------------------------------- ### ID-Based Object Spawning in Unity DOTS Source: https://context7.com/tertle/com.bovinelabs.core/llms.txt Implements an ID-based object system for deterministic prefab assignment and runtime spawning in Unity DOTS. It includes component definitions, authoring scripts with search filtering, and a runtime spawning system. ```csharp // Create ObjectDefinitions via Create → BovineLabs → Object Definition // Configure via BovineLabs → Settings with categories // Component definition public struct SpawnCommand : IComponentData { public ObjectId Prefab; public float3 Position; public float3 Velocity; } // Authoring with search filtering public class SpawnCommandAuthoring : MonoBehaviour { [SearchContext("ca=creature cid=5", ObjectDefinition.SearchProviderType)] public ObjectDefinition Prefab; public Vector3 Position; public class Baker : Baker { public override void Bake(SpawnCommandAuthoring authoring) { AddComponent(GetEntity(TransformUsageFlags.None), new SpawnCommand { Prefab = authoring.Prefab, // Implicit cast to ObjectId Position = authoring.Position }); } } } // Runtime spawning system [BurstCompile] public partial struct SpawnSystem : ISystem { [BurstCompile] public void OnUpdate(ref SystemState state) { var ecb = new EntityCommandBuffer(state.WorldUpdateAllocator); var registry = SystemAPI.GetSingleton(); foreach (var (command, entity) in SystemAPI.Query>() .WithEntityAccess()) { // O(1) lookup using ObjectId as index Entity prefab = registry[command.ValueRO.Prefab]; Entity spawned = ecb.Instantiate(prefab); ecb.SetComponent(spawned, LocalTransform.FromPosition(command.ValueRO.Position)); ecb.DestroyEntity(entity); } ecb.Playback(state.EntityManager); } } ``` -------------------------------- ### Extension Methods for Hash Map Operations Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/Jobs.md Provides extension methods for common operations on hash maps and hash sets within Unity's job system. These include reading key-value pairs, reading keys, checking for entry validity, and getting hash map capacity. ```cs // Read key-value pair from hash map this.Read(hashMap, entryIndex, out TKey key, out TValue value); // Read only key from hash set this.Read(hashSet, entryIndex, out T key); // Check if entry exists at index bool exists = this.IsValid(hashMap, entryIndex); // Get hash map capacity int capacity = this.GetCapacity(hashMap); ``` -------------------------------- ### Register Client State using StateAPI with K overload (C#) Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/States.md Registers client states using the `StateAPI` with its K overload, allowing for registration with a string identifier ('options') and a generic type for state configuration (`StateOptions`). ```csharp public partial struct OptionsStateSystem : ISystem { public void OnCreate(ref SystemState state) { StateAPI.Register(ref state, "options"); } } ``` -------------------------------- ### Create Processing System - C# Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/SingletonCollection.md Sets up a system to process events from singleton collections. It utilizes a SingletonCollectionUtil for managing the collections and schedules a job to handle the event processing. Includes OnCreate, OnDestroy, and OnUpdate methods. ```csharp public partial struct EventSystem : ISystem { private SingletonCollectionUtil> util; public void OnCreate(ref SystemState state) // Cannot be burst-compiled { util = new SingletonCollectionUtil>(ref state); } public void OnDestroy(ref SystemState state) // Cannot be burst-compiled { util.Dispose(); } [BurstCompile] public unsafe void OnUpdate(ref SystemState state) { var containers = util.Containers; for (int i = 0; i < containers.Length; i++) { state.Dependency = new ProcessEventsJob { Events = containers.Ptr[i] } .Schedule(state.Dependency); } util.ClearRewind(); // Essential: clears containers and rewinds allocator } [BurstCompile] private struct ProcessEventsJob : IJob { public NativeList Events; public void Execute() { for (int i = 0; i < Events.Length; i++) { // Process event } } } } ``` -------------------------------- ### Set Default K Values (C#) Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/K.md Illustrates how to set default key-value pairs for a K settings class. The `SetReset` method allows pre-defining common string-value mappings that will be available upon creation or reset of the settings asset. ```csharp public class ClientStates : KSettings { protected override IEnumerable> SetReset() { yield return new NameValue("menu", 0); yield return new NameValue("loading", 1); yield return new NameValue("gameplay", 2); yield return new NameValue("paused", 3); } } ``` -------------------------------- ### Movement System Implementation using EntityCommandBuffer in C# Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/EntityCommands.md This C# `MovementSystem` uses `EntityCommandBuffer` for deferred entity manipulation within Unity DOTS. It queries for `SpawnRequest` components, creates new entities, configures them using `SetupMovementEntity`, and then destroys the original entity that triggered the spawn. Finally, it plays back the command buffer. ```cs [BurstCompile] public partial struct MovementSystem : ISystem { public void OnUpdate(ref SystemState state) { var ecb = new EntityCommandBuffer(state.WorldUpdateAllocator); foreach (var (spawn, entity) in SystemAPI.Query>().WithEntityAccess()) { var newEntity = ecb.CreateEntity(); var commands = new CommandBufferCommands(ecb, newEntity); SetupMovementEntity(ref commands, spawn.ValueRO.Position, spawn.ValueRO.Velocity); ecb.DestroyEntity(entity); } ecb.Playback(state.EntityManager); } } ``` -------------------------------- ### Access Settings in Editor Tools (C#) Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/Settings.md Demonstrates how to retrieve settings configurations within the Unity editor environment using the 'EditorSettingsUtility'. This is useful for accessing configuration data in editor scripts or custom inspectors. ```csharp var gameConfig = EditorSettingsUtility.GetSettings(); ``` -------------------------------- ### Toggle Camera State (C#) Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/States.md Demonstrates how to toggle or switch to a specific camera state by directly setting the `CameraState` singleton component. This is a simple way to change the active state. ```csharp // Switch to state 15 SystemAPI.SetSingleton(new CameraState { Value = 15 }); ``` -------------------------------- ### ECS Unit Testing with ECSTestsFixture and AssertMath Source: https://gitlab.com/tertle/com.bovinelabs.core/-/blob/master/Documentation~/Debug.md This snippet demonstrates setting up ECS unit tests using `ECSTestsFixture` and `AssertMath`. `ECSTestsFixture` provides an isolated test world, while `AssertMath` offers specialized assertion methods for mathematical types like quaternions and vectors. ```csharp [TestLeakDetection] public class MyECSTest : ECSTestsFixture { [Test] public void TestEntityCreation() { var entity = EntityManager.CreateEntity(); AssertMath.AreApproximatelyEqual(expected, actual, 0.01f); } } ```